<!-- 树状选择器 -->
<template>
  <Poptip
    v-model="showStatus"
    placement="bottom-start"
    trigger="click"
    popper-class="select-menu"
    @on-popper-show="onShowPopover"
    @on-popper-hide="onHidePopover"
  >
    <div slot="content">
      <div class="select-tree" :style="`width:${TreeWid - 32}px`">
        <h-tree :data="tree" :current="current" @changeCurrent="onClickNode" :defaultProps="defaultProps"></h-tree>
      </div>
    </div>
    <Input
      class='search-col'
      ref="input"
      v-model="labelModel"
      clearable
      @on-clear="onClear"
      :style="`width:${TreeWid}px`"
      :class="{ rotate: showStatus }"
      suffix="ios-arrow-down"
      :placeholder="placeholder"
      @change="filter"
    >
    </Input>
  </Poptip>
</template>

<script>
import HTree from '../tree/index.js'
// import { DepartmentGet } from '@/api/data.js'
export default {
  name: 'HSelectTree',
  components: { HTree },
  props: {
    // 接收绑定参数
    value: String,
    // 输入框宽度
    width: String,
    // 选项数据
    options: {
      type: Array,
      required: true
    },
    // 输入框占位符
    placeholder: {
      type: String,
      required: false,
      default: '请选择部门'
    },
    // 树节点配置选项
    props: {
      type: Object,
      required: false,
      default: () => ({
        parent: 'parentId',
        value: 'rowGuid',
        label: 'areaName',
        children: 'children'
      })
    },
    TreeWid: Number
  },
  // 设置绑定参数
  model: {
    prop: 'value',
    event: 'selected'
  },
  mounted() {
  },
  computed: {
    // 是否为树状结构数据
    dataType() {
      const jsonStr = JSON.stringify(this.options)
      return jsonStr.indexOf(this.props.children) !== -1
    },
    // 若非树状结构，则转化为树状结构数据
    data() {
      return this.dataType ? this.options : this.switchTree()
    }
  },
  watch: {
    labelModel(val) {
      if (!val) {
        this.valueModel = ''
      }
      //   this.$refs.tree.filter(val);
      this.filter()
    },
    value(val) {
      this.labelModel = this.queryTree(this.data, val)
    }
  },
  data() {
    return {
      // 树状菜单显示状态
      showStatus: false,
      // 菜单宽度
      treeWidth: 'auto',
      // 输入框显示值
      labelModel: '',
      // 实际请求传值
      valueModel: '',
      current: {},
      tree: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        id: 'identifieId'
      }
    }
  },
  created() {
    // 检测输入框原有值并显示对应 label
    if (this.value) {
      if (this.data.length > 0) {
        this.labelModel = this.queryTree(this.data, this.value)
      } else {
        this.queryData(this.value)
      }
    }
  },
  methods: {
    filter() {
      // var newarr = []
      // this.tree = this.render(this.data, newarr, this.labelModel)
      this.tree = this.deal(
        JSON.parse(JSON.stringify(this.data)),
        node => node.name.indexOf(this.labelModel) !== -1
      )
    },
    // render(arr, newarr, val) {
    //   let i = 0
    //   const len = arr.length
    //   for (; i < len; i++) {
    //     if (arr[i].name.indexOf(val) !== -1) {
    //       newarr.push(arr[i])
    //     }
    //     if (arr[i].children && arr[i].children.length > 0) {
    //       this.render(arr[i].children, newarr, val)
    //     }
    //   }
    //   return newarr
    // },
    deal(nodes, predicate) {
      // 如果已经没有节点了，结束递归
      if (!(nodes && nodes.length)) {
        return []
      }
      const newChildren = []
      for (const node of nodes) {
        if (predicate(node)) {
          // 如果节点符合条件，直接加入新的节点集
          newChildren.push(node)
          node.children = this.deal(node.children, predicate)
        } else {
          // 如果当前节点不符合条件，递归过滤子节点，
          // 把符合条件的子节点提升上来，并入新节点集
          newChildren.push(...this.deal(node.children, predicate))
        }
      }
      return newChildren
    },
    onClear() {
      this.showStatus = false
      this.$emit('onClear')
    },
    // 单击节点
    onClickNode(node) {
      // debugger
      this.current = node
      this.labelModel = node[this.props.label]
      this.valueModel = node[this.props.value]
      this.$emit('on-node', node) // 选择节点返回当前节点数据
      this.onCloseTree()
    },
    // 偏平数组转化为树状层级结构
    switchTree() {
      return this.cleanChildren(this.buildTree(this.options, '0'))
    },
    // 隐藏树状菜单
    onCloseTree() {
      this.showStatus = false
      // this.$refs.popover.showPopper = false;
    },
    // 显示时触发
    onShowPopover() {
      this.showStatus = true
      //   this.$refs.tree.filter(false);
      // this.filter();
      this.tree = JSON.parse(JSON.stringify(this.data))
    },
    // 隐藏时触发
    onHidePopover() {
      this.showStatus = false
      this.$emit('selected', this.valueModel)
    },
    // 树节点过滤方法
    filterNode(query, data) {
      if (!query) return true
      return data[this.props.label].indexOf(query) !== -1
    },
    // 搜索树状数据中的 ID
    queryTree(tree, id) {
      let stark = []
      stark = stark.concat(tree)
      while (stark.length) {
        const temp = stark.shift()
        if (temp[this.props.children]) {
          stark = stark.concat(temp[this.props.children])
        }
        if (temp[this.props.value] === id) {
          return temp[this.props.label]
        }
      }
      return ''
    },
    // 将一维的扁平数组转换为多层级对象
    buildTree(data, id = '0') {
      const fa = parentId => {
        const temp = []
        for (let i = 0; i < data.length; i++) {
          const n = data[i]
          if (n[this.props.parent] === parentId) {
            n.children = fa(n.rowGuid)
            temp.push(n)
          }
        }
        return temp
      }
      return fa(id)
    },
    // 清除空 children项
    cleanChildren(data) {
      const fa = list => {
        list.map(e => {
          if (e.children.length) {
            fa(e.children)
          } else {
            delete e.children
          }
          return e
        })
        return list
      }
      return fa(data)
    },
    queryData(id) {
      // 自定义查询
      // DepartmentGet('getDeapartmeDetail', { id: id })
      //   .then(response => {
      //     if (response.data.code == 1) {
      //       this.labelModel = response.data.data.name
      //     }
      //   })
      //   .catch(response => {
      //     x
      //   })
    }
  }
}
</script>

