<template>
  <Dialog title="企业职位发布类型权限更新" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="职位发布类型" prop="pubJobTypePerm">
        <el-checkbox-group v-model="formData.pubJobTypePerm">
          <el-checkbox v-for="k in getIntDictOptions(DICT_TYPE.MENDUNER_JOB_TYPE)" :key="k.value" :label="k.label" :value="k.value" />
        </el-checkbox-group>
      </el-form-item>
    </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">
defineOptions({ name: 'EnterpriseForm' })
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { EnterpriseApi } from '@/api/menduner/system/enterprise/message'

const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: '',
  pubJobTypePerm: []
})
const formRef = ref()

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await EnterpriseApi.getEnterprise(id)
      formData.value.id = data.id
      formData.value.pubJobTypePerm = data.pubJobTypePerm ? data.pubJobTypePerm.map(e => Number(e)) : []
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    await EnterpriseApi.updateEnterpriseJobType(formData.value)
    dialogVisible.value = false
    message.success('操作成功')
    // 发送操作成功的事件
    emit('success')
    resetForm()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: '',
    pubJobTypePerm: []
  }
}
</script>