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

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

export default {
  name: 'addRoleMenu',
  data () {
    return {
      treeData: [],
      ajaxTreeData: []
    }
  },
  props: {
    roleId: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  methods: {
    getMenuListData () {
      getMenuList().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 => {
        if (item.parent) {
          item.parent_id = item.parent.id
          item.title = item.name
          item.parent_sort = item.parent.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
          }
        }
      })
      // 转换成树形数据
      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>
