<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="600px"
    :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="formRules"
      label-width="100px"
    >
      <el-form-item label="试卷类型" prop="paperType">
        <el-select
          v-model="formModel.paperType"
          placeholder="请选择试卷类型"
          style="width: 100%"
        >
          <el-option label="A" value="A" />
          <el-option label="B" value="B" />
        </el-select>
      </el-form-item>

      <el-form-item label="大题名称" prop="bigQuestionName">
        <el-input
          v-model="formModel.bigQuestionName"
          placeholder="请输入大题名称"
          maxlength="50"
        />
      </el-form-item>

      <el-form-item label="大题昵称" prop="bigQuestionNickname">
        <el-input
          v-model="formModel.bigQuestionNickname"
          placeholder="请输入大题昵称"
          maxlength="50"
        />
      </el-form-item>

      <el-form-item label="大题号" prop="bigQuestionNo">
        <el-input-number
          v-model="formModel.bigQuestionNo"
          :min="1"
          :max="99"
          placeholder="请输入大题号"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="小题号" prop="smallQuestionNo">
        <el-input-number
          v-model="formModel.smallQuestionNo"
          :min="1"
          :max="999"
          placeholder="请输入小题号"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="满分" prop="fullScore">
        <el-input-number
          v-model="formModel.fullScore"
          :min="0"
          :max="999"
          :precision="1"
          placeholder="请输入满分"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="给分次数" prop="giveScoreCount">
        <el-input-number
          v-model="formModel.giveScoreCount"
          :min="1"
          :max="10"
          placeholder="请输入给分次数"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="是否客观题">
        <el-checkbox v-model="formModel.isObjective">客观题</el-checkbox>
      </el-form-item>

      <el-form-item label="间隔分" prop="intervalScore">
        <el-input-number
          v-model="formModel.intervalScore"
          :min="0"
          :max="10"
          :precision="1"
          placeholder="请输入间隔分"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="题型" prop="questionType">
        <el-select
          v-model="formModel.questionType"
          placeholder="请选择题型"
          style="width: 100%"
        >
          <el-option label="单选" value="单选" />
          <el-option label="多选" value="多选" />
          <el-option label="填空" value="填空" />
          <el-option label="简答" value="简答" />
          <el-option label="计算" value="计算" />
          <el-option label="作文" value="作文" />
        </el-select>
      </el-form-item>

      <el-form-item label="答案" prop="answer">
        <el-input
          v-model="formModel.answer"
          placeholder="请输入答案"
          maxlength="200"
        />
      </el-form-item>

      <el-form-item label="判分策略" prop="scoringStrategy">
        <el-select
          v-model="formModel.scoringStrategy"
          placeholder="请选择判分策略"
          style="width: 100%"
        >
          <el-option label="无" value="无" />
          <el-option label="全对全错" value="全对全错" />
          <el-option label="按步给分" value="按步给分" />
        </el-select>
      </el-form-item>

      <el-form-item label="分组" prop="grouping">
        <el-input
          v-model="formModel.grouping"
          placeholder="请输入分组信息（可选）"
          maxlength="10"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirm">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { reactive, ref, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import type { FormInstance, FormRules } from 'element-plus';
  import { savePaperStructure } from '@/api/subject';
  import type {
    PaperStructureItem,
    PaperStructureUpdateParams,
  } from '@/api/types/subject';

  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { objAssign, objModifyAssign } from '@/utils/utils';

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

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

  interface Props {
    rowData: PaperStructureItem;
    subjectId: number;
  }

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

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

  const isEdit = computed(() => !!props.rowData.id);
  const title = computed(() => `${isEdit.value ? '编辑' : '新增'}试卷结构`);

  const formRef = ref<FormInstance>();
  const initialFormState: PaperStructureUpdateParams = {
    paperType: '',
    bigQuestionName: '',
    bigQuestionNickname: '',
    bigQuestionNo: 1,
    smallQuestionNo: 1,
    fullScore: 0,
    giveScoreCount: 1,
    isObjective: false,
    intervalScore: 0.5,
    questionType: '',
    answer: '',
    scoringStrategy: '无',
    grouping: '',
  };
  const formModel = reactive<PaperStructureUpdateParams>({
    ...initialFormState,
  });

  const formRules: FormRules<keyof PaperStructureUpdateParams> = {
    paperType: [
      { required: true, message: '请选择试卷类型', trigger: 'change' },
    ],
    bigQuestionName: [
      { required: true, message: '请输入大题名称', trigger: 'blur' },
      { max: 50, message: '大题名称不能超过50个字符', trigger: 'blur' },
    ],
    bigQuestionNickname: [
      { max: 50, message: '大题昵称不能超过50个字符', trigger: 'blur' },
    ],
    bigQuestionNo: [
      { required: true, message: '请输入大题号', trigger: 'blur' },
    ],
    smallQuestionNo: [
      { required: true, message: '请输入小题号', trigger: 'blur' },
    ],
    fullScore: [{ required: true, message: '请输入满分', trigger: 'blur' }],
    giveScoreCount: [
      { required: true, message: '请输入给分次数', trigger: 'blur' },
    ],
    intervalScore: [
      { required: true, message: '请输入间隔分', trigger: 'blur' },
    ],
    questionType: [
      { required: true, message: '请选择题型', trigger: 'change' },
    ],
    answer: [{ max: 200, message: '答案不能超过200个字符', trigger: 'blur' }],
    scoringStrategy: [
      { required: true, message: '请选择判分策略', trigger: 'change' },
    ],
    grouping: [
      { max: 10, message: '分组信息不能超过10个字符', trigger: 'blur' },
    ],
  };

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

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

    setLoading(true);
    const datas = objAssign(formModel, {});
    if (isEdit.value) {
      datas.id = props.rowData.id;
    }
    let res = true;
    await savePaperStructure(datas).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;
    ElMessage.success(`${title.value}成功！`);
    emit('modified', datas);
    close();
  };

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