<template>
  <div class="end-score-manage">
    <div class="part-box part-box-pad box-justify">
      <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="uploadData"
      :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="uploadData"
      :format="['xls', 'xlsx']"
      :download-handle="() => downloadTemplate('paperStruct')"
      :download-filename="upload.paper.dfilename"
      :auto-upload="false"
      :uploading="uploading"
      @upload-success="uploadSuccess"
      @upload-error="uploadError"
    >
      <template #bodyfoot>
        <div class="mt-1">
          <div class="box-justify mb-2">
            <div></div>
            <el-button type="danger" @click="toClearStruct">清除</el-button>
          </div>
          <div class="part-box part-box-pad">
            <el-table :data="structList" border height="300">
              <el-table-column
                prop="mainNumber"
                label="大题号"
              ></el-table-column>
              <el-table-column
                prop="subNumber"
                label="小题号"
              ></el-table-column>
              <el-table-column prop="score" label="小题满分"></el-table-column>
            </el-table>
          </div>
        </div>
      </template>
    </import-file>
    <!-- SetBlueDialog -->
    <set-blue-dialog ref="SetBlueDialog" :course="course"> </set-blue-dialog>
    <!-- select papers -->
    <sync-paper-dialog
      ref="SyncPaperDialog"
      :course="course"
      @modified="paperSynced"
    ></sync-paper-dialog>
  </div>
</template>

<script>
import {
  endScoreListPage,
  endScoreEnable,
  endScoreTemplateDownload,
  endScorePaperPositiveDetail,
  endScorePaperStructClear,
} 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";
import { pickByNotNull } from "@/plugins/utils";

export default {
  name: "end-score-manage",
  components: { ModifyEndScore, SetBlueDialog, ImportFile, SyncPaperDialog },
  mixins: [templateDownload],
  props: {
    course: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      filter: {
        cultureProgramId: "",
        courseId: "",
        examId: "",
        paperNumber: "",
      },
      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,
      structList: [],
    };
  },
  computed: {
    uploadData() {
      return pickByNotNull(this.filter);
    },
  },
  mounted() {
    this.filter = this.$objAssign(this.filter, this.course);
    this.toPage(1);
    this.getBlueDetail();
  },
  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();
    },
    async getBlueDetail() {
      const res = await endScorePaperPositiveDetail({
        cultureProgramId: this.course.cultureProgramId,
        courseId: this.course.courseId,
        examId: this.course.examId,
        paperNumber: this.course.paperNumber,
      });
      this.structList = res || [];
    },
    async toClearStruct() {
      const confirm = await this.$confirm(
        `清除会清除掉导入试卷结构及成绩和蓝图设置，确定要清除吗?`,
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (confirm !== "confirm") return;

      const res = await endScorePaperStructClear({
        cultureProgramId: this.course.cultureProgramId,
        courseId: this.course.courseId,
        examId: this.course.examId,
        paperNumber: this.course.paperNumber,
      }).catch(() => {});
      if (!res) return;

      this.$message.success("清除成功！");
      this.getBlueDetail();
      this.getList();
    },
    toImportEndScore() {
      this.$refs.ImportEndScore.open();
    },
    toImportPaperStruct() {
      this.$refs.ImportPaperStruct.open();
    },
    toSync() {
      this.$refs.SyncPaperDialog.open();
    },
    paperSynced() {
      this.getList();
      this.getBlueDetail();
    },
    toSetBlue() {
      this.$refs.SetBlueDialog.open();
    },
    toEdit(row) {
      this.curRow = { ...row, ...this.filter };
      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();
      this.getBlueDetail();
    },
    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,
      });
      row.enable = enable;
      this.$message.success("操作成功！");
    },
  },
};
</script>
