<template>
  <el-dialog
    v-model="visible"
    title="高级设置"
    width="700px"
    :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="180px"
    >
      <el-form-item label="评卷时强制试卷拉到底部">
        <el-checkbox v-model="formModel.markScrollBottom"> </el-checkbox>
      </el-form-item>

      <el-form-item label="最小阅卷时长(秒)" prop="minMarkDuration">
        <el-input-number
          v-model="formModel.minMarkDuration"
          :min="0"
          :max="999999"
          :step="1"
          :precision="0"
          :controls="false"
          step-strictly
          placeholder="请输入最小阅卷时长"
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="单卷回评次数" prop="reMarkLimitCount">
        <el-input-number
          v-model="formModel.reMarkLimitCount"
          :min="0"
          :max="100"
          :step="1"
          :precision="0"
          :controls="false"
          step-strictly
          placeholder="请输入单卷回评次数"
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="给分次数限制" prop="trackCountPolicy">
        <el-select
          v-model="formModel.trackCountPolicy"
          placeholder="请选择给分次数限制类型"
          style="width: 200px"
          clearable
        >
          <el-option label="小于等于" value="LE" />
          <el-option label="等于" value="EQ" />
        </el-select>
      </el-form-item>

      <el-form-item label="启用条码粘贴AI检测">
        <el-checkbox v-model="formModel.barcodeAiCheck"> </el-checkbox>
        <span v-show="formModel.barcodeAiCheck" class="tip-text"
          >预计耗时: 15小时12分</span
        >
        <div class="ai-detection-tip">
          <span class="tip-warning">
            *AI检测均耗时较久，如需使用此功能，建议在开始扫描时就配置启用此功能
          </span>
        </div>
      </el-form-item>

      <el-form-item label="启用题卡作答AI检测">
        <el-checkbox v-model="formModel.answerAiCheck"> </el-checkbox>
        <div class="ai-detection-tip">
          <span class="tip-warning">
            *AI检测均耗时较久，如需使用此功能，建议在开始扫描时就配置启用此功能
          </span>
        </div>
      </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 type { ExamAdvancedConfig } from '@/api/types/exam';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { objAssign, objModifyAssign } from '@/utils/utils';

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

  interface Props {
    advancedConfig?: ExamAdvancedConfig;
  }

  const props = withDefaults(defineProps<Props>(), {
    advancedConfig: () => ({
      markScrollBottom: false,
      minMarkDuration: undefined,
      reMarkLimitCount: undefined,
      trackCountPolicy: null,
      barcodeAiCheck: false,
      answerAiCheck: false,
    }),
  });

  const emit = defineEmits<{
    confirm: [config: ExamAdvancedConfig];
  }>();

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

  const formRef = ref<FormInstance>();
  const { loading, setLoading } = useLoading();

  const initialFormState: ExamAdvancedConfig = {
    markScrollBottom: false,
    minMarkDuration: undefined,
    reMarkLimitCount: undefined,
    trackCountPolicy: null,
    barcodeAiCheck: false,
    answerAiCheck: false,
  };

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

  const rules: FormRules<keyof ExamAdvancedConfig> = {
    minMarkDuration: [
      {
        validator: (rule, value, callback) => {
          if (value !== undefined && value < 0) {
            callback(new Error('最小阅卷时长不能小于0'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    reMarkLimitCount: [
      {
        validator: (rule, value, callback) => {
          if (value !== undefined && value < 0) {
            callback(new Error('单卷回评次数不能小于0'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
  };

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

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

    setLoading(true);
    try {
      const config = objAssign(formModel, {}) as ExamAdvancedConfig;
      emit('confirm', config);
      close();
    } catch (error) {
      console.error('保存高级设置失败:', error);
    } finally {
      setLoading(false);
    }
  }

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

<style scoped>
  .ai-detection-tip {
    width: 100%;
  }

  .tip-text {
    color: #666;
    margin-right: 10px;
  }

  .tip-warning {
    color: #e6a23c;
  }

  .dialog-footer .el-button {
    margin: 0 5px;
  }
</style>
