<template>
  <div class="students ">
    <div class="part-box-head">
      <div class="part-box-head-left">
        <Button
          icon="upload icon"
          shape="circle"
          @click="$refs.ExportStudent.open()"
          >导入考生信息</Button
        >
        <Button
          icon="upload icon"
          shape="circle"
          @click="$refs.ExportRelate.open()"
          >导入关联信息</Button
        >
      </div>
      <div class="part-box-head-right">
        <Button
          type="success"
          icon="recode-white icon"
          shape="circle"
          @click="toEdit({})"
          >添加考生</Button
        >
      </div>
    </div>
    <div class="part-box part-box-filter">
      <Form ref="FilterForm" label-position="left" inline>
        <FormItem>
          <Select
            v-model="filter.subject"
            @on-change="subjectChange"
            placeholder="选择科目"
          >
            <Option
              v-for="(subject, index) in subjects"
              :key="index"
              :value="subject.subject"
              >{{ subject.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem>
          <Select v-model="filter.areaCode" placeholder="选择考区">
            <Option
              v-for="area in areas"
              :key="area.id"
              :value="area.areaCode"
              :label="area.areaName"
            ></Option>
          </Select>
        </FormItem>
        <FormItem>
          <Select v-model="filter.schoolId" placeholder="选择学校">
            <Option value=""></Option>
          </Select>
        </FormItem>
        <FormItem>
          <Select v-model="filter.examRoom" placeholder="选择考场">
            <Option value=""></Option>
          </Select>
        </FormItem>

        <FormItem>
          <InputNumber
            v-model="filter.startNumber"
            :min="1"
            :precision="0"
            placeholder="输入起始考号"
            clearable
          ></InputNumber>
        </FormItem>
        <FormItem>
          <InputNumber
            :min="filter.startNumber"
            v-model="filter.endNumber"
            :precision="0"
            placeholder="输入终止考号"
            clearable
          ></InputNumber>
        </FormItem>
        <FormItem>
          <Input
            v-model.trim="filter.name"
            placeholder="输入姓名"
            clearable
          ></Input>
        </FormItem>
        <FormItem>
          <Select v-model="filter.isAbsent" placeholder="是否缺考" clearable>
            <Option
              v-for="(val, key) in BOOLEAN_TYPE"
              :key="key"
              :value="key * 1"
              >{{ val }}</Option
            >
          </Select>
        </FormItem>
        <FormItem>
          <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
            size="small"
            class="border-radius-small btn-form-search"
            type="primary"
            @click="toPage(1)"
            >查询</Button
          >
        </FormItem>
      </Form>
    </div>
    <Table
      ref="TableList"
      :columns="columns"
      :data="students"
      disabled-hover
      border
    ></Table>

    <div class="part-page" v-if="total > size">
      <Page
        :current="current"
        :total="total"
        :page-size="size"
        show-total
        show-elevator
        @on-change="toPage"
      ></Page>
    </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"
      @upload-success="uploadSuccess"
      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 { areaList, 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: [],
      areas: [],
      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: 100
        },
        {
          title: "考号",
          key: "examNumber",
          minWidth: 120
        },
        {
          title: "考区",
          key: "areaName",
          minWidth: 120
        },
        {
          title: "学校",
          key: "sourceName",
          minWidth: 150
        },
        {
          title: "考场",
          key: "examRoom",
          minWidth: 100
        },
        {
          title: "操作",
          key: "action",
          width: 100,
          align: "center",
          className: "table-action",
          render: (h, param) => {
            let actions = [];

            if (param.row.canEdit) {
              actions.push({
                icon: "md-create",
                attrs: {
                  title: "编辑"
                },
                action: () => {
                  this.toEdit(param.row);
                }
              });
            }
            if (param.row.canDelete) {
              actions.push({
                icon: "md-trash",
                classes: ["icon-danger"],
                attrs: {
                  title: "删除"
                },
                action: () => {
                  this.toDelete(param.row);
                }
              });
            }

            return h("div", this.$tableIconAction(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 getAreaList() {
      const data = await areaList({
        workId: this.filter.workId,
        subject: this.filter.subject
      });
      this.areas = data.map(item => {
        return {
          id: item.id,
          areaName: item.areaName,
          areaCode: item.areaCode
        };
      });
    },
    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);
      });
    },
    subjectChange() {
      this.filter.areaCode = "";
      this.getAreaList();
    },
    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: "导入成功！"
        };
      }
    },
    uploadSuccess(result) {
      if (!result.success) return;
      this.getList();
    },
    toDelete(row) {
      this.$Modal.confirm({
        width: 340,
        content: "确定要删除该考生吗？",
        onOk: () => {
          this.toDel(row.id);
        }
      });
    },
    async toDel(id) {
      await deleteStudent(id);
      this.$Message.success("删除成功！");
      this.deletePageLastItem();
    }
  }
};
</script>
