<template>
  <van-popup
    v-model="dialogVisible"
    closeable
    position="left"
    :style="{ height: '100%',width:'60%'}"
    get-container="body"
    @close="handleClose"
  >
    <van-nav-bar
      fixed
      class="employee-tree"
    >
      <template #title>
        <van-dropdown-menu>
          <van-dropdown-item
            v-model="partyType"
            get-containe="body"
            :options="partyTypeOptions"
            @change="changePartyType"
          />
        </van-dropdown-menu>
      </template>
    </van-nav-bar>
    <div class="ibps-fixed-navbar ibps-fixed-top">
      <van-loading
        v-if="dialogLoading"
        vertical
      >加载中...</van-loading>
      <ibps-tree
        v-else
        ref="ibpsTree"
        :tree-data="treeData"
        :expand-on-click-node="false"
        :props="props"
        :default-expanded-keys="defaultExpandedKeys"
        :default-expand-all="defaultExpandAll"
        :load="lazyTree?loadOrgTreeNode:null"
        :lazy="lazyTree"
        node-key="id"
        highlight-current
        @node-click="handleNodeClick"
      />
    </div>

  </van-popup>
</template>

<script
>
import { findTreeData as getOrgTreeData } from '@/api/platform/org/org'
import { findTreeData as getPositionTreeData } from '@/api/platform/org/entity'
import { getTreeData as getRoleTreeData } from '@/api/platform/org/role'
import { getTreeData as getGroupTreeData } from '@/api/platform/org/group'
import { findAllSubsystem } from '@/api/platform/auth/subsystem'

import TreeUtils from '@/utils/tree'
import IbpsTree from '@/components/ibps-tree/index.vue'

export default {
  components: {
    IbpsTree
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    range: String,
    partyTypeOptions: {
      type: Array,
      default: function() {
        return [
          {
            text: '组织',
            value: 'org'
          }, {
            text: '部门',
            value: 'position'
          }, {
            text: '角色',
            value: 'role'
          }, {
            text: '用户组',
            value: 'group'
          }]
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogLoading: false,
      treeData: [],
      loazTreeData: [],
      props: {
        children: 'children',
        label: 'name'
      },
      partyType: 'position',

      lazyTree: true,
      defaultExpandedKeys: ['0'],
      defaultExpandAll: false
    }
  },
  watch: {
    visible(val, oldVal) {
      if (val !== oldVal) {
        this.dialogVisible = val
      }
    },
    range(val) {
      this.partyType = val
    },
    partyType(val) {
      this.$emit('update:range', val)
    }
  },
  created() {
    this.loadTreeData()
  },

  methods: {
    changePartyType(value) {
      this.partyType = value
      this.loadTreeData()
    },
    loadTreeData(init) {
      this.loadingTree = true
      // this.inclueChild = true
      this.partyId = ''
      this.treeData = []

      if (this.partyType === 'org') {
        this.lazyTree = true
        this.defaultExpandedKeys = ['0']
        this.defaultExpandAll = false
        this.loadOrgTreeData(init)
      } else {
        this.lazyTree = false
        this.defaultExpandedKeys = null
        this.defaultExpandAll = true
        if (this.partyType === 'position') {
          this.loadPositionTreeData()
        } else if (this.partyType === 'role') {
          // this.inclueChild = false
          this.loadRoleTreeData()
        } else if (this.partyType === 'group') {
          // this.inclueChild = false
          this.loadGroupTreeData()
        }
      }
    },
    // 加载机构树
    loadOrgTreeData(init) {
      const type = this.type !== '' ? this.typeId : 1
      getOrgTreeData({
        type: type
      }).then(response => {
        this.loadingTree = false
        if (!init) {
          const data = response.data
          this.treeData = TreeUtils.transformToTreeFormat(data)
          this.setTree(true, this.treeData)
        }

        this.treeDatas = response.data
        // this.checkTreeId(this.treeData)
      }).catch(() => {
        this.loadingTree = false
      })
    },
    loadOrgTreeNode(node, resolve) {
      this.loadingTree = true
      const nodeData = this.$utils.isNotEmpty(node.data) ? this.$utils.isArray(node.data) ? node.data[0] : node.data : {}
      const type = this.type !== '' ? this.typeId : 1
      const check = this.$utils.isNotEmpty(this.groundId) && nodeData.id === '0' && !this.$store.getters.isSuper

      getOrgTreeData({
        type: type,
        orgId: node.level === 0 ? null : check ? this.groundId : nodeData.id
      }).then(res => {
        this.loadingTree = false
        const arr = JSON.parse(JSON.stringify(res.data))
        resolve(this.toTree(arr))
        this.loazTreeData.push(...res.data)
      }).catch(res => {
        this.loadingTree = false
        resolve([])
      })
    },
    toTree(data) {
      return TreeUtils.transformToTreeFormat(data, {
        idKey: 'id',
        pIdKey: 'parentId',
        childrenKey: 'children'
      })
    },
    // 加载岗位树
    loadPositionTreeData() {
      getPositionTreeData({
        parameters: [],
        requestPage: {},
        sorts: []
      }).then(response => {
        this.loadingTree = false
        const data = response.data
        this.treeData = TreeUtils.transformToTreeFormat(data)
        this.setTree(false, this.treeData)
        // this.checkTreeId(this.treeData)
      }).catch(() => {
        this.loadingTree = false
      })
    },
    // 加载角色树
    loadRoleTreeData() {
      getRoleTreeData().then(response => {
        const data = response.data
        data.unshift({
          id: 0,
          name: '角色树',
          parentId: null
        })
        findAllSubsystem().then(response => {
          this.loadingTree = false
          const subSystemList = response.data
          subSystemList.forEach(subSystem => {
            data.push({
              id: subSystem.id,
              name: subSystem.name,
              parentId: 0
            })
          })
          this.treeData = TreeUtils.transformToTreeFormat(data)
          this.setTree(false, this.treeData)
          // this.checkTreeId(this.treeData)
        }).catch(() => {
          this.loadingTree = false
        })
      }).catch(() => {
        this.loadingTree = false
      })
    },
    // 加载用户组树
    loadGroupTreeData() {
      getGroupTreeData({
        type: '1'
      }).then(response => {
        this.loadingTree = false
        const data = response.data
        this.treeData = TreeUtils.transformToTreeFormat(data)
        this.setTree(false, this.treeData)
        // this.checkTreeId(this.treeData)
      }).catch(() => {
        this.loadingTree = false
      })
    },
    setTree(lazy, data) {
      this.$refs.ibpsTree.store.lazy = lazy
      this.$refs.ibpsTree.store.defaultExpandAll = !lazy
      this.$refs.ibpsTree.store.defaultExpandedKeys = lazy ? ['0'] : null
      this.$refs.ibpsTree.store.setData(data)
      if (lazy) {
        this.$refs.ibpsTree.store.load = this.loadOrgTreeNode
      }
    },

    handleClose() {
      this.$emit('close', false)
    },
    handleNodeClick(item) {
      this.handleClose()
      const data = item.data || {}
      this.$emit('node-click', data.id || '')
    }
  }
}
</script>
<style lang="scss">
  .employee-tree{
    .van-nav-bar__title{
      width: 100%;
    }
  }

</style>

