<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="10vh"
    append-to-body
    @close="handleClose"
    @open="modalBeforeOpen"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="登录名" prop="loginName">
        <el-input
          v-model="formModel.loginName"
          placeholder="请输入登录名"
          :disabled="isEdit"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="formModel.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="工号" prop="empno">
        <el-input v-model="formModel.empno" placeholder="请输入工号" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="formModel.password"
          type="password"
          show-password
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-select v-model="formModel.enable" placeholder="请选择状态">
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="formModel.role" placeholder="请选择角色">
          <el-option
            v-for="(val, key) in ROLE_TYPE"
            :key="key"
            :label="val"
            :value="key"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirm"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import type { UserItem, UserUpdateParam } from '@/api/types/user';
  import { updateUser } from '@/api/user';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { ROLE_TYPE } from '@/constants/enumerate';

  import { objAssign, objModifyAssign } from '@/utils/utils';

  defineOptions({
    name: 'ModifyUser',
  });

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close });

  interface Props {
    rowData?: UserItem; // 编辑时传入，新增时为空
  }

  const props = defineProps<Props>();
  const emit = defineEmits(['modified']);

  const isEdit = computed(() => !!props.rowData?.id);
  const title = computed(() => (isEdit.value ? '编辑用户' : '新增用户'));

  const formRef = ref<FormInstance>();

  const initialFormState: UserUpdateParam = {
    id: 0,
    loginName: '',
    name: '',
    employeeId: '',
    password: '',
    enable: true,
    role: 'EVALUATOR', // 默认角色
  };

  const formModel = reactive<UserUpdateParam>({ ...initialFormState });

  const validatePass = (rule: any, value: any, callback: any) => {
    if (!isEdit.value && value === '') {
      callback(new Error('请输入密码'));
    } else if (!isEdit.value && value.length < 6) {
      callback(new Error('密码长度至少为6位'));
    } else {
      callback();
    }
  };

  const rules: FormRules<keyof UserUpdateParam> = {
    loginName: [
      { required: true, message: '请输入登录名', trigger: 'change' },
      { max: 50, message: '登录名最多50字符', trigger: 'change' },
    ],
    name: [
      { required: true, message: '请输入名称', trigger: 'change' },
      { max: 50, message: '名称最多50字符', trigger: 'change' },
    ],
    employeeId: [{ max: 50, message: '工号最多50字符', trigger: 'change' }],
    password: [
      { required: !isEdit.value, validator: validatePass, trigger: 'change' },
    ],
    enable: [{ required: true, message: '请选择状态', trigger: 'change' }],
    role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  };

  const handleClose = () => {
    formRef.value?.resetFields();
    Object.assign(formModel, initialFormState);
  };

  /* confirm */
  const { loading, setLoading } = useLoading();
  async function confirm() {
    if (!formRef.value) return;
    try {
      const valid = await formRef.value?.validate().catch(() => false);
      if (!valid) return;

      setLoading(true);
      const datas = objAssign(formModel, {});
      let res = true;
      await updateUser(datas).catch(() => {
        res = false;
      });
      setLoading(false);
      if (!res) return;
      ElMessage.success(`${isEdit.value ? '修改' : '新增'}成功！`);
      emit('modified');
      close();
    } catch (error) {
      console.error('表单校验失败或API请求错误:', error);
      setLoading(false);
    }
  }

  /* init modal */
  function modalBeforeOpen() {
    if (props.rowData?.id) {
      // 编辑时，填充表单
      objModifyAssign(formModel, props.rowData);
    } else {
      // 新增时，重置为初始状态（确保密码字段为空）
      objModifyAssign(formModel, initialFormState);
    }
  }
</script>
