<template>
  <div class="blueprint-config">
    <div class="mb-4 box-justify">
      <el-button type="success" @click="toImport">导入</el-button>
      <el-button
        v-if="baseInfo.structureChange"
        type="primary"
        :loading="updating"
        @click="toUpdateExamCloudStruct"
        >更新试卷结构</el-button
      >
    </div>

    <div class="part-box part-box-border-bold">
      <el-table ref="TableList" :data="dataList">
        <el-table-column prop="courseCode" label="课程代码"></el-table-column>
        <el-table-column prop="courseName" label="课程名称"> </el-table-column>
        <el-table-column prop="paperNumber" label="试卷编号"> </el-table-column>
        <el-table-column prop="bigQuestionNumber" label="大题号" width="80">
        </el-table-column>
        <el-table-column prop="smallQuestionNumber" label="小题号" width="80">
        </el-table-column>
        <el-table-column prop="bigTopicName" label="题目类型" width="100">
        </el-table-column>
        <el-table-column prop="fullScore" label="题目满分" width="80">
        </el-table-column>
        <el-table-column prop="knowledgeDimension" label="知识模块" width="260">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.knowledgeDimension"
              placeholder="请选择"
              filterable
              clearable
              multiple
            >
              <el-option
                v-for="item in knowledgeList"
                :key="item.code"
                :value="item.code"
                :label="item.code"
              >
                {{ item.code }}（{{ item.name }}）
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="abilityDimension" label="能力模块" width="260">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.abilityDimension"
              placeholder="请选择"
              filterable
              clearable
              multiple
            >
              <el-option
                v-for="item in abilityList"
                :key="item.code"
                :value="item.code"
                :label="item.code"
              >
                {{ item.code }}（{{ item.name }}）
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="config-footer">
      <el-button
        class="width-200"
        type="primary"
        :loading="loading"
        @click="toSubmit"
        >保存</el-button
      >
    </div>

    <import-file
      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 { mapState, mapMutations, mapActions } from "vuex";
import ImportFile from "@/components/ImportFile";
import {
  updatePaperStruct,
  paperStructExport,
  syncPaperStruct
} from "../../api";
import { downloadByApi } from "@/plugins/download";

export default {
  name: "blueprint-config",
  components: { ImportFile },
  data() {
    return {
      dataList: [],
      knowledgeList: [],
      abilityList: [],
      loading: false,
      updating: false,
      // upload
      uploadUrl: "/api/admin/grade/paper/struct/import",
      uploadData: {},
      downloading: false
    };
  },
  computed: {
    ...mapState("baseConfigs", ["dimensionList", "structList", "baseInfo"])
  },
  created() {
    this.initDimensions();
    this.initData();
  },
  methods: {
    ...mapMutations("baseConfigs", ["setBaseInfo"]),
    ...mapActions("baseConfigs", ["fetchStructList"]),
    initDimensions() {
      this.knowledgeList = this.dimensionList
        .filter(item => item.dimensionType === "KNOWLEDGE")
        .map(item => {
          return {
            name: item.nameSecond,
            code: item.codeSecond
          };
        });
      this.abilityList = this.dimensionList
        .filter(item => item.dimensionType === "ABILITY")
        .map(item => {
          return {
            name: item.namePrimary,
            code: item.codePrimary
          };
        });
    },
    initData() {
      const knowledgeCodes = this.knowledgeList.map(item => item.code);
      const abilityCodes = this.abilityList.map(item => item.code);
      this.dataList = this.structList.map(item => {
        let nitem = { ...item };
        let knowledgeDimension = (item.knowledgeDimension || "").split(",");
        if (knowledgeDimension.length) {
          knowledgeDimension = knowledgeDimension.filter(item =>
            knowledgeCodes.includes(item)
          );
        }
        nitem.knowledgeDimension = knowledgeDimension;

        let abilityDimension = (item.abilityDimension || "").split(",");
        if (abilityDimension.length) {
          abilityDimension = abilityDimension.filter(item =>
            abilityCodes.includes(item)
          );
        }
        nitem.abilityDimension = abilityDimension;

        return nitem;
      });
      this.uploadData = {
        paperNumber: this.baseInfo.paperNumber,
        paperType: this.baseInfo.paperType,
        paperName: this.baseInfo.paperName
      };
    },
    toImport() {
      this.$refs.ImportFile.open();
    },
    async toUpdateExamCloudStruct() {
      const confirm = await this.$confirm(
        `云阅卷试卷结构和本页面设置的试卷结构不一致，请重新设置，重新设置会清除该页面之前设置过的试卷结构参数！`,
        "提示",
        {
          type: "warning"
        }
      ).catch(() => {});
      if (confirm !== "confirm") return;

      if (this.updating) return;
      this.updating = true;

      const res = await syncPaperStruct({
        paperNumber: this.baseInfo.paperNumber,
        paperType: this.baseInfo.paperType
      }).catch(() => {});
      this.updating = false;
      if (!res) return;

      this.setBaseInfo({ ...this.baseInfo, structureChange: false });
      await this.fetchStructList();
      this.initData();
    },
    async downloadHandle() {
      if (this.downloading) return;
      this.downloading = true;

      const res = await downloadByApi(() => {
        let datas = {
          paperNumber: this.baseInfo.paperNumber,
          paperType: this.baseInfo.paperType
        };
        return paperStructExport(datas);
      }).catch(e => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    async fileUploaded() {
      this.$message.success("导入成功！");
      await this.fetchStructList();
      this.initData();
    },
    checkData() {
      let errMsg = [];
      const needCheckAbility = !!this.abilityList.length;
      this.dataList.forEach(item => {
        let names = [];
        if (!item.knowledgeDimension.length) names.push("知识模块");
        if (!item.abilityDimension.length && needCheckAbility)
          names.push("能力模块");

        if (names.length) {
          errMsg.push(
            `第${item.bigQuestionNumber}大题、第${
              item.smallQuestionNumber
            }小题${names.join("和")}未选择`
          );
        }
      });

      if (errMsg.length) {
        if (errMsg.length > 5) {
          this.$message.error("未选择模块的小题数过多！");
        } else {
          this.$message.error(errMsg.join("。"));
        }
        return false;
      }

      return true;
    },
    async toSubmit() {
      if (!this.checkData()) return;

      if (this.loading) return;
      this.loading = true;
      const datasource = this.dataList.map(item => {
        let nitem = { ...item };
        nitem.knowledgeDimension = item.knowledgeDimension.join();
        nitem.abilityDimension = item.abilityDimension.join();
        return nitem;
      });
      const datas = {
        datasource,
        paperNumber: this.baseInfo.paperNumber,
        paperName: this.baseInfo.paperName,
        paperType: this.baseInfo.paperType
      };
      let errorInfo = null;
      await updatePaperStruct(datas).catch(error => {
        errorInfo = error;
      });
      this.loading = false;
      if (errorInfo) {
        if (errorInfo.code == 5100003) {
          this.toUpdateExamCloudStruct();
          return;
        }
      } else {
        this.$message.success("保存成功！");
        this.$emit("modified");
      }
    }
  }
};
</script>
