<template>
  <div class="dimension-knowledge-list">
    <div v-if="!viewMode" class="mb-4 box-justify">
      <el-button type="success" @click="toImport">导入</el-button>
      <el-button type="primary" @click="toAdd">新增</el-button>
    </div>

    <div class="part-box part-box-border-bold dimension-table">
      <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="namePrimary" label="一级知识维度">
        </el-table-column>
        <el-table-column prop="codePrimary" label="一级维度编号" width="110">
        </el-table-column>
        <el-table-column prop="nameSecond" label="二级知识维度">
        </el-table-column>
        <el-table-column prop="codeSecond" label="二级维度编号" width="110">
        </el-table-column>
        <el-table-column prop="interpretation" label="一级维度术语解释">
        </el-table-column>
        <el-table-column
          v-if="!viewMode"
          class-name="action-column"
          label="操作"
          width="180px"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              class="btn-danger"
              type="text"
              :disabled="loading"
              @click="toDelete(scope)"
              >删除</el-button
            >
            <el-button
              class="btn-primary"
              type="text"
              :disabled="loading || scope.row.secondInd === 1"
              @click="toUp(scope)"
              >上移</el-button
            >
            <el-button
              class="btn-primary"
              type="text"
              :disabled="loading || scope.row.isLastSec"
              @click="toDown(scope)"
              >下移</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <import-file
      v-if="!viewMode"
      ref="ImportFile"
      title="上传文件"
      :upload-url="uploadUrl"
      :upload-data="uploadData"
      :download-handle="downloadHandle"
      download-filename="知识维度模板"
      :format="['xls', 'xlsx']"
      @upload-success="fileUploaded"
    >
    </import-file>
    <!-- ModifyKnowledgeDim -->
    <modify-knowledge-dim
      v-if="!viewMode"
      ref="ModifyKnowledgeDim"
      :instance="curRow"
      @modified="modified"
    ></modify-knowledge-dim>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import ImportFile from "@/components/ImportFile";
import ModifyKnowledgeDim from "./ModifyKnowledgeDim.vue";
import { paperDimensionExport } from "../../api";
import { downloadByApi } from "@/plugins/download";

export default {
  name: "dimension-knowledge-list",
  components: { ImportFile, ModifyKnowledgeDim },
  data() {
    return {
      dataList: [],
      curRow: {},
      loading: false,
      structSelectedDimension: [],
      // upload
      uploadUrl: "/api/admin/grade/paper/dimension/import",
      uploadData: {},
      downloading: false,
    };
  },
  computed: {
    ...mapState("baseConfigs", [
      "dimensionList",
      "structList",
      "baseInfo",
      "viewMode",
    ]),
  },
  mounted() {
    this.initStructSelectedDimension();
    this.initData();
  },
  methods: {
    ...mapMutations("baseConfigs", ["setDimensionList"]),
    ...mapActions("baseConfigs", ["fetchDimensionList"]),
    initStructSelectedDimension() {
      const dimensions = this.structList.map((item) => item.knowledgeDimension);
      if (!dimensions.length) return;

      const dimSet = new Set(dimensions.join().split(","));
      this.structSelectedDimension = Array.from(dimSet);
    },
    initData() {
      this.dataList = this.dimensionList
        .filter((item) => item.dimensionType === "KNOWLEDGE")
        .map((item) => {
          return {
            ...item,
            secondInd: item.codeSecond.substring(1) * 1,
            isLastSec: false,
            id: this.$randomCode(),
          };
        });
      this.sortDataList();
      this.uploadData = {
        examId: this.baseInfo.examId,
        paperNumber: this.baseInfo.paperNumber,
        paperType: this.baseInfo.paperType,
        paperName: this.baseInfo.paperName,
        courseId: this.baseInfo.courseId,
        dimensionType: "KNOWLEDGE",
      };
    },
    toImport() {
      this.$refs.ImportFile.open();
    },
    async downloadHandle() {
      if (this.downloading) return;
      this.downloading = true;

      const res = await downloadByApi(() => {
        return paperDimensionExport({
          courseId: this.baseInfo.courseId,
          courseName: this.baseInfo.courseName,
          dimensionType: "KNOWLEDGE",
        });
      }).catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    async fileUploaded() {
      this.$message.success("导入成功！");
      await this.fetchDimensionList();
      this.initData();
    },
    modified(data) {
      const priDims = this.dataList.filter(
        (item) => item.codePrimary === data.codePrimary
      );
      if (data.id) {
        const pos = this.dataList.findIndex((item) => item.id === data.id);
        this.dataList.splice(pos, 1, data);
      } else {
        if (!data.interpretation)
          data.interpretation = priDims[0] && priDims[0].interpretation;

        this.dataList.push({
          ...data,
          id: this.$randomCode(),
        });
      }

      priDims.map((item) => {
        item.namePrimary = data.namePrimary;
        item.interpretation = data.interpretation;
      });
      this.sortDataList();
      this.updateChange();
    },
    sortDataList() {
      if (!this.dataList.length) return;
      this.dataList.sort((a, b) => {
        if (a.codePrimary < b.codePrimary) return -1;
        if (a.codePrimary > b.codePrimary) return 1;

        return a.secondInd < b.secondInd ? -1 : 1;
      });
      this.dataList.forEach((item, index) => {
        const nextItem = this.dataList[index + 1];
        item.isLastSec = nextItem && nextItem.codePrimary !== item.codePrimary;
      });
      this.dataList[this.dataList.length - 1].isLastSec = true;
    },
    toAdd() {
      this.curRow = {
        courseId: this.baseInfo.courseId,
        courseCode: this.baseInfo.courseCode,
        courseName: this.baseInfo.courseName,
      };
      this.$refs.ModifyKnowledgeDim.open();
    },
    toEdit(row) {
      this.curRow = row;
      this.$refs.ModifyKnowledgeDim.open();
    },
    toDelete({ row, $index }) {
      if (this.structSelectedDimension.includes(row.codeSecond)) {
        this.$message.error("蓝图中已选择当前维度，禁止删除！");
        return;
      }
      this.dataList.splice($index, 1);
      this.sortDataList();
      this.updateChange();
    },
    toUp({ row, $index }) {
      const pos = $index;
      const rowSecondInd = row.secondInd;
      const rowFirstCode = row.codePrimary;
      this.dataList.splice(pos, 1);
      this.dataList.splice(pos - 1, 0, row);
      this.dataList[pos - 1].secondInd = rowSecondInd - 1;
      this.dataList[pos - 1].codeSecond = `${rowFirstCode}${rowSecondInd - 1}`;
      this.dataList[pos].secondInd = rowSecondInd;
      this.dataList[pos].codeSecond = `${rowFirstCode}${rowSecondInd}`;
      this.sortDataList();
      this.updateChange();
    },
    toDown({ row, $index }) {
      const pos = $index;
      const rowSecondInd = row.secondInd;
      const rowFirstCode = row.codePrimary;
      this.dataList.splice(pos, 1);
      this.dataList.splice(pos + 1, 0, row);
      this.dataList[pos + 1].secondInd = rowSecondInd + 1;
      this.dataList[pos + 1].codeSecond = `${rowFirstCode}${rowSecondInd + 1}`;
      this.dataList[pos].secondInd = rowSecondInd;
      this.dataList[pos].codeSecond = `${rowFirstCode}${rowSecondInd}`;
      this.sortDataList();
      this.updateChange();
    },
    updateChange() {
      const abilityList = this.dimensionList.filter(
        (item) => item.dimensionType === "ABILITY"
      );
      this.setDimensionList([...this.dataList, ...abilityList]);
    },
  },
};
</script>
