<template>
  <div>
    <el-dialog
      class="modify-mark-setting"
      :visible.sync="modalIsShow"
      :title="title"
      top="10px"
      width="660px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      destroy-on-close
      @open="visibleChange"
    >
      <el-form
        ref="modalFormComp"
        :model="modalForm"
        :rules="rules"
        :key="modalForm.paperNumber"
        label-width="120px"
      >
        <el-form-item prop="markMode" label="评卷模式：">
          <el-select v-model="modalForm.markMode">
            <el-option
              v-for="(val, key) in MARK_MODE_TYPE"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评卷时间：">
          <el-date-picker
            v-model="markTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="评卷开始日期"
            end-placeholder="评卷结束日期"
            value-format="timestamp"
            align="right"
            unlink-panels
            @change="dateChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="passScore" label="及格分：">
          <el-input-number
            style="width: 125px"
            v-model="modalForm.passScore"
            :min="1"
            :max="100"
            :step="1"
            step-strictly
            :controls="false"
          ></el-input-number>
          <span class="ml-1">%</span>
        </el-form-item>
        <el-form-item prop="excellentScore" label="优秀分：">
          <el-input-number
            style="width: 125px"
            v-model="modalForm.excellentScore"
            :min="1"
            :max="100"
            :step="1"
            step-strictly
            :controls="false"
          ></el-input-number>
          <span class="ml-1">%</span>
        </el-form-item>
        <el-form-item v-if="!isMultiple" prop="sheetConfig" label="原图遮盖：">
          <el-button class="btn-primary" type="text" @click="toSetSheetConfig"
            >设置</el-button
          >
          <i
            v-if="modalForm.sheetConfig?.length"
            class="el-icon-success color-success ml-1"
          ></i>
        </el-form-item>
        <el-form-item class="form-item-info">
          <el-checkbox v-model="modalForm.showObjectScore"
            >评卷显示客观分</el-checkbox
          >
        </el-form-item>
        <el-form-item class="form-item-info">
          <el-checkbox v-model="modalForm.autoScroll"
            >评卷提交自动定位</el-checkbox
          >
        </el-form-item>
        <el-form-item class="form-item-info">
          <el-checkbox v-model="modalForm.doubleMark">是否开启双评</el-checkbox>
        </el-form-item>
        <el-form-item class="form-item-info">
          <el-checkbox v-model="modalForm.mergeMarker"
            >填空题作为一个整体设置评卷员及评卷方式</el-checkbox
          >
        </el-form-item>
        <el-form-item prop="aiMarkType" class="form-item-info">
          <el-checkbox
            v-model="modalForm.enableAIMark"
            @change="enableAIMarkChange"
            >启用AI智能评卷</el-checkbox
          >
          <el-radio-group
            v-if="modalForm.enableAIMark"
            v-model="modalForm.aiMarkType"
            class="ml-2"
          >
            <el-radio label="AI_ONLY">仅AI评卷</el-radio>
            <el-radio label="AI_HUMAN">人机双评</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item class="form-item-info">
          <el-checkbox v-model="modalForm.allowCloseBeforeFinish"
            >允许不评卷结束评卷</el-checkbox
          >
        </el-form-item> -->
      </el-form>
      <div slot="footer">
        <el-button type="primary" :disabled="isSubmit" @click="submit"
          >确认</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- ModifyPaperArea -->
    <modify-paper-area
      ref="ModifyPaperArea"
      :areaConfigs="modalForm.sheetConfig"
      :paperList="paperList"
      @modified="areaModified"
    ></modify-paper-area>
  </div>
</template>

<script>
import {
  markSettingSave,
  markSettingBatchSave,
  markSettingDetail,
  examStructureFindJpg,
} from "../api";
import { cardDetail } from "../../card/api";

import { MARK_MODE_TYPE } from "@/constants/enumerate";
import ModifyPaperArea from "./ModifyPaperArea.vue";

const initModalForm = {
  examId: null,
  paperNumber: "",
  markMode: "",
  markStartTime: "",
  markEndTime: "",
  showObjectScore: false,
  doubleMark: false,
  autoScroll: false,
  mergeMarker: true,
  enableAIMark: false,
  aiMarkType: "",
  // allowCloseBeforeFinish: false,
  passScore: 60,
  excellentScore: 80,
  sheetConfig: [],
};

