<template>
  <div :class="[$style.treewrap, { [$style.collapse]: fold }]">
    <a-card>
      <a-spin v-if="!fold" :spinning="spinning" :class="$style.spin" />
      <a-empty v-if="empty" />
      <a-tree
        v-if="treeData.length > 0"
        show-icon
        :tree-data="treeData"
        :load-data="onLoadData"
        :replace-fields="replacefields"
        :default-selected-keys="defaultselectedkey"
        :expanded-keys.sync="expandedKeys"
        @select="onSelect"
      >
        <template slot="title" slot-scope="{ text, props }">
          <span :title="text">{{ text }}</span
          ><span v-if="props.count > 0">（{{ props.count }}）</span>
        </template>
      </a-tree>
    </a-card>
    <a-button type="primary" :class="$style.fold" @click="foldClick">
      <a-icon :type="fold ? 'right' : 'left'" />
    </a-button>
  </div>
</template>

<script>
import FlowcenterService from './flowcenter-service'
import components from './_import-components/sd-worktree-import'

// 给所有对象增加scopedSlots属性
const addSlot = (obj) => {
  for (let i = 0; i < obj.length; i++) {
    obj[i].isLeaf = obj[i].leaf
    Object.assign(obj[i], { scopedSlots: { title: 'title' } })
    // 因叶子节点和非叶子节点id可能有重复，所以在这里处理一下
    if (obj[i].id !== '0' && obj[i].id !== 'other' && obj[i].id !== 'oaDocReceiptExchange') {
      if (obj[i].leaf) {
        obj[i].id = '0' + obj[i].id
      } else {
        obj[i].id = '1' + obj[i].id
      }
    }
    if (obj[i].children) {
      addSlot(obj[i].children)
    }
  }
}

export default {
  name: 'SdWorktree',
  components,
  props: {
    dataType: {
      type: String,
      default: undefined,
    },
  },
  data() {
    return {
      spinning: true,
      empty: false,
      fold: true,
      treeData: [],
      replacefields: {
        // 转换树的默认字段title和key
        title: 'text',
        key: 'id',
      },
      defaultselectedkey: [], // 默认选中的节点
      selectedkey: [], // 选中节点
      selectNode: null,
      expandedKeys: [],
    }
  },
  watch: {
    dataType() {
      this.getTreeData()
    },
  },
  mounted() {},
  methods: {
    // 获取工作树数据
    getTreeData() {
      this.treeData = []
      this.spinning = true
      FlowcenterService.getFrameWorktree({ label: this.dataType }).then((res) => {
        this.spinning = false
        const newArr = res.data
        addSlot(newArr)
        if (newArr[0].children.length > 0) {
          this.expandedKeys = [newArr[0].id]
          this.treeData = newArr
          this.empty = false
        } else {
          this.treeData = []
          this.expandedKeys = []
          this.empty = true
        }
        this.defaultselectedkey = [newArr[0].id] // 默认选中节点
        this.selectNode = newArr[0]

        // this.$emit('treeSelectd', res.data[0], this.dataType)
      })
    },
    // 刷新树，选中原来的节点，不发送选中节点
    refresh() {
      this.treeData = []
      this.spinning = true
      FlowcenterService.getFrameWorktree({ label: this.dataType }).then((res) => {
        this.spinning = false
        const newArr = res.data
        addSlot(newArr)
        if (newArr[0].children.length > 0) {
          this.treeData = newArr
          this.selectNode = newArr[0]
          this.empty = false
        } else {
          this.treeData = []
          this.selectNode = null
          this.empty = true
        }
        this.defaultselectedkey = this.selectedkey
      })
    },
    onLoadData(treeNode) {
      if (treeNode.dataRef.children) {
        return Promise.resolve()
      }
      const params = { label: this.dataType }
      if (treeNode.dataRef.props?.appId) {
        params.appId = treeNode.dataRef.props.appId
      }
      if (treeNode.dataRef.props?.categoryId) {
        params.categoryId = treeNode.dataRef.props.categoryId
      }
      return FlowcenterService.getFrameWorktree(params).then((res) => {
        const newArr = res.data
        addSlot(newArr)
        treeNode.dataRef.children = newArr
        this.treeData = [...this.treeData]
      })
    },
    // 树形控件选中时通知父组件，父组件根据选中的业务类型筛选数据
    onSelect(selectedKeys, info) {
      this.selectedkey = selectedKeys
      this.selectNode = info.node.dataRef
      this.$emit('treeSelectd', info, this.dataType)
    },

    // 小箭头点击事件
    foldClick() {
      this.fold = !this.fold
      // 判断工作树是否第一次加载，第一次加载时获取工作树数据
      if (this.treeData.length === 0) {
        this.$emit('foldFirstTime', this.dataType)
        this.getTreeData()
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.spin {
  width: 100%;
  line-height: 30;
}

.treewrap {
  position: relative;
  display: flex;
  width: 20%;
  min-height: 100%;
  margin-right: $padding-lg;
  transition: width 0.2s;
  &.collapse {
    :global(.ant-card) {
      display: none;
    }
  }
  :global(.ant-card) {
    width: 100%;
    height: 100%;
    overflow: auto;
    :global(.ant-card-body) {
      background: $white;
    }
  }
  .fold {
    position: absolute;
    top: calc(50% - 30px);
    right: -15px;
    z-index: 2;
    width: 15px;
    height: 75px;
    padding: 0;
    border-radius: 0 10px 10px 0;
  }
  :global(.ant-tree) {
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.collapse {
  width: 0;
  :global(.ant-card-body) {
    background: transparent;
    :global(.ant-empty) {
      display: none;
    }
  }
}
</style>
