<!-- 搜索树组件 -->
<template>
  <div v-clickoutside="handleClickOutside" class="select-tree">
    <el-input
      v-model.trim="selectParam"
      class="select-param-input"
      :placeholder="`请选择${defaultProps[searchType].attr}`"
      @click.native="handleInput"
      @input="filterInput"
      @mouseenter.native="paramInputHover"
      @mouseleave.native="paramInputOut"
    >
      <i slot="suffix" class="el-input__icon" :class="icon" @click="iconClick(icon)" />
    </el-input>
    <div v-show="treeShowFlag" style="position:absolute;z-index: 3333;">
      <div class="triangle"><span /></div>
      <div class="drop-down-div">
        <el-tree
          ref="tree"
          :data="data"
          :props="defaultProps[searchType]"
          :filter-node-method="filterNode"
          :default-expand-all="defaultExpand"
          highlight-current
          class="drop-down-tree"
          @node-click="nodeClick"
        >
          <span slot-scope="{ data, node }" class="custom-tree-node">
            <span v-dompurify-html="getNodeText(node.label)" :title="node.label" :class="data.type" />
          </span>
        </el-tree>
      </div>
    </div>
  </div>
</template>
<script>
import Clickoutside from 'element-ui/src/utils/clickoutside'
import { getCloudcenterList } from '@/api/cloudSeatSetting'
import request from '@/utils/request'

