import axios from '@/common/services/axios-instance'
import pickValues from '@/common/services/pick-values'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import sdGroupPicker from '@/common/components/sd-group-picker.vue'
function extendNode(item, options = {}) {
  // 按穿梭组件的要求添加属性
  const type = item.props?.type?.startsWith('G') ? 'Group' : 'User'
  let code = item.id
  if (item.props.type === 'U') {
    code = item.props.account
  }
  item.title = item.text
  item.isLeaf = item.leaf
  item.code = code
  item.name = options.levPath && item.props?.levPath ? item.props.levPath : item.text
  item.type = type
  return item
}
class AddressBook {
  selectGroup(option = {}) {
    return pickValues(sdGroupPicker, option)
  }

  selectUser(option = {}) {
    return pickValues(sdUserPicker, option)
  }

  getRootNode(params) {
    return axios // 获取部门下用户
      .get(`api/framework/v1/group-manager/group/root-node`, { params })
      .then((res) => [extendNode(res.data)])
  }

  getChildNodes(id, options = {}) {
    let type, isContainSub, hierarchical, levPath, secretLevel
    // 8.0.16后参数放到object里了，并且兼容之前的方式
    if (typeof arguments[1] === 'object') {
      ;({ type = 'GU', isContainSub = false, hierarchical, levPath, secretLevel } = options)
    } else {
      ;[id, type = 'GU', isContainSub = false, hierarchical, levPath] = arguments
    }
    const paramsU = {}
    const paramsD = {}
    paramsU.isContainSub = isContainSub
    paramsD.parent = id
    if (hierarchical === undefined) {
      hierarchical = ''
    } else if (hierarchical) {
      hierarchical = '1'
    } else {
      hierarchical = '0'
    }
    if (secretLevel) {
      paramsU.securityLevel = secretLevel
    }
    if (type === 'U') {
      return axios // 获取部门下用户
        .get(
          `api/framework/v1/user-manager/users/${id}/users?orderBy=${encodeURIComponent(
            'weight asc,id asc'
          )}`,
          { params: { ...paramsU, hierarchical } }
        )
        .then((res) => res.data.map((item) => extendNode(item, { levPath })))
    } else {
      return axios // 获取部门下的部门
        .get(`api/framework/v1/group-manager/group/getChildren`, {
          params: { ...paramsD, hierarchical },
        })
        .then((res) => res.data.map((item) => extendNode(item, { levPath })))
    }
  }

  getUserGroups() {
    return axios // 获取群组
      .get(`api/framework/v1/usergroup-manager/usergroups/groupnodes`)
      .then((res) => res.data.map((item) => extendNode(item)))
  }

  getDepUserGroupsMembers(parentId, options = {}) {
    const params = {}
    if (options.secretLevel) {
      params.securityLevel = options.secretLevel
    }
    return axios // 获取部门群组下的用户
      .get(`api/framework/v1/user-manager/groups/${parentId}/users`, { params })
      .then((res) => res.data.map((item) => extendNode(item)))
  }

  getUserGroupsMembers(userGroupId, options = {}) {
    const params = {}
    if (options.secretLevel) {
      params.securityLevel = options.secretLevel
    }
    return axios // 获取群组下的用户
      .get(`api/framework/v1/usergroup-manager/usergroups/${userGroupId}/members`, { params })
      .then((res) => res.data.map((item) => extendNode(item)))
  }

  getRoles(params = {}) {
    return axios // 获取角色
      .get(`api/framework/v1/role-manager/roles/${encodeURI('code ASC')}`, { params })
      .then((res) => {
        res.data.forEach((item) => {
          item.title = item.name // 按树的要求添加属性
          item.key = item.code
          item.slots = { icon: 'G' }
        })
        return res.data
      })
  }

  getRolesMembers(roleCode) {
    return axios //  获取角色下的用户
      .get(`api/framework/v1/user-manager/roles/${roleCode}/users`)
      .then((res) => res.data.map((item) => extendNode(item)))
  }

