<template>
  <div class="student-manage">
    <div class="part-box part-box-filter">
      <el-form ref="FilterForm" label-position="left" label-width="90px" inline>
        <secp-select
          v-model="filterSe"
          defaultSelectExam
          @exam-default="search"
          @exam-change="examChange"
        ></secp-select>
        <el-form-item label="任课老师：">
          <el-input
            v-model.trim="filter.teacher"
            placeholder="任课老师"
            clearable
          ></el-input>
        </el-form-item>
        <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.major"
            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.examStudentInfo"
            placeholder="姓名/学号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @click="search"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="box-justify">
        <div>
          <el-button
            v-if="checkPrivilege('button', 'DeleteBatch')"
            type="danger"
            icon="el-icon-delete"
            @click="toBatchDelete"
            >批量删除</el-button
          >
          <el-button
            v-if="checkPrivilege('button', 'export')"
            type="primary"
            icon="el-icon-download"
            :loading="loading"
            @click="toExportStudent"
            >导出</el-button
          >
          <el-button
            v-if="checkPrivilege('button', 'export')"
            type="primary"
            icon="el-icon-s-order"
            @click="handleTaskType('BASIC_EXAM_STUDENT_EXPORT')"
            >导出结果查询</el-button
          >
        </div>
        <div>
          <el-button
            v-if="checkPrivilege('button', 'ImportTeacher')"
            type="success"
            icon="el-icon-upload2"
            @click="toImportTeacher"
            >导入任课老师</el-button
          >
          <el-button
            v-if="checkPrivilege('button', 'import')"
            type="success"
            icon="el-icon-upload2"
            @click="toImport"
            >导入</el-button
          >
          <template
            v-if="
              checkPrivilege('button', 'import') ||
              checkPrivilege('button', 'ImportTeacher')
            "
          >
            <el-button
              v-if="taskTypes.length === 1"
              type="primary"
              icon="el-icon-s-order"
              @click="toDataTask"
            >
              导入结果查询
            </el-button>
            <el-dropdown v-if="taskTypes.length > 1" @command="handleTaskType">
              <el-button
                type="primary"
                icon="el-icon-s-order"
                style="margin: 0 10px"
              >
                导入结果查询 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="BASIC_EXAM_STUDENT_IMPORT"
                  >考生导入</el-dropdown-item
                >
                <el-dropdown-item command="BASIC_EXAM_STUDENT_TEACHER_IMPORT"
                  >任课老师导入</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>

          <el-button
            v-if="checkPrivilege('button', 'add')"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="toAdd"
            >新增</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="studentName"
          label="姓名"
          min-width="200"
        ></el-table-column>
        <el-table-column
          prop="studentCode"
          label="学号"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="courseName"
          label="课程名称"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="courseCode"
          label="课程代码"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="teachingRoomName"
          label="开课学院"
          min-width="180"
        ></el-table-column>
        <el-table-column
          prop="paperNumber"
          label="试卷编号"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="paperType"
          label="卷型"
          width="80"
        ></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            {{ scope.row.status | studentStatusFilter }}
          </template>
        </el-table-column>
        <el-table-column
          prop="breachStatus"
          label="违纪状态"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="teacherName"
          label="任课老师"
          min-width="100"
        ></el-table-column>
        <el-table-column
          prop="teacherCode"
          label="任课老师工号"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="collegeName"
          label="学院"
          min-width="180"
        ></el-table-column>
        <el-table-column
          prop="majorName"
          label="专业"
          min-width="180"
        ></el-table-column>
        <el-table-column
          prop="teachClassName"
          label="教学班"
          min-width="180"
        ></el-table-column>
        <el-table-column
          prop="className"
          label="行政班"
          min-width="180"
        ></el-table-column>
        <el-table-column
          prop="examDate"
          label="考试日期"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="examTime"
          label="考试时间"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="examPlace"
          label="校区（考点）"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="examRoom"
          label="考试教室（考场）"
          width="160"
        ></el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="140"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'edit')"
              class="btn-primary"
              type="text"
              @click="toSet(scope.row)"
              >设置</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'edit')"
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'delete')"
              class="btn-danger"
              type="text"
              @click="toDelete(scope.row)"
              >删除</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>

    <modify-exam-student
      :instance="curRow"
      :exam-data="curExam"
      @modified="getList"
      ref="ModifyExamStudent"
    ></modify-exam-student>
    <!-- ModifyExamStudentStatus -->
    <modify-exam-student-status
      ref="ModifyExamStudentStatus"
      :instance="curRow"
      @modified="getList"
    ></modify-exam-student-status>
    <!-- ImportFile -->
    <import-file
      v-if="checkPrivilege('button', 'import')"
      ref="ImportFile"
      title="导入考生"
      :upload-url="uploadUrl"
      :upload-data="{
        examId: filterSe.examId,
        semesterId: filterSe.semesterId,
      }"
      :format="['xls', 'xlsx']"
      :download-handle="() => downloadHandle(dfilename)"
      :download-filename="dfilename"
      :auto-upload="false"
      @upload-success="uploadSuccess"
    ></import-file>
    <!-- ImportFileTeacher -->
    <import-file
      v-if="checkPrivilege('button', 'ImportTeacher')"
      ref="ImportFileTeacher"
      title="导入任课老师"
      :upload-url="uploadTeacherUrl"
      :upload-data="{
        examId: filterSe.examId,
        semesterId: filterSe.semesterId,
      }"
      :format="['xls', 'xlsx']"
      :download-handle="() => downloadHandle(teacherDfilename)"
      :download-filename="teacherDfilename"
      :auto-upload="false"
      @upload-success="uploadSuccess"
    ></import-file>
    <!-- data-task-dialog -->
    <data-task-dialog
      v-if="
        checkPrivilege('button', 'import') ||
        checkPrivilege('button', 'ImportTeacher')
      "
      ref="DataTaskDialog"
      :task-type="curTaskType"
    ></data-task-dialog>
  </div>
