<template>
  <el-dialog
    class="mark-detail"
    :visible.sync="modalIsShow"
    top="0"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
    fullscreen
    @open="initData"
  >
    <div slot="title">
      <h2 class="el-dialog__title">成绩详情</h2>
      <span
        >课程名称：{{ instance.courseName }}（{{ instance.courseCode }}）</span
      >
      <span>试卷编号：{{ instance.paperNumber }}</span>
      <button class="el-dialog__headerbtn" @click="cancel"></button>
    </div>

    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <el-form-item label="学院">
          <el-input v-model.trim="filter.college" placeholder="学院" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="专业">
          <el-input
            v-model.trim="filter.majorName"
            placeholder="专业"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="教学班">
          <el-input
            v-model.trim="filter.teachClassName"
            placeholder="教学班"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="行政班">
          <el-input
            v-model.trim="filter.className"
            placeholder="行政班"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="任课老师">
          <el-input
            v-model.trim="filter.teacher"
            placeholder="任课老师"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="复核条件">
          <el-select v-model="filter.filter" placeholder="复核条件">
            <el-option :value="0" label="无"></el-option>
            <el-option :value="1" label="客观题0分"></el-option>
            <el-option :value="2" label="客观题0分，主观题有分"></el-option>
            <el-option :value="3" label="主观题0分，客观题有分"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filter.status" placeholder="状态" clearable>
            <el-option value="ABSENT" label="缺考"></el-option>
            <el-option value="NORMAL" label="正常"></el-option>
            <el-option value="UNEXISTS" label="未扫描"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否违纪">
          <el-select v-model="filter.breach" placeholder="是否违纪" clearable>
            <el-option :value="1" label="违纪"></el-option>
            <el-option :value="0" label="正常"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试卷总分">
          <el-input-number
            v-model="filter.startScore"
            placeholder="试卷总分"
            :min="0"
            :max="9999"
            :step="0.01"
            step-strictly
            :controls="false"
            clearable
          >
          </el-input-number>
          <span class="mlr-1">-</span>
          <el-input-number
            v-model="filter.endScore"
            placeholder="试卷总分"
            :min="0"
            :max="9999"
            :step="0.01"
            step-strictly
            :controls="false"
            clearable
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="客观题总分">
          <el-input-number
            v-model="filter.objectiveStartScore"
            placeholder="客观题总分"
            :min="0"
            :max="9999"
            :step="0.01"
            step-strictly
            :controls="false"
            clearable
          >
          </el-input-number>
          <span class="mlr-1">-</span>
          <el-input-number
            v-model="filter.objectiveEndScore"
            placeholder="客观题总分"
            :min="0"
            :max="9999"
            :step="0.01"
            step-strictly
            :controls="false"
            clearable
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="主观题总分">
          <el-input-number
            v-model="filter.subjectiveStartScore"
            placeholder="主观题总分"
            :min="0"
            :max="9999"
            :step="0.01"
            step-strictly
            :controls="false"
            clearable
          >
          </el-input-number>
          <span class="mlr-1">-</span>
          <el-input-number
            v-model="filter.subjectiveEndScore"
            placeholder="主观题总分"
            :min="0"
            :max="9999"
            :step="0.01"
            step-strictly
            :controls="false"
            clearable
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="小题得分">
          <el-input-number
            v-model="filter.subScore"
            placeholder="小题得分"
            :min="0"
            :max="9999"
            :step="0.01"
            step-strictly
            :controls="false"
            clearable
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="客观分">
          <el-input-number
            v-model="filter.objectiveScoreRateLt"
            placeholder="客观分小于X%"
            :min="1"
            :max="100"
            :step="1"
            step-strictly
            :controls="false"
            clearable
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model.trim="filter.studentName"
            placeholder="姓名"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="学号">
          <el-input
            v-model.trim="filter.studentCode"
            placeholder="学号"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="密号">
          <el-input
            v-model.trim="filter.secretNumber"
            placeholder="密号"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label-width="0px">
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <el-button
          class="mr-2"
          type="primary"
          :loading="loading"
          @click="toCalcObjective"
          >客观题统分</el-button
        >
        <el-dropdown
          v-if="
            checkPrivilege('button', 'BatchInspectedSubjective') ||
            checkPrivilege('button', 'BatchObjectiveSubjective')
          "
          :disabled="!multipleSelection.length"
          @command="toBatchCheck"
        >
          <el-button type="primary" :disabled="!multipleSelection.length">
            批量复核<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-if="checkPrivilege('button', 'BatchInspectedSubjective')"
              command="subjective"
              >主观题复核</el-dropdown-item
            >
            <el-dropdown-item
              v-if="checkPrivilege('button', 'BatchObjectiveSubjective')"
              command="objective"
              >客观题复核</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
        <el-button
          v-if="checkPrivilege('button', 'ScoreExport')"
          class="ml-2"
          type="success"
          :loading="downloading"
          :disabled="!canExport"
          @click="toExportScore"
          >成绩导出</el-button
        >
      </div>
    </div>

    <div class="part-box part-box-pad">
      <el-table
        ref="TableList"
        :data="dataList"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column
          type="selection"
          fixed="left"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column prop="studentName" label="姓名" min-width="150">
        </el-table-column>
        <el-table-column
          prop="studentCode"
          label="学号"
          width="150"
          sortable
        ></el-table-column>
        <el-table-column
          prop="secretNumber"
          label="密号"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="studentStatusDisplay"
          label="状态"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="breachStatus"
          label="违纪状态"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="paperType"
          label="卷型"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="objectiveScore"
          label="客观分"
          width="85"
          sortable
        ></el-table-column>
        <el-table-column
          prop="subjectiveScore"
          label="主观分"
          width="85"
          sortable
        ></el-table-column>
        <el-table-column
          prop="totalScore"
          label="总分"
          width="80"
          sortable
        ></el-table-column>
        <el-table-column
          prop="subjectiveScoreList"
          label="主观题明细"
          min-width="300"
        ></el-table-column>
        <el-table-column
          prop="college"
          label="学院"
          min-width="200"
          sortable
        ></el-table-column>
        <el-table-column
          prop="majorName"
          label="专业"
          min-width="200"
          sortable
        ></el-table-column>
        <el-table-column
          prop="teachClassName"
          label="教学班"
          min-width="160"
          sortable
        ></el-table-column>
        <el-table-column
          prop="className"
          label="行政班"
          min-width="200"
          sortable
        ></el-table-column>
        <el-table-column prop="checkUserName" label="复核人" min-width="140">
          <span slot-scope="scope"
            >{{ scope.row.checkUserName | defaultFieldFilter }}（{{
              scope.row.checkUserLoginName | defaultFieldFilter
            }}）</span
          ></el-table-column
        >
        <el-table-column prop="checkTime" label="复核时间" width="170">
          <span slot-scope="scope">{{
            scope.row.checkTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="260"
          fixed="right"
        >
          <template v-if="checkActionValid(scope.row)" slot-scope="scope">
            <el-button
              class="btn-primary"
              type="text"
              @click="toViewSheetPaper(scope.row)"
              >原图</el-button
            >
            <el-button
              class="btn-primary"
              type="text"
              @click="toViewTrack(scope.row)"
              >轨迹图</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'InspectedSubjective')"
              class="btn-primary"
              type="text"
              :disabled="!scope.row.subjectiveCheckFlag"
              @click="toCheckQuestion(scope.row, 'subjective')"
              >主观题复核</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'ObjectiveSubjective')"
              class="btn-primary"
              type="text"
              :disabled="!scope.row.objectiveCheckFlag"
              @click="toCheckQuestion(scope.row, 'objective')"
              >客观题复核</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="5"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
          @size-change="pageSizeChange"
        >
        </el-pagination>
      </div>
    </div>

    <!-- image-preview -->
    <simple-image-preview
      :cur-image="curImage"
      @on-prev="toPrevImage"
      @on-next="toNextImage"
      ref="SimpleImagePreview"
    ></simple-image-preview>

    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import {
  scoreDetailListPage,
  objectiveScoreCalculate,
  scoreDetailListExport,
} from "../api";
import SimpleImagePreview from "@/components/SimpleImagePreview";
import markMinxin from "../markMinxin";
import { downloadByApi } from "@/plugins/download";

