<template>
  <div class="exam-edit">
    <page-breadcrumb
      :data="['考试批次管理', isEdit ? '编辑考试' : '创建考试']"
    />

    <div class="part-box is-border">
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="200px"
      >
        <!-- 考试信息 -->
        <div class="form-section">
          <div class="section-head">
            <h3>考试信息</h3>
          </div>
          <div class="section-body">
            <el-form-item label="考试名称" prop="name" label-width="110px">
              <el-input
                v-model.trim="formModel.name"
                placeholder="请输入考试名称"
                style="width: 200px"
              />
            </el-form-item>

            <el-form-item label="类型" prop="type" label-width="110px">
              <el-select
                v-model="formModel.type"
                placeholder="请选择类型"
                style="width: 200px"
              >
                <el-option
                  v-for="(val, key) in EXAM_TYPE"
                  :key="key"
                  :label="val"
                  :value="key"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="评卷开始日期" label-width="110px">
              <el-date-picker
                v-model="formModel.startTime"
                type="date"
                placeholder="请选择评卷开始日期"
                style="width: 200px"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item label="评卷结束日期" label-width="110px">
              <el-date-picker
                v-model="formModel.endTime"
                type="date"
                placeholder="请选择评卷结束日期"
                style="width: 200px"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item v-if="isEdit" label="状态" label-width="110px">
              <el-select
                v-model="formModel.status"
                placeholder="请选择"
                style="width: 200px"
              >
                <el-option
                  v-for="(val, key) in EXAM_STATUS"
                  :key="key"
                  :label="val"
                  :value="key"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>

        <!-- 阅卷设置 -->
        <div class="form-section">
          <div class="section-head is-flex">
            <h3>阅卷设置</h3>
            <el-button type="primary" link @click="openAdvancedSettings">
              高级设置
            </el-button>
          </div>
          <div class="section-body">
            <div class="section-part">
              <h4 class="section-part-title">评卷给分方式</h4>
              <el-space :size="40">
                <el-form-item
                  label="评卷模式"
                  prop="markMode"
                  label-width="110px"
                >
                  <el-select
                    v-model="formModel.markMode"
                    placeholder="请选择"
                    style="width: 200px"
                  >
                    <el-option
                      v-for="(val, key) in MARKING_MODE"
                      :key="key"
                      :label="val"
                      :value="key"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="强制标记" label-width="110px">
                  <el-checkbox
                    v-model="formModel.forceSpecialTag"
                  ></el-checkbox>
                </el-form-item>
              </el-space>
            </div>

            <div class="section-part">
              <h4 class="section-part-title">数据安全</h4>
              <el-space :size="10">
                <el-form-item label="禁止他人查看考生信息" label-width="194px">
                  <el-checkbox v-model="formModel.forbiddenInfo"></el-checkbox>
                </el-form-item>

                <el-form-item label="禁止科组长成绩查询" label-width="200px">
                  <el-checkbox v-model="formModel.forbiddenScore"></el-checkbox>
                </el-form-item>
              </el-space>
            </div>

            <div class="section-part">
              <h4 class="section-part-title">全卷复核设置</h4>
              <el-space :size="30">
                <el-form-item
                  label="全卷多次复核不能同一账号"
                  label-width="220px"
                >
                  <el-checkbox
                    v-model="formModel.inspectUnrepeated"
                  ></el-checkbox>
                </el-form-item>

                <el-form-item
                  label="全卷复核强制试卷拉到底部"
                  label-width="200px"
                >
                  <el-checkbox
                    v-model="formModel.inspectScrollBottom"
                  ></el-checkbox>
                </el-form-item>
                <el-form-item
                  label="全卷复核进度100%时才能再次复核"
                  label-width="240px"
                >
                  <el-checkbox
                    v-model="formModel.inspectRoundLimit"
                  ></el-checkbox>
                </el-form-item>
              </el-space>
            </div>

            <div class="section-part">
              <h4 class="section-part-title">其他</h4>
              <el-space :size="40">
                <el-form-item
                  label="回评卷数"
                  prop="remarkCount"
                  label-width="110px"
                >
                  <el-input-number
                    v-model="formModel.remarkCount"
                    :min="0"
                    :max="100"
                    :step="1"
                    :precision="0"
                    :controls="false"
                    step-strictly
                    style="width: 200px"
                  />
                </el-form-item>

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

              <el-space :size="20">
                <el-form-item label="评卷端显示客观分" label-width="166px">
                  <el-checkbox
                    v-model="formModel.showObjectiveScore"
                  ></el-checkbox>
                </el-form-item>

                <el-form-item label="原图遮盖" label-width="140px">
                  <el-button type="primary" link @click="onSetMarkingArea"
                    >设置</el-button
                  >
                </el-form-item>
              </el-space>
              <br />

              <el-space :size="20">
                <el-form-item
                  label="打回后显示原分值及轨迹"
                  label-width="207px"
                >
                  <el-checkbox v-model="formModel.showReject"></el-checkbox>
                </el-form-item>

                <el-form-item label="原卷显示" label-width="100px">
                  <el-checkbox v-model="formModel.sheetView"></el-checkbox>
                </el-form-item>
              </el-space>
              <br />

              <el-space :size="20">
                <el-form-item label="评卷提交自动定位" label-width="165px">
                  <el-checkbox v-model="formModel.autoScroll"></el-checkbox>
                </el-form-item>

                <el-form-item label="自动对切题卡" label-width="168px">
                  <el-checkbox v-model="formModel.enableSplit"></el-checkbox>
                </el-form-item>
              </el-space>
            </div>

            <div class="section-part">
              <h4 class="section-part-title">数据分析设置</h4>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item
                    label="及格分"
                    prop="passScore"
                    label-width="110px"
                  >
                    <el-input-number
                      v-model="formModel.passScore"
                      :min="0"
                      :max="100"
                      :step="1"
                      :precision="0"
                      :controls="false"
                      step-strictly
                      style="width: 200px"
                    >
                      <template #suffix>
                        <span>%</span>
                      </template>
                    </el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label="优秀分"
                    prop="excellentScore"
                    label-width="110px"
                  >
                    <el-input-number
                      v-model="formModel.excellentScore"
                      :min="0"
                      :max="100"
                      :step="1"
                      :precision="0"
                      :controls="false"
                      step-strictly
                      style="width: 200px"
                    >
                      <template #suffix>
                        <span>%</span>
                      </template>
                    </el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="16">
                  <el-form-item label="备注描述" label-width="110px">
                    <el-input
                      v-model.trim="formModel.description"
                      type="textarea"
                      :rows="4"
                      maxlength="999"
                      placeholder="请输入备注描述"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
        <div class="form-actions">
          <el-button @click="goBack">返回</el-button>
          <el-button type="primary" :loading="loading" @click="handleSave">
            保存
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 高级设置弹窗 -->
    <ExamAdvancedDialog
      ref="advancedDialogRef"
      :advanced-config="advancedConfig"
      @confirm="handleAdvancedConfirm"
    />

    <!-- 添加遮盖区域弹窗 -->
    <SelectImgArea
      ref="imgAreaRef"
      v-model="selectedAreas"
      :img-list="imgList"
      @change="onImgAreaChange"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import { getExamDetail, updateExam } from '@/api/exam';
  import type { ExamUpdateParam, ExamAdvancedConfig } from '@/api/types/exam';
  import useLoading from '@/hooks/loading';
  import { MARKING_MODE, EXAM_TYPE, EXAM_STATUS } from '@/constants/enumerate';
  import { CoverArea } from '@/api/types/common';
  import { objModifyAssign } from '@/utils/utils';

  import SelectImgArea from '@/components/select-img-area/index.vue';
  import ExamAdvancedDialog from './components/ExamAdvancedDialog.vue';

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

  const route = useRoute();
  const router = useRouter();
  const { loading, setLoading } = useLoading();

  const examId = computed(() => Number(route.query.id) || 0);
  const isEdit = computed(() => !!examId.value);

  const formRef = ref<FormInstance>();
  const advancedDialogRef = ref();

  // 表单数据
  const getInitialFormState = () => {
    const initialFormState: Partial<ExamUpdateParam> = {
      id: undefined,
      name: '',
      type: 'SCAN_IMAGE',
      startTime: '',
      endTime: '',
      status: 'START',
      markMode: 'TRACK',
      forceSpecialTag: false,
      forbiddenInfo: false,
      forbiddenScore: false,
      inspectUnrepeated: false,
      inspectScrollBottom: false,
      inspectRoundLimit: false,
      showObjectiveScore: false,
      showReject: false,
      remarkCount: undefined,
      passScore: 60,
      excellentScore: 90,
      sheetView: false,
      sheetConfig: [],
      autoScroll: false,
      enableSplit: false,
      description: '',
      // 高级配置默认值
      markScrollBottom: false,
      minMarkDuration: undefined,
      reMarkLimitCount: undefined,
      trackCountPolicy: null,
      barcodeAiCheck: false,
      answerAiCheck: false,
    };
    return initialFormState;
  };

  const formModel = reactive(getInitialFormState());

  // 高级配置数据
  const advancedConfig = computed<ExamAdvancedConfig>(() => ({
    markScrollBottom: formModel.markScrollBottom,
    minMarkDuration: formModel.minMarkDuration,
    reMarkLimitCount: formModel.reMarkLimitCount,
    trackCountPolicy: formModel.trackCountPolicy,
    barcodeAiCheck: formModel.barcodeAiCheck,
    answerAiCheck: formModel.answerAiCheck,
  }));

  // 表单验证规则
  const rules: FormRules<keyof ExamUpdateParam> = {
    name: [{ required: true, message: '请输入考试名称', trigger: 'change' }],
    type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  };

  // 加载考试详情
  async function loadExamDetail() {
    if (!examId.value) return;

    setLoading(true);
    try {
      const result = await getExamDetail(examId.value);
      objModifyAssign(formModel, result);
    } catch (error) {
      console.error('获取考试详情失败:', error);
      ElMessage.error('获取考试详情失败');
    } finally {
      setLoading(false);
    }
  }

  // 打开高级设置弹窗
  function openAdvancedSettings() {
    advancedDialogRef.value?.open();
  }

  // 高级设置确认回调
  function handleAdvancedConfirm(config: ExamAdvancedConfig) {
    Object.assign(formModel, config);
  }

  // 原图遮盖
  const imgAreaRef = ref();
  const selectedAreas = ref<CoverArea[]>([]);
  // TODO:获取imgList
  const imgList = ref([]);
  function onSetMarkingArea() {
    selectedAreas.value = formModel.sheetConfig || [];
    imgAreaRef.value.open();
  }
  function onImgAreaChange(areas: CoverArea[]) {
    formModel.sheetConfig = areas;
  }

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

    setLoading(true);
    try {
      const data = { ...formModel } as ExamUpdateParam;

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

  // 返回
  function goBack() {
    router.push({ name: 'ExamManage' });
  }

  onMounted(() => {
    loadExamDetail();
  });
</script>
