<template>
  <div class="permission-user-wrap">
    <div class="permission-tree-wrap" :class="permissionList.length ? 'pd' : ''">
      <Tree :data="treeData" show-checkbox multiple check-strictly @on-check-change="checkChange"></Tree>
      <div class="action-btn" @click="editPermission" v-if="roleId && !disabled">
        <Icon type="ios-add-circle-outline" size="18" />确定修改
      </div>
      <Spin size="large" fix v-if="loading"></Spin>
    </div>
    <div class="user-list" v-if="roleUsers.length">
      <div class="user-item" v-for="(item, index) in roleUsers" :key="index">
        <Avatar size="small" :icon="item.headimgurl ? '' : 'ios-person'" :src="item.headimgurl" /><span class="name">{{item.userName}}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { deepCopy } from '../../utils/assist'
import role from '../../apis/role'
import collect from '../../utils/collect'

export default {
  props: {
    permissionList: Array,
    sysId: String,
    roleId: String
  },
  data () {
    return {
      treeData: [],
      selectedIdList: [], // 选择的权限id
      roleUsers: [], // 该角色下的用户
      disabled: false,
      loading: false
    }
  },
  created () {
  },
  methods: {
    async getPermissions () {
      try {
        this.loading = true
        let res = await role.roleDetail(this.roleId)
        let { disabled, permissions, roleUsers = [] } = res.data
        this.selectedIdList = permissions
        this.disabled = disabled
        this.roleUsers = roleUsers
        this.treeData = deepCopy(this.permissionList)
        this.calTreeData(this.treeData)
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    calTreeData (list) {
      list.forEach(item => {
        item.title = item.name
        this.$set(item, 'disabled', this.disabled)
        this.$set(item, 'expand', true)
        this.$set(item, 'checked', this.selectedIdList.includes(item.id))
        item.children && this.calTreeData(item.children)
      })
    },
    emptyPermission () {
      this.treeData = deepCopy(this.permissionList)
      this.selectedIdList = []
      this.roleUsers = []
      this.calTreeData(this.treeData)
    },
    async editPermission () {
      try {
        this.loading = true
        await role.editPermission(this.sysId, this.roleId, this.selectedIdList)
        this.$Message.success('修改成功')
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    checkChange (checkedArr) {
      this.selectedIdList = collect.getValueList(checkedArr, 'id')
    }
  }
}
</script>