<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading">
      <el-form-item label="所属队伍" prop="deptId">
        <el-tree-select
          clearable
          v-model="formData.deptId"
          :data="deptList2"
          :props="defaultProps"
          :check-strictly="false"
          node-key="id"
          filterable
          @node-click="handleDeptTreeNodeClick"
          placeholder="请选择所在部门" />
      </el-form-item>
      <el-form-item label="姓名" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" />
      </el-form-item>

      <el-form-item label="岗位" prop="postName">
        <el-input v-model="formData.postName" placeholder="请输入岗位名称" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>

      <el-divider>是否需要相关证书</el-divider>

      <div class="flex flex-wrap items-center justify-between">
        <el-form-item label="硫化氢证" prop="lsh">
          <el-radio-group v-model="formData.lsh">
            <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-form-item label="井控证" prop="jk">
          <el-radio-group v-model="formData.jk">
            <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-form-item label="HSE证" prop="hse">
          <el-radio-group v-model="formData.hse">
            <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-form-item label="司钻证" prop="sz">
          <el-radio-group v-model="formData.sz">
            <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-form-item label="高处作业证" prop="gczy">
          <el-radio-group v-model="formData.gczy">
            <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-form-item label="电工证" prop="dg">
          <el-radio-group v-model="formData.dg">
            <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-form-item
          label="连续油管主操证"
          prop="lxygzc"
          label-width="auto"
          style="margin-left: -5px">
          <el-radio-group v-model="formData.lxygzc">
            <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-form-item label="吊装证" prop="dz">
          <el-radio-group v-model="formData.dz">
            <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-form-item label="安全管理证" prop="aqgl">
          <el-radio-group v-model="formData.aqgl">
            <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-form-item label="国际井控证" prop="gjjk">
          <el-radio-group v-model="formData.gjjk">
            <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-form-item label="消防证" prop="xiaofang">
          <el-radio-group v-model="formData.xiaofang">
            <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-form-item label="急救证" prop="jijiu">
          <el-radio-group v-model="formData.jijiu">
            <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>
      </div>
    </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 { CertPersonApi } from '@/api/pms/qhse/index'
import { handleTree, defaultProps } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { useUserStore } from '@/store/modules/user'
import { ElMessageBox } from 'element-plus'
import { DICT_TYPE, getBoolDictOptions } from '@/utils/dict'
/** SOC卡汇总 表单 */
defineOptions({ name: 'IotSocSummaryForm' })

const userStore = useUserStore()

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const deptList2 = ref<Tree[]>([]) // 树形结构
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  username: undefined,
  nickname: undefined,
  mobile: undefined,
  postName: undefined,

  remark: undefined,
  deptId: undefined,
  deptName: undefined,
  lsh: undefined,
  jk: undefined,
  hse: undefined,
  sz: undefined,
  gczy: undefined,
  dg: undefined,
  lxygzc: undefined,
  dz: undefined,
  aqgl: undefined,
  gjjk: undefined,
  xiaofang: undefined,
  jijiu: undefined
})
const formRules = reactive({
  nickname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择所属队伍', trigger: 'blur' }],
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  postName: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],

  lsh: [{ required: true, message: '请选择', trigger: 'blur' }],
  jk: [{ required: true, message: '请选择', trigger: 'blur' }],
  hse: [{ required: true, message: '请选择', trigger: 'blur' }],
  sz: [{ required: true, message: '请选择', trigger: 'blur' }],
  gczy: [{ required: true, message: '请选择', trigger: 'blur' }],
  dg: [{ required: true, message: '请选择', trigger: 'blur' }],
  lxygzc: [{ required: true, message: '请选择', trigger: 'blur' }],
  dz: [{ required: true, message: '请选择', trigger: 'blur' }],
  aqgl: [{ required: true, message: '请选择', trigger: 'blur' }],
  gjjk: [{ required: true, message: '请选择', trigger: 'blur' }],
  xiaofang: [{ required: true, message: '请选择', trigger: 'blur' }],
  jijiu: [{ required: true, message: '请选择', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const handleDeptTreeNodeClick = (data: Tree) => {
  console.log(data)

  formData.value.deptId = data.id
}

/** 打开弹窗 */
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 data = await CertPersonApi.getCertPerson(id)
      formData.value = {
        ...data
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验手机号格式（仅提示，不阻止提交）
  // 校验手机号格式，格式不正确时弹出二次确认
  if (formData.value.mobile && !/^1[3-9]\d{9}$/.test(formData.value.mobile)) {
    try {
      await ElMessageBox.confirm('手机号格式不正确，是否继续提交？', '提示', {
        confirmButtonText: '继续提交',
        cancelButtonText: '取消',
        type: 'warning'
      })
    } catch {
      return // 用户点击取消，终止提交
    }
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value }

    if (formType.value === 'create') {
      // data.deptId = userStore.getUser.deptId
      await CertPersonApi.createCertPerson(data)
      message.success(t('common.createSuccess'))
    } else {
      await CertPersonApi.updateCertPerson(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    username: undefined,
    nickname: undefined,
    mobile: undefined,
    postName: undefined,
    remark: undefined,
    deptId: undefined,
    deptName: undefined
  }
  formRef.value?.resetFields()
}

onMounted(async () => {
  deptList2.value = handleTree(await DeptApi.getSimpleDeptList())
})
</script>
