<template>
  <Tree
    ref="menuTree"
    class="menu-tree"
    style="margin-top: -8px;"
    v-bind="$attrs"
    :data="menuTree"
    v-on="$listeners"
  ></Tree>
</template>
<script>
import { QueryMenus } from '../server.js';
import Three from '../../util/getThree.js';
export default {
  props: {
    roleId: {
      type: String,
      default: null
    },
    onlyMenu: {
      type: Boolean,
      default: false
    },
    delItem: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      defaultTree: [{
        title: this.$t('菜单树'),
        menuId: '0',
        menuCode: '0',
        menuName: this.$t('菜单树'),
        sort: '0',
        menuType: '1',
        expand: true,
        children: [] // 后台调取的树中的data放在这里
      }],
      menuTree: [],
      treeData: null,
      backup: null,
      filterList: [],
      filterIdList: {},
      paramsData: {
        menuType: this.onlyMenu ? '1' : ''
      }
    };
  },
  created() {
    this.menuTree = JSON.parse(JSON.stringify(this.defaultTree));
    this.search();
  },
  methods: {
    search(param = {}, menuId) {
      if (this.roleId || this.roleId === '') {
        param = {
          roleId: this.roleId
        };
      }
      this.param = param;
      QueryMenus({
        ...param,
        ...this.paramsData,
        commonPageDTO: {
          currentPage: 1,
          pageSize: 100000
        }
      }).then(res => {
        this.$emit('searchFinish');
        let selected = [];
        let checked = [];
        let menuList = [];
        if (this.roleId || this.roleId === '') {
          checked = res.dataResult.menuChoiceList.map(item => item.menuId);
          menuList = res.dataResult.menuList;
        } else {
          menuId && (selected = [menuId]);
          menuList = res.dataResult.recordList;
        }
        if (this.onlyMenu) {
          // 只取类型为目录的
          menuList = menuList.filter(item => item.menuType === '1');
        }
        const tree = new Three(menuList, {
          sort: true,
          setParent: true,
          selected,
          checked,
          delItem: this.delItem,
          noExpand: !(param.menuCode || param.menuName || param.actionUrl)
        });
        const menuTree = JSON.parse(JSON.stringify(this.defaultTree));
        menuTree[0].children = tree.json;
        // 当menuId有传入但是为空 为菜单树添加选中
        if (menuId === '') {
          menuTree[0].selected = true;
        }
        this.menuTree = menuTree;
      }).catch(() => this.$emit('searchFinish'));
    },
    getSelectedNodes() {
      return this.$refs.menuTree.getSelectedNodes();
    },
    getCheckedNodes() {
      return this.$refs.menuTree.getCheckedNodes();
    },
    reload(menuId) {
      this.search(this.param, menuId);
    }
  }
};

</script>
<style lang="less">
.menu-tree {
  .ivu-tree-arrow-disabled + .ivu-tree-title {
    color: #c5c8ce;
    cursor: not-allowed;
    &:hover {
      background-color: #fff;
    }
  }
}
</style>
