<template>
  <div class="mark-manage">
    <div class="part-box part-box-filter">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <template v-if="checkPrivilege('condition', 'condition')">
          <secp-select
            v-model="filter"
            defaultSelectExam
            @exam-default="search"
          ></secp-select>
        </template>
        <el-form-item label="完成进度">
          <el-select
            v-model="filter.progressStatus"
            style="width: 120px"
            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-width="0px">
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @click="search"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="box-justify">
        <div></div>
        <div>
          <el-button
            v-if="checkPrivilege('button', 'MarkStudentImport')"
            type="primary"
            icon="el-icon-download"
            @click="toImportMarkData"
          >
            导入阅卷数据
          </el-button>
          <el-button
            v-if="checkPrivilege('button', 'Export')"
            type="primary"
            icon="el-icon-download"
            @click="toExport"
          >
            导出评卷员工作量
          </el-button>
          <el-button
            v-if="checkPrivilege('button', 'BatchFinish')"
            type="primary"
            icon="el-icon-document-checked"
            :disabled="!multipleSelection.length"
            @click="toBatchFinish"
          >
            结束评卷
          </el-button>
        </div>
      </div>
    </div>

    <div class="part-box part-box-pad">
      <el-table
        ref="TableList"
        :data="dataList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          fixed="left"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column prop="courseName" label="课程（代码）" min-width="260">
          <template slot-scope="scope">
            {{ scope.row.courseName }}（{{ scope.row.courseCode }}）
          </template>
        </el-table-column>
        <el-table-column
          prop="openCollege"
          label="开课学院"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="paperNumber"
          label="试卷编号"
          min-width="140"
        ></el-table-column>
        <el-table-column
          prop="paperType"
          label="卷型"
          width="80"
        ></el-table-column>
        <el-table-column prop="percent" label="阅卷进度" width="120">
          <span slot-scope="scope">{{ scope.row.percent || 0 }}%</span>
        </el-table-column>
        <el-table-column
          prop="totalCount"
          label="任务数"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="currentCount"
          label="正在评卷"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="problemCount"
          label="问题卷"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="statusDisplay"
          label="评卷状态"
          width="100"
        ></el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="160"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'Detail')"
              class="btn-primary"
              type="text"
              @click="toDetail(scope.row)"
              >查看详情</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'Finish')"
              class="btn-primary"
              type="text"
              @click="toSimpleFinish(scope.row)"
              >{{
                scope.row.status === "FORMAL" ? "结束评卷" : "开始评卷"
              }}</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 class="tips-markedness">
        <p>
          结束评卷后可以在归档管理模块——成绩查询菜单，查看成绩、成绩报告及导出成绩
          <el-button
            type="text"
            class="btn-primary btn-link ml-2"
            @click="toScoreManage"
            >点击跳转成绩查询</el-button
          >
        </p>
      </div>
    </div>
    <!-- MarkDetail -->
    <mark-detail ref="MarkDetail" :instance="curRow"></mark-detail>
    <!-- ImportFile -->
    <import-file
      v-if="checkPrivilege('button', 'MarkStudentImport')"
      ref="ImportFile"
      title="导入阅卷数据"
      :upload-url="uploadUrl"
      :upload-data="{
        semesterId: filter.semesterId,
        examId: filter.examId,
      }"
      :format="['xls', 'xlsx']"
      :download-handle="() => downloadTemplate('markStudent')"
      :download-filename="dfilename"
      :auto-upload="false"
      @upload-success="uploadSuccess"
    ></import-file>
  </div>
</template>

<script>
import {
  markManageListPage,
  markManageItemFinish,
  markManageListExport,
} from "../api";
import { downloadByApi } from "@/plugins/download";
import MarkDetail from "../components/markDetail/MarkDetail.vue";
import ImportFile from "@/components/ImportFile.vue";
import templateDownload from "@/mixins/templateDownload";

export default {
  name: "mark-manage",
  components: { MarkDetail, ImportFile },
  mixins: [templateDownload],
  data() {
    return {
      filter: {
        semesterId: "",
        examId: "",
        openCollegeId: "",
        courseId: "",
        paperNumber: "",
        progressStatus: null,
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      curRow: {},
      multipleSelection: [],
      downloading: false,
      // import
      uploadUrl: "/api/admin/mark/setting/mark_student_import",
      dfilename: "阅卷数据导入模板.xlsx",
    };
  },
  methods: {
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      if (datas.progressStatus !== null && datas.progressStatus !== "")
        datas.progressStatus = !!datas.progressStatus;

      const data = await markManageListPage(datas);
      this.dataList = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    search() {
      this.toPage(1);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    toScoreManage() {
      this.$router.push({ name: "ScoreManage" });
    },
    async toExport() {
      if (this.downloading) return;
      this.downloading = true;

      const res = await downloadByApi(() => {
        return markManageListExport({
          ...this.filter,
        });
      }).catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    toDetail(row) {
      this.curRow = row;
      this.$refs.MarkDetail.open();
    },
    async toBatchFinish() {
      if (!this.multipleSelection.length) return;

      const confirm = await this.$confirm("确定要结束选中的评卷？", "提示", {
        type: "warning",
      }).catch(() => {});
      if (confirm !== "confirm") return;

      this.toFinish(
        this.multipleSelection[0].examId,
        this.multipleSelection.map((item) => item.paperNumber),
        "FINISH"
      );
    },
    async toSimpleFinish(row) {
      const confirm = await this.$confirm(
        "确定要" + (row.status === "FORMAL" ? "结束" : "开始") + "当前评卷？",
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (confirm !== "confirm") return;

      this.toFinish(
        row.examId,
        [row.paperNumber],
        row.status === "FINISH" ? "FORMAL" : "FINISH"
      );
    },
    async toFinish(examId, paperNumbers, status) {
      if (!paperNumbers.length) return;

      await markManageItemFinish({
        examId,
        paperNumbers,
        status,
      });
      this.$message.success("操作成功！");
      this.getList();
    },
    toBatchModifySetting() {
      if (!this.multipleSelection.length) {
        this.$message.error("请选择数据");
        return;
      }
    },
    toImportMarkData() {
      this.$refs.ImportFile.open();
    },
    uploadSuccess() {
      this.$message.success("文件上传成功，后台正在导入！");
      this.getList();
    },
  },
};
</script>
