<template>
  <div class="business-data-export">
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <template v-if="checkPrivilege('condition', 'condition')">
          <el-form-item label="印刷计划：">
            <print-plan-select
              v-model.trim="filter.printPlanIdList"
              placeholder="印刷计划"
              clearable
              multiple
              @change="printPlanChange"
            ></print-plan-select>
          </el-form-item>
          <el-form-item label="课程（代码）：" label-width="110px">
            <course-select
              v-model.trim="filter.courseCode"
              :print-plan-id="filter.printPlanIdList"
              placeholder="课程（代码）"
              clearable
            ></course-select>
          </el-form-item>
          <el-form-item label="试卷编号：">
            <paper-number-select
              ref="PaperNumberSelect"
              v-model="filter.paperNumber"
              :print-plan-id="filter.printPlanIdList"
              placeholder="试卷编号"
              clearable
            ></paper-number-select>
          </el-form-item>
          <el-form-item label="考点：" label-width="55px">
            <place-select
              v-model.trim="filter.examPlace"
              :print-plan-id="filter.printPlanIdList"
              placeholder="考点"
              clearable
            ></place-select>
          </el-form-item>
          <el-form-item label="考场：" label-width="55px">
            <room-select
              v-model.trim="filter.examRoom"
              :print-plan-id="filter.printPlanIdList"
              placeholder="考场"
              clearable
            ></room-select>
          </el-form-item>
          <el-form-item label="卷袋号：" label-width="70px">
            <el-input
              v-model="filter.packageCode"
              placeholder="卷袋号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="考试日期：">
            <el-date-picker
              v-model="createTime"
              type="daterange"
              :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="checkPrivilege('button', 'select')"
            type="primary"
            @click="search"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <el-button
          v-if="checkPrivilege('button', 'TempleteDownload')"
          icon="el-icon-download"
          type="success"
          :loading="loading"
          @click="toDownloadTemplate"
        >
          考务数据模板下载
        </el-button>
        <el-button
          v-if="checkPrivilege('button', 'import')"
          icon="el-icon-circle-plus-outline"
          type="success"
          @click="toUpload"
        >
          导入
        </el-button>
        <el-button
          v-if="checkPrivilege('button', 'export')"
          icon="el-icon-download"
          type="primary"
          :loading="loading"
          @click="toExport"
        >
          导出查询结果
        </el-button>
      </div>
    </div>

    <div class="part-box part-box-pad">
      <el-table class="mb-2" ref="TableList" :data="dataList">
        <el-table-column
          type="index"
          label="序号"
          width="70"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column
          prop="printPlanName"
          label="印刷计划"
        ></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="考点"> </el-table-column>
        <el-table-column prop="examRoom" label="考场"> </el-table-column>
        <el-table-column prop="packageCode" label="卷袋号"> </el-table-column>
        <el-table-column prop="courseNameCode" label="课程（代码）">
        </el-table-column>
        <el-table-column prop="paperNumber" label="试卷编号"></el-table-column>
        <el-table-column prop="totalSubjects" label="科次" width="80">
        </el-table-column>
        <el-table-column class-name="action-column" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'preview')"
              class="btn-primary"
              type="text"
              @click="toPreview(scope.row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="box-justify">
        <div>
          <span class="mr-2"
            >科次总计：<i class="color-primary">{{
              totalData.totalSubjects
            }}</i>
            科次</span
          >
          <span
            >卷袋数量总计：<i class="color-primary">{{
              totalData.packageCount
            }}</i>
            个</span
          >
        </div>
        <el-pagination
          background
          layout="total,prev, pager, next"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
        >
        </el-pagination>
      </div>
    </div>

    <!-- PreviewBusinessDetail -->
    <preview-business-detail
      ref="PreviewBusinessDetail"
      :instance="curRow"
    ></preview-business-detail>
    <!-- UploadBusinessDataDialog -->
    <upload-business-data-dialog
      ref="UploadBusinessDataDialog"
      @modified="getList"
    ></upload-business-data-dialog>
  </div>
</template>

<script>
import {
  businessDataListPage,
  businessTotalData,
  businessTemplateDownload,
  businessDataExport
} from "../api";
import PreviewBusinessDetail from "../components/PreviewBusinessDetail";
import UploadBusinessDataDialog from "../components/UploadBusinessDataDialog";
import { parseTimeRangeDateAndTime } from "@/plugins/utils";
import { downloadByApi } from "@/plugins/download";
import pickerOptions from "@/constants/datePickerOptions";

export default {
  name: "business-data-export",
  components: { PreviewBusinessDetail, UploadBusinessDataDialog },
  data() {
    return {
      filter: {
        printPlanIdList: "",
        courseCode: "",
        paperNumber: "",
        examPlace: "",
        examRoom: "",
        packageCode: "",
        startDate: "",
        endDate: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      curRow: {},
      totalData: {},
      curPrintPlan: {},
      loading: false,
      // date-picker
      createTime: [],
      pickerOptions,
      // import
      // TODO:
      uploadUrl: "/api/admin/exam/print/data_import",
      uploadData: {
        type: "FILE",
        printPlanId: ""
      }
    };
  },
  computed: {
    canImport() {
      return (
        this.curPrintPlan && ["NEW", "READY"].includes(this.curPrintPlan.status)
      );
    }
  },
  mounted() {
    this.search();
  },
  methods: {
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size
      };
      if (this.createTime) {
        datas.startDate = this.createTime[0];
        datas.endDate = this.createTime[1];
      }
      const data = await businessDataListPage(datas);
      this.dataList = data.records.map(item => {
        const { date, time } = parseTimeRangeDateAndTime(
          item.examStartTime,
          item.examEndTime
        );
        item.examDate = date || "--";
        item.examTime = time || "--";
        return item;
      });
      this.total = data.total;
    },
    async getTotalData() {
      const datas = {
        ...this.filter
      };
      if (this.createTime) {
        datas.startDate = this.createTime[0];
        datas.endDate = this.createTime[1];
      }
      this.totalData = await businessTotalData(datas);
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    search() {
      this.toPage(1);
      this.getTotalData();
    },
    printPlanChange() {
      this.filter.paperNumber = "";
      this.filter.courseCode = "";
      this.filter.examRoom = "";
      this.filter.examPlace = "";
    },
    toUpload() {
      this.$refs.UploadBusinessDataDialog.open();
    },
    async toExport() {
      // 异步导出
      if (this.loading) return;

      this.loading = true;
      const datas = {
        ...this.filter
      };
      if (this.createTime) {
        datas.startDate = this.createTime[0];
        datas.endDate = this.createTime[1];
      }
      const res = await businessDataExport(datas).catch(() => {});
      this.loading = false;

      if (res) {
        this.$message.success(
          "导出任务已提交，请在系统设置-任务管理中下载文件！"
        );
      } else {
        this.$message.error("导出任务提交失败，请重新尝试！");
      }
    },
    async toDownloadTemplate() {
      if (this.loading) return;

      this.loading = true;
      const res = await downloadByApi(() => {
        return businessTemplateDownload();
      }, `考务数据模板.xlsx`).catch(e => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    toPreview(row) {
      this.curRow = { ...row };
      this.$refs.PreviewBusinessDetail.open();
    }
  }
};
</script>
