<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="uploadData"
      :format="['xls', 'xlsx']"
      :download-handle="downloadHandle"
      :download-filename="dfilename"
      :auto-upload="false"
      :before-submit-handle="beforeSubmitHandle"
      @upload-success="uploadSuccess"
    >
      <div class="mt-1 part-box part-box-pad" slot="bodyfoot">
        <el-table :data="evaluationList" border>
          <el-table-column prop="name" label="评价方式"></el-table-column>
          <el-table-column prop="value" label="评价方式满分" width="140px">
            <template slot="header">
              <span>评价方式满分</span>
              <el-tooltip effect="dark" placement="top">
                <div slot="content" class="tooltip-area">
                  <p>帮助说明</p>
                  <p>
                    1.系统会根据填写满分自动转换成100分下得分，如该学生在该评价方式下得分8分，满分10分，导入后该学生在该评价方式下转换后的得分为80分；
                  </p>
                  <p>2.如果不填写满分，默认满分为100分。</p>
                </div>
                <i class="el-icon-info ml-1 tooltip-info-icon"></i>
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.value"
                :min="1"
                :max="999"
                :step="1"
                step-strictly
                :controls="false"
                style="width: 100px"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </import-file>
  </div>
</template>

<script>
import { pickByNotNull } from "@/plugins/utils";
import {
  normalScoreListPage,
  normalScoreEnable,
  scoreTemplateDownload,
  courseEvaluationList,
} 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: "",
        examId: "",
        paperNumber: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      curRow: {},
      normalScoreItems: [],
      evaluationList: [],
      // import
      uploadData: {},
      uploadUrl: "/api/admin/course/degree/usual_score/import",
      dfilename: "平时成绩导入模板.xlsx",
      downloading: false,
    };
  },
  async mounted() {
    this.filter = this.$objAssign(this.filter, this.course);
    this.getEvaluation();
    await this.toPage(1);
  },
  methods: {
    async getEvaluation() {
      const res = await courseEvaluationList(this.filter);
      this.evaluationList = (res || []).map((item) => {
        return {
          name: item.name,
          value: undefined,
        };
      });
    },
    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.evaluationList.forEach((item) => {
        item.value = undefined;
      });
      this.$refs.ImportFile.open();
    },
    toEdit(row) {
      this.curRow = { ...row, ...this.filter };
      this.$refs.ModifyNormalScore.open();
    },
    beforeSubmitHandle() {
      // const valid = !this.evaluationList.some((item) => !item.value);
      // if (!valid) {
      //   this.$message.error("请完成评价方式满分设置！");
      //   return Promise.reject();
      // }

      this.uploadData = pickByNotNull({
        ...this.filter,
        usualScoreList: JSON.stringify(this.evaluationList),
      });
    },
    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>
