<template>
  <div>
    <el-tree
      :data="menuList"
      show-checkbox
      default-expand-all
      node-key="permissionId"
      ref="tree"
      highlight-current
      :props="defaultProps"
    >
    </el-tree>
  </div>
</template>

<script>
import { getAllMenu } from "@/api/system.js";
import { checkListFn, getcheckListFn } from "@/utils/getMenu.js";

export default {
  props: {
    treeObj: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      menuList: [],
      defaultProps: {
        children: "children",
        label: "permissionName",
      },
    };
  },
  watch: {
    treeObj: {
      handler(newVal) {
        this.updateTreeCheckState(newVal.checkList);
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.getMenuList();
  },
  mounted() {
    this.updateTreeCheckState(this.treeObj.checkList);
  },
  methods: {
    getMenuList() {
      getAllMenu().then((res) => {
        this.menuList = res.data;
      });
    },
    getCheckTreeKey() {
      const result = getcheckListFn(
        this.$refs.tree.getCheckedKeys(),
        this.menuList
      );
      return {
        permissionIds: [...new Set(result)].join(","),
        roleId: this.treeObj.roleId,
      };
    },
    updateTreeCheckState(checkList) {
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedKeys(checkListFn(checkList));
      }
    },
  },
};
</script>

<style scoped lang="scss">
.el-tree {
  height: 300px;
  overflow: hidden;
  overflow-y: auto;
}
</style>
