<template>
  <div class="height100 bi-screen-tree">
    <div class="keywords">
      <ts-input
        v-model="keywords"
        title
        placeholder="请输入关键字"
        width="100%"
        suffix-icon="iconfont icon-Group-14"
      ></ts-input>
    </div>
    <div class="treeCon hidden scroll_y">
      <div class="loading_base" v-if="treeLoad == true">加载中...</div>
      <ts-tree
        :source="treeObj"
        width="100%"
        height="100%"
        row-id="id"
        :is-border="false"
        :checkRows="checkRows"
        :expandAll="config.expandAll||false"
        :search-words="keywords"
        ref="tstree"
        :key="uuid"
        @change="treeChange"
        v-else
      ></ts-tree>
    </div>
  </div>
</template>

<script>
// import targetInfoTab from '../targetInfoTab'
export default {
  name: 'biScreenTree',
  props: {
    value: {
      type: [Object, String],
      default: () => {
        return {}
      }
    },
    config: {
      // 属性内容
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      keywords: '',
      treeObj: {
        dataType: 'local',
        data: [],
        textName: 'name',
        childName: 'children',
        text: 'name',
        code: 'id',
        children: 'children',
        noParent: !this.config.isParent,
        type: this.config.isCheckbox ? 'checkbox' : 'normal'
      },
      checkRows: [],
      treeLoad: false,
      currentValue: '',
      uuid: this.$utils.uuid(6),
      treeChoiceList: [],
      textValue: ''
    }
  },
  created() {},
  mounted() {
    // if (!this.treeObj.data || this.treeObj.data.length == 0) {
    if (!sessionStorage.getItem('deptTree')) {
      this.leftTree()
    } else {
      this.treeObj.data = JSON.parse(sessionStorage.getItem('deptTree'))
    }
  },
  deactivated(val) {},
  methods: {
    // 左侧树数据
    leftTree() {
      const _this = this
      this.treeLoad = true
      this.$api({
        url: '/ts-system/dept/getDeptTree',
        method: 'get'
      })
        .then(function(response) {
          // 请求成功
          if (response.success === true) {
            _this.treeObj.data = response.object
            sessionStorage.setItem('deptTree', JSON.stringify(response.object))
          } else {
            _this.$utils.msg(_this, '操作失败！', 'error')
          }
          _this.treeLoad = false
        })
        .catch(function(error) {
          // 请求失败
          _this.treeLoad = false
          _this.$utils.msg(_this, '操作失败！', 'error')
        })
    },
    // 树选择触发
    treeChange(row, node) {
      const _this = this
      if (!this.config.isCheckbox) {
        // 单选
        this.textValue = row[_this.treeObj.text] || ''
        this.currentValue = row[_this.treeObj.code] || ''
        this.treeChoiceList = [row]
      } else {
        if (row.checked) {
          this.setTreeChild([row])
        } else {
          // 未选中
          this.getTreeChild([row])
        }
      }
      // this.setValue(this.textValue, this.currentValue)
      if (row) {
        this.$nextTick(() => {
          // this.$emit('selected', row, this.treeChoiceList)
          this.$emit('change', this.currentValue, row)
        })
      }
    },
    // 设置no parent的情况
    setTreeChild(array) {
      for (let item of array) {
        if (
          !this.treeObj.noParent ||
          !item[this.treeObj.children] ||
          item[this.treeObj.children].length == 0
        ) {
          this.treeChoiceList.push(item)
          if (this.currentValue === '') {
            this.textValue = item[this.treeObj.text]
            this.currentValue = item[this.treeObj.code]
          } else {
            this.textValue += ',' + item[this.treeObj.text]
            this.currentValue += ',' + item[this.treeObj.code]
          }
        }
        if (
          item[this.treeObj.children] &&
          item[this.treeObj.children].length > 0
        ) {
          this.setTreeChild(item[this.treeObj.children])
        }
      }
    },
    // 删除多的
    getTreeChild(array) {
      for (let item of array) {
        let text = item[this.treeObj.text] || ''
        let code = item[this.treeObj.code] || ''
        this.removeTree(null, code)
        if (
          item[this.treeObj.children] &&
          item[this.treeObj.children].length > 0
        ) {
          this.getTreeChild(item[this.treeObj.children])
        }
      }
    },
    removeTree(event, id) {
      event ? event.stopPropagation() : ''
      let _val = this.currentValue
      if (_val) {
        let arr = _val.split(',')
        let index = arr.findIndex(res => res == id)
        if (index > -1) {
          arr.splice(index, 1)
        }
        this.currentValue = arr.join(',') // 暂未对text进行处理
      }
    }
  },
  watch: {
    value(val) {
      this.currentValue = val
    },
    currentValue(val) {
      this.$emit('input', val)
    },
    'config.expandAll': {
      handler(val) {
        this.$refs.tstree.setAllTreeExpand(val)
      }
    },
    'config.isCheckbox': {
      handler(val) {
        this.treeObj.type = this.config.isCheckbox ? 'checkbox' : 'normal'
        this.uuid = this.$utils.uuid(6)
      }
    },
    'config.isParent': {
      handler(val) {
        this.treeObj.noParent = !this.config.isParent
      }
    }
  },
  beforeDestroy: function() {}
}
</script>
<style lang="scss" scoped>
.bi-screen-tree {
  height: 100%;
  width: 100%;
  .treeCon {
    height: calc(100% - 30px);
  }
  .keywords{
    margin: 8px 8px 0 8px;
  }
  /deep/ .ztree {
    li {
      a {
        height: 20px;
      }
      line-height: 16px;
    }
    li span.button.ico_open,
    li span.button.ico_close {
      color: var(--base-acv);
      font-size: 18px;
    }
    li span.button.ico_open::before,
    li span.button.ico_close::before {
      content: '\e689';
    }
    li span.button.ico_docu:before {
      content: '\e667';
    }
  }
}
</style>
