<!-- /mng/class 实体类-左侧页面-->
<template>
  <div class="flex-col">
    <a-button
      v-if="editable"
      type="primary"
      block
      class="entity-class-z"
      @click="addRootEntityClassModal"
    >
      <a-icon type="plus" />
      新增根{{ TEXT.ENT_CLS }}
    </a-button>
    <a-input-search :placeholder="'搜索' + TEXT.ENT_CLS" @change="search" />
    <a-spin tip="Loading..." class="entity-class-tree auto-overflow flex1" :spinning="spinning">
      <a-tree
        ref="entClsTree"
        :default-selected-keys="selectTreeNodeIdList"
        :tree-data="treeData"
        :selected-keys.sync="selectTreeNodeIdList"
        :expanded-keys.sync="expandedKeys"
        :auto-expand-parent="autoExpandParent"
        @select="onSelect"
      >
        <template slot="custom" slot-scope="{entClsName,entClsID}">
          <span v-if="entClsName.indexOf(searchValue) > -1">
            {{ entClsName.substr(0, entClsName.indexOf(searchValue)) }}
            <span style="color: #f50">{{ searchValue }}</span>
            {{ entClsName.substr(entClsName.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ entClsName }}</span>
          <!--{{entClsID}}-->
          <span v-if="editable" class="handleButton">
            <a-icon type="plus-circle" style="margin-right:5px;" @click.stop="addChildEntityClass(entClsID)" />
            <a-icon type="minus-circle" @click.stop="deleteEntityClass(entClsID)" />
          </span>
        </template>
      </a-tree>
    </a-spin>
    <!--<Button @click="test">test</Button>-->
  </div>
</template>

<script>
//  import $ from 'jquery'
const api = require('@/api/index')
const TEXT = window.USER_ROLE_LANGUAGE[window.USER_ROLE]
const gData = [] // 左侧实体类树

const dataList = []
// 根据树生成一个列表
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    const key = node.key
    dataList.push({ key, title: node.entClsName, entClsName: node.entClsName })
    if (node.children) {
      generateList(node.children, node.key)
    }
  }
}
//  得到需要展开的父节点key
const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key
      } else {
        const tp = getParentKey(key, node.children)
        if (tp) {
          parentKey = tp
        }
      }
    }
  }
  return parentKey
}
export default {
  name: 'EntityClassTree',
  //  editable 是否显示操作按钮  isLink: 是否能进行路由跳转
  props: {
    editable: {
      type: Boolean,
      default: true
    },
    isLink: {
      type: Boolean,
      default: true
    },
    id: {
      type: String
    },
    activeId: {
      type: String
    },
    rootId: {
      type: String
    }
  },
  data() {
    return {
      TEXT,
      expandedKeys: [], // 要展开的节点
      searchValue: '', // 搜索的实体类名字
      autoExpandParent: true,
      gData,
      selectTreeNodeIdList: [],
      spinning: false
    }
  },
  events: {
    /**
       *更新后刷新左侧树
       * @param msg
       */
    'entityClass:entityClassUpdated'(msg) {
      this.refreshEntityClassList()
    }
  },
  computed: {
    /**
       * 实际绑定在树上的变量,根据rootId可能有不同
       **/
    treeData() {
      var returnData = []
      if (this.rootId) {
        // 搜索根节点
        this.$utils.tree.walk(this.gData, (node) => {
          if (node.entClsID === this.rootId) {
            returnData = [node]
            return false
          }
        })
      } else {
        returnData = this.gData
      }
      // 如果有搜索字符串
      var searchStr = this.searchValue
      if (searchStr) {
        // 向上遍历到所有要展开的父节点
        const expandedKeys = dataList.map((item) => {
          if (item.title.indexOf(searchStr) > -1) {
            return getParentKey(item.key, returnData) // 返回要展开的父节点keys
          }
          return null
        }).filter((item, i, self) => item && self.indexOf(item) === i)
        // 设定展开
        Object.assign(this, {
          expandedKeys,
          autoExpandParent: true
        })
        // 遍历整个树
        var showParentNodeList = []
        this.$utils.tree.walk(returnData, (node, index, way) => {
          if (node.entClsName.indexOf(searchStr) > -1) {
            node.style = ''
            //   node.style = "background:red"
            showParentNodeList = showParentNodeList.concat(way)
          } else {
            // node.style = "background:blue"
            node.style = 'display:none'
          }
        })
        for (var i = 0; i < showParentNodeList.length; i++) {
          // showParentNodeList[i].style = "background:red"
          showParentNodeList[i].style = ''
        }
      } else {
        // 没有搜索串,遍历清空display:none
        this.$utils.tree.walk(returnData, (node) => {
          node.style = ''
        })
      }
      console.log('重新计算树的节点')
      return returnData
    }
  },
  watch: {
    activeId() {
      this.selectTreeNodeIdList = [this.activeId]
    }
  },
  created() {
    this.refreshEntityClassList()
    if (this.activeId) this.selectTreeNodeIdList = [this.activeId]
  },
  mounted() {
    if (this.activeId) {
      var timId = setTimeout(() => {
        var $li = document.getElementsByClassName('ant-tree-treenode-selected')
        $li[0].scrollIntoView()
        clearTimeout(timId)
      }, 3000)
    }
  },
  methods: {
    search(e) {
      var str = e.data
      if (this.searchTimeoutHandler) {
        clearTimeout(this.searchTimeoutHandler)
      }
      this.searchTimeoutHandler = setTimeout(() => {
        this.searchValue = str
        this.searchTimeoutHandler = false
      }, 800)
      // debugger
    },
    onSelect(keys, node) {
      // this.selectTreeNodeIdList = [node.key]
      this.expandedKeys = keys // 选中展开的key
      // this.autoExpandParent = false  // 选中时设置不展开父节点
      const entClsID = node.node.dataRef.entClsID
      this.$emit('nodeSelected', node.node.dataRef) // nodeSelected 往新建关系模态窗里传值
      // this.$emit('emitEntityClassId', node.node.dataRef.entClassID)
    },
    /**
       * 进入页面刷新实体类树
       */
    refreshEntityClassList() {
      this.spinning = true
      api.entityClass.getAllEntityClass().then((data) => {
        var rootEntClsList = []
        for (let i = 0; i < data.length; i++) {
          data[i]['key'] = data[i]['entClsID']
          data[i]['title'] = data[i]['entClsName']
          data[i]['scopedSlots'] = { title: 'custom' }
          if (data[i].pid == null || data[i].pid === undefined) {
            rootEntClsList.push(data[i])
          }
        }
        this.$emit('getAllRootList', rootEntClsList)
        // 此处传固定的option
        const option = {
          idName: 'entClsID',
          pidName: 'pid',
          childName: 'children'
        }
        const treeData = this.$utils.tree.listToTree(data, option) // 数组转成树
        console.log('数组拼接成的树', treeData)
        this.gData = treeData
        generateList(treeData) // 生成个列表
        const vm = this
        // 遍历树找到需要展开的节点
        this.$utils.tree.walk(treeData, function(node, index, way) {
          var id = vm.$route && vm.$route.params.classId // 路由中的id
          var myWay = [] // 需要找到的展开节点key
          if (node.key === id) {
            for (let i = 0; i < way.length; i++) {
              myWay.push(way[i]['key'])
            }
            vm.expandedKeys = myWay
            return false
          }
        })
        // 跳转到展开的节点
        // var selected = document.getElementsByClassName('ant-tree-treenode-selected')
        // if(selected.length>0){
        //   // 跳转
        //   selected[0].scrollIntoView()
        // }
        vm.spinning = false
      })
    },
    /**
       * 注入:添加根节点实体类模态窗
       * @param null
       * @returns {*}
       */
    addRootEntityClassModal() {
      this.$open('addRootEntityClassModal', {}, function() {
        this.refreshEntityClassList()
      })
    },
    /**
       * 注入：删除实体类
       */
    deleteEntityClass(id) {
      const vm = this
      this.$confirm({
        title: '你确定要删除吗?',
        content: '删除此' + this.TEXT.ENT_CLS + '会删除下面所有的关系，请慎重！',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          api.entityClass.delEntityClass(id).then((data) => {
            if (data !== false) {
              // 刷新实体类的树
              vm.refreshEntityClassList()
              vm.$message.success('删除' + this.TEXT.ENT_CLS + '成功')
              vm.$trigger('entityClass:nodeDestroyed', id)
            }
          })
        },
        onCancel() {
          console.log('取消删除')
        }
      })
    },
    /**
       * 添加子实体类
       * @param null
       */
    addChildEntityClass(id) {
      if (id === undefined) id = ''
      this.$open('addChildEntityClassModal', {
        pid: id
      }, function() {
        this.refreshEntityClassList()
      })
    }
  }
}
</script>

<style>
    .ant-tree.entity-class-tree {
        margin: 5px -10px;
        padding: 0 10px;
    }

    .entity-class-tree .ant-tree-title:hover .handleButton {
        visibility: visible;
    }

    .entity-class-tree .handleButton {
        visibility: hidden;
        line-height: 25px;
        position: relative;
        left: 5px;
    }

    .entity-class-z {
        margin-bottom: 10px;
    }

</style>
