<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="125px"
      v-loading="formLoading"
    >
      <el-form-item label="部门名称" prop="department_zh">
        <el-input v-model.trim="formData.department_zh" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="部门英文名称" prop="department_en">
        <el-input v-model.trim="formData.department_en" placeholder="请输入部门英文名称" />
      </el-form-item>
      <el-form-item label="职位名称" prop="position_zh">
        <el-input v-model.trim="formData.position_zh" placeholder="请输入职位名称" />
      </el-form-item>
      <el-form-item label="职位英文名称" prop="position_en">
        <el-input v-model.trim="formData.position_en" placeholder="请输入职位英文名称" />
      </el-form-item>
      <el-form-item label="职位英文名称缩写" prop="position_abbr">
        <el-input v-model.trim="formData.position_abbr" placeholder="请输入职位英文名称缩写" />
      </el-form-item>
      <el-form-item label="职级(中)" prop="level_zh">
        <el-input v-model.trim="formData.level_zh" placeholder="请输入职级名称（中）" />
      </el-form-item>
      <el-form-item label="职级(英)" prop="level_en">
        <el-input v-model.trim="formData.level_en" placeholder="请输入职级名称（英）" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in statusOptions"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-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>
import { talentPositionApi } from '@/api/menduner/system/talentMap/position'
import _ from 'lodash-es'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const statusOptions = [
	{ label: '启用', value: 'active' },
	{ label: '禁用', value: 'inactive' },
]

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref
const formData = ref({
  department_zh: undefined,
  department_en: undefined,
  position_zh: undefined,
  position_en: undefined,
  position_abbr: undefined,
  level_zh: undefined,
  level_en: undefined,
  created_by: 'system',
  updated_by: 'system',
  status: 'active'
})
const formRules = reactive({
  department_zh: [{ required: true, message: '部门中文名称不能为空', trigger: 'blur' }],
  department_en: [{ required: true, message: '部门英文名称不能为空', trigger: 'blur' }],
  position_zh: [{ required: true, message: '职位中文名称不能为空', trigger: 'blur' }],
  position_en: [{ required: true, message: '职位英文名称不能为空', trigger: 'blur' }],
  level_zh: [{ required: true, message: '职级中文名称不能为空', trigger: 'blur' }],
  level_en: [{ required: true, message: '职级英文名称不能为空', trigger: 'blur' }]
})

/** 打开弹窗 */
const valueKeys = ['department_zh', 'department_en', 'position_zh', 'position_en', 'position_abbr', 'level_zh', 'level_en', 'status']
const editItemData = ref({})
const open = async (type, data) => {
  editItemData.value = {}
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时，设置数据
  if (data && Object.keys(data).length) {
    formData.value = _.cloneDeep(data)
    valueKeys.forEach(key => editItemData.value[key] = data[key])
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  await formRef.value.validate()

  // 更新标签时，至少需要提供一个要更新的项
  const params = {}
  if (formType.value === 'update') {
    valueKeys.forEach(key => params[key] = formData.value[key])
    const isEqual = _.isEqual(params, editItemData.value)
    if (isEqual) return message.warning('请修改任意项后再提交！')
  }

  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await talentPositionApi.createHotelPosition(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await talentPositionApi.updateHotelPosition(formData.value.id, params)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    department_zh: undefined,
    department_en: undefined,
    position_zh: undefined,
    position_en: undefined,
    position_abbr: undefined,
    level_zh: undefined,
    level_en: undefined,
    created_by: 'system',
    updated_by: 'system',
    status: 'active'
  }
  formRef.value?.resetFields()
}
</script>