<template>
  <div class="normal-score-manage">
    <div class="part-box part-box-pad box-justify">
      <p>请根据权重管理里权重项导入相应的平时成绩</p>
      <div>
        <el-button type="success" @click="toImport">导入平时成绩</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="姓名"
          minWidth="140"
        ></el-table-column>
        <el-table-column
          prop="studentCode"
          label="学号"
          minWidth="140"
        ></el-table-column>
        <template v-for="(item, index) in normalScoreItems">
          <el-table-column :key="index" :label="item">
            <template slot-scope="scope">
              {{ scope.row[item] }}
            </template>
          </el-table-column>
        </template>
        <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>

    <!-- ModifyNormalScore -->
    <modify-normal-score
      ref="ModifyNormalScore"
      :instance="curRow"
      @modified="getList"
    ></modify-normal-score>
    <!-- ImportFile -->
    <import-file
      ref="ImportFile"
      title="导入平时成绩"
      :upload-url="uploadUrl"
      :upload-data="filter"
      :format="['xls', 'xlsx']"
      :download-handle="downloadHandle"
      :download-filename="dfilename"
      :auto-upload="false"
      @upload-success="uploadSuccess"
    ></import-file>
  </div>
</template>

<script>
import {
  normalScoreListPage,
  normalScoreEnable,
  scoreTemplateDownload,
} from "../../api";
import ModifyNormalScore from "./ModifyNormalScore.vue";
import ImportFile from "@/components/ImportFile.vue";
import { downloadByApi } from "@/plugins/download";

export default {
  name: "normal-score-manage",
  components: { ModifyNormalScore, ImportFile },
  props: {
    course: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      filter: {
        cultureProgramId: "",
        courseId: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      curRow: {},
      normalScoreItems: [],
      // import
      uploadUrl: "/api/admin/course/degree/usual_score/import",
      dfilename: "平时成绩导入模板.xlsx",
      downloading: false,
    };
  },
  async mounted() {
    this.filter = this.$objAssign(this.filter, this.course);
    await this.toPage(1);
  },
  methods: {
    async getList() {
      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      const data = await normalScoreListPage(datas);
      this.dataList = data.records.map((item) => {
        const nitem = { ...item };
        if (!item.score) {
          return nitem;
        }

        nitem.normalScore = JSON.parse(item.score);
        nitem.normalScore.forEach((sItem) => {
          nitem[sItem.name] = sItem.score;
        });
        return nitem;
      });
      this.total = data.total;

      const score = data.records[0]?.score;
      if (score) {
        this.normalScoreItems = JSON.parse(score).map((item) => item.name);
      }
    },
    async toPage(page) {
      this.current = page;
      await this.getList();
    },
    toImport() {
      this.$refs.ImportFile.open();
    },
    toEdit(row) {
      this.curRow = { ...row, ...this.filter };
      this.$refs.ModifyNormalScore.open();
    },
    uploadSuccess({ data }) {
      const msg = `${data.success}，错误：${data.error}`;
      this.$message.success(msg);
      this.getList();
    },
    async downloadHandle() {
      if (this.downloading) return;
      this.downloading = true;

      const res = await downloadByApi(() => {
        return scoreTemplateDownload(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 normalScoreEnable({
        id: row.id,
        enable,
      });
      row.enable = enable;
      this.$message.success("操作成功！");
    },
  },
};
</script>
