<!--
----------侧边企业树选择组件（新）
-->
<template>
  <div :class="showTree?'aside':'aside-hidden'">
    <el-input v-show="showTree" v-model.trim="searchText" placeholder="请输入" />
    <el-scrollbar v-show="showTree" class="scrollbar">
      <el-tree
        ref="selectTree"
        :data="companyList"
        highlight-current="true"
        node-key="sid"
        :default-expanded-keys="defaultExpandKeys"
        :default-expand-all="defaultExpand"
        :expand-on-click-node="false"
        :props="defaultProps"
        indent="10"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      >
        <span slot-scope="{ data, node }" class="custom-tree-node">
          <span :title="node.label" :class="data.type" v-html="getNodeText(node.label)" />
        </span>
      </el-tree>
    </el-scrollbar>
    <hamburger
      id="hamburger-container"
      :is-active="showTree"
      class="hamburger-container"
      @toggleClick="show"
    />
  </div>
</template>

<script>
import request from '@/utils/request'
import Hamburger from '@/components/Hamburger'
export default {
  components: {
    Hamburger
  },
  props: {
    // 是否需要过滤数据
    isFilter: {
      type: Boolean,
      default: false
    },
    // 与isFilter组合使用,isfilter为true时key和value都不可为空
    // key: 过滤属性名
    // value: 过滤属性值
    filterInfo: {
      type: Object,
      default: () => {
        return {
          key: '',
          value: ''
        }
      }
    },
    // 是否需要子节点id
    hasChildernIds: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defaultExpandKeys: [],
      defaultExpand: false,
      searchText: '',
      companyList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      selectNode: {},
      childrenIds: [],
      showTree: true
    }
  },
  watch: {
    searchText(val) {
      this.$refs.selectTree.filter(val)
    }
  },
  created() {
    this.getSelectNodeInfo()
    if (this.$store.state.parkTree.proTreeData.length) {
      this.dataInit(this.$store.state.parkTree.proTreeData)
    } else {
      this.getInfo()
    }
  },
  methods: {
    // 处理树（过滤掉子车场）
    filterTree(tree, arr = []) {
      if (!tree.length) return []
      for (const item of tree) {
        // 循环数组，然后过滤数据
        // 如果该条数据type不为0时，跳出本次循环
        if (item.type === 'park' && item.keyword != -1) continue
        // 如果是 E8，则再屏蔽人行
        if (item.type === 'person') continue
        // 如果满足条件时，用新node代替，然后把chilren清空
        const node = { ...item, children: [] }
        // 然后添加到新数组中
        arr.push(node)
        // 如果有子节点，调用递归函数，并把空数组传给下一个函数
        // 利用引用数据类型的特性，实现浅拷贝
        // 递归函数过滤时会改变这个空数组数据，从而实现层级结构过滤
        if (item.children && item.children.length) {
          this.filterTree(item.children, node.children)
        }
      }
      return arr
    },
    show() {
      this.showTree = !this.showTree
    },
    /**
     * 获取树形节点数据
     */
    getInfo() {
      request({
        url: '/fsuser/dataPermission/getEntProjectItemTree',
        method: 'get'
      }).then((res) => {
        if (res.success) {
          const list = this.filterTree(res.data)
          this.$store.commit('updateProTreeData', list)
          // debugger
          this.dataInit(this.$store.state.parkTree.proTreeData)
          this.$nextTick(() => { // 查询条件存在时无效bug
            this.searchText && this.$refs.selectTree.filter(this.searchText)
          })
        }
      })
    },
    dataInit(data) {
      data = data || []
      if (!data.length) return

      this.companyList = this.isFilter ? this.filterData(data) : data
      this.setChildIdsAndSid(this.companyList)

      let sid = ''
      if (this.selectNode && this.selectNode.type === 'ent' && this.isFilter || this.selectNode && this.selectNode.type === 'park' && !this.isFilter) {
        sid = this.selectNode.sid
        this.addNodeAll()
      } else if (this.isFilter) {
        sid = this.companyList[0].sid
        this.addNodeAll()
      } else {
        for (let i = 0; i < this.companyList.length; i++) {
          const arr = this.companyList[i].childrenIds.filter(item => item.type === 'park')
          if (arr.length) {
            sid = arr[0].sid
            break
          }
        }
      }

      // 设置选中项与展开项
      this.$nextTick(() => {
        this.$refs.selectTree.setCurrentKey(sid)
        this.defaultExpandKeys = [sid]
        const currentNode = this.$refs.selectTree.getCurrentNode()
        this.handleNodeClick(currentNode)
      })
    },
    addNodeAll() {
      if (this.isFilter) {
        const obj = {
          id: -1,
          name: '全部',
          type: 'all',
          sid: 'all',
          children: this.companyList
        }
        this.companyList = [obj]
      }
    },
    setChildIdsAndSid(treeData, pObj) {
      treeData && treeData.forEach(item => {
        // 节点设置sid（唯一值）
        item.sid = item.type + item.id
        if (this.hasChildernIds) {
          item['childrenIds'] = [{ id: item.id, type: item.type, sid: item.sid }]
        }
        if (item.children && item.children.length) {
          this.setChildIdsAndSid(item.children, item)
          if (pObj && this.hasChildernIds) {
            const arr = JSON.parse(JSON.stringify(item['childrenIds']))
            pObj['childrenIds'].push(...arr)
          }
        } else if (pObj && this.hasChildernIds) {
          pObj['childrenIds'].push({ id: item.id, type: item.type, sid: item.sid })
        }
      })
    },
    // 过滤节点
    filterData(treeData) {
      const tree = []
      treeData.forEach(item => {
        if (item[this.filterInfo.key] === this.filterInfo.value) {
          const obj = {
            id: item.id,
            name: item.name,
            type: item.type,
            children: []
          }
          obj.children = this.filterData(item.children)
          tree.push(obj)
        }
      })
      return tree
    },
    /**
     * 从localStorage中获取选择节点
     */
    getSelectNodeInfo() {
      const info = JSON.parse(localStorage.getItem('entProParkInfo'))
      if (info && info.id && info.type) {
        this.selectNode = info
      }
    },
    handleNodeClick(e) {
      const data = {
        id: e.id,
        name: e.name,
        type: e.type,
        sid: e.sid
      }
      if (this.hasChildernIds) {
        data['childrenIds'] = e.childrenIds
      }
      localStorage.setItem('entProParkInfo', JSON.stringify(data))
      this.$emit('changeTree', data)
    },
    filterNode(value, data) {
      if (!value) {
        return true
      }
      return data.name.indexOf(value) !== -1
    },
    /**
     * 关键字标红
     */
    getNodeText(value) {
      let textHtml = `<span>${value}</span>`
      textHtml = value.replace(
        this.searchText,
        `<span style="color:#FF891E;">${this.searchText}</span>`
      )
      return textHtml
    }
  }
}
</script>

 <style lang="scss" scoped>
