<style lang="less" scoped>
.div_dept {
  overflow: auto;
  width: 100%;
  height: 100%;
  background-color: #fff;
  border-radius: 4px;
  font-size: 13px;
}
</style>
<template>
  <div class="div_dept">
    <Tree
      ref="_tree"
      :data="treeData"
      :load-data="loadData"
      @on-select-change="onSelected"
    />
  </div>
</template>
<script>
import baseDataMixin from '../util/baseDataMixin'
export default {
  mixins: [baseDataMixin],
  data() {
    return {
      innerValue: [],
      treeData: [],
      allOrgTreeNode: [],
      allDeptNode: [],
      currSelectItem: null, // 记录当前选中项node信息
      currLoadNode: {}, // 当前加载的节点,
      treeDataMap: {} //由于基础数据过滤需求，使用list接口懒加载时接口无法返回被过滤节点的父节点且后端不改，只能首次加载整棵树但节点分多次渲染,且可以接受全部加载带来的性能问题
    }
  },
  props: {
    primaryKey: {
      type: String,
      require: true,
    },
    selectedId: {
      type: Array,
      default: () => [],
    },
    /**
     * 指定根节点id，可为空
     */
    rootId: {
      type: String,
    },
    /**
     * 指定根节点的数据类型， 可为空
     */
    rootType: {
      type: String,
    },
    filterList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    // 是否需要前端过滤树节点
    isFilterTree() {
      return this.structtype !== 1 && this.structtype !== -1 && this.isFilter
    }
  },
  watch: {
    selectedId: {
      handler: function (newVal) {
        this.initInnerValue(newVal)
      },
      deep: true,
    },
    filterList: {
      handler: function(nv) {
          this.getBaseDataList()
      },
      deep: true
    }
  },
  mounted() {
    this.getBaseDataList()
  },
  methods: {
    async getBaseDataList() {
      if (this.isOrg) {
        let param = {
          pagination: false,
          parentcode: '-',
          queryDataStructure: 'ALL',
        }
        let result = await this.getOrg(param)
        this.treeData = this.formateTree(result)
      } else {
        // 修改list接口为tree接口
        const getTreeDataMap = (nodes) => {
          nodes.forEach(node => {
            this.treeDataMap[node.id] = node.children? node.children: []
            if (node.children) {
              getTreeDataMap(node.children)
            }
          })
        }
        
        const postData = {
          tableName: this.tableName,
          queryDataStructure: 'ALL',
          authType: this.authType,
          versionDate: this.versionDate,
          expression: this.filterFormular,
          'BI-SYNTAX': null
        }
        if (this.structtype === 1) {
          if (this.groupTableName.define.showFields) {
            const relevance = this.groupTableName.define.showFields.find(item => item.columnName === this.groupTableName.groupFieldName)
            let relevanceField = ''
            if (relevance) {
              relevanceField = relevance.mapping? relevance.mapping.split('.')[0]: ''
              postData.tableName = relevanceField
            }
          }
        }
        const { data } = await this.getBaseData(postData, '/baseData/data/tree')
        getTreeDataMap(data.rows)
        this.$emit('init-tree', this.treeDataMap, this.groupTableName.groupFieldName)

        // 默认展开根节点
        const sonCodes = this.filterList.map(item => item.parents.split('/')[0])
        const formateRootNode = (nodes) => {
          let node = nodes[0]
          node.expand = true
          node.title = node.name || node.text
          node.loading = false
          node.code = node.code || node.id
          if (node.children) {
            let nodeChildren = []
            if (this.isFilterTree) {
              nodeChildren = node.children.filter(item => sonCodes.indexOf(item.id) !== -1)
            } else {
              nodeChildren = node.children
            }
            node.children = nodeChildren.map(item => {
              if (item.hasChildren) {
                item.children = []
                item.loading = false
              }
              item.title = item.name || item.text
              item.code = item.code || item.id
              return item
            })
          }
          return [node]
        }
        this.treeData = formateRootNode(data.rows)
      }

      let data = this.treeData
      this.emitSelectEvent('on-select', data.length > 0? data[0]: {})
    },
    formateTree(data) {
      return data.map((item) => {
        item.children = []
        item.title = item.name || item.text
        item.loading = false
        item.code = item.code || item.id
        return item
      })
    },

    initInnerValue(val) {
      // 这里是按多选逻辑处理的，但目前这里只会有单选，不会有多选
      let id = ''
      if (val) {
        this.innerValue = Array.isArray(val) ? val : [val]
        id = val
      } else {
        this.innerValue = []
      }
      if (!this.currSelectItem || this.currSelectItem[this.primaryKey] != id) {
        this.setInitSelectedSelectionState(id)
      }
      if (0 == this.innerValue.length) {
        this.currSelectItem = null
      }
    },
    setInitSelectedSelectionState(id) {
      let tree = this.$refs['_tree'] ? this.$refs['_tree'].stateTree : undefined
      if (!tree || tree.length == 0) {
        return
      }
      tree.map((node) => {
        let equal = this.isEqual(node, id)
        node.selected = equal
        if (equal) {
          this.updateNodeSelectionState(node)
        }
        if (node.children && node.children.length > 0) {
          this.updateTreeSelectionState(node.children, id)
        }
      })
    },
    isEqual(node, id) {
      return node[this.primaryKey] == id
    },
    setDefaultSelectStatus() {
      let node =
        this.treeData && this.treeData.length > 0 ? this.treeData[0] : null
      if (node && this.selectedId.length == 0) {
        this.updateNodeSelectionState(node)
        this.emitSelectEvent('on-select', node)
      }
    },
    async loadData(item, callback) {
      this.currLoadNode = item
      if (this.isOrg) {
        let param = {
          pagination: false,
          parentcode: this.currLoadNode.code,
          queryDataStructure: 'ALL',
        }
        let result = await this.getOrg(param)
        let arr = this.formateTree(result)
        callback(arr)
      } else {
        // list接口更改为tree
        let resultNodes = []
        let nodes = this.formateTree(this.treeDataMap[item.id])
        if (this.isFilterTree) {
          nodes = nodes.filter(one => typeof this.filterList.find(x => x.code === one.id) === 'object')
        }
        resultNodes = nodes.map(one => {
          if (one.hasChildren === false) {
            delete one.loading
          }
          return one
        })
        callback(resultNodes)
      }
    },
    /**
     * 更新当前选中节点的下级节点
     */
    updateCurrSelectionSubNodes(nodes) {
      if (this.selectedId.length > 0) {
        nodes.map((value) => {
          let find = false
          this.selectedId.map((id) => {
            find = id == value[this.primaryKey]
          })
          if (find) {
            this.updateNodeSelectionState(value)
            return
          }
        })
      }
    },

    onSelected(node, data) {

      if (
        !this.currSelectItem ||
        this.currSelectItem[this.primaryKey] != data[this.primaryKey]
      ) {
        this.updateNodeSelectionState(data)
        this.emitSelectEvent('on-select', data)
      }
    },
    emitSelectEvent(eventName, node) {
      this.$emit(eventName, node[this.primaryKey], node)
    },
    updateNodeSelectionState(item) {
      if (this.currSelectItem) {
        this.$set(this.currSelectItem, 'selected', false)
      }
      this.currSelectItem = item
      if (item) {
        this.$set(this.currSelectItem, 'selected', true)
      }
    },
   
  },
}
</script>