<template>
  <div class="widget-ComTreeList">
    <el-select
      ref="stlectTree"
      v-model="treeSelectText"
      :placeholder="placeholder"
      clearable
      filterable
      :filter-method="filterMethod"
      @clear="clearInput"
      size="small"
      :popper-append-to-body="false"
    >
      <el-option :value="treeValue.id" :label="treeValue.label" style="height: auto; padding: 0">
        <el-tree
          :data="datas"
          :props="defaultProps"
          :expand-on-click-node="false"
          node-key="pbsTree"
          highlight-current
          @node-click="nodeClick"
          :filter-node-method="filterNode"
          ref="tree"
        />
      </el-option>
    </el-select>
  </div>
</template>

<script lang="ts">
import { pbsTreeList_api } from '@/api/APIs'
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
//公共结构树列表
@Component({ name: 'ComTreeList' })
export default class ComTreeList extends Vue {
  @Prop(Number) prjId!: number
  @Prop({ type: String, default: '' }) placeholder!: string
  @Prop({ type: Boolean, default: false }) isSelectDefault!: boolean
  treeSelectText = ''
  treeValue = { id: '', label: '' }
  datas = []
  defaultProps = {
    children: 'children',
    label: 'name'
  }
  created() {
    this.getPbsTree()
  }
  async getPbsTree() {
    const res = await pbsTreeList_api({ prjId: this.prjId })
    const { code, result } = res
    if (code === 1) {
      function formatTree(obj) {
        const copyedObj = JSON.parse(JSON.stringify(obj)) // 深拷贝源数据
        return copyedObj.filter((parent) => {
          const findChildren = copyedObj.filter(
            (child) => parent.id === child.pid && child.levelname != '分部工程（专业）'
          )
          findChildren.length > 0 ? (parent.children = findChildren) : delete (parent as any).children
          return parent.pid === null // 返回顶层，依据实际情况判断这里的返回值
        })
      }
      if (result[0]) {
        this.datas = formatTree(result[0].structures)
        if (this.isSelectDefault) {
          this.treeSelectText = this.datas[0].name
          this.$emit('changeProjectName', { name: this.treeSelectText })
        }
      }
    } else {
      this.$message.error('信息获取失败')
    }
  }
  // 点击tree节点
  nodeClick(item) {
    const { id, name, code } = item
    this.treeValue.id = id
    this.treeValue.label = name
    this.treeSelectText = name
    ;(this.$refs.stlectTree as any).blur()
    //项目改变
    let emitInfo = item
    this.$emit('changeProjectName', emitInfo)
  }
  // 搜索逻辑
  filterMethod(value) {
    ;(this.$refs.tree as any).filter(value)
  }
  // tree节点过滤
  filterNode(value, data) {
    if (!value) return true
    return data.name.indexOf(value) !== -1
  }
  clearInput() {
    ;(this.$refs.tree as any).filter('')
    //项目改变
    this.$emit('changeProjectName', '')
  }
}
</script>

<style lang="scss">
</style>