<template>
  <div class="customer-card">
    <div class="mb-4 tab-btns">
      <el-button
        v-for="(val, key) in AUDITING_TYPE"
        :key="key"
        size="medium"
        :type="filter.status == key ? 'primary' : 'default'"
        @click="selectMenu(key)"
        >{{ val }}</el-button
      >
    </div>
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <template
          v-if="
            (AUDITED && checkPrivilege('condition', 'reviewCondition')) ||
              (!AUDITED && checkPrivilege('condition', 'notReviewCondition'))
          "
        >
          <el-form-item label="学校：">
            <school-select
              v-model="filter.schoolId"
              placeholder="学校"
            ></school-select>
          </el-form-item>
          <!-- <el-form-item label="试卷编号：">
          <paper-number-select
            ref="PaperNumberSelect"
            v-model="filter.paperNumber"
            placeholder="请选择"
            clearable
          ></paper-number-select>
        </el-form-item>
        <el-form-item label="申请人：">
          <question-teacher-select
            ref="QuestionTeacherSelect"
            v-model="filter.userId"
            :school-id="filter.schoolId"
            placeholder="请选择"
          ></question-teacher-select>
        </el-form-item> -->
          <el-form-item label="申请时间：">
            <el-date-picker
              v-model="createTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="申请开始时间"
              end-placeholder="申请结束时间"
              value-format="timestamp"
              align="right"
              unlink-panels
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="完成时间：" v-if="AUDITED">
            <el-date-picker
              v-model="finishTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="完成开始时间"
              end-placeholder="完成结束时间"
              value-format="timestamp"
              align="right"
              unlink-panels
            >
            </el-date-picker>
          </el-form-item>
        </template>

        <el-form-item label-width="0px">
          <el-button
            v-if="
              (AUDITED && checkPrivilege('button', 'reviewSelect')) ||
                (!AUDITED && checkPrivilege('button', 'notReviewSelect'))
            "
            type="primary"
            @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="part-box-action" v-if="!AUDITED">
        <el-button
          v-if="checkPrivilege('button', 'notReviewBatchDownload')"
          icon="el-icon-download"
          type="primary"
          :disabled="loading"
          @click="toExport"
        >
          批量下载试卷文件
        </el-button>
      </div>
    </div>

    <div class="part-box part-box-pad">
      <el-table
        ref="TableList"
        :data="taskList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="70"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column prop="paperNumber" label="试卷编号"></el-table-column>
        <el-table-column prop="schoolName" label="学校名称"></el-table-column>
        <el-table-column prop="orgName" label="所属部门"> </el-table-column>
        <el-table-column
          prop="createName"
          label="申请人"
          width="100"
        ></el-table-column>
        <el-table-column prop="createTime" label="申请时间">
          <span slot-scope="scope">{{
            scope.row.createTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="updateTime" label="完成时间" v-if="AUDITED">
          <span slot-scope="scope">{{
            scope.row.updateTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column class-name="action-column" label="操作" width="140">
          <template slot-scope="scope">
            <el-button
              v-if="AUDITED && checkPrivilege('link', 'reviewPreview')"
              class="btn-primary"
              type="text"
              @click="toPreview(scope.row)"
              >查看详情</el-button
            >
            <el-button
              v-if="!AUDITED && checkPrivilege('link', 'notReviewDesign')"
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >设计题卡</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          v-if="taskList.length"
          background
          layout="total,prev, pager, next"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import pickerOptions from "@/constants/datePickerOptions";
import { customerCardTaskList, customerPaperExport } from "../api";
import { randomCode } from "@/plugins/utils";
import { downloadByApi } from "@/plugins/download";

export default {
  name: "customer-card",
  data() {
    return {
      filter: {
        schoolId: "",
        status: "STAGE",
        paperNumber: "",
        userId: "",
        applyStartTime: null,
        applyEndTime: null,
        finishStartTime: null,
        finishEndTime: null
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      multipleSelection: [],
      AUDITING_TYPE: {
        STAGE: "待审核",
        SUBMIT: "已审核"
      },
      caches: {},
      taskList: [],
      loading: false,
      // date-picker
      createTime: [],
      finishTime: [],
      pickerOptions
    };
  },
  computed: {
    AUDITED() {
      return this.filter.status === "SUBMIT";
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      const cachePageInfo = this.$ls.get("cachePageInfo");
      if (cachePageInfo) {
        this.filter = this.$objAssign(this.filter, cachePageInfo.filter);
        if (this.filter.applyStartTime && this.filter.applyEndTime)
          this.createTime = [
            this.filter.applyStartTime,
            this.filter.applyEndTime
          ];
        if (this.filter.finishStartTime && this.filter.finishEndTime)
          this.finishTime = [
            this.filter.finishStartTime,
            this.filter.finishEndTime
          ];
        this.toPage(cachePageInfo.page);
      } else {
        this.toPage(1);
      }
      this.$ls.remove("cachePageInfo");
    },
    async getList() {
      const valid =
        (this.AUDITED && this.checkPrivilege("list", "reviewList")) ||
        (!this.AUDITED && this.checkPrivilege("list", "notReviewList"));
      if (!valid) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size
      };
      if (this.createTime) {
        datas.applyStartTime = this.createTime[0];
        datas.applyEndTime = this.createTime[1];
      }
      if (this.finishTime) {
        datas.finishStartTime = this.finishTime[0];
        datas.finishEndTime = this.finishTime[1];
      }
      const data = await customerCardTaskList(datas);
      this.taskList = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.cardId);
    },
    selectMenu(val) {
      if (this.filter.status === val) return;
      this.multipleSelection = [];
      this.caches[this.filter.status] = {
        current: this.current,
        taskList: this.taskList,
        total: this.total
      };
      this.filter.status = val;
      if (this.caches[val] && this.caches[val].taskList) {
        this.current = this.caches[val].current;
        this.total = this.caches[val].total;
        this.taskList = this.caches[val].taskList;
      } else {
        this.toPage(1);
      }
    },
    async toExport() {
      if (this.loading) return;

      if (!this.multipleSelection.length) {
        this.$message.error("请选择要下载的记录！");
        return;
      }

      this.loading = true;
      const res = await downloadByApi(() => {
        return customerPaperExport({ ids: this.multipleSelection });
      }, `${randomCode()}.zip`).catch(e => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    toEdit(row) {
      this.$ls.set("prepareTcPCard", {
        examTaskId: row.examTaskId,
        courseCode: row.courseCode,
        courseName: row.courseName,
        schoolName: row.schoolName,
        makeMethod: "CUST",
        type: "CUSTOM",
        createMethod: "STANDARD",
        cardRuleId: row.cardRuleId,
        schoolId: row.schoolId
      });
      // 打开题卡编辑页，创建题卡，并预设需要绑定的任务
      this.$router.push({
        name: "CardEdit",
        params: {
          cardId: row.cardId
        }
      });
    },
    toPreview(row) {
      window.open(
        this.getRouterPath({
          name: "CardPreview",
          params: {
            cardId: row.cardId,
            viewType: "view"
          }
        })
      );
    }
  },
  beforeRouteLeave(to, from, next) {
    if (to.name === "CardEdit") {
      this.$ls.set("cachePageInfo", {
        page: this.current,
        filter: this.filter
      });
    } else {
      this.$ls.remove("cachePageInfo");
    }
    next();
  }
};
</script>
