<template>
  <div style="background: #f0efef; height: 100%">
    <a-input-search style="margin-bottom: 8px" placeholder="请输入消防队单位关键字" @change="filterNode" />
    <!-- <a-button @click="newlyAdded">新增</a-button> -->
    <a-tree
      :expanded-keys="expandedKeys"
      :auto-expand-parent="autoExpandParent"
      :tree-data="carTypeList"
      :replaceFields="replaceFields"
      @select="handleNodeClick"
      @expand="onExpand"
    >
      <template slot="custom" slot-scope="item">
        <div>
          <span class="node-title">{{ item.title }} </span>
          <span style="margin-left: 20px">
            <span style="margin-right: 10px">
              <a-icon type="plus-circle" @click="subordinateItem(item)" />
            </span>
            <span style="margin-right: 10px">
              <a-icon type="edit" @click="modifyItem(item)" />
            </span>
            <span style="margin-right: 10px">
              <a-popconfirm title="是否要删除此行？" @confirm="deleteItem(item)">
                <a-icon type="delete" />
              </a-popconfirm>
            </span>
          </span>
        </div>
      </template>
    </a-tree>
    <tree-lower-modules ref="treeLowerModules" @ok="onOk" />
  </div>
</template>
<script>
import treeLowerModules from './treeLowerModules.vue'
const getParentKey = (id, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some((item) => item.categoryId === id)) {
        parentKey = node.categoryId
      } else if (getParentKey(id, node.children)) {
        parentKey = getParentKey(id, node.children)
      }
    }
  }
  return parentKey
}
export default {
  name: 'Trees',
  props: {
    carTypeList: {
      type: Array,
      required: true,
    },
  },
  components: { treeLowerModules },
  data() {
    return {
      replaceFields: { children: 'children', title: 'categoryName', key: 'categoryId', value: 'categoryId' },
      deptNodes: [],
      expandedKeys: [],
      searchValue: '',
      searchStr: '',
      autoExpandParent: true,
    }
  },
  filters: {},
  created() {},
  computed: {},
  watch: {},
  methods: {
    getAllDeptNode(nodes) {
      if (!nodes || nodes.length === 0) {
        return []
      }
      nodes.forEach((node) => {
        // console.log('----node',node);
        this.deptNodes.push({ categoryId: node.categoryId, categoryName: node.categoryName })
        return this.getAllDeptNode(node.children)
      })
    },
    // 筛选节点
    filterNode(e) {
      //   this.searchStr = e.target.value
      this.getAllDeptNode(this.carTypeList)
      const value = e.target.value
      const gData = this.carTypeList
      const expandedKeys = this.deptNodes
        .map((item) => {
          if (item.categoryName.indexOf(value) > -1) {
            return getParentKey(item.categoryId, gData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys: expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      })
      this.deptNodes = []
    },
    // 节点单击事件
    handleNodeClick(keys, event) {
      this.$emit('select', keys)
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    // 新增
    newlyAdded() {
      const item = { key: this.carTypeList[0].key, operation: 1 }
      this.$refs.treeLowerModules.add(item)
    },
    // 添加下级
    subordinateItem(item) {
      item.operation = 2
      this.$refs.treeLowerModules.add(item)
    },
    // 修改
    modifyItem(item) {
      this.$refs.treeLowerModules.edit(item)
    },
    // 删除
    deleteItem(item) {
      this.selectKeys = [item.categoryId]
      this.dataDriveDelete()
    },
    onOk(val) {
      if (val.operation === 1) {
        this.selectKeys = [val.categoryId]
        this.dataDriveAddSame(val.categoryName)
      } else if (val.operation === 2) {
        this.selectKeys = [val.categoryId]
        this.dataDriveAddSub(val.categoryName)
      } else if (val.operation === 3) {
        this.selectKeys = [val.categoryId]
        this.dataDriveModify(val.categoryName)
      }
    },
    getTreeDataByKey(childs = [], findKey) {
      let finditem = null
      for (let i = 0, len = childs.length; i < len; i++) {
        const item = childs[i]
        if (item.categoryId !== findKey && item.children && item.children.length > 0) {
          finditem = this.getTreeDataByKey(item.children, findKey)
        }
        if (item.categoryId == findKey) {
          finditem = item
        }
        if (finditem != null) {
          break
        }
      }
      return finditem
    },
    getTreeParentChilds(childs = [], findKey) {
      let parentChilds = []
      for (let i = 0, len = childs.length; i < len; i++) {
        const item = childs[i]
        if (item.categoryId !== findKey && item.children && item.children.length > 0) {
          parentChilds = this.getTreeParentChilds(item.children, findKey)
        }
        if (item.categoryId == findKey) {
          parentChilds = childs
        }
        if (parentChilds.length > 0) {
          break
        }
      }
      return parentChilds
    },
    // 添加同级
    dataDriveAddSame(title) {
      const parentChilds = this.getTreeParentChilds(this.carTypeList, this.selectKeys[0])
      parentChilds.push({
        title: title,
        key: new Date().getTime(),
        scopedSlots: { title: 'custom' },
      })
    },
    // 添加下级
    dataDriveAddSub(title) {
      const selectItem = this.getTreeDataByKey(this.carTypeList, this.selectKeys[0])
      if (!selectItem.children) {
        this.$set(selectItem, 'children', [])
      }
      selectItem.children.push({
        title: title,
        key: new Date().getTime(),
        scopedSlots: { title: 'custom' },
      })
      this.$forceUpdate()
    },
    // 修改
    dataDriveModify(title) {
      const selectItem = this.getTreeDataByKey(this.carTypeList, this.selectKeys[0])
      selectItem.title = title
    },
    // 删除
    dataDriveDelete() {
      const parentChilds = this.getTreeParentChilds(this.carTypeList, this.selectKeys[0])
      const delIndex = parentChilds.findIndex((item) => item.categoryId == this.selectKeys[0])
      parentChilds.splice(delIndex, 1)
    },
  },
}
</script>
