<template>
  <div class="p-2">
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="450" :draggable="draggable">
      <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="岗位名称" prop="postName">
          <el-input v-model="formData.postName" placeholder="请输入岗位名称" :readonly="formData.sysData === 'Y'" />
        </el-form-item>
        <el-form-item label="岗位编码" prop="postCode">
          <el-input v-model="formData.postCode" placeholder="请输入编码名称" />
        </el-form-item>
        <el-form-item label="岗位顺序" prop="postSort">
          <el-input-number v-model="formData.postSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="岗位状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }} </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="系统岗位" prop="sysData">
          <el-radio-group v-model="formData.sysData">
            <el-radio v-for="dict in sys_yes_no" :key="dict.value" :value="dict.value" :disabled="formData.sysData === 'Y'"
              >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script name="PostForm" setup lang="ts">
// 模块导入
import { PostForm } from '@/api/system/params/post/types';
import api from '@/api/system/params/post';
import { useI18n } from 'vue-i18n';
// 国际化
const { t } = useI18n();
// 当前组件属性
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 引用的数据字典
const { sys_normal_disable, sys_yes_no } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'sys_yes_no'));

// 对话框
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 窗体是否可以拖动
const draggable = ref(true);
// 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formLoading = ref(false);
// 表单的类型：add - 新增；update - 修改
const formType = ref('');
// 表单引用
const formRef = ref<ElFormInstance>();
// 表单数据
const formData = ref<PostForm>({
  postId: undefined,
  postCode: '',
  postName: '',
  postSort: 0,
  status: '0',
  sysData: 'N',
  remark: ''
});
// 表单校验规则
const formRules = reactive({
  postName: [{ required: true, message: '岗位名称不能为空', trigger: 'blur' }],
  postCode: [{ required: true, message: '岗位编码不能为空', trigger: 'blur' }],
  postSort: [{ required: true, message: '岗位顺序不能为空', trigger: 'blur' }]
});
/** 当前组件方法 */
/** 窗体打开事件 */
const open = async (type: string, id?: number) => {
  dialog.visible = true;
  dialog.title = t('action.' + type);
  formType.value = type;
  resetForm();
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      const res = await api.getPost(id);
      Object.assign(formData.value, res.data);
    } finally {
      formLoading.value = false;
    }
  }
};
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    postId: undefined,
    postCode: '',
    postName: '',
    postSort: 0,
    status: '0',
    sysData: 'N',
    remark: ''
  };
  formRef.value?.resetFields();
};
/** 传回给父组件的属性与方法 */
// 提供 open 方法，用于打开弹窗
defineExpose({ open });

/** 触发父组件的事件 */
/** 定义 success 事件，用于操作成功后的回调 */
const emit = defineEmits(['success']);
/** 提交窗体 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return;
  const valid = await formRef.value?.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as PostForm;
    if (formType.value === 'add') {
      await api.addPost(data);
      proxy?.$modal.msgSuccess('新增岗位成功');
    } else {
      await api.updatePost(data);
      proxy?.$modal.msgSuccess('修改岗位成功');
    }
    dialog.visible = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};
</script>
