<template>
  <div class="end-score-manage">
    <div class="part-box part-box-pad box-justify">
      <p></p>
      <div>
        <el-button
          type="success"
          :loading="syncing"
          :disabled="importing"
          @click="toSync"
          >同步成绩</el-button
        >
        <el-button
          type="success"
          :loading="importing"
          :disabled="syncing"
          @click="toImportPaperStruct"
          >导入试卷结构</el-button
        >
        <el-button
          type="success"
          :loading="importing"
          :disabled="syncing"
          @click="toImportEndScore"
          >导入期末成绩</el-button
        >
        <el-button type="success" @click="toSetBlue">设置试卷蓝图</el-button>
      </div>
    </div>
    <div class="part-box part-box-pad">
      <el-table :data="dataList">
        <el-table-column type="index" label="序号" width="70"></el-table-column>
        <el-table-column prop="name" label="姓名" width="140"></el-table-column>
        <el-table-column
          prop="studentCode"
          label="学号"
          width="140"
        ></el-table-column>
        <el-table-column prop="score" label="成绩" width="80">
        </el-table-column>
        <el-table-column prop="scoreDetailContent" label="成绩明细">
        </el-table-column>
        <el-table-column class-name="action-column" label="操作" width="120px">
          <template slot-scope="scope">
            <el-button
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              :class="scope.row.enable ? 'btn-danger' : 'btn-primary'"
              type="text"
              @click="toEnable(scope.row)"
              >{{ scope.row.enable ? "禁用" : "启用" }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <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>

    <!-- ModifyEndScore -->
    <modify-end-score
      ref="ModifyEndScore"
      :instance="curRow"
      @modified="getList"
    ></modify-end-score>
    <!-- ImportEndScore -->
    <import-file
      ref="ImportEndScore"
      title="导入期末成绩"
      :upload-url="upload.score.uploadUrl"
      :upload-data="filter"
      :format="['xls', 'xlsx']"
      :download-handle="downloadHandle"
      :download-filename="upload.score.dfilename"
      :auto-upload="false"
      :uploading="uploading"
      @upload-success="uploadSuccess"
      @upload-error="uploadError"
    ></import-file>
    <!-- ImportPaperStruct -->
    <import-file
      ref="ImportPaperStruct"
      title="导入试卷结构"
      :upload-url="upload.paper.uploadUrl"
      :upload-data="filter"
      :format="['xls', 'xlsx']"
      :download-handle="() => downloadTemplate('paperStruct')"
      :download-filename="upload.paper.dfilename"
      :auto-upload="false"
      :uploading="uploading"
      @upload-success="uploadSuccess"
      @upload-error="uploadError"
    ></import-file>
    <!-- SetBlueDialog -->
    <set-blue-dialog ref="SetBlueDialog" :course="course"> </set-blue-dialog>
    <!-- select papers -->
    <sync-paper-dialog
      ref="SyncPaperDialog"
      :course="filter"
      @modified="getList"
    ></sync-paper-dialog>
  </div>
</template>

<script>
import {
  endScoreListPage,
  endScoreEnable,
  endScoreTemplateDownload,
} from "../../api";
import ModifyEndScore from "./ModifyEndScore.vue";
import SetBlueDialog from "./SetBlueDialog.vue";
import ImportFile from "@/components/ImportFile.vue";
import SyncPaperDialog from "./SyncPaperDialog.vue";
import { downloadByApi } from "@/plugins/download";
import templateDownload from "@/mixins/templateDownload";

export default {
  name: "end-score-manage",
  components: { ModifyEndScore, SetBlueDialog, ImportFile, SyncPaperDialog },
  mixins: [templateDownload],
  props: {
    course: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      filter: {
        cultureProgramId: "",
        courseId: "",
        teachCourseId: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      curRow: {},
      syncing: false,
      importing: false,
      // import
      upload: {
        score: {
          uploadUrl: "/api/admin/course/degree/final_score/import",
          dfilename: "期末成绩导入模板.xlsx",
        },
        paper: {
          uploadUrl: "/api/admin/course/degree/final_score/paper_struct/import",
          dfilename: "试卷结构导入模板.xlsx",
        },
      },
      downloading: false,
    };
  },
  mounted() {
    this.filter = this.$objAssign(this.filter, this.course);
    this.toPage(1);
  },
  methods: {
    async getList() {
      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      const data = await endScoreListPage(datas);
      this.dataList = data.records.map((item) => {
        const nitem = { ...item };
        if (item.scoreDetail) {
          nitem.scoreDetail = JSON.parse(item.scoreDetail);
          nitem.scoreDetailContent = nitem.scoreDetail
            .map((item) => item.score)
            .join();
        }

        return nitem;
      });
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    toImportEndScore() {
      this.$refs.ImportEndScore.open();
    },
    toImportPaperStruct() {
      this.$refs.ImportPaperStruct.open();
    },
    toSync() {
      this.$refs.SyncPaperDialog.open();
    },
    toSetBlue() {
      this.$refs.SetBlueDialog.open();
    },
    toEdit(row) {
      this.curRow = { ...row, teachCourseId: this.course.teachCourseId };
      this.$refs.ModifyEndScore.open();
    },
    uploading() {
      this.importing = true;
    },
    uploadSuccess({ data }) {
      this.importing = false;
      const msg = `${data.success}，错误：${data.error}`;
      this.$message.success(msg);
      this.getList();
    },
    uploadError() {
      this.importing = false;
    },
    async downloadHandle() {
      if (this.downloading) return;
      this.downloading = true;

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

      if (!res) return;
      this.$message.success("下载成功！");
    },
    async toEnable(row) {
      const action = row.enable ? "禁用" : "启用";
      const confirm = await this.$confirm(
        `确定要${action}考生【${row.name}】的成绩吗?`,
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (confirm !== "confirm") return;

      const enable = !row.enable;
      await endScoreEnable({
        id: row.id,
        enable,
        teachCourseId: this.course.teachCourseId,
      });
      row.enable = enable;
      this.$message.success("操作成功！");
    },
  },
};
</script>
