<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="mainTitle">
        <el-input v-model="formModel.mainTitle" placeholder="请输入大题名称" />
      </el-form-item>
      <el-form-item label="大题昵称" prop="name">
        <el-input v-model="formModel.name" placeholder="请输入大题昵称" />
      </el-form-item>
      <el-form-item label="大题号" prop="mainNumber">
        <el-input-number
          v-model="formModel.mainNumber"
          :min="1"
          :max="99"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="小题号" prop="subNumber">
        <el-input-number
          v-model="formModel.subNumber"
          :min="1"
          :max="99"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="满分" prop="totalScore">
        <el-input-number
          v-model="formModel.totalScore"
          :min="0"
          :max="999"
          :precision="1"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="给分次数" prop="trackCount">
        <el-input-number
          v-model="formModel.trackCount"
          :min="1"
          :max="9"
          controls-position="right"
        />
      </el-form-item>

      <el-form-item label="是否客观题" prop="objective">
        <el-radio-group v-model="formModel.objective">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </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>
      <template v-if="formModel.objective">
        <el-form-item label="试卷类型" prop="paperType">
          <el-input v-model="formModel.paperType" clearable />
        </el-form-item>
        <el-form-item label="题型" prop="type">
          <el-select v-model="formModel.type" placeholder="请选择题型">
            <el-option
              v-for="(label, value) in OBJECTIVE_QUESTION_TYPE"
              :key="value"
              :label="label"
              :value="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="objectivePolicy">
          <el-select
            v-model="formModel.objectivePolicy"
            placeholder="请选择判分策略"
          >
            <el-option
              v-for="(label, value) in OBJECTIVE_POLICY"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
      </template>
    </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';
  import {
    OBJECTIVE_POLICY,
    OBJECTIVE_QUESTION_TYPE,
  } from '@/constants/enumerate';

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

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

  interface Props {
    rowData: PaperStructureItem;
    subjectCode: string;
  }

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

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

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

  const formRef = ref<FormInstance>();
  const initialFormState: PaperStructureUpdateParams = {
    paperType: '',
    mainTitle: '',
    name: '',
    mainNumber: 1,
    subNumber: 1,
    totalScore: 0,
    trackCount: 1,
    objective: false,
    intervalScore: undefined,
    type: 'SINGLE',
    answer: '',
    objectivePolicy: 'NONE',
  };
  const formModel = reactive<PaperStructureUpdateParams>({
    ...initialFormState,
  });

  const formRules: FormRules<keyof PaperStructureUpdateParams> = {
    paperType: [
      { required: false, message: '请选择试卷类型', trigger: 'change' },
    ],
    mainTitle: [
      { required: true, message: '请输入大题名称', trigger: 'blur' },
      { max: 50, message: '大题名称不能超过50个字符', trigger: 'blur' },
    ],
    name: [{ max: 50, message: '大题昵称不能超过50个字符', trigger: 'blur' }],
    mainNumber: [{ required: true, message: '请输入大题号', trigger: 'blur' }],
    subNumber: [{ required: true, message: '请输入小题号', trigger: 'blur' }],
    totalScore: [{ required: true, message: '请输入满分', trigger: 'blur' }],
    trackCount: [
      { required: true, message: '请输入给分次数', trigger: 'blur' },
    ],
    intervalScore: [
      { required: true, message: '请输入间隔分', trigger: 'blur' },
    ],
    type: [{ required: true, message: '请选择题型', trigger: 'change' }],
    answer: [{ max: 200, message: '答案不能超过200个字符', trigger: 'blur' }],
    objectivePolicy: [
      { required: true, message: '请选择判分策略', trigger: 'change' },
    ],
    groupNumber: [
      { 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>