export default {
  directives: { Clickoutside }, // 声明指令
  props: {
    // 传入树形列表数据
    treeData: {
      default: () => [],
      type: [Array, Object]
    },
    // value监听的是父组件的v-model
    value: {
      default: '',
      type: String
    },
    // 是否需要过滤数据
    isFilter: {
      type: Boolean,
      default: true
    },
    // 与isFilter组合使用,isfilter为true时key和value都不可为空
    // key: 过滤属性键
    // value: 过滤属性值
    filterInfo: {
      default: () => {
        return {
          key: '',
          value: ''
        }
      },
      type: Object
    },
    searchType: {
      default: 0, // 搜索树类型:0=>坐席中心,1=>企业树
      type: Number
    }
  },
  data() {
    return {
      treeShowFlag: false, // 是否显示下拉树
      defaultProps: [// 默认接收参数名
        {
          attr: '坐席中心',
          children: 'children',
          label: 'centername',
          type: 'state'
        },
        {
          attr: '所属企业',
          children: 'children',
          label: 'name',
          type: 'type'
        }
      ],
      selectParam: '全部',
      icon: 'el-icon-arrow-down',
      defaultExpand: false, // 默认不展开
      clicked: true, // 是否有选择节点,没选择移开将清除输入框数据,编辑时也需要改为false
      data: []
    }
  },
  watch: {
    treeShowFlag(val) {
      this.icon = val ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
    },
    value(val) {
      this.selectParam = val
    },
    // 监听树形列表数据
    treeData: {
      handler(newVal, oldVal) {
        // 切换搜索树类型
        if (newVal) { this.switchType(newVal) }
      }

    },
    selectParam(val) {
      if (val == '' && this.clicked == true) {
        this.clearData()
      }
    }
  },
  created() {
    // 从vuex中获取企业树数据
    if (this.searchType == 0) {
      // 获取坐席中心列表
      this.$store.state.cloudCenter.centerData.length ? this.dataInit(this.$store.state.cloudCenter.centerData) : this.getCloudTreeList()
    } else if (this.searchType == 1) {
      // 获取企业树列表
      this.getCompanyTreeList()
    }
    // 切换搜索树类型
    this.switchType()
  },
  methods: {
    // 点击外部区域收起下拉框
    handleClickOutside() {
      if (!this.clicked) { this.clearData() }
      this.treeShowFlag = false
    },
    // 点击输入框展开/收起下拉框
    handleInput() {
      this.treeShowFlag = !this.treeShowFlag
    },
    // 输入文字进行模糊查询
    filterInput(val) {
      this.clicked = false
      this.treeShowFlag = true
      this.$refs.tree.filter(val)
    },
    // 鼠标悬浮，如果由内容的话就显示清除图标
    paramInputHover() {
      if (this.selectParam !== '') {
        this.icon = 'el-icon-circle-close'
      }
    },
    // 鼠标由悬浮离开，如果图标显示的是清除的话，就换成原来的图标
    paramInputOut() {
      if (this.icon === 'el-icon-circle-close') {
        this.icon = this.treeShowFlag ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
      }
    },
    // 点击清除图标时清除输入框的内容
    iconClick(icon) {
      if (icon === 'el-icon-circle-close') {
        this.treeShowFlag = false // 由于此事件会同时触发handleInput(),所以将treeShowFlag设为false，防止出现下拉列表
        this.clearData()
      }
    },
    // 清除输入框数据
    clearData() {
      this.clicked = false
      this.filterInput('') // 内容清除后显示所有数据
      this.selectParam = '全部'
      this.treeShowFlag = false
      this.$emit(`change${this.searchType}`, {})
    },
    // 节点过滤（模糊查询）
    filterNode(value, data) {
      if (!value) return true
      return data[this.defaultProps[this.searchType].label].indexOf(value) !== -1
    },
    // 树形节点点击事件
    nodeClick(val) {
      this.clicked = true
      this.treeShowFlag = !this.treeShowFlag
      this.$emit(`change${this.searchType}`, val)
    },
    // 过滤车场
    filterData(treeData) {
      const tree = []
      treeData.forEach(item => {
        if (item[this.filterInfo.key] === this.filterInfo.value) {
          const obj = {
            id: item.id,
            children: []
          }
          obj[this.defaultProps[this.searchType].type] = item[this.defaultProps[this.searchType].type]
          obj[this.defaultProps[this.searchType].label] = item[this.defaultProps[this.searchType].label]
          obj.children = this.filterData(item.children)
          tree.push(obj)
        }
      })
      return tree
    },
    // 关键字标红
    getNodeText(value) {
      let textHtml = `<span>${value}</span>`
      textHtml = value.replace(
        this.selectParam,
        `<span style="color: #2d72ff;font-weight: 700;">${this.selectParam}</span>`
      )
      return textHtml
    },
    // 切换搜索树过滤类型
    switchType(newVal) {
      const treeData = newVal || this.treeData

      switch (this.searchType) {
        case 0:
          // 过滤禁用
          // this.data = this.isFilter ? this.filterData(treeData || []) : (treeData || [])
          this.data = treeData
          break
        case 1:
          this.data = this.isFilter ? this.filterData(treeData || []) : (treeData || [])
          break
        default:
          this.data = treeData
      }
    },
    // 获取树形节点数据(带车场)
    getCompanyTreeList() {
      request({
        url: '/tenterprises/getEntAndParkList',
        method: 'get'
      }).then((res) => {
        if (res.success) {
          res.data.unshift({ id: '', name: '全部', children: [], type: 'ent' })
          this.dataInit(res.data)
        }
      })
    },
    // 数据初始化
    dataInit(data) {
      if (this.switchType == 0) {
        console.log('坐席')
      } else {
        console.log('企业')
      }
      if (!data || data.length < 1) {
        return
      }
      this.treeData = data || []
    },

    // 坐席中心下拉树接口
    getCloudTreeList() {
      getCloudcenterList({ childstate: 1 }).then((res) => {
        // 更新坐席中心vuex
        res.data.unshift({ id: '', centername: '全部', children: [] })
        this.$store.commit('CHANGE_CLOUD_CENTER', res.data)
        this.dataInit(res.data)
      }).catch((e) => {
        console.log(e)
      })
    }
  }
}
</script>
  <style lang="scss" scoped>
  .select-tree {
    width:100%;
    display:inline-block;
    transition: 0.5s;
    .select-param-input {
      width: 100%;
      cursor: pointer;
    }
  }
  .drop-down-div {
    border-radius: 3px;
    max-height: 200px;
    min-width: 200px;
    padding: 10px 0;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    box-shadow: 1px 2px 8px 1px rgba(0, 0, 0, 0.2);
  }
  .drop-down-div .drop-down-tree {
    overflow: auto;
  }
  .triangle {
    width:0;
    height:0;
    border-width:0 8px 7px;
    border-style:solid;
    border-color:transparent transparent rgb(220, 223, 230);
    margin-left: 60px;
    margin-top: 3px;
    position:relative;
  }
  .triangle span{
    display:block;
    width:0;
    height:0;
    border-width:0 7px 6px;
    border-style:solid;
    border-color:transparent transparent rgb(255, 255, 255);
    position:absolute;
    top:1px;
    left:-7px;
  }
  //修改全局的滚动条//
  //滚动条的宽度//
  ::-webkit-scrollbar {
    width: 6px;
  }
  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #eaecf1;
    border-radius: 3px;

  }
  //控制滚动条移入移出隐藏
  .drop-down-div:hover ::-webkit-scrollbar-thumb {
    display: block;
  }
  ::-webkit-scrollbar-thumb {
    display: none;
  }

  </style>
