<template>
  <div class="student-manage">
    <div class="part-box part-box-filter">
      <el-form ref="FilterForm" label-position="left" label-width="90px" inline>
        <el-form-item label="学期：">
          <semester-select
            v-model="filter.semesterId"
            default-select
            placeholder="学期"
            @default-selected="getList"
          ></semester-select>
        </el-form-item>
        <el-form-item label="考试：">
          <exam-select
            v-model="filter.examId"
            :semester-id="filter.semesterId"
            placeholder="考试"
          ></exam-select>
        </el-form-item>
        <el-form-item label="课程：">
          <course-select
            v-model.trim="filter.courseCode"
            :semester-id="filter.semesterId"
            :exam-id="filter.examId"
            placeholder="课程"
            clearable
          ></course-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', 'delete')"
            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', 'import')"
            type="success"
            icon="el-icon-upload2"
            @click="toImport"
            >导入</el-button
          >
          <el-button
            v-if="checkPrivilege('button', 'import')"
            type="primary"
            icon="el-icon-s-order"
            @click="toDataTask"
            >导入结果查询</el-button
          >
          <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"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column prop="courseName" label="课程名称"></el-table-column>
        <el-table-column prop="courseCode" label="课程代码"></el-table-column>
        <el-table-column prop="examstudentName" label="姓名"></el-table-column>
        <el-table-column prop="studentCode" label="学号"></el-table-column>
        <el-table-column prop="college" label="学院"></el-table-column>
        <el-table-column prop="major" label="专业"></el-table-column>
        <el-table-column prop="teachClazz" label="教学班"></el-table-column>
        <el-table-column prop="paperNumber" label="试卷编号"></el-table-column>
        <el-table-column prop="teacherName" label="任课老师"></el-table-column>
        <el-table-column
          prop="teacherCode"
          label="任课老师工号"
          width="120"
        ></el-table-column>
        <el-table-column prop="examDate" label="考试日期"></el-table-column>
        <el-table-column prop="examTime" label="考试时间"></el-table-column>
        <el-table-column
          prop="examPlace"
          label="考点（校区）"
          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="100"
          fixed="right"
        >
          <template slot-scope="scope">
            <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>
    <!-- ImportFile -->
    <import-file
      v-if="checkPrivilege('button', 'import')"
      ref="ImportFile"
      title="导入考生"
      :upload-url="uploadUrl"
      :format="['xls', 'xlsx']"
      :download-handle="() => downloadTemplate('examStudent')"
      :download-filename="dfilename"
      :auto-upload="false"
      @upload-success="uploadSuccess"
    ></import-file>
    <!-- data-task-dialog -->
    <data-task-dialog
      v-if="checkPrivilege('button', 'import')"
      ref="DataTaskDialog"
      task-type="EXAM_STUDENT_IMPORT"
    ></data-task-dialog>
  </div>
</template>

<script>
import {
  examStudentListPage,
  deleteExamStudent,
  exportExamStudent,
} from "../api";
import ModifyExamStudent from "../components/ModifyExamStudent";
import ImportFile from "../../../components/ImportFile.vue";
import { downloadByApi } from "@/plugins/download";
import templateDownload from "@/mixins/templateDownload";

export default {
  name: "exam-student-manage",
  components: { ModifyExamStudent, ImportFile },
  mixins: [templateDownload],
  data() {
    return {
      filter: {
        semesterId: "",
        examId: "",
        courseCode: "",
        teacher: "",
        college: "",
        major: "",
        teachClazz: "",
        examStudentInfo: "",
      },
      queriedFilter: {},
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      multipleSelection: [],
      curRow: {},
      loading: false,
      // import
      uploadUrl: "/api/admin/basic/exam_student/import",
      dfilename: "考生导入模板.xlsx",
    };
  },
  computed: {
    filterHasQuery() {
      return !Object.keys(this.filter).some(
        (k) => this.filter[k] !== this.queriedFilter[k]
      );
    },
  },
  mounted() {
    // this.getList();
  },
  methods: {
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      const data = await examStudentListPage(datas);
      this.dataList = data.records;
      this.total = data.total;
      this.queriedFilter = { ...this.filter };
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id);
    },
    toAdd() {
      this.curRow = {};
      this.$refs.ModifyExamStudent.open();
    },
    toEdit(row) {
      this.curRow = row;
      this.$refs.ModifyExamStudent.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.filter);
      }, "").catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.loading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    // import
    toImport() {
      this.$refs.ImportFile.open();
    },
    toDataTask() {
      this.$refs.DataTaskDialog.open();
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess() {
      this.$message.success("文件上传成功，后台正在导入！");
      this.getList();
    },
  },
};
</script>
