<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"
        ></secp-select>
        <el-form-item label="课程（代码）：">
          <course-common-select
            v-model="filter.courseId"
            placeholder="课程（代码）"
            clearable
          ></course-common-select>
        </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-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.teachClazz"
            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="toPage(1)"
            >查询</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
          >
        </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="100"
        ></el-table-column>
        <el-table-column
          prop="studentCode"
          label="学号"
          width="140"
        ></el-table-column>
        <el-table-column
          prop="courseName"
          label="课程名称"
          min-width="300"
        ></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="120"
        ></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="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="考点（校区）"
          min-width="120"
        ></el-table-column>
        <el-table-column
          prop="examRoom"
          label="考场（考试教室）"
          width="140"
        ></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"
      @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,
} 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: "",
      },
      filter: {
        courseId: "",
        teacher: "",
        college: "",
        major: "",
        teachClazz: "",
        examStudentInfo: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      multipleSelection: [],
      curRow: {},
      loading: false,
      download: false,
      curTaskType: "BASIC_EXAM_STUDENT_IMPORT",
      taskTypes: [],
      // 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.curTaskType = 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);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id);
    },
    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 confirm = await this.$confirm(
        `确定要删除当前选择的所有考生吗?`,
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});

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

      await deleteExamStudent(this.multipleSelection);
      this.$message.success("删除成功！");
      this.deletePageLastItem();
    },
    toDelete(row) {
      this.$confirm(`确定要删除考生【${row.studentName}】吗?`, "提示", {
        type: "warning",
      })
        .then(async () => {
          await deleteExamStudent([row.id]);
          this.$message.success("删除成功！");
          this.deletePageLastItem();
        })
        .catch(() => {});
    },
    async toExportStudent() {
      if (this.loading) return;

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

      if (!res) return;
      this.$message.success("下载成功！");
    },
    // import
    toImport() {
      this.$refs.ImportFile.open();
    },
    toImportTeacher() {
      this.$refs.ImportFileTeacher.open();
    },
    toDataTask() {
      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>
