<!--
----------侧边企业树选择组件（新）
-->
<template>
  <div :class="showTree?'aside':'aside-hidden'">
    <el-input v-show="showTree" v-model.trim="searchText" placeholder="请输入" />
    <el-scrollbar v-show="showTree" class="scrollbar" :style="{height:height ? height: '' }">
      <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
      v-if="isShowHamburger"
      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
    },
    storeEntVal: {// 企业车场树是否需要存储企业
      type: Boolean,
      default: false
    },
    isUser: {
      type: Boolean,
      default: false
    },
    treeList: {
      type: Object,
      default: () => {
        return {}
      }
    },
    height: {
      type: String,
      default: ''
    },
    isShowHamburger: {
      type: Boolean,
      default: true
    }
  },
  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.isUser) {
      if (this.$store.state.parkTree.treeData.length && !this.isPark) {
        this.dataInit(this.$store.state.parkTree.treeData)
      } else {
        this.getInfo()
      }
    } else {
      this.getInfo()
    }
  },
  methods: {
    show() {
      this.showTree = !this.showTree
    },
    /**
     * 获取树形节点数据
     */
    getInfo() {
      request({
        url: '/tenterprises/getEntAndParkList',
        method: 'get'
      }).then((res) => {
        if (res.success) {
          this.$store.commit('updateTreeData', res.data)
          if (!this.isUser) {
            this.dataInit(this.$store.state.parkTree.treeData)
          } else {
            this.selectNode = {}
            this.dataInit(this.treeList)
          }
          this.$nextTick(() => { // 查询条件存在时无效bug
            this.searchText && this.$refs.selectTree.filter(this.searchText)
          })
        }
      })
    },
    // 递归
    recursion(arr) {
      arr = arr || []
      const obj = arr[0] || {}
      if (obj.children?.length) {
        this.recursion(obj?.children)
      } else {
        this.userSid = obj.sid
      }
    },
    async 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 || this.selectNode && this.selectNode.type === 'ent' && this.storeEntVal) {
        sid = this.selectNode.sid
        this.addNodeAll()
      } else if (this.isFilter) {
        sid = this.companyList[0].sid
        this.addNodeAll()
      } else {
        if (!this.isUser) {
          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
            }
          }
        } else {
          this.recursion(this.companyList)
          sid = this.userSid
        }
      }

      // 设置选中项与展开项
      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('parkInfo'))
      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('parkInfo', 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;
  min-width: 199px;
  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,.project{
  position:relative;
  left:20px;
}
.ent:before,.park:before,.project::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%;
}
.project::before{
  background:url("../../assets/select_project.png");
  background-size:100% 100%;
}
</style>
