<template>
  <div class="dimension-config">
    <div class="mb-4 tab-btns">
      <el-button
        v-for="tab in tabs"
        :key="tab.val"
        size="medium"
        :type="curTab == tab.val ? 'primary' : 'default'"
        @click="selectMenu(tab.val)"
        >{{ tab.name }}
      </el-button>
    </div>

    <component :is="compName"></component>

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

<script>
import { mapState } from "vuex";
import DimensionKnowledgeList from "./DimensionKnowledgeList.vue";
import DimensionAbilityList from "./DimensionAbilityList.vue";
import { updatePaperDimension } from "../../api";

export default {
  name: "dimension-config",
  components: { DimensionKnowledgeList, DimensionAbilityList },
  data() {
    return {
      curTab: "knowledge",
      tabs: [
        {
          name: "知识维度",
          val: "knowledge",
        },
        {
          name: "能力维度",
          val: "ability",
        },
      ],
      loading: false,
    };
  },
  computed: {
    ...mapState("baseConfigs", ["dimensionList", "baseInfo", "viewMode"]),
    compName() {
      return `dimension-${this.curTab}-list`;
    },
  },
  methods: {
    selectMenu(tab) {
      this.curTab = tab;
    },
    async toSubmit() {
      if (this.loading) return;
      this.loading = true;

      const defData = {
        examId: this.baseInfo.examId,
        paperNumber: this.baseInfo.paperNumber,
        paperName: this.baseInfo.paperName,
        paperType: this.baseInfo.paperType,
      };
      const knowledgeList = this.dimensionList.filter(
        (item) => item.dimensionType === "KNOWLEDGE"
      );
      if (!knowledgeList.length) {
        this.$message.error("请设置知识维度");
        this.loading = false;
        return;
      }

      const abilityList = this.dimensionList.filter(
        (item) => item.dimensionType === "ABILITY"
      );
      if (!abilityList.length) {
        const confirm = await this.$confirm(
          `能力维度未设置，确定要提交吗?`,
          "提示",
          {
            type: "warning",
          }
        ).catch(() => {});
        if (confirm !== "confirm") {
          this.loading = false;
          return;
        }
      }

      const funcs = [
        updatePaperDimension({
          ...defData,
          datasource: knowledgeList,
          dimensionType: "KNOWLEDGE",
        }),
        updatePaperDimension({
          ...defData,
          datasource: abilityList,
          dimensionType: "ABILITY",
        }),
      ];

      const res = await Promise.all(funcs).catch(() => {});
      this.loading = false;

      if (!res) return;
      this.$message.success("保存成功！");
      this.$emit("modified");
    },
  },
};
</script>
