<template>
  <el-dialog
    v-model="visible"
    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="adminName">
        <el-input
          v-model="formModel.adminName"
          placeholder="请输入管理员名称"
        />
      </el-form-item>
      <el-form-item label="账号" prop="adminLoginName">
        <el-input
          v-model="formModel.adminLoginName"
          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="confirmPassword">
        <el-input
          v-model="formModel.confirmPassword"
          type="password"
          show-password
          placeholder="请再次输入重复输入"
        />
      </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 } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { updateSchoolAdmin } from '@/api/admin'; // 假设有更新学校管理员的API
  import type { SchoolItem, SchoolUpdateAdminParam } from '@/api/types/admin'; // 假设的管理员信息类型
  import { objModifyAssign } from '@/utils/utils';

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

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

  interface Props {
    rowData: SchoolItem;
  }

  const props = withDefaults(defineProps<Props>(), {
    rowData: {} as SchoolItem,
  });

  const emit = defineEmits(['modified']);

  const formRef = ref<FormInstance>();

  const initialFormState: SchoolUpdateAdminParam & { confirmPassword: string } =
    {
      id: 0,
      adminName: '',
      adminLoginName: '',
      password: '',
      confirmPassword: '',
    };

  const formModel = reactive({ ...initialFormState });

  const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error('请输入密码'));
    } else {
      if (formModel.confirmPassword !== '') {
        if (!formRef.value) return;
        formRef.value.validateField('confirmPassword');
      }
      callback();
    }
  };

  const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error('请再次输入密码'));
    } else if (value !== formModel.password) {
      callback(new Error('两次输入的密码不一致!'));
    } else {
      callback();
    }
  };

  const rules = reactive<FormRules>({
    adminName: [
      { required: true, message: '请输入管理员名称', trigger: 'blur' },
    ],
    adminLoginName: [
      { required: true, message: '请输入登录账号', trigger: 'blur' },
    ],
    password: [
      { required: true, validator: validatePass, trigger: 'blur' },
      { min: 6, message: '密码长度至少为6位', trigger: 'blur' },
    ],
    confirmPassword: [
      { required: true, validator: validatePass2, trigger: 'blur' },
    ],
  });

  const handleClose = () => {
    formRef.value?.resetFields();
  };

  /* 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 params = {
        ...formModel,
      };
      // delete params.confirmPassword;
      await updateSchoolAdmin(params);
      ElMessage.success('管理员信息保存成功！');
      emit('modified');
      close();
    } catch (error) {
      console.error('表单校验失败或API请求错误:', error);
      // ElMessage.error('保存失败，请检查表单');
    } finally {
      setLoading(false);
    }
  }

  /* init modal */
  function modalBeforeOpen() {
    objModifyAssign(formModel, props.rowData || {});
  }
</script>
