<template>
  <div>
    <el-dialog
      class="select-dimension-dialog page-dialog"
      :visible.sync="modalIsShow"
      title="选择知识点"
      top="10px"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @opened="visibleChange"
    >
      <div class="box-justify mb-2">
        <div></div>
        <el-button type="success" @click="toImport">导入课程知识点</el-button>
      </div>
      <div class="part-box part-box-pad mb-0">
        <el-tree
          ref="treeRef"
          :key="treeKey"
          :data="treeData"
          show-checkbox
          check-on-click-node
          check-strictly
          :expand-on-click-node="false"
          node-key="id"
          default-expand-all
          :props="defaultProps"
        >
        </el-tree>
      </div>

      <div slot="footer">
        <el-button type="primary" @click="submit">确认</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- ImportFile -->
    <import-file
      ref="ImportFile"
      title="导入课程知识点"
      :upload-url="uploadUrl"
      :upload-data="{
        teachCourseId: course.teachCourseId,
      }"
      :format="['xls', 'xlsx']"
      :download-handle="() => downloadTemplate('courseProperty')"
      :download-filename="dfilename"
      :auto-upload="false"
      @upload-success="dimensionUploaded"
    ></import-file>
  </div>
</template>

<script>
import { courseDimensionTree } from "../../api";
import ImportFile from "@/components/ImportFile.vue";
import templateDownload from "@/mixins/templateDownload";

export default {
  name: "select-dimension-dialog",
  components: { ImportFile },
  mixins: [templateDownload],
  props: {
    selectedData: {
      type: Array,
      default() {
        return [];
      },
    },
    disabledData: {
      type: Array,
      default() {
        return [];
      },
    },
    course: {
      type: Object,
      default() {
        return {
          teachCourseId: "",
        };
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      treeKey: "",
      // import
      uploadUrl: "/api/admin/teach/course_target/dimension_import",
      dfilename: "课程知识点导入模板.xlsx",
    };
  },
  watch: {
    "course.teachCourseId": {
      immediate: true,
      handler(val, oldVal) {
        if (val !== oldVal) {
          this.getTree();
        }
      },
    },
  },
  methods: {
    async dimensionUploaded() {
      const data = await courseDimensionTree({
        teachCourseId: this.course.teachCourseId,
      });
      this.treeData = data || [];

      // 已存在课程目标的情况，强制关闭弹窗
      if (this.disabledData.length) {
        this.modalIsShow = false;
        this.$emit("enforce-close");
        return;
      }

      this.$nextTick(() => {
        this.$refs.treeRef.setCheckedKeys([]);
      });
    },
    async getTree() {
      if (!this.course.teachCourseId) return;

      const data = await courseDimensionTree({
        teachCourseId: this.course.teachCourseId,
      });
      this.treeData = data || [];
      this.updateDisableNode();
    },
    updateDisableNode() {
      const mdTree = (list) => {
        list.forEach((item) => {
          item.disabled = this.disabledData.includes(item.id);
          if (item.children && item.children.length) mdTree(item.children);
        });
      };
      mdTree(this.treeData);
      this.treeKey = this.$randomCode();
    },
    toImport() {
      this.$refs.ImportFile.open();
    },
    visibleChange() {
      this.updateDisableNode();

      this.$nextTick(() => {
        this.$refs.treeRef.setCheckedKeys(this.selectedData);
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    submit() {
      const selectedNodes = this.$refs.treeRef.getCheckedNodes();

      if (!selectedNodes.length) {
        this.$message.error("请选择知识点");
        return;
      }

      this.$emit(
        "confirm",
        selectedNodes.map((item) => {
          return {
            id: item.id,
            name: item.name,
            code: item.code,
          };
        })
      );
      this.cancel();
    },
  },
};
</script>
