<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="trialCount">
        <el-input-number
          v-model="formModel.trialCount"
          placeholder="请输入试评数量"
          :min="0"
          :max="9999"
          :step="1"
          :controls="true"
          step-strictly
          style="width: 100%"
        />
      </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 } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import { markGroupSetTrialCount } from '@/api/mark';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { objAssign } from '@/utils/utils';

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

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

  interface Props {
    subjectCode: number; // 科目ID
  }

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

  const formRef = ref<FormInstance>();

  interface FormModel {
    subjectCode: number;
    trialCount: number;
  }

  const initialFormState: FormModel = {
    subjectCode: 0,
    trialCount: 0,
  };

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

  const rules: FormRules<keyof FormModel> = {
    trialCount: [
      { 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;

    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return;

    if (!formModel.subjectCode) {
      ElMessage.warning('请选择科目');
      return;
    }

    setLoading(true);
    const datas = objAssign(formModel, {});
    let res = true;
    await markGroupSetTrialCount(datas).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;
    ElMessage.success('设置试评数量成功！');
    emit('modified');
    close();
  }

  /* init modal */
  function modalBeforeOpen() {
    if (props.subjectCode) {
      formModel.subjectCode = props.subjectCode;
    }
  }
</script>
