<template>
  <div class='grant-tree-box'>
    <el-tree
      ref='grantMenuTree'
      show-checkbox
      node-key='id'
      :props='treeProps'
      :data='treeData'
      :expand-on-click-node='false'
      :default-checked-keys='defaultCheckedKeys'
      @check='handleNodeCheck'
    ></el-tree>
  </div>
</template>

<script>
import { loadTree, loadTreeSelected, createAuthDepartment } from '@api/upms/api-data-scope';

export default {
  name: 'RoleScope',
  components: {},
  props: {
    roleId: {
      type: String,
      default: '0'
    }
  },
  data() {
    return {
      bodyStyle: {
        height: '420px',
        padding: '8px'
      },
      treeProps: {
        label: 'title',
        children: 'children'
      },
      menuTitle: '',
      treeData: [],
      defaultCheckedKeys: [],
      grantPermissions: [],
      permissions: [],
      selectedPermissions: [],
      oldPermissions: [],
      selectedMenuId: 0
    };
  },
  methods: {
    initSelectedDepartment() {
      let vm = this;
      let params = {
        roleId: vm.roleId
      };
      loadTreeSelected(params).then(
        (res) => {
          vm.defaultCheckedKeys = res.data;
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    loadTreeData() {
      let vm = this;
      loadTree().then(
        (res) => {
          vm.treeData = res.data;
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    async handleNodeCheck(data, nodeData) {
      let vm = this;
      const checkArr = vm.$refs.grantMenuTree.getCheckedNodes(false, false);
      let arr = [];
      checkArr.forEach(item => {
        arr.push(item.id);
      });
      await createAuthDepartment({ roleId: vm.roleId, departmentIds: arr });
      vm.initSelectedDepartment();
      vm.permissions = [];
    }
  },
  mounted() {
    this.initSelectedDepartment();
  },
  created() {
    this.loadTreeData();
  }
};
</script>

<style scoped lang='less'>
.grant-text {
  font-size: 16px;
  margin-bottom: 5px;
}
</style>
