<template>
  <div>
    <el-dialog
      class="library-dialog page-dialog"
      :visible.sync="modalIsShow"
      title="数据处理"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      fullscreen
      @open="visibleChange"
      @closed="closed"
    >
      <div class="data-check-body">
        <div class="data-check-action part-box">
          <div class="data-check-action-form">
            <el-button size="mini" type="primary" @click="toSelectTaskStd"
              >所有任务考生信息</el-button
            >
            <el-button
              v-if="openCodeOcr"
              size="mini"
              type="success"
              @click="toSetOcrArea"
              >设置信息识别区</el-button
            >
            <div class="mt-2" v-if="openCodeOcr">
              <el-radio-group v-model="areaType">
                <el-radio v-if="openOcr" label="OCR">OCR识别</el-radio>
                <el-radio v-if="openBarCode" label="BAR_CODE"
                  >条码识别</el-radio
                >
              </el-radio-group>
            </div>

            <el-divider></el-divider>
            <div v-if="openGlobalMatch" class="box-justify mb-2">
              <h4>绑定学生</h4>
              <div>
                <span class="inline-middle mr-1">全局匹配</span>
                <el-switch
                  v-model="globalMatch"
                  @change="getStudentList"
                ></el-switch>
              </div>
            </div>
            <el-input
              v-model="studentNameOrNo"
              class="width-full"
              placeholder="请输入学号/姓名"
              clearable
              @input="nameOrNoInput"
            ></el-input>
          </div>
          <div class="data-check-action-student">
            <el-table ref="TableList" :data="studentList">
              <el-table-column
                prop="studentName"
                label="姓名"
                width="80"
              ></el-table-column>
              <el-table-column
                prop="studentCode"
                label="学号"
              ></el-table-column>
              <el-table-column label="操作" width="55">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    :disabled="loading"
                    @click="toBind(scope.row)"
                    >绑定</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div v-show="!isSetOcrSet" class="data-check-content part-box">
          <div v-if="curPagePapers.length" class="data-check-content-page">
            <el-button
              :type="curPagePaperIndex === 0 ? 'primary' : 'default'"
              :disabled="isSwitchFb"
              @click="switchCurPage(0)"
              >正面</el-button
            >
            <el-button
              :type="curPagePaperIndex === 1 ? 'primary' : 'default'"
              :disabled="isSwitchFb"
              @click="switchCurPage(1)"
              >反面</el-button
            >
            <el-button
              type="danger"
              :disabled="curPage.abnormal"
              @click="toAbnormalPaper"
              >标记异常</el-button
            >
          </div>
          <image-contain
            ref="ImageContain"
            :image="curPagePaper"
            :show-guide="false"
          ></image-contain>
        </div>
        <div v-if="isSetOcrSet" class="data-check-content part-box">
          <ocr-area-set
            :image-url="curPagePaper.url"
            :setting="ocrArea"
            @cancel="isSetOcrSet = false"
            @confirm="ocrAreaChange"
          ></ocr-area-set>
        </div>
      </div>
    </el-dialog>

    <!-- RelateStudentDialog -->
    <relate-student-dialog
      ref="RelateStudentDialog"
      :page-data="curPage"
      @confirm="toBind"
    ></relate-student-dialog>
    <!-- ocr-result -->
    <el-dialog
      class="page-dialog"
      :visible.sync="ocrResultDialogIsShow"
      title="OCR识别结果"
      top="10vh"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <div class="part-box part-box-pad mb-0">
        <el-table :data="ocrResult">
          <el-table-column prop="result" label="结果"></el-table-column>
          <el-table-column class-name="action-column" label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                class="btn-primary"
                type="text"
                @click="selectOcrResule(scope.row)"
              >
                <span class="cont-link">选择</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer"></div>
    </el-dialog>
  </div>
</template>

