<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="name">
        <el-input
          v-model="formModel.name"
          placeholder="请输入分类名称"
          maxlength="50"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" :loading="loading" @click="confirm">
        保存
      </el-button>
    </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 {
    RejectTypeItem,
    RejectTypeUpdateParam,
  } from '@/api/types/reject';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { objAssign, objModifyAssign } from '@/utils/utils';
  import { updateRejectType } from '@/api/reject';

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

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

  interface Props {
    rowData: RejectTypeItem;
    examId: number;
  }

  const props = withDefaults(defineProps<Props>(), {
    rowData: {} as RejectTypeItem,
    examId: 0,
  });
  const emit = defineEmits(['modified']);

  const isEdit = computed(() => !!props.rowData?.id);
  const title = computed(() => `${isEdit.value ? '编辑' : '新增'}打回卷分类`);

  const formRef = ref<FormInstance>();
  const initialFormState: Partial<RejectTypeUpdateParam> = {
    name: '',
    custom: true,
  };

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

  const rules: FormRules<keyof RejectTypeUpdateParam> = {
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  };

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

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

    setLoading(true);
    try {
      const data = objAssign(formModel, {}) as RejectTypeUpdateParam;
      data.examId = props.examId;

      if (isEdit.value) {
        data.id = props.rowData.id;
      }

      await updateRejectType(data);
      ElMessage.success(`${isEdit.value ? '编辑' : '新增'}成功！`);
      emit('modified', data);
      close();
    } catch (error) {
      console.error('保存失败:', error);
      ElMessage.error('保存失败');
    } finally {
      setLoading(false);
    }
  }

  /* init modal */
  function modalBeforeOpen() {
    if (props.rowData.id) {
      // 编辑模式，映射字段
      objModifyAssign(formModel, props.rowData);
    } else {
      objModifyAssign(formModel, initialFormState);
    }
  }
</script>
