<template>
  <div class="students ">
    <div class="part-box-top">
      <Button
        type="primary"
        icon="md-cloud-upload"
        @click="$refs.ExportStudent.open()"
        >导入考生信息</Button
      >
      <Button
        type="primary"
        icon="md-cloud-upload"
        @click="$refs.ExportRelate.open()"
        >导入关联信息</Button
      >
    </div>
    <div class="part-box">
      <Form ref="FilterForm" label-position="left" inline>
        <FormItem label="考区">
          <Select v-model="filter.areaCode" placeholder="请选择考区">
            <Option value=""></Option>
          </Select>
        </FormItem>
        <FormItem label="学校">
          <Select v-model="filter.schoolId" placeholder="请选择学校">
            <Option value=""></Option>
          </Select>
        </FormItem>
        <FormItem label="考场">
          <Select v-model="filter.examRoom" placeholder="请选择考场">
            <Option value=""></Option>
          </Select>
        </FormItem>
        <FormItem label="科目">
          <Select v-model="filter.subject" placeholder="请选择科目">
            <Option
              v-for="(subject, index) in subjects"
              :key="index"
              :value="subject.subject"
              >{{ subject.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="起始考号">
          <InputNumber
            v-model="filter.startNumber"
            placeholder="请输入数字"
            clearable
          ></InputNumber>
        </FormItem>
        <FormItem label="终止考号">
          <InputNumber
            v-model="filter.endNumber"
            placeholder="请输入数字"
            clearable
          ></InputNumber>
        </FormItem>
        <FormItem label="姓名">
          <Input
            v-model.trim="filter.name"
            placeholder="工作名称"
            clearable
          ></Input>
        </FormItem>
        <FormItem label="是否缺考">
          <Select v-model="filter.isAbsent" placeholder="请选择是否缺考">
            <Option
              v-for="(val, key) in BOOLEAN_TYPE"
              :key="key"
              :value="key * 1"
              >{{ val }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="状态">
          <Select v-model="filter.upload" placeholder="请选择状态">
            <Option
              v-for="(val, key) in PAPER_UPLOAD_TYPE"
              :key="key"
              :value="key * 1"
              >{{ val }}</Option
            >
          </Select>
        </FormItem>
        <FormItem>
          <Button type="primary" icon="ios-search" @click="toPage(1)"
            >查询</Button
          >
        </FormItem>
      </Form>

      <Table
        ref="TableList"
        :columns="columns"
        :data="students"
        disabled-hover
        border
      ></Table>

      <div class="part-page">
        <Page
          :current="current"
          :total="total"
          :page-size="size"
          show-total
          show-elevator
          @on-change="toPage"
        ></Page>
      </div>
    </div>

    <!-- import student  -->
    <import-file
      title="导入考生信息"
      :upload-url="uploadStudentUrl"
      :upload-data="uploadData"
      :download-url="downloadStudentTemplateUrl"
      :download-filename="downloadStudentTemplateFilename"
      :headers="headers"
      :format="['xls', 'xlsx']"
      :upload-success-handle="uploadStudentSuccess"
      ref="ExportStudent"
    >
    </import-file>
    <!-- import-relate -->
    <import-file
      title="导入关联信息"
      :upload-url="uploadRelateUrl"
      :upload-data="uploadData"
      :download-url="downloadRelateTemplateUrl"
      :download-filename="downloadRelateTemplateFilename"
      :headers="headers"
      :format="['xls', 'xlsx']"
      :upload-success-handle="uploadStudentSuccess"
      ref="ExportRelate"
    >
    </import-file>
    <!-- modify-student -->
    <modify-student
      :instance="curStudent"
      @modified="getList"
      ref="ModifyStudent"
    ></modify-student>
  </div>
</template>

<script>
import { subjectList, studentPageList, deleteStudent } from "@/api";
import ImportFile from "@/components/common/ImportFile";
import ModifyStudent from "./components/ModifyStudent";
import { BOOLEAN_TYPE, PAPER_UPLOAD_TYPE } from "@/constants/enumerate";

export default {
  name: "students",
  components: { ImportFile, ModifyStudent },
  data() {
    return {
      filter: {
        workId: this.$route.params.workId,
        name: "",
        schoolId: "",
        examRoom: "",
        startNumber: null,
        endNumber: null,
        subject: null,
        areaCode: null,
        upload: null,
        isAbsent: 0
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      students: [],
      curStudent: {},
      subjects: [],
      BOOLEAN_TYPE,
      PAPER_UPLOAD_TYPE,
      columns: [
        {
          type: "index",
          title: "序号",
          width: 80,
          align: "center",
          indexMethod: row => {
            return (this.current - 1) * this.size + row._index + 1;
          }
        },
        {
          title: "姓名",
          key: "name",
          width: 80
        },
        {
          title: "考号",
          key: "examNumber",
          minWidth: 120
        },
        {
          title: "考区",
          key: "areaName",
          minWidth: 120
        },
        {
          title: "学校",
          key: "sourceName",
          minWidth: 150
        },
        {
          title: "考场",
          key: "examRoom",
          minWidth: 100
        },
        {
          title: "操作",
          key: "action",
          width: 160,
          align: "center",
          render: (h, param) => {
            let actions = [];

            if (param.row.canEdit) {
              actions.push({
                name: "编辑",
                action: () => {
                  this.toEdit(param.row);
                }
              });
            }
            if (param.row.canDelete) {
              actions.push({
                name: "删除",
                type: "error",
                action: () => {
                  this.toDelete(param.row);
                }
              });
            }

            return h("div", this.$tableAction(h, actions));
          }
        }
      ],
      // upload
      headers: {
        Authorization: "token"
      },
      uploadData: {
        workId: this.$route.params.workId
      },
      uploadStudentUrl: this.GLOBAL.domain + "/api/import/students",
      downloadStudentTemplateUrl: "/templates/考生信息表-模板.xlsx",
      downloadStudentTemplateFilename: "考生信息表-模板.xlsx",
      uploadRelateUrl: "/api/import/students/relateStudent",
      downloadRelateTemplateUrl: "/templates/关联考生信息表-模板.xlsx",
      downloadRelateTemplateFilename: "关联考生信息表-模板.xlsx"
    };
  },
  mounted() {
    this.iniData();
  },
  methods: {
    async iniData() {
      await this.getSubjects();
      this.getList();
    },
    async getList() {
      const datas = {
        // ...this.filter,
        workId: this.filter.workId,
        page: this.current - 1,
        size: this.size
      };
      const data = await studentPageList(datas);
      this.students = data.data.map(student => {
        student.uploadStatus.split(",").map(status => {
          const [subjectCode, subjectUploadStatus] = status.split(":");
          student[subjectCode] = subjectUploadStatus * 1;
        });
        student.canEdit = student.uploadStatus.includes("0");
        student.canDelete = !student.uploadStatus.includes("1");
        student.uploadStatus.split(",").map(status => {
          const [subject, hasScan] = status.split(":");
          student[subject] = hasScan;
        });
        return student;
      });
      this.total = data.totalCount;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    async getSubjects() {
      const data = await subjectList(this.filter.workId);
      this.subjects = data.filter(item => item.enable);
      this.subjects.map(item => {
        const column = {
          title: item.name,
          key: item.subject,
          minWidth: 80
        };
        this.columns.splice(this.columns.length - 1, 0, column);
      });
    },
    toEdit(row) {
      this.curStudent = row;
      this.$refs.ModifyStudent.open();
    },
    uploadStudentSuccess(response) {
      if (response && !response.length) {
        return {
          success: true,
          msg: "导入成功！"
        };
      }
      var errorInfos = response
        .filter(function(item) {
          return !!item.excelErrorType;
        })
        .map(function(item) {
          return "第" + item.row + "行，" + item.excelErrorType;
        })
        .join("；");
      if (errorInfos) {
        return {
          success: false,
          msg: errorInfos
        };
      } else {
        return {
          success: true,
          msg: "导入成功！"
        };
      }
    },
    toDelete(row) {
      this.$Modal.confirm({
        title: "删除警告",
        content: "确定要删除当前学生吗？",
        onOk: () => {
          this.toDel(row.id);
        }
      });
    },
    async toDel(id) {
      await deleteStudent(id);
      this.$Message.success("删除成功！");
      this.deletePageLastItem();
    }
  }
};
</script>
