<template>
  <div class="analysis-batch-manage">
    <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="分析批次：">
            <el-input
              style="width:100%;"
              v-model.trim="filter.gradeBatchName"
              placeholder="请输入批次名称"
              clearable
            ></el-input>
          </el-form-item>
        </template>
        <el-form-item>
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <el-button
          v-if="checkPrivilege('button', 'delete')"
          type="danger"
          :loading="loading"
          @click="toBatchDelete"
          >批量删除</el-button
        >
        <el-button
          v-if="checkPrivilege('button', 'add')"
          type="primary"
          @click="toAdd"
          >新建分析批次</el-button
        >
      </div>
    </div>
    <div class="part-box part-box-pad">
      <el-table
        ref="TableList"
        :data="dataList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column prop="batchName" label="分析批次"></el-table-column>
        <el-table-column prop="semesterName" label="学期"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span>
              {{ scope.row.status | analysisBatchStatusFilter }}
            </span>
            <span v-if="scope.row.status === 'CALCULATING'" class="ml-2">
              {{ scope.row.progress }}%</span
            >
            <span
              v-if="scope.row.status === 'FINISH_CALCULATE'"
              :class="[
                'ml-2',
                scope.row.result === 'SUCCESS'
                  ? 'color-success'
                  : 'color-danger'
              ]"
            >
              {{ scope.row.result === "SUCCESS" ? "成功" : "失败" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="300"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'window')"
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toAddCourse(scope.row)"
              >添加分析试卷</el-button
            >
            <el-button
              v-if="
                checkPrivilege('link', 'StartCalc') &&
                  scope.row.status === 'READY_TO_CALCULATE'
              "
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toCalc(scope.row)"
              >开始计算</el-button
            >
            <el-button
              v-if="
                checkPrivilege('link', 'push') &&
                  scope.row.status === 'PUSH_GRADE_BATCH'
              "
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toImportAnalysisData(scope.row)"
              >提交分析数据</el-button
            >
            <el-button
              v-if="
                checkPrivilege('link', 'import') &&
                  scope.row.status !== 'SETTING_GRADE_PAPER'
              "
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toImport(scope.row)"
              >导入</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'delete')"
              class="btn-danger"
              type="text"
              :disabled="loading"
              @click="toDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              v-if="
                scope.row.reportFilePath &&
                  scope.row.status === 'FINISH_CALCULATE'
              "
              class="btn-primary"
              type="text"
              @click="toViewLog(row)"
              >下载日志</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="total,prev, pager, next"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
        >
        </el-pagination>
      </div>
    </div>

    <!-- ModifyAnalysisBatch -->
    <modify-analysis-batch
      v-if="checkPrivilege('button', 'add')"
      ref="ModifyAnalysisBatch"
      :instance="curRow"
      @modified="getList"
    ></modify-analysis-batch>
    <!-- ModifyAnalysisBatchPaper -->
    <modify-analysis-batch-paper
      v-if="checkPrivilege('link', 'window')"
      ref="ModifyAnalysisBatchPaper"
      :instance="curRow"
      @closed="getList"
    ></modify-analysis-batch-paper>
    <!-- 数据导入 -->
    <import-file
      v-if="checkPrivilege('link', 'import')"
      ref="ImportFile"
      title="上传文件"
      :upload-url="uploadUrl"
      :upload-data="uploadData"
      :download-handle="downloadHandle"
      download-filename="考务数据模板"
      :format="['xls', 'xlsx']"
      @upload-success="fileUploaded"
    >
    </import-file>
  </div>
</template>

<script>
import {
  analysisBatchList,
  deleteAnalysisBatch,
  analysisBatchTemplateExport,
  analysisDataImport,
  analysisBatchCalc
} from "../api";
import ModifyAnalysisBatch from "../components/ModifyAnalysisBatch.vue";
import ModifyAnalysisBatchPaper from "../components/ModifyAnalysisBatchPaper.vue";
import ImportFile from "@/components/ImportFile";
import { downloadByApi } from "@/plugins/download";
import timeMixins from "../../../mixins/timeMixin";

export default {
  name: "analysis-batch-manage",
  components: { ModifyAnalysisBatch, ModifyAnalysisBatchPaper, ImportFile },
  mixins: [timeMixins],
  data() {
    return {
      filter: {
        gradeBatchName: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      curRow: {},
      batchs: [],
      loading: false,
      multipleSelection: [],
      // upload
      uploadUrl: "/api/admin/grade/batch/upload",
      uploadData: {},
      downloading: false
    };
  },
  mounted() {
    this.toPage(1);
  },
  beforeDestroy() {
    this.clearSetTs();
  },
  methods: {
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;
      this.clearSetTs();

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size
      };
      const data = await analysisBatchList(datas);
      this.dataList = data.records.map(item => {
        item.loading = false;
        return item;
      });
      this.total = data.total;

      if (this.dataList.some(item => item.status === "CALCULATING")) {
        this.addSetTime(() => {
          this.getList();
        }, 10 * 1000);
      }
    },
    toPage(page) {
      this.multipleSelection = [];
      this.current = page;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id);
    },
    async toBatchDelete() {
      if (!this.multipleSelection.length) {
        this.$message.error("请选择要删除的批次！");
        return;
      }

      const confirm = await this.$confirm(`确定要删除选中的批次吗?`, "提示", {
        type: "warning"
      }).catch(() => {});
      if (confirm !== "confirm") return;

      await deleteAnalysisBatch(this.multipleSelection);
      this.$message.success("删除成功！");
      this.deletePageLastItem();
    },
    toAdd() {
      this.curRow = {};
      this.$refs.ModifyAnalysisBatch.open();
    },
    toAddCourse(row) {
      this.curRow = row;
      this.$refs.ModifyAnalysisBatchPaper.open();
    },
    async toCalc(row) {
      if (row.loading) return;
      row.loading = true;

      const res = await analysisBatchCalc({ batchId: row.id }).catch(() => {});
      row.loading = false;
      if (!res) return;

      this.$message.success("操作成功！");
      this.getList();
    },
    async toImportAnalysisData(row) {
      if (row.loading) return;
      row.loading = true;

      const res = await analysisDataImport({ batchId: row.id }).catch(() => {});
      row.loading = false;
      if (!res) return;

      this.$message.success("操作成功！");
      this.getList();
    },
    toImport(row) {
      this.curRow = row;
      this.uploadData = {
        batchId: row.id
      };
      this.$refs.ImportFile.open();
    },
    fileUploaded() {
      this.getList();
    },
    async downloadHandle() {
      if (this.downloading) return;
      this.downloading = true;

      const res = await downloadByApi(() => {
        return analysisBatchTemplateExport({
          batchId: this.curRow.id
        });
      }).catch(e => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    async toDelete(row) {
      const confirm = await this.$confirm(
        `确定要删除批次【${row.batchName}】吗?`,
        "提示",
        {
          type: "warning"
        }
      ).catch(() => {});
      if (confirm !== "confirm") return;

      await deleteAnalysisBatch([row.id]);
      this.$message.success("删除成功！");
      this.deletePageLastItem();
    },
    toViewLog(row) {
      window.open(row.reportFilePath);
    }
  }
};
</script>