<style lang="less" scoped>
.ivu-poptip{
   width: 100%;
}
.ivu-input.ivu-input-suffix {
  cursor: pointer;
  /*overflow: auto;*/
}

.ivu-input.ivu-input-suffix.rotate .ivu-input__suffix {
  transform: rotate(180deg);
}
.search-col{
  width: 100% !important;
  margin-top: 10px;
  margin-left: 5px;
}
.select-tree {
  max-height: 350px;
  overflow-y: scroll;
  // width: 176px;
}

/* 菜单滚动条 */
.select-tree::-webkit-scrollbar {
  z-index: 11;
  width: 6px;
}

.select-tree::-webkit-scrollbar-track,
.select-tree::-webkit-scrollbar-corner {
  background: #fff;
}

.select-tree::-webkit-scrollbar-thumb {
  border-radius: 5px;
  width: 6px;
  background: lightseagreen;
}

.select-tree::-webkit-scrollbar-track-piece {
  background: #e8e8e8;
  width: 6px;
}
/deep/.style {
  color: #515a6e;
  .expand,
  .iconfont {
    color: #515a6e;
  }
  .file {
    color: #ffcd2c;
  }
}
/deep/.style:hover {
  background-color: #f3f3f3;
}
/deep/.active{
  background-color: #f3f3f3!important;
}
</style>
