<template>
    <Tree :data="treeData" show-checkbox ref="Tree"></Tree>
</template>

<script>
import { getCompanyUserMenuList, getRoleMenuList } from '../../../../../api/system/system'

export default {
  name: 'addRoleMenu',
  data () {
    return {
      treeData: [],
      ajaxTreeData: []
    }
  },
  props: {
    roleId: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  methods: {
    getMenuListData () {
      getCompanyUserMenuList().then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.ajaxTreeData = data.data
        } else {
          this.$Message.error('获取授权菜单失败')
        }
      })
    },
    createNewTreeData (roleId) {
      getRoleMenuList(roleId).then(ret => {
        let result = ret.data
        if (result.errcode === 0) {
          this.filterTreeData(result.data)
        } else {
          this.$Message.error('请检查网络')
        }
      })
    },
    filterTreeData (menuIdsArr) {
      this.ajaxTreeData.forEach(item => {
        item.title = item.name
        item.parent_sort = item.sort
        item.expand = true
        item.render = (h, { root, node, data }) => {
          let color = 'red'
          if (data.type === '2') {
            color = 'green'
          }
          return h('span', {
            style: {
              color: color,
              width: '100%'
            }
          }, data.title)
        }
        if (this.$common.xeUtils.some(menuIdsArr, items => items.menu_id === item.id)) {
          item.checked = true
        } else {
          item.checked = false
        }
        // 公共接口中心默认选择
        if (item.id === 'd7e77d78-612b-11e7-8eaa-7cd30abda6a8' || item.id === '27' || item.id === '28') {
          item.checked = true
          item.disabled = true
        }
      })
      // 转换成树形数据
      let resultTreeData = this.$common.toTree(this.ajaxTreeData, 'children', 'id', 'parent_id')
      this.$common.xeUtils.eachTree(resultTreeData, item => {
        if (item.children && item.children.length > 0) {
          item.checked = false
        }
      })
      this.treeData = this.$common.xeUtils.clone(resultTreeData, true)
    },
    getTreeSelectNodes () {
      return this.$refs.Tree.getCheckedAndIndeterminateNodes()
    }
  },
  mounted () {
    this.getMenuListData()
  },
  watch: {
    roleId (id) {
      this.createNewTreeData(id)
    }
  }
}
</script>

<style scoped>

</style>
