<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :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="140px"
      class="setting-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="科目名称" prop="name">
            {{ formModel.name }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="科目代码" prop="code">
            {{ formModel.code }}
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="及格分" prop="passScore">
            <el-input-number
              v-model="formModel.passScore"
              :min="0"
              :max="1000"
              :precision="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优秀分" prop="excellentScore">
            <el-input-number
              v-model="formModel.excellentScore"
              :min="0"
              :max="1000"
              :precision="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="评卷显示题目昵称">
        <el-checkbox v-model="formModel.displayQuestionName" />
      </el-form-item>

      <el-form-item label="评卷提交自动定位">
        <el-radio-group v-model="formModel.autoScroll">
          <el-radio :value="3">设置以考试为准</el-radio>
          <el-radio :value="6">是</el-radio>
          <el-radio :value="9">否</el-radio>
        </el-radio-group>
        <p>
          *开启后，当前试卷评完后，下份试卷自动定位到上份试卷的第一个轨迹点
        </p>
      </el-form-item>

      <el-form-item label="自动对切题卡">
        <el-radio-group v-model="formModel.enableSplit">
          <el-radio :value="3">设置以考试为准</el-radio>
          <el-radio :value="6">是</el-radio>
          <el-radio :value="9">否</el-radio>
        </el-radio-group>
        <p>
          *选持自动对切题卡后，在阅卷端自动按照题卡的55%的比例进行对切，纸张大小A4时不生效
        </p>
      </el-form-item>

      <el-form-item label="原图遮盖">
        <el-button type="primary" size="small" @click="addCoverArea">
          设置
        </el-button>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirm">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>

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

<script setup lang="ts">
  import { reactive, ref, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import type { FormInstance, FormRules } from 'element-plus';
  import { saveSubjectSetting, getSubjectDetail } from '@/api/subject';
  import type { SubjectItem, SubjectSettingInfo } from '@/api/types/subject';

  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { objAssign, objModifyAssign } from '@/utils/utils';

  import SelectImgArea from '@/components/select-img-area/index.vue';
  import { CoverArea } from '@/api/types/common';

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

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

  interface Props {
    rowData?: SubjectItem;
  }

  const props = defineProps<Props>();

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

  const title = computed(() => '科目设置');

  const formRef = ref<FormInstance>();

  const initialFormState: SubjectSettingInfo = {
    id: 0,
    name: '',
    code: '',
    displayQuestionName: false,
    passScore: 60,
    excellentScore: 85,
    sheetConfig: null,
    autoScroll: false,
    enableSplit: false,
  };

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

  const formRules: FormRules<keyof SubjectSettingInfo> = {
    passScore: [
      { required: true, message: '请输入及格分', trigger: 'blur' },
      {
        type: 'number',
        min: 0,
        max: 1000,
        message: '及格分必须在0-1000之间',
        trigger: 'blur',
      },
    ],
    excellentScore: [
      { required: true, message: '请输入优秀分', trigger: 'blur' },
      {
        type: 'number',
        min: 0,
        max: 1000,
        message: '优秀分必须在0-1000之间',
        trigger: 'blur',
      },
    ],
  };

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

  // 添加遮盖区域
  const imgAreaRef = ref();
  const selectedAreas = ref<CoverArea[]>([]);
  // TODO:获取imgList
  const imgList = ref([]);
  const addCoverArea = () => {
    selectedAreas.value = formModel.sheetConfig || [];
    imgAreaRef.value.open();
  };

  // 提交
  const { loading, setLoading } = useLoading();
  const confirm = async () => {
    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return;

    setLoading(true);
    const datas = objAssign(formModel, {});
    datas.sheetConfig = selectedAreas.value;
    let res = true;
    await saveSubjectSetting(datas).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;
    ElMessage.success('保存成功！');
    emit('modified', datas);
    close();
  };

  /* init modal */
  async function modalBeforeOpen() {
    if (props.rowData) {
      try {
        // 获取科目设置信息
        const settingData = await getSubjectDetail(props.rowData.code);
        objModifyAssign(formModel, settingData);
      } catch (error) {
        // 如果获取失败，使用默认值
        objModifyAssign(formModel, {
          ...initialFormState,
          id: props.rowData.id,
          name: props.rowData.name,
          code: props.rowData.code,
        });
      }
    } else {
      objModifyAssign(formModel, initialFormState);
    }
  }
</script>
