<template>
  <div class="business-data-export">
    <div class="part-box part-box-filter">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <template v-if="checkPrivilege('condition', 'condition')">
          <el-form-item label="学期：">
            <semester-select
              v-model.trim="filter.semesterId"
              placeholder="学期"
              default-select
            ></semester-select>
          </el-form-item>
          <el-form-item label="考试：">
            <exam-select
              v-model="filter.examId"
              :semester-id="filter.semesterId"
              default-select
              @default-selected="search"
            ></exam-select>
          </el-form-item>
          <el-form-item label="印刷计划：">
            <print-plan-select
              v-model.trim="filter.printPlanIdList"
              placeholder="印刷计划"
              clearable
              multiple
              :semester-id="filter.semesterId"
              :exam-id="filter.examId"
              @change="printPlanChange"
            ></print-plan-select>
          </el-form-item>
          <el-form-item label="课程（代码）：" label-width="110px">
            <course-select
              v-model.trim="filter.courseId"
              :semester-id="filter.semesterId"
              :exam-id="filter.examId"
              :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"
              :semester-id="filter.semesterId"
              :exam-id="filter.examId"
              :print-plan-id="filter.printPlanIdList"
              :course-id="filter.courseId"
              placeholder="试卷编号"
              clearable
            ></paper-number-select>
          </el-form-item>
          <el-form-item label="考点：" label-width="55px">
            <place-select
              v-model.trim="filter.examPlace"
              :exam-id="filter.examId"
              :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"
              :exam-id="filter.examId"
              :print-plan-id="filter.printPlanIdList"
              placeholder="考场"
              clearable
            ></room-select>
          </el-form-item>
          <el-form-item label="卷袋号：" label-width="70px">
            <el-input
              v-model.trim="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="box-justify">
        <div>
          <el-button
            v-if="checkPrivilege('button', 'export')"
            icon="el-icon-download"
            type="primary"
            :loading="loading"
            @click="toExport"
          >
            导出
          </el-button>
          <el-button
            v-if="checkPrivilege('button', 'export')"
            type="primary"
            icon="el-icon-s-order"
            @click="toDataTask('EXAMINATION_EXPORT')"
            >导出结果查询</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('EXAMINATION_IMPORT')"
            >导入结果查询</el-button
          >
        </div>
      </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="semesterName"
          label="学期"
          min-width="210"
        ></el-table-column>
        <el-table-column
          prop="examName"
          label="考试"
          min-width="160"
        ></el-table-column> -->
        <el-table-column
          prop="printPlanName"
          label="印刷计划"
          min-width="240"
        ></el-table-column>
        <el-table-column
          prop="courseNameCode"
          label="课程（代码）"
          min-width="260"
        >
        </el-table-column>
        <el-table-column
          prop="paperNumber"
          label="试卷编号"
          width="160"
        ></el-table-column>
        <el-table-column prop="examDate" label="考试日期" width="100">
        </el-table-column>
        <el-table-column prop="examTime" label="考试时间" width="100">
        </el-table-column>
        <el-table-column prop="packageCode" label="卷袋号" width="160">
        </el-table-column>
        <el-table-column prop="examPlace" label="考点" min-width="160">
        </el-table-column>
        <el-table-column prop="examRoom" label="考场" min-width="160">
        </el-table-column>
        <el-table-column prop="totalSubjects" label="科次" width="60">
        </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', 'preview')"
              class="btn-primary"
              type="text"
              @click="toPreview(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="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, 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>

    <!-- PreviewBusinessDetail -->
    <preview-business-detail
      ref="PreviewBusinessDetail"
      :instance="curRow"
    ></preview-business-detail>
    <!-- ImportFile -->
    <import-file
      v-if="checkPrivilege('button', 'import')"
      ref="ImportFile"
      title="导入考务数据"
      :upload-url="uploadUrl"
      :upload-data="uploadData"
      :format="['xls', 'xlsx']"
      :auto-upload="false"
      :before-submit-handle="submitImport"
      @upload-success="uploadSuccess"
    >
      <el-form
        ref="modalFormComp"
        :model="modalForm"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="模板下载：">
          <el-button type="text" :loading="loading" @click="toDownloadTemplate">
            <span class="cont-link">
              {{ dfilename }}
            </span>
          </el-button>
        </el-form-item>

        <el-form-item prop="printPlanId" label="印刷计划：">
          <el-select
            v-model="modalForm.printPlanId"
            placeholder="请选择"
            filterable
            :disabled="loading"
            style="width: 100%"
          >
            <el-option
              v-for="item in plans"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </import-file>
    <!-- data-task-dialog -->
    <data-task-dialog
      v-if="
        checkPrivilege('button', 'import') || checkPrivilege('button', 'export')
      "
      ref="DataTaskDialog"
      :task-type="taskType"
    ></data-task-dialog>
  </div>
</template>

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

export default {
  name: "business-data-export",
  components: { PreviewBusinessDetail, ImportFile },
  data() {
    return {
      filter: {
        semesterId: "",
        examId: "",
        printPlanIdList: "",
        courseId: "",
        paperNumber: "",
        examPlace: "",
        examRoom: "",
        packageCode: "",
        startDate: "",
        endDate: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      curRow: {},
      totalData: {},
      loading: false,
      // date-picker
      createTime: [],
      pickerOptions,
      // import
      plans: [],
      modalForm: { type: "FILE", printPlanId: "" },
      rules: {
        printPlanId: [
          {
            required: true,
            message: "请选择印刷计划",
            trigger: "change",
          },
        ],
      },
      taskType: "",
      uploadUrl: "/api/admin/exam/print/data_import",
      dfilename: "考务数据模板.xlsx",
      uploadData: {},
    };
  },
  mounted() {
    // this.search();
    this.getPlans();
  },
  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.examRoom = "";
      this.filter.examPlace = "";
    },
    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.loading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    toPreview(row) {
      this.curRow = { ...row };
      this.$refs.PreviewBusinessDetail.open();
    },
    async toDelete(row) {
      const result = await this.$confirm(`确定要删除吗?`, "提示", {
        type: "warning",
      }).catch(() => {});
      if (result !== "confirm") return;

      await deleteBusinessData(row.id);
      this.$message.success("操作成功！");
      this.deletePageLastItem();
    },
    // import
    async getPlans() {
      const res = await printPlanQuery();
      this.plans = res.filter((item) => ["NEW", "READY"].includes(item.status));
    },
    toImport() {
      this.$refs.ImportFile.open();
    },
    toDataTask(taskType) {
      this.taskType = taskType;
      this.$refs.DataTaskDialog.open();
    },
    async submitImport() {
      this.uploadData = { ...this.modalForm };
      return this.$refs.modalFormComp.validate();
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess() {
      this.$message.success("文件上传成功，后台正在导入！");
      this.getList();
    },
  },
};
</script>
