<template>
<div class="v-component group-tree">
  <Tree :data="treeData" :load-data="loadChildData" show-checkbox check-strictly @on-check-change="checkChange"></Tree>
  <Spin size="large" fix v-if="loading"></Spin>
</div>
</template>

<script>
import org from '../../apis/org'
import { deepCopy } from '../../utils/assist'
export default {
  name: 'GroupTree',
  props: {
    value: Array
  },
  data () {
    return {
      currentValue: [],
      originTreeData: [],
      treeData: [],
      loading: false,
      noDataRender: (h, { root, node, data }) => {
        return h('span', { class: 'gray' }, '暂无子级')
      }
    }
  },
  watch: {
    value (val) {
      this.currentValue = val
      this.changeTreeChecked(this.treeData)
    },
    currentValue (val) {
      this.$emit('input', val)
    }
  },
  methods: {
    async getTreeData () {
      try {
        this.loading = true
        let res = await org.getOrg()
        this.originTreeData = res.data
        this.treeData = deepCopy(this.originTreeData)
        this.calTreeData(this.treeData, true)
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    async loadChildData (item, callback) {
      let res = await org.getOrg(item.orgId)
      let childData = []
      if (res.data.length) {
        childData = deepCopy(res.data)
        this.calTreeData(childData)
      } else {
        childData = [{
          disableCheckbox: true,
          render: this.noDataRender
        }]
      }
      callback(childData)
    },
    calTreeData (list, isRoot = false) {
      list.forEach(item => {
        item.title = item.orgName
        this.$set(item, 'disabled', isRoot)
        this.$set(item, 'expand', isRoot)
        this.$set(item, 'checked', this.currentValue.includes(item.orgId))
        this.$set(item, 'loading', false)
        item.children && this.calTreeData(item.children)
      })
    },
    changeTreeChecked (list) {
      list.forEach(item => {
        this.$set(item, 'checked', this.currentValue.includes(item.orgId))
        item.children && this.changeTreeChecked(item.children)
      })
    },
    checkChange (checkedArr) {
      this.currentValue = checkedArr.map(item => item.orgId)
    }
  }
}
</script>