<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="应急物资名称" prop="emergencyName">
            <el-input v-model="formData.emergencyName" placeholder="请输入应急物资名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="应急物资单位" prop="emergencyUnit">
            <el-input
              v-model="formData.emergencyUnit"
              placeholder="请输入应急物资单位，如：个、台等" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="是否录入证书" prop="ifCert">
            <el-radio-group v-model="formData.ifCert">
              <el-radio
                v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                :key="dict.value"
                :value="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数量" prop="emergencyNumber">
            <el-input-number
              v-model="formData.emergencyNumber"
              :disabled="isCertEntered"
              :min="0"
              :precision="0"
              controls-position="right"
              class="!w-full" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="存放位置" prop="emergencyLocation">
            <el-input v-model="formData.emergencyLocation" placeholder="请输入存放位置" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任人" prop="dutyPerson">
            <el-input v-model="formData.dutyPerson" placeholder="请输入责任人" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              node-key="id"
              filterable
              clearable
              :check-strictly="deptType !== '3'"
              placeholder="请选择部门"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="附件" prop="file">
            <UploadFile
              v-model="formData.file"
              :file-type="['doc', 'docx', 'pdf', 'jpg', 'png', 'jpeg', 'xls', 'xlsx', 'bmp']"
              :limit="3"
              :file-size="100"
              class="min-w-80px" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确定</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { EmergencyDrillApi } from '@/api/pms/qhse/index'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { useUserStore } from '@/store/modules/user'
import { getUserProfile } from '@/api/system/user/profile'
import { DICT_TYPE, getBoolDictOptions } from '@/utils/dict'

defineOptions({ name: 'QHSEEmergencyDrillForm' })

const { t } = useI18n()
const message = useMessage()
const userStore = useUserStore()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()
const deptList = ref<Tree[]>([])

const createDefaultFormData = () => ({
  id: undefined,
  emergencyName: '',
  emergencyUnit: '',
  emergencyNumber: undefined,
  emergencyLocation: '',
  dutyPerson: '',
  mobile: '',
  file: '',
  deptId: undefined,
  remark: '',
  ifCert: ''
})

const formData = ref(createDefaultFormData())

const isCertEntered = computed(() => formData.value.ifCert === true)

const formRules = reactive({
  emergencyName: [{ required: true, message: '应急物资名称不能为空', trigger: 'blur' }],
  emergencyUnit: [{ required: true, message: '应急物资单位不能为空', trigger: 'blur' }],
  dutyPerson: [{ required: true, message: '责任人不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'change' }],
  ifCert: [{ required: true, message: '请选择是否录入证书', trigger: 'change' }],
  emergencyNumber: [{ required: true, message: '数量不能为空', trigger: 'blur' }]
})

const emit = defineEmits(['success'])

const resetForm = () => {
  formData.value = createDefaultFormData()
  formRef.value?.resetFields()
}

watch(
  () => formData.value.ifCert,
  (value) => {
    if (value === true) {
      formData.value.emergencyNumber = 1
    }
  }
)

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.deptId = userStore.getUser.deptId
  if (id) {
    formLoading.value = true
    try {
      const res = await EmergencyDrillApi.getEmergencyDrill(id)
      formData.value = {
        ...createDefaultFormData(),
        ...res
      }
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open })

const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = { ...formData.value } as any
    if (data.file instanceof Array) {
      data.file = data.file.join(',')
    }

    if (formType.value === 'create') {
      await EmergencyDrillApi.createEmergencyDrill(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmergencyDrillApi.updateEmergencyDrill(data)
      message.success(t('common.updateSuccess'))
    }

    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

let deptType = ref('')
onMounted(async () => {
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())

  const users = await getUserProfile()
  deptType.value = users.dept.type
})
</script>
