
import { getScriptValue } from '@/api/platform/form/formDef'// 脚本
import { findTreeData as getOrgTreeData } from '@/api/platform/org/org'
import { findTreeData as getPositionTreeData } from '@/api/platform/org/position'
import { getTreeData as getRoleTreeData, queryBySubSysIdOrName as getUseScopeRoleTreeData } 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'
export default {
  // 取子id
  methods: {
    checkTreeId(treeData) {
      const arr = []
      const filter = function(datas) {
        datas.find(item => {
          if (item.children && item.children !== []) {
            item.children.forEach(i => {
              arr.push(i.id)
            })
            filter(item.children)
          }
        })
        return arr
      }
      filter(treeData)
      this.treeIds = arr
      this.loadListData()
    },
    toTree(data) {
      return TreeUtils.transformToTreeFormat(data, {
        idKey: 'id',
        pIdKey: 'parentId',
        childrenKey: 'children'
      })
    },
    // 根据渲染的数据范围类型，筛选目标节点
    filterPositionTreeChildren(treeData, treeScope) {
      const data = []
      // 返回设置的范围节点
      if (treeScope === 'root') {
        const currentOrgIds = this.currentOrgId.split(',')
        treeData.forEach(f => {
          if (currentOrgIds.includes(f.id)) {
            f.leaf = true
            data.push(f)
          }
        })
      }
      return data
    },
    // 脚本执行函数
    getScriptData(scriptValue, once = false) {
      if (this.scriptExecuteTime) return
      getScriptValue({
        script: scriptValue,
        vars: ''
      }).then(response => {
        const data = JSON.parse(response.data)
        this.treeData = TreeUtils.transformToTreeFormat(data.data)
        this.setTree(this.partyType === 'position', this.treeData)
        this.scriptExecuteTime = once
      })
    },
    // 树属性方法动态调整
    setTree(lazy, data) {
      console.log(data, 'datadata')
      const ref = this.$refs.elTree
      ref.store.lazy = lazy
      ref.store.defaultExpandAll = !lazy
      ref.store.defaultExpandedKeys = lazy ? ['0'] : null
      ref.store.setData(data)
      if (lazy && !this.isUseScope && (this.partyType !== 'org' || (this.partyType === 'org' && this.partyTypeId !== '3'))) {
      // 普通模式懒加载函数调用
        ref.store.load = this.loadOrgTreeNode
      } else if (lazy && this.isUseScope) {
        if (this.partyType === 'org') {
          ref.store.load = this.partyTypeId === '3' ? this.loadOrgTreeNode3 : this.loadOrgTreeNode
        } else if (this.partyType === 'position') {
          ref.store.load = this.partyTypeId === '3' ? this.loadPosTreeNode3 : this.loadPosTreeNode
        }
      }
    },
    loadTreeData(init, resetParams = false) {
      this.hiddenTree = false
      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, resetParams)
      } else if (this.partyType === 'position') {
        this.lazyTree = true
        this.defaultExpandedKeys = ['0']
        this.defaultExpandAll = true
        this.loadPositionTreeData(init, resetParams)
      } else {
        this.lazyTree = false
        this.defaultExpandedKeys = null
        this.defaultExpandAll = true
        if (this.partyType === 'role') {
        // this.inclueChild = false
          this.loadRoleTreeData()
        } else if (this.partyType === 'group') {
        // this.inclueChild = false
          this.loadGroupTreeData()
        }
      }
      // this.loadData()
    },
    // 加载机构树
    loadOrgTreeData(init) {
      const type = this.partyTypeIdValue !== '' ? this.partyTypeIdValue : '1'
      this.loadingTree = true
      this.hiddenTree = true
      if (type === 'script') {
        this.getScriptData(this.scriptValue)
        this.loadingTree = false
        return
      }
      const params = {}
      params.type = type
      getOrgTreeData(params).then(response => {
        this.loadingTree = false
        this.hiddenTree = 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.partyTypeIdValue !== '' ? this.partyTypeIdValue : 1
      const check = this.$utils.isNotEmpty(this.currentOrgIdValue) && nodeData.id === '0' && !this.$store.getters.isSuper
      const params = {}
      params.type = type
      if (type === 'script') {
        if (this.$utils.isEmpty(node.data) || node.data.id === '0') {
          this.getScriptData(this.scriptValue, true)
          this.loadingTree = false
          return
        } else {
          params.type = '2'
        }
      }
      params.orgId = node.level === 0 ? null : check ? this.currentOrgIdValue : nodeData.id
      if (type === '5') {
        params.includeSub = true
      }
      getOrgTreeData(params).then(res => {
        this.loadingTree = false
        // const arr = JSON.parse(JSON.stringify(res.data))
        // resolve(this.toTree(arr))
        this.loadingTree = false
        const arr = JSON.parse(JSON.stringify(res.data))
        let treeData
        if (this.$utils.isNotEmpty(this.isSuperInitTree)) {
          if (!this.isSuperInitTree.initNode && node.level !== 0) {
            const nodeData = this.filterTreeChildren(this.toTree(arr), 'node', node.data.id)
            resolve(this.toTree(nodeData))
          } else {
            resolve(this.toTree(arr))
          }
        } else if (this.isUseScope && (this.$utils.isEmpty(node.data) || node.data.id === '0')) {
        // 初始化和查询全部时得数据加载
          if (this.$utils.isEmpty(node.data) || type === '1') {
            treeData = arr
            resolve(this.toTree(treeData))
          } else {
          // 类型2，3得初始化数据节点筛选
            treeData = this.filterTreeChildren(arr, 'root')
            resolve(this.toTree(treeData))
          }
        } else if (this.isUseScope && (this.$utils.isArray(node.data) && node.data[0].id === '0')) {
        // 节点数据为数组时得初始化处理
          treeData = arr
          resolve(this.toTree(treeData))
        } else if (this.isUseScope && type === '1' && node.data.id !== '0') {
          resolve(this.toTree(arr))
        }
        if (!this.isUseScope && this.$utils.isEmpty(this.isSuperInitTree)) {
          resolve(this.toTree(arr))
        }

        this.loazTreeData.push(...res.data)
      }).catch(res => {
        this.loadingTree = false
        resolve([])
      })
    },
    // 加载岗位树
    loadPositionTreeData(init, resetParams = false) {
      const type = this.partyTypeIdValue !== '' ? this.partyTypeIdValue : '1'
      this.loadingTree = true
      this.hiddenTree = true
      if (type === 'script') {
        this.getScriptData(this.scriptValue)
        this.loadingTree = false
        return
      }
      const params = {}
      params.type = type
      if (resetParams && this.isUseScope) {
        params.partyId = this.currentOrgIdValue
        params.includeSub = false
      }
      getPositionTreeData(params).then(response => {
        const data = response.data
        data.forEach((item) => {
          if (item.name === '岗位树') {
            item.name = '部门树'
            item.title = '部门树'
          }
        })
        this.loadingTree = false
        this.hiddenTree = false
        // 普通模式
        if (!this.isUseScope) {
          if (!init) {
            // const data = response.data
            this.treeData = TreeUtils.transformToTreeFormat(data)
            this.setTree(true, this.treeData)
          }
          this.treeDatas = response.data
        } else {
        // 选择器范围模式
          if (resetParams) {
            // const data = response.data
            this.treeData = TreeUtils.transformToTreeFormat(data)
            this.setTree(true, this.treeData)
          } else {
            if (!init) {
              // const data = response.data
              this.treeData = TreeUtils.transformToTreeFormat(data)
              this.setTree(true, this.treeData)
            }
            this.treeDatas = response.data
          }
        }
      // const data = response.data
      // this.treeData = TreeUtils.transformToTreeFormat(data)
      // this.setTree(false, this.treeData)
      // this.checkTreeId(this.treeData)
      }).catch(() => {
        this.loadingTree = false
      })
    },
    // 岗位树节点函数
    loadPosTreeNode(node, resolve) {
      console.log(node, 'nodenodenodenode')
      let params = {}
      const type = this.partyTypeIdValue !== '' ? this.partyTypeIdValue : '1'
      if (this.isUseScope) {
      // 选择器范围模式参数
        params.type = type
        params.includeSub = type === '1'
        if (type === '2') {
          params.partyId = node.level === 0 ? null : node.data.id
        }
        if (type === '3') {
          params.partyId = this.currentOrgIdValue
        }
        if (type === '1') {
          params.posId = node.level === 0 ? null : node.data.id
        }
        if (type === 'script') {
          this.getScriptData(this.scriptValue)
          this.loadingTree = false
          return
        }
      } else {
        params.type = '1'
        params.posId = node.level === 0 ? null : node.data.id
      }
      if (this.moreSearchParams) {
        Object.assign(params, this.moreSearchParams)
      }
      if (this.$utils.isEmpty(node.data) || node.data.id === '0') {
        getPositionTreeData(params).then(res => {
          this.loadingTree = false
          const arr = JSON.parse(JSON.stringify(res.data))
          arr.forEach((item) => {
            if (item.name === '岗位树') {
              item.name = '部门树'
              item.title = '部门树'
            }
          })
          let arrList
          const frist = this.$store.getters.level.first || ''
          if ((type === '1' || type === '2') && frist) {
            const showBoo = arr.some((item) => item.id === frist)
            if (showBoo) {
              arrList = arr.filter((item) => item.id === frist)
            } else {
              arrList = arr
            }
          } else {
            arrList = arr
          }
          if (type === '2') {
            this.getPosiData(arrList, true)
          }
          let treeData
          if (this.$utils.isEmpty(node.data)) {
            treeData = arrList
            resolve(this.toTree(treeData))
          } else {
            treeData = type !== '2' ? arrList : this.filterPositionTreeChildren(arrList, 'root')
            resolve(this.toTree(treeData))
          }
        }).catch(res => {
          this.loadingTree = false
          resolve([])
        })
      } else if (node.data.id !== '0') {
        if (type === '2') {
          params = {}
          params.type = '1'
          params.posId = node.data.id
        }
        getPositionTreeData(params).then(res => {
          this.loadingTree = false
          const arr = JSON.parse(JSON.stringify(res.data))
          arr.forEach((item) => {
            if (item.name === '岗位树') {
              item.name = '部门树'
              item.title = '部门树'
            }
          })
          let arrList = []
          const second = this.$store.getters.level.second || ''
          if ((type === '1' || type === '2') && this.filtrate && second) {
            const showBoo = arr.some((item) => item.id === second)
            if (showBoo) {
              arrList = arr.filter((item) => item.id === second)
            } else {
              arrList = arr
            }
          } else {
            arrList = arr
          }
          if (type === '2') {
            this.getPosiData(arrList, node.data.disabled)
          }
          resolve(this.toTree(arrList))
        }).catch(res => {
          this.loadingTree = false
          resolve([])
        })
      }
    },
    getPosiData(arrList, disabled) {
      const positions = this.$store.getters.userInfo.employee.positions
      if (positions) {
        const positionsList = positions.split(',')
        positionsList.forEach(item => {
          const index = arrList.findIndex(it => it.id === item)
          if (index >= 0) {
            arrList[index].disabled = true
          }
        })
      }
      // 如果上级可以选择 也就是 disabled false，下级一定是false
      if (!disabled) {
        arrList.forEach(item => {
          item.disabled = false
        })
      } else {
        arrList.forEach(item => {
          if (item.disabled) {
            item.disabled = false
          } else {
            item.disabled = true
          }
        })
      }
    },
    // 加载角色树
    loadRoleTreeData() {
      if (this.isUseScope) {
      // 选择器范围模式参数
        const params = { parameters: [], requestPage: {}, sorts: [] }
        const type = this.partyTypeIdValue !== '' ? this.partyTypeIdValue : '1'
        params.parameters.push({ key: 'type', value: type })
        if (this.isUseScope) {
          params.parameters.push({ key: 'includeSub', value: this.partyTypeIdValue === '1' })
          if (type === '3') {
            params.parameters.push({ key: 'partyId', value: this.currentOrgIdValue })
          }
          if (type === 'script') {
            this.getScriptData(this.scriptValue)
            this.loadingTree = false
            return
          }
        }
        getUseScopeRoleTreeData(params).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
        })
      } else {
        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() {
      const params = {}
      const type = this.partyTypeIdValue !== '' ? this.partyTypeIdValue : '1'
      params.type = type
      if (this.isUseScope) {
      // 选择器范围模式参数
        params.includeSub = type === '1'
        if (type === '3') {
          params.partyId = this.currentOrgIdValue
        }
        if (type === 'script') {
          this.getScriptData(this.scriptValue)
          this.loadingTree = false
          return
        }
      }
      getGroupTreeData(params).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
      })
    }
  }
}
