<template>
    <div>
        <Card>
            <p slot="title">机构列表</p>
            <Spin fix v-if="treeLoading"></Spin>
            <Tree :data="treeData" @on-select-change="selectAction"></Tree>
        </Card>
    </div>
</template>

<script>
import {
  getList
} from '../../../../../api/system/system'

export default {
  name: 'TreeList',
  props: {},
  data () {
    return {
      treeLoading: false,
      treeData: [],
      currentId: '',
      currentName: ''
    }
  },
  watch: {
  },
  methods: {
    success () {
      this.$Message.success('操作成功')
    },
    error (data) {
      this.$Message.error({
        content: '操作失败,\n' + data.errmsg
      })
    },
    init () {
      this.treeLoading = true
      getList().then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          data.data.forEach(item => {
            item.title = item.name
          })
          this.treeData = this.$common.xeUtils.clone(this.$common.toTree(data.data, 'children', 'id', 'parent_id'), true)
          // 获取当前树形结构后的第一个父节点后执行默认显示操作
          this.selectAction(this.treeData)
          this.treeLoading = false
        } else {
          this.treeLoading = false
          this.error(data)
        }
      })
    },
    selectAction (val) {
      // console.log('treeClick', val)
      this.currentId = val.length > 0 ? val[0].id : ''
      this.currentName = val.length > 0 ? val[0].name : ''
      if (val.length > 0) {
        this.$emit('change', this.currentId, this.currentName)
      }
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style scoped>
</style>