</template>

<script>
import {
  examStudentListPage,
  deleteExamStudent,
  exportExamStudent,
  getExamStudentStatus,
} from "../api";
import { businessTemplateDownload } from "@/modules/print/api";
import ModifyExamStudent from "../components/ModifyExamStudent.vue";
import ModifyExamStudentStatus from "../components/ModifyExamStudentStatus.vue";
import ImportFile from "../../../components/ImportFile.vue";
import { downloadByApi } from "@/plugins/download";
import templateDownload from "@/mixins/templateDownload";
import { getExamDateTime } from "@/plugins/utils";

export default {
  name: "exam-student-manage",
  components: { ModifyExamStudent, ModifyExamStudentStatus, ImportFile },
  mixins: [templateDownload],
  data() {
    return {
      filterSe: {
        semesterId: "",
        examId: "",
        openCollegeId: "",
        courseId: "",
        paperNumber: "",
      },
      filter: {
        teacher: "",
        college: "",
        major: "",
        teachClassName: "",
        className: "",
        examStudentInfo: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      multipleSelection: [],
      curRow: {},
      loading: false,
      download: false,
      importTaskType: "BASIC_EXAM_STUDENT_IMPORT",
      curTaskType: "BASIC_EXAM_STUDENT_IMPORT",
      taskTypes: [],
      curExam: {},
      selectExam: {},
      // import
      uploadUrl: "/api/admin/basic/exam_student/import",
      dfilename: "考生导入模板.xlsx",
      // import teacher
      uploadTeacherUrl: "/api/admin/basic/exam_student/import_teacher",
      teacherDfilename: "任课老师导入模板.xlsx",
    };
  },
  mounted() {
    const taskTypes = [];
    if (this.checkPrivilege("button", "import")) {
      taskTypes.push("BASIC_EXAM_STUDENT_IMPORT");
    }
    if (this.checkPrivilege("button", "ImportTeacher")) {
      taskTypes.push("BASIC_EXAM_STUDENT_TEACHER_IMPORT");
    }
    if (taskTypes.length === 1) this.importTaskType = taskTypes[0];
    this.taskTypes = taskTypes;
  },
  methods: {
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      const datas = {
        ...this.filterSe,
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      const data = await examStudentListPage(datas);
      this.dataList = data.records.map((item) => {
        const { examDate, examTime } = getExamDateTime(
          item.examStartTime,
          item.examEndTime
        );
        item.examDate = examDate;
        item.examTime = examTime;
        return item;
      });
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    search() {
      this.toPage(1);
      this.curExam = { ...this.selectExam };
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id);
    },
    examChange(val) {
      this.selectExam = val;
    },
    async downloadHandle(filename) {
      if (this.download) return;

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

      if (!res) return;
      this.$message.success("下载成功！");
    },
    toAdd() {
      this.curRow = {};
      this.$refs.ModifyExamStudent.open();
    },
    toEdit(row) {
      this.curRow = row;
      this.$refs.ModifyExamStudent.open();
    },
    toSet(row) {
      this.curRow = row;
      this.$refs.ModifyExamStudentStatus.open();
    },
    async toBatchDelete() {
      if (!this.multipleSelection.length) {
        this.$message.error("请选择要删除的考生");
        return;
      }

      const students = await getExamStudentStatus(this.multipleSelection);
      const errorStudents = students.filter(
        (student) => student.scanStatus && student.markTaskStatus
      );
      if (errorStudents.length) {
        const names = errorStudents.map((item) => item.studentName).join();
        this.$message.error(`考生【${names}】已经生成阅卷任务，禁止删除！`);
        return;
      }

      const warningStudents = students.filter((student) => student.scanStatus);
      let pretips = "";
      if (warningStudents.length) {
        const names = warningStudents.map((item) => item.studentName).join();
        pretips = `考生【${names}】已扫描图片，确定要删除当前选择的所有考生吗？`;
      } else {
        pretips = `确定要删除当前选择的所有考生吗?`;
      }

      const confirm = await this.$confirm(pretips, "提示", {
        type: "warning",
      }).catch(() => {});

      if (confirm !== "confirm") return;

      await deleteExamStudent(this.multipleSelection);
      this.$message.success("删除成功！");
      this.deletePageLastItem();
    },
    async toDelete(row) {
      // "scanStatus": true, //是否扫描
      // "markTaskStatus": true // 是否生成阅卷任务
      const students = await getExamStudentStatus([row.id]);
      const student = students[0];

      if (student && student.scanStatus && student.markTaskStatus) {
        this.$message.error(
          `考生【${row.studentName}】已经生成阅卷任务，禁止删除！`
        );
        return;
      }

      let pretips = "";
      if (student && student.scanStatus) {
        pretips = `考生【${row.studentName}】已扫描图片，确定要删除吗？`;
      } else {
        pretips = `确定要删除考生【${row.studentName}】吗?`;
      }

      const confirm = await this.$confirm(pretips, "提示", {
        type: "warning",
      }).catch(() => {});

      if (confirm !== "confirm") return;

      await deleteExamStudent([row.id]);
      this.$message.success("删除成功！");
      this.deletePageLastItem();
    },
    async toExportStudent() {
      if (this.loading) return;

      this.loading = true;
      const res = await exportExamStudent({
        ...this.filterSe,
        ...this.filter,
      }).catch(() => {});
      this.loading = false;

      if (!res) return;
      this.$message.success(
        "操作成功，请在右侧导入导出结果查询中查看导出结果！"
      );
    },
    // import
    toImport() {
      this.$refs.ImportFile.open();
    },
    toImportTeacher() {
      this.$refs.ImportFileTeacher.open();
    },
    toDataTask() {
      this.curTaskType = this.importTaskType;
      this.$refs.DataTaskDialog.open();
    },
    handleTaskType(val) {
      this.curTaskType = val;
      this.$refs.DataTaskDialog.open();
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess() {
      this.$message.success("文件上传成功，后台正在导入！");
      this.getList();
    },
  },
};
</script>
