<template>
  <el-dialog
    class="select-blue-dimension-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="id"
      :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 { courseTargetList } from "../../base/api";

export default {
  name: "select-blue-dimension-dialog",
  props: {
    selectedData: {
      type: Array,
      default() {
        return [];
      },
    },
    course: {
      type: Object,
      default() {
        return {
          examId: "",
          courseCode: "",
        };
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  watch: {
    course: {
      immediate: true,
      handler(val, oldVal) {
        if (!val) return;
        if (val !== oldVal) this.getTree();
      },
    },
  },
  methods: {
    async getTree() {
      const data = await courseTargetList({
        examId: this.course.examId,
        courseCode: this.course.courseCode,
      });
      this.treeData = (data || []).map((item) => {
        return {
          id: item.id,
          name: item.targetName,
          children: item.dimensionList,
        };
      });
    },
    visibleChange() {
      this.$refs.treeRef.setCheckedKeys(this.selectedData);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    submit() {
      const selectedNodes = this.$refs.treeRef.getCheckedNodes(false, true);

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

      const targetNodes = selectedNodes.filter(
        (item) => item.children && item.children.length
      );
      if (targetNodes.length > 1) {
        this.$message.error("只能选择一个课程目标的知识点");
        return;
      }

      const dimensionIds = selectedNodes
        .filter((item) => !item.children)
        .map((item) => item.id);

      this.$emit(
        "confirm",
        targetNodes.map((item) => {
          return {
            targetId: item.id,
            targetName: item.name,
            dimensionList: item.children
              .filter((ditem) => dimensionIds.includes(ditem.id))
              .map((dimension) => {
                return {
                  dimensionId: dimension.id,
                  dimensionCode: dimension.code,
                  dimensionName: dimension.name,
                };
              }),
          };
        })
      );
      this.cancel();
    },
  },
};
</script>