.scrollbar {
  height: calc(100% - 50px);
  margin: 10px 0;
  width: 100%;
  overflow-y: auto;
  /deep/ .el-scrollbar__wrap {
    overflow-x: hidden;
    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
    }
    .is-current {
      position: relative;
      >.el-tree-node__content {
        background: #E6F7FF;
        overflow: hidden;
        color: #53AEFF;
        &::after {
          content: '';
          position: absolute;
          display: block;
          background: #1890FF;
          width: 4px;
          height: 26px;
          right: 0;
        }
        .custom-tree-node{
          .ent::before{
            background:url("../../assets/select_ent.png");
            background-size:100% 100%;
          }
          .park::before{
            background:url("../../assets/select_park.png");
            background-size:100% 100%;
          }
        }
      }
    }
  }
}
.aside {
  width: 200px;
  padding-right: 20px;
  position: relative;
  border-right: 1px solid #eee;
}
.aside-hidden {
  width: 0px;
  padding: 0px;
  position: relative;
  margin: 0;
}

.ent,.park{
  position:relative;
  left:20px;
}
.ent:before,.park:before{
  position:absolute;
  content:" ";
  width:12px;
  height:12px;
  // border-radius:50%;
  top:50%;
  left:-20px;
  margin-top:-7px;

}
.ent:before{
  background:url("../../assets/ent.png");
  background-size:100% 100%;
}
.park:before{
  background:url("../../assets/park.png");
  background-size:100% 100%;
}
</style>