<script>
import timeMixin from "../../../mixins/timeMixin";
import {
  paperBindUser,
  studentUnbindTaskListPage,
  scanTaskStudentListPage,
  libraryOcrResult,
  abnormalPaper
} from "../api";
import { systemSettingQuery } from "../../base/api";
import ImageContain from "../../../components/ImageContain.vue";
import RelateStudentDialog from "./RelateStudentDialog.vue";
import OcrAreaSet from "./OcrAreaSet.vue";

const initModalForm = {
  paperLibraryId: "",
  paperScanTaskDetailId: ""
};

export default {
  name: "library-dialog",
  props: {
    mode: {
      type: String,
      default: "undo",
      validate: val => ["undo", "fix"].includes(val)
    },
    filterData: {
      tyep: Object,
      default() {
        return {};
      }
    },
    student: {
      type: Object,
      default() {
        return {
          curPagePaperIndex: 0,
          pageList: []
        };
      }
    }
  },
  components: { ImageContain, RelateStudentDialog, OcrAreaSet },
  mixins: [timeMixin],
  data() {
    return {
      modalIsShow: false,
      studentNameOrNo: "",
      modalForm: { ...initModalForm },
      inputSearchDelay: 300,
      studentList: [],
      courseList: [],
      loading: false,
      donePageList: [],
      undoPageList: [],
      curPage: null,
      curPagePapers: [],
      curPagePaperIndex: 0,
      curPagePaper: { url: "" },
      lastPaperScanTaskId: "",
      isSwitchFb: false,
      // ocr
      isSetOcrSet: false,
      openOcr: false,
      openBarCode: false,
      openGlobalMatch: false,
      globalMatch: false,
      areaType: "",
      ocrArea: { x: null, y: null, width: null, height: null, rotate: 0 },
      ocrResult: [],
      ocrResultDialogIsShow: false
    };
  },
  computed: {
    IS_UNDO_MODEL() {
      return this.mode === "undo";
    },
    openCodeOcr() {
      return this.openBarCode || this.openOcr;
    }
  },
  mounted() {
    this.ocrArea = this.$ls.get("ocrArea") || this.ocrArea;
    this.getSysSet();
  },
  methods: {
    async visibleChange() {
      this.modalForm = { ...initModalForm };
      this.studentNameOrNo = "";
      this.donePageList = [];
      this.undoPageList = [];
      this.curPage = null;
      this.curPagePapers = [];
      this.curPagePaper = { url: "" };
      this.lastPaperScanTaskId = "";

      if (this.IS_UNDO_MODEL) {
        this.curPagePaperIndex = 0;
        await this.getUndoPageList();
      } else {
        this.undoPageList = this.student.pageList;
        this.curPagePaperIndex = this.student.curPagePaperIndex;
      }

      if (!this.undoPageList.length) {
        this.$message.error("当前无任务需要处理！");
        return;
      }

      this.getNextPaper();
    },
    closed() {
      this.$emit("closed");
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async getSysSet() {
      const data = await systemSettingQuery();
      data.forEach(item => {
        item.data.forEach(field => {
          if (field.code === "openOcr") {
            this.openOcr = field.value === "true";
          }
          if (field.code === "openBarCode") {
            this.openBarCode = field.value === "true";
          }
          if (field.code === "openGlobalMatch") {
            this.openGlobalMatch = field.value === "true";
          }
        });
      });

      if (this.openOcr) {
        this.areaType = "OCR";
      } else if (this.openBarCode) {
        this.areaType = "BAR_CODE";
      }
    },
    nameOrNoInput() {
      this.clearSetTs();

      this.addSetTime(() => {
        this.getStudentList();
      }, this.inputSearchDelay);
    },
    async getStudentList() {
      if (!this.curPage || !this.curPage.paperScanTaskId) return;
      const datas = {
        paperScanTaskId: this.curPage.paperScanTaskId,
        param: this.studentNameOrNo,
        globalMatch: this.globalMatch,
        pageNumber: 1,
        pageSize: 30
      };
      const data = await scanTaskStudentListPage(datas);
      this.studentList = data.records;
    },
    toSelectTaskStd() {
      this.$refs.RelateStudentDialog.open();
    },
    async switchCurPage(curPagePaperIndex) {
      if (this.isSwitchFb) return;
      this.curPagePaperIndex = curPagePaperIndex;
      this.curPagePaper = {
        url: this.curPagePapers[this.curPagePaperIndex]
      };
      if (this.openCodeOcr) {
        this.isSwitchFb = true;
        await this.getOrcResult().catch(() => {});
        this.isSwitchFb = false;
      }
    },
    async toAbnormalPaper() {
      const res = await this.$confirm(`确定要标记当前试卷为异常吗?`, "提示", {
        type: "warning"
      }).catch(() => {});
      if (res !== "confirm") return;

      await abnormalPaper(this.curPage.id);
      this.$message.success("标记成功！");
      this.toNextPaper();
    },
    async getUndoPageList() {
      const data = await studentUnbindTaskListPage({ ...this.filterData });
      this.undoPageList.push(...data);
    },
    async toNextPaper() {
      if (!this.undoPageList.length && this.IS_UNDO_MODEL)
        await this.getUndoPageList();

      if (!this.undoPageList.length) {
        this.$message.warning("已全部处理完！");
        this.cancel();
        return;
      }

      // 已处理的最多记录10条
      if (this.curPage) this.donePageList.push({ ...this.curPage });
      if (this.donePageList.length > 10)
        this.donePageList = this.donePageList.slice(-10);

      this.curPagePaperIndex = 0;
      this.getNextPaper();
    },
    getNextPaper() {
      this.curPage = this.undoPageList.shift();
      this.curPagePapers = this.curPage.fileUrls;
      this.switchCurPage(this.curPagePaperIndex);

      if (
        !this.openCodeOcr &&
        this.lastPaperScanTaskId !== this.curPage.paperScanTaskId
      ) {
        this.getStudentList();
      }
    },
    toBind(row) {
      this.lastPaperScanTaskId = this.curPage.paperScanTaskId;
      this.modalForm.paperScanTaskDetailId = row.paperScanTaskDetailId;
      this.confirm();
    },
    async confirm() {
      if (this.loading) return;
      this.loading = true;
      let datas = { ...this.modalForm };
      datas.paperLibraryId = this.curPage.id;
      const res = await paperBindUser(datas).catch(() => {});
      this.loading = false;

      if (!res) return;

      this.$message.success("绑定成功！");
      if (this.IS_UNDO_MODEL) {
        this.toNextPaper();
      } else {
        this.cancel();
      }
    },
    // ocr
    toSetOcrArea() {
      if (!this.openOcr && !this.openBarCode) return;
      this.isSetOcrSet = true;
    },
    ocrAreaChange(ocrArea) {
      Object.keys(ocrArea).forEach(key => {
        ocrArea[key] = Math.floor(ocrArea[key]);
      });
      this.ocrArea = this.$objAssign(this.ocrArea, ocrArea);
      this.$ls.set("ocrArea", this.ocrArea);
      this.isSetOcrSet = false;
      this.getOrcResult();
    },
    async getOrcResult() {
      if (this.ocrArea.x === null) {
        this.$message.error("请设置信息识别区");
        if (
          !this.studentList.length ||
          this.lastPaperScanTaskId !== this.curPage.paperScanTaskId
        )
          this.getStudentList();
        return;
      }

      const res = await libraryOcrResult({
        paperLibraryId: this.curPage.id,
        index: this.curPagePaperIndex,
        type: this.areaType,
        ...this.ocrArea
      });
      if (res && res.length) {
        if (res.length === 1) {
          this.studentNameOrNo = res[0];
          this.getStudentList();
        } else {
          this.ocrResult = res.map(result => {
            return {
              result
            };
          });
          this.ocrResultDialogIsShow = true;
        }
      } else {
        this.getStudentList();
      }
    },
    selectOcrResule(cont) {
      this.studentNameOrNo = cont.result;
      this.getStudentList();
      this.ocrResultDialogIsShow = false;
    }
  }
};
</script>
