<template>
  <div class="dimension-ability-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="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.$index === 0"
              @click="toUp(scope)"
              >上移</el-button
            >
            <el-button
              class="btn-primary"
              type="text"
              :disabled="loading || scope.$index === dataListLastInd"
              @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>
    <!-- ModifyAbilityDim -->
    <modify-ability-dim
      v-if="!viewMode"
      ref="ModifyAbilityDim"
      :instance="curRow"
      :dict-data="dataList"
      @modified="modified"
    ></modify-ability-dim>
  </div>
</template>

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

export default {
  name: "dimension-ability-list",
  components: { ImportFile, ModifyAbilityDim },
  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",
    ]),
    dataListLastInd() {
      return this.dataList.length - 1;
    },
  },
  mounted() {
    this.initStructSelectedDimension();
    this.initData();
  },
  methods: {
    ...mapMutations("baseConfigs", ["setDimensionList"]),
    ...mapActions("baseConfigs", ["fetchDimensionList"]),
    initStructSelectedDimension() {
      const dimensions = this.structList.map((item) => item.abilityDimension);
      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 === "ABILITY")
        .map((item) => {
          return { ...item, 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: "ABILITY",
      };
    },
    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: "ABILITY",
        });
      }).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) {
      if (data.id) {
        const pos = this.dataList.findIndex((item) => item.id === data.id);
        this.dataList.splice(pos, 1, data);
      } else {
        this.dataList.push({ ...data, id: this.$randomCode() });
      }
      this.sortDataList();
      this.updateChange();
    },
    sortDataList() {
      this.dataList.sort((a, b) => {
        return a.codePrimary < b.codePrimary ? -1 : 1;
      });
    },
    toAdd() {
      this.curRow = {
        courseId: this.baseInfo.courseId,
        courseName: this.baseInfo.courseName,
        courseCode: this.baseInfo.courseCode,
      };
      this.$refs.ModifyAbilityDim.open();
    },
    toEdit(row) {
      this.curRow = row;
      this.$refs.ModifyAbilityDim.open();
    },
    toDelete({ row, $index }) {
      if (this.structSelectedDimension.includes(row.codePrimary)) {
        this.$message.error("蓝图中已选择当前维度，禁止删除！");
        return;
      }
      this.dataList.splice($index, 1);
      this.updateChange();
    },
    toUp({ row, $index }) {
      const pos = $index;
      const curRowCode = row.codePrimary;
      const prevRowCode = this.dataList[$index - 1].codePrimary;
      this.dataList.splice(pos, 1);
      this.dataList.splice(pos - 1, 0, row);
      this.dataList[pos].codePrimary = curRowCode;
      this.dataList[pos - 1].codePrimary = prevRowCode;
      this.updateChange();
    },
    toDown({ row, $index }) {
      const pos = $index;
      const curRowCode = row.codePrimary;
      const nextRowCode = this.dataList[$index + 1].codePrimary;
      this.dataList.splice(pos, 1);
      this.dataList.splice(pos + 1, 0, row);
      this.dataList[pos].codePrimary = curRowCode;
      this.dataList[pos + 1].codePrimary = nextRowCode;
      this.updateChange();
    },
    updateChange() {
      const knowledgeList = this.dimensionList.filter(
        (item) => item.dimensionType === "KNOWLEDGE"
      );
      this.setDimensionList([...knowledgeList, ...this.dataList]);
    },
  },
};
</script>
