<template>
  <el-dialog
    class="select-user-dialog"
    :visible.sync="modalIsShow"
    title="选择知识点"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <el-tree
      ref="treeRef"
      :data="treeData"
      show-checkbox
      check-on-click-node
      node-key="dimensionId"
      :props="defaultProps"
    >
    </el-tree>

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

<script>
import { courseDimensionTree } from "../../api";

export default {
  name: "select-dimension-dialog",
  props: {
    selectedData: {
      type: Array,
      default() {
        return [];
      },
    },
    courseCode: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      modalIsShow: false,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "dimensionName",
      },
    };
  },
  watch: {
    courseCode: {
      immediate: true,
      handler(val, oldVal) {
        if (!val) return;
        if (val !== oldVal) this.getTree();
      },
    },
  },
  methods: {
    async getTree() {
      const data = await courseDimensionTree(this.courseCode);
      this.treeData = data || [];
    },
    visibleChange() {
      this.$refs.treeRef.setCheckedKeys(this.selectedData);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    submit() {
      const selectedNodes = this.$refs.treeRef.setCheckedNodes();

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

      this.$emit(
        "confirm",
        selectedNodes.map((item) => {
          return {
            dimensionId: item.dimensionId,
            dimensionCode: item.dimensionCode,
            dimensionName: item.dimensionName,
          };
        })
      );
      this.cancel();
    },
  },
};
</script>