export default {
  name: "score-check-detail",
  components: { SimpleImagePreview },
  mixins: [markMinxin],
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      filter: {
        college: "",
        majorName: "",
        className: "",
        teacher: "",
        filter: 0,
        status: "",
        breach: "",
        startScore: undefined,
        endScore: undefined,
        objectiveStartScore: undefined,
        objectiveEndScore: undefined,
        subjectiveStartScore: undefined,
        subjectiveEndScore: undefined,
        subScore: undefined,
        objectiveScoreRateLt: undefined,
        studentName: "",
        studentCode: "",
        secretNumber: "",
        orderType: undefined,
        orderField: undefined,
      },
      searchfilter: {},
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      loading: false,
      multipleSelection: [],
      downloading: false,
      // img view
      curImage: {},
      curImageIndex: 0,
      imageList: [],
    };
  },
  computed: {
    canExport() {
      return (
        JSON.stringify(this.filter) === JSON.stringify(this.searchfilter) &&
        this.total > 0
      );
    },
  },
  methods: {
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    initData() {
      this.search();
    },
    async getList() {
      const datas = {
        ...this.filter,
        examId: this.instance.examId,
        paperNumber: this.instance.paperNumber,
        pageNumber: this.current,
        pageSize: this.size,
      };
      if (datas.absent !== null && datas.absent !== "")
        datas.absent = !!datas.absent;
      if (datas.breach !== null && datas.breach !== "")
        datas.breach = !!datas.breach;

      const data = await scoreDetailListPage(datas);
      this.dataList = data.records;
      this.total = data.total;
      this.searchfilter = { ...this.filter };
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    search() {
      this.toPage(1);
    },
    checkActionValid(row) {
      return !["UNEXIST", "MANUAL_ABSENT"].includes(row.scanStatus);
    },
    collegeChange(val) {
      this.filter.college = val?.name;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    sortChange({ prop, order }) {
      if (!order) {
        this.filter.orderField = undefined;
        this.filter.orderType = undefined;
      } else {
        this.filter.orderField = prop;
        this.filter.orderType = order === "ascending" ? "ASC" : "DESC";
      }
      this.getList();
    },
    toBatchCheck(type) {
      if (!this.multipleSelection.length) return;
      if (type === "objective") {
        const studentIds = this.multipleSelection
          .filter((item) => item.objectiveCheckFlag)
          .map((item) => item.studentId);
        if (!studentIds.length) {
          this.$message.error("没有可复核数据！");
          return;
        }

        this.toMarkObjectiveAnswer(studentIds);
      } else {
        const studentIds = this.multipleSelection
          .filter((item) => item.subjectiveCheckFlag)
          .map((item) => item.studentId);
        if (!studentIds.length) {
          this.$message.error("没有可复核数据！");
          return;
        }
        this.toMarkSubjectiveAnswer({
          examId: this.instance.examId,
          paperNumber: this.instance.paperNumber,
          studentIds: studentIds,
        });
      }
    },
    toCheckQuestion(row, type) {
      if (type === "objective") {
        this.toMarkObjectiveAnswer([row.studentId]);
      } else {
        this.toMarkSubjectiveAnswer({
          examId: row.examId,
          paperNumber: row.paperNumber,
          studentIds: [row.studentId],
        });
      }
    },
    async toCalcObjective() {
      if (this.loading) return;

      this.loading = true;
      const res = await objectiveScoreCalculate({
        examId: this.instance.examId,
        paperNumber: this.instance.paperNumber,
      }).catch(() => {});
      this.loading = false;

      if (!res) return;
      this.$message.success("操作成功！");
      this.getList();
    },
    async toExportScore() {
      if (this.downloading) return;
      this.downloading = true;

      const res = await downloadByApi(() => {
        return scoreDetailListExport({
          ...this.searchfilter,
          examId: this.instance.examId,
          paperNumber: this.instance.paperNumber,
        });
      }).catch((e) => {
        this.$message.error(e || "导出失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("导出成功！");
    },
    // img view
    async toViewTrack(row) {
      this.toMarkTrack(row.studentId);
    },
    toViewSheetPaper(row) {
      this.curImageIndex = 0;
      this.imageList = row.sheetUrls || [];
      this.selectImage(this.curImageIndex);
      this.$refs.SimpleImagePreview.open();
    },
    selectImage(index) {
      this.curImage = this.imageList[index];
    },
    toPrevImage() {
      if (this.curImageIndex === 0) {
        this.curImageIndex = this.imageList.length - 1;
      } else {
        this.curImageIndex--;
      }

      this.selectImage(this.curImageIndex);
    },
    toNextImage() {
      if (this.curImageIndex === this.imageList.length - 1) {
        this.curImageIndex = 0;
      } else {
        this.curImageIndex++;
      }

      this.selectImage(this.curImageIndex);
    },
  },
};
</script>
