<template>
  <el-form
    ref="formRef"
    :model="formModel"
    :rules="formRules"
    label-width="120px"
  >
    <el-form-item label="分组序号" prop="groupNumber">
      <el-input-number
        v-model="formModel.groupNumber"
        :min="1"
        :max="99"
        :step="1"
        :precision="0"
        :controls="false"
        step-strictly
        placeholder="请输入"
        :readonly="isEdit || isReset"
      />
    </el-form-item>

    <el-form-item v-if="isEdit" label="名称">
      <el-input v-model="formModel.groupName" :readonly="isEdit"></el-input>
    </el-form-item>

    <el-form-item label="图片显示">
      <el-button type="primary" link @click="onSetMarkingArea">设置</el-button>
    </el-form-item>

    <template v-if="isReset || isAdd">
      <el-form-item label="双评">
        <el-checkbox
          v-model="formModel.openDouble"
          @change="onDoubleMarkingChange"
        ></el-checkbox>
      </el-form-item>

      <template v-if="formModel.openDouble">
        <el-form-item label="仲裁方式" prop="arbitrateType">
          <el-select
            v-model="formModel.arbitrateType"
            placeholder="请选择"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="(val, key) in ARBITRATION_TYPE"
              :key="key"
              :label="val"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="双评比例" prop="doubleRate">
          <el-input-number
            v-model="formModel.doubleRate"
            :min="0"
            :max="1"
            :step="0.01"
            :precision="2"
            :controls="false"
            step-strictly
            placeholder="请输入"
          />
        </el-form-item>
        <!-- 按组仲裁 阀值 -->
        <el-form-item
          v-if="formModel.arbitrateType === 'GROUP'"
          label="仲裁阀值"
          prop="arbitrateThreshold"
        >
          <el-input-number
            v-model="formModel.arbitrateThreshold"
            :min="0"
            :max="9999"
            :step="0.1"
            :precision="1"
            :controls="false"
            step-strictly
            placeholder="请输入"
          />
        </el-form-item>
        <!-- 小题仲裁 阀值 -->
        <template v-if="formModel.arbitrateType === 'QUESTION'">
          <template
            v-for="(question, qindex) in formModel.questions"
            :key="`a${qindex}`"
          >
            <el-form-item
              :label="`${question.mainNumber}-${question.subNumber}仲裁阀值`"
              :prop="'questions.' + qindex + '.arbitrateThreshold'"
              :rules="{
                required: true,
                message: '请输入仲裁阀值',
                trigger: 'change',
              }"
            >
              <el-input-number
                v-model="question.arbitrateThreshold"
                :min="1"
                :max="999"
                :step="0.1"
                :precision="1"
                :controls="false"
                step-strictly
                placeholder="请输入"
              />
            </el-form-item>
          </template>
        </template>

        <el-form-item label="合分策略" prop="scorePolicy">
          <el-select
            v-model="formModel.scorePolicy"
            placeholder="请选择"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="(val, key) in COMBINE_SCORE_STRATEGY"
              :key="key"
              :label="val"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="三评规则" prop="thirdPolicy">
          <el-select
            v-model="formModel.thirdPolicy"
            placeholder="请选择"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="(val, key) in THREE_EVALUATION_RULE"
              :key="key"
              :label="val"
              :value="key"
            />
          </el-select>
        </el-form-item>
      </template>

      <el-form-item v-if="isReset" label="重要提示">
        <el-alert
          title="保存后分组关联所有评卷任务都将删除，并生成新的分组任务"
          type="error"
          effect="dark"
        />
      </el-form-item>
    </template>

    <template v-if="isEdit && formModel.questions">
      <template
        v-for="(question, qindex) in formModel.questions"
        :key="`i${qindex}`"
      >
        <el-form-item
          :label="`${question.mainNumber}-${question.subNumber}间隔分`"
          :prop="'questions.' + qindex + '.intervalScore'"
          :rules="{
            required: true,
            message: '请输入间隔分',
            trigger: 'change',
          }"
        >
          <el-input-number
            v-model="question.intervalScore"
            :min="1"
            :max="999"
            :step="0.1"
            :precision="1"
            :controls="false"
            step-strictly
            placeholder="请输入"
          />
        </el-form-item>
      </template>
    </template>
  </el-form>

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

<script setup lang="ts">
  import { ref, watch, onMounted, computed } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import type { MarkGroupUpdateParams } from '@/api/types/mark';
  import {
    COMBINE_SCORE_STRATEGY,
    ARBITRATION_TYPE,
    THREE_EVALUATION_RULE,
  } from '@/constants/enumerate';
  import { deepCopy } from '@/utils/utils';
  import { CoverArea } from '@/api/types/common';

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

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

  interface Props {
    modelValue: MarkGroupUpdateParams;
    editType: 'add' | 'edit' | 'reset';
  }

  const props = defineProps<Props>();
  const emit = defineEmits<{
    'update:modelValue': [value: MarkGroupUpdateParams];
  }>();

  const isEdit = computed(() => props.editType === 'edit');
  const isReset = computed(() => props.editType === 'reset');
  const isAdd = computed(() => props.editType === 'add');

  const formRef = ref<FormInstance>();
  const formModel = ref<MarkGroupUpdateParams>({ ...props.modelValue });

  const formRules: FormRules<keyof MarkGroupUpdateParams> = {
    groupNumber: [
      { required: true, message: '请输入分组序号', trigger: 'change' },
    ],
    groupName: [
      { required: true, message: '请输入分组名称', trigger: 'change' },
    ],
    arbitrateType: [{ required: true, message: '请选择', trigger: 'change' }],
    scorePolicy: [{ required: true, message: '请选择', trigger: 'change' }],
    thirdPolicy: [{ required: true, message: '请选择', trigger: 'change' }],
    doubleRate: [{ required: true, message: '请输入', trigger: 'change' }],
    arbitrateThreshold: [
      { required: true, message: '请输入', trigger: 'change' },
    ],
  };

  function onDoubleMarkingChange(val: boolean) {
    if (!val) {
      formModel.value.arbitrateType = 'GROUP';
      formModel.value.scorePolicy = 'AVG_SCORE';
      formModel.value.thirdPolicy = 'CLOSE';
      formModel.value.doubleRate = undefined;
      formModel.value.arbitrateThreshold = undefined;
      formModel.value.questions.forEach((item) => {
        item.arbitrateThreshold = undefined;
      });
    }
  }

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

  // 监听表单数据变化，同步到父组件
  watch(
    formModel,
    (newVal) => {
      emit('update:modelValue', newVal);
    },
    { deep: true }
  );

  // 暴露验证方法
  const validate = () => {
    return formRef.value?.validate();
  };

  defineExpose({
    validate,
  });

  onMounted(() => {
    formModel.value = deepCopy(props.modelValue);
  });
</script>
