<template>
  <el-tree
    class="multiselectTree"
    ref="treeNode"
    :data="treeData"
    :load="loadNode"
    lazy
    :props="defaultProps"
    :node-key="nodeKey"
    :default-expanded-keys="defaultExpandedKeys"
    :current-node-key="currentNodeKey"
    :default-expand-all="defaultExpandAll"
    :highlight-current="highlightCurrent"
    @node-click="handleNodeClick"
    :render-content="renderContent"
    >
  </el-tree>
</template>

<script>
  import Api from '@/api/index.js'

  export default{ 
    props: {
      treeData: { 
        type: Array,
        default: () => []
      },
      nodeKey: {
        type: String,
        default: 'id'
      },
      tab2Onoff: { 
        type: Boolean,
        default: false 
      },
      defaultProps: {
        type: Object,
        default: () => ({
          children: 'childrens',
          label: 'text',
          isLeaf: function (data, node) {
            // console.log(data)
          }
        })
      },
      editOnoff: { 
        type: Boolean,
        default: false  
      },
      defaultExpandedKeys: { 
        type: Array,
        default: () => []
      },
      defaultCheckedKeys: { 
        type: Array,
        default: () => []
      },
      defaultExpandAll: { 
        type: Boolean,
        default: false 
      },
      highlightCurrent: {
        type: Boolean,
        default: true
      }
    },
    data () { 
      return { 
        currentNodeKey: '', // 当前选中节点的 key -> string, number
        getCheckedKeys: [],
        id: ''
      }
    },
    watch: { 
      tab2Onoff (val) { 
        if (val) { 
          this.$refs['treeNode'].setCheckedKeys(this.getCheckedKeys)
        }
      },
      editOnoff (val) { 
        this.$refs['treeNode'].setCheckedKeys(this.defaultCheckedKeys)
      }
    },
    methods: {
      renderContent (createElement, {node, data, store}) {
        var self = this 
        return createElement('span', [
          createElement('span', {attrs: {
            style: 'width: 22px;height: 36px;float: left; margin: 0 4px 0 6px;font-size: 18px;'
          }}, [createElement('svg', {class: 'icon', attrs: {'aria-hidden': true, style: 'width: 22px;height: 36px;'}}, data.type === 'S' ? [createElement('use', {attrs: {'xlink:href': '#icon-fuwurizhi'}})] : [createElement('use', {attrs: {'xlink:href': '#icon-folderpaper'}})])]),
          createElement('span', {attrs: {
            style: 'float: left;font-size: 14px;'
          }}, node.label)
        ])
      },
      // 目录树
      getCatalogServiceTree (serviceId) { 
        this.isLoadingTree = true

        Api.getdirectoryAndServicesTree(serviceId).then(data => { 
          this.isLoadingTree = false
          if (data.status === 0) {
            this.treeData = data.data
          } else {
            this.$message({
              type: 'error',
              message: '获取数据失败！'
            })
          }
        }).catch(res => {
          this.isLoadingTree = false

          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        })
      }, 
      // 异步加载树
      loadNode (node, resolve) { // 加载节点
        let vm = this
        if (node.level === 0) { // 直接显示第一级菜单
          return false
        }
        let arr = []
        
        Api.getdirectoryAndServicesTree(node.data.id).then(data => {
          if (data.status === 0) {
            let body = data.data
            if (body instanceof Array) {
              if (body.length !== 0) {
                // console.log(body)
                body.forEach((item) => {
                  let leaf = true
                  if (item.isLeaf === false) {
                    leaf = false
                  }
                  arr.push({
                    id: item.id,
                    nameCn: item.nameCn,
                    nameEn: item.nameEn,
                    type: item.type,
                    isLeaf: leaf
                  })
                })
              } else {
                arr = []
                resolve([])
                return
              }
            } else {
              arr = []
            }

            // 加载下级
            let childData = (node.data.type === 'D') ? arr : []

            setTimeout(() => {
              resolve(childData)
            }, 300)
          } else {
            this.$message({
              type: 'error',
              message: '获取数据失败！'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        })
      },
      handleNodeClick (data) {
        this.$emit('node-click', data)
      }
    }
  }
</script>

<style lang="scss">
  .multiselectTree { 
    width: 360px;
    max-height: 360px;
    overflow-y: auto;
    float: left;
    margin-top: 10px;
  }
</style>