export default {
  name: "modify-mark-setting",
  components: { ModifyPaperArea },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
    multipleInst: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      MARK_MODE_TYPE,
      modalForm: { ...initModalForm },
      paperList: [],
      rules: {
        markMode: [
          {
            required: true,
            message: "请选择评卷模式",
            trigger: "change",
          },
        ],
        markStartTime: [
          {
            required: true,
            message: "请设置评卷时间",
            trigger: "change",
          },
        ],
        passScore: [
          {
            required: true,
            message: "请设置及格分",
            trigger: "change",
          },
        ],
        excellentScore: [
          {
            required: true,
            message: "请设置优秀分",
            trigger: "change",
          },
        ],
        aiMarkType: [
          {
            required: true,
            message: "请选择AI评卷方式",
            trigger: "change",
            validator: (rule, value, callback) => {
              if (this.modalForm.enableAIMark && !value) {
                callback(new Error("请选择AI评卷方式"));
              } else {
                callback();
              }
            },
          },
        ],
      },
      // date-picker
      markTime: [],
    };
  },
  computed: {
    isMultiple() {
      return !!this.multipleInst.length;
    },
    title() {
      return this.isMultiple ? "评卷批量设置" : "评卷设置";
    },
  },
  methods: {
    async getPaperList() {
      this.paperList = [];
      const data = await examStructureFindJpg({
        examId: this.instance.examId,
        courseId: this.instance.courseId,
        paperNumber: this.instance.paperNumber,
        serialNumber: this.instance.serialNumber,
      });
      const papers = data || [];
      papers.sort((a, b) => a.index - b.index);
      this.paperList = papers.map((paper) => {
        return {
          imgUrl: paper.path,
          areas: [],
        };
      });
    },
    async initData(val) {
      if (this.isMultiple) {
        this.modalForm = { ...initModalForm };
        this.markTime = [undefined, undefined];
        return;
      }
      await this.getPaperList();
      const res = await markSettingDetail({
        examId: this.instance.examId,
        paperNumber: this.instance.paperNumber,
      });
      this.modalForm = this.$objAssign(initModalForm, res || {});
      this.markTime = [
        this.modalForm.markStartTime || undefined,
        this.modalForm.markEndTime || undefined,
      ];
      if (res.sheetConfig) {
        this.modalForm.sheetConfig = JSON.parse(res.sheetConfig);
      } else {
        this.modalForm.sheetConfig = await this.getDefaultSheetConfig();
      }

      this.modalForm.passScore = this.modalForm.passScore || 60;
      this.modalForm.excellentScore = this.modalForm.excellentScore || 80;
    },
    async getDefaultSheetConfig() {
      const detData = await cardDetail(this.instance.cardId);
      const cardContent = detData?.content
        ? JSON.parse(detData.content)
        : { pages: [] };
      const areas = [];
      cardContent.pages.forEach((item, index) => {
        if (item.exchange.info_area && item.exchange.info_area.length) {
          item.exchange.info_area.forEach((area) => {
            const [x, y, w, h] = area;
            areas.push({
              i: index + 1,
              x,
              y,
              w,
              h,
            });
          });
        }
      });
      return areas;
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    dateChange() {
      if (this.markTime) {
        this.modalForm.markStartTime = this.markTime[0];
        this.modalForm.markEndTime = this.markTime[1];
      } else {
        this.modalForm.markStartTime = "";
        this.modalForm.markEndTime = "";
      }
    },
    enableAIMarkChange() {
      if (this.modalForm.enableAIMark) {
        this.modalForm.aiMarkType = "AI_HUMAN";
      } else {
        this.modalForm.aiMarkType = "";
      }
    },
    areaModified(areas) {
      this.modalForm.sheetConfig = areas;
    },
    toSetSheetConfig() {
      this.$refs.ModifyPaperArea.open();
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;

      let res = null;
      if (this.isMultiple) {
        const datas = {
          list: this.multipleInst.map((item) => {
            return {
              examId: item.examId,
              paperNumber: item.paperNumber,
            };
          }),
          config: { ...this.modalForm },
        };
        res = await markSettingBatchSave(datas).catch(() => {});
      } else {
        const data = { ...this.modalForm };
        data.sheetConfig = JSON.stringify(data.sheetConfig);
        res = await markSettingSave(data).catch(() => {});
      }

      this.isSubmit = false;
      if (!res) return;

      this.$message.success("修改成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