  // 查询
  usersQuery(str, ids = [], options = {}) {
    const param = {
      expressions: [
        {
          dataType: 'exps',
          op: 'or',
          expressionsValue: [
            {
              dataType: 'str',
              name: 'name',
              op: 'like',
              stringValue: `%${str}%`,
            },
            {
              dataType: 'str',
              name: 'account',
              op: 'like',
              stringValue: `%${str}%`,
            },
          ],
        },
      ],
      ids,
    }
    if (options.secretLevel) {
      param.securityLevel = options.secretLevel
    }
    param.hierarchical = options.hierarchical

    if (param.hierarchical === undefined) {
      param.hierarchical = ''
    } else if (param.hierarchical) {
      param.hierarchical = '1'
    } else {
      param.hierarchical = '0'
    }
    param.rootIds = options.rootIds
    return axios
      .post('api/framework/v1/user-manager/users_query', param)
      .then((res) => res.data.map((item) => extendNode(item)))
  }

  // 查询
  groupsQuery(str, options = {}) {
    let hierarchical, levPath
    if (typeof arguments[1] === 'object') {
      ;({ hierarchical, levPath } = options)
    } else {
      ;[str, hierarchical, levPath] = arguments
    }
    if (hierarchical === undefined) {
      hierarchical = undefined
    } else if (hierarchical) {
      hierarchical = '1'
    } else {
      hierarchical = '0'
    }
    const param = {
      expressions: [
        {
          dataType: 'str',
          name: 'name',
          op: 'like',
          stringValue: `%${str}%`,
        },
      ],
      orderBy: 'name asc',
      hierarchical,
      maxResults: -1,
    }
    return axios
      .post('api/framework/v1/group-manager/groups_query', param, {
        headers: {
          'Content-Type': 'application/json',
        },
      })
      .then((res) => res.data.map((item) => extendNode(item, { levPath })))
  }

  getFullPath(id) {
    return axios
      .get(`api/framework/v1/group-manager/groups/${id}/fullpath`)
      .then((res) => res.data.map((item) => extendNode(item)))
  }

  getGroupTree({ expandedKey, rootNode, hierarchical, levPath }) {
    if (rootNode && rootNode.code && rootNode.name) {
      rootNode = Promise.resolve([
        { text: rootNode.name, checkable: true, type: 'Group', isLeaf: false, ...rootNode },
      ])
    } else {
      rootNode = this.getRootNode({
        hierarchical: hierarchical === undefined ? '' : hierarchical ? '1' : '0',
      })
    }
    return rootNode.then((data) => {
      let p = Promise.resolve()
      if (expandedKey && expandedKey[0]) {
        // 设置了默认展开节点，获取每层树节点
        p = this.getFullPath(expandedKey[0]).then((items) => {
          if (!items.length) return
          const index = items.findIndex((item) => item.code === data[0].code)
          if (index !== -1) {
            // 根节点在fullpath路径里,从fullpath截取
            items.splice(index + 1, 99)
          } else {
            // 如果不是分级授权，路径信息里没有绝对根节点，这种情况下自己拼上根节点
            items = [...items, ...data]
          }
          const pArray = items.map((item) =>
            this.getChildNodes(item.code, {
              type: 'G',
              isContainSub: false,
              hierarchical,
              levPath,
            })
          )
          return Promise.all(pArray).then((items) => {
            const tree = items.reduce((a, b) => {
              // 通过fullpathId找到父节点
              if (a.length !== 0) {
                const node = b.find((item) => a[0].props.fullpathId.endsWith(item.code))
                if (node) node.children = a
              }
              return b
            })
            return tree
          })
        })
      }
      return p.then((tree) => {
        data[0].children = tree
        return data
      })
    })
  }

  // 根据群组名称检查是否已经存在个人用户群组
  checkExistGroupByName(groupName) {
    return axios
      .get(`api/framework/v1/usergroup-manager/usergroups/check?groupName=${groupName}`)
      .then((res) => res)
  }

  // 删除个人用户群组
  delGroupById(params) {
    return axios
      .delete(`api/framework/v1/page/oaPersonalUserGroup`, { params: params })
      .then((res) => res)
  }
}

export default new AddressBook()
