import axios from '@/common/services/axios-instance'

function extendNode(item) {
  // 按穿梭组件的要求添加属性
  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 = item.text
  item.type = type
  item.scopedSlots = { title: 'custom' }
  // 使用checkable控制树节点是否可选
  item.checkable = item.props.isHasAdmin === 'true'
  return item
}
class AddressbookService {
  // 组树
  groupTree() {
    return axios({
      url: 'api/framework/v1/address-manager/address-group/group-statistic-list',
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }

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

  // 获取部门下的部门
  getChildNodes(id, params = {}) {
    return axios
      .get(
        `api/framework/v1/oa-base-address-unit/group/get-children?orderBy=${encodeURIComponent(
          'weight asc'
        )}&parent=${id}`,
        { params }
      )
      .then((res) => res.data.map((item) => extendNode(item)))
  }

  getFullPath(deptId) {
    return axios
      .get(`api/framework/v1/oa-base-address-unit/groups/${deptId}/full-path`)
      .then((res) => res.data.map((item) => extendNode(item)))
  }

  getGroupTree({ expandedKey, rootNode, nonSysId }) {
    if (rootNode && rootNode.code && rootNode.name) {
      rootNode = Promise.resolve([
        { text: rootNode.name, checkable: true, type: 'Group', isLeaf: false, ...rootNode },
      ])
    } else {
      rootNode = this.getRootNode()
    }
    return rootNode.then((data) => {
      let p = Promise.resolve()
      let fullPath = []
      if (expandedKey && expandedKey[0]) {
        // 设置了默认展开节点，获取每层树节点
        p = this.getFullPath(expandedKey[0]).then((items) => {
          if (!items.length) return
          fullPath = items
          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, nonSysId ? { nonSysId } : {})
          )
          return Promise.all(pArray).then((items) => {
            const tree = items.reduce((a, b) => {
              // 通过fullpathId找到父节点
              if (a.length !== 0) {
                const arrId = a[0].props.fullpathId.split('/')
                const fullpathId = arrId[arrId.length - 1]
                const node = b.find((item) => fullpathId === item.code)
                if (node) node.children = a
              }
              return b
            })
            return tree
          })
        })
      }
      return p.then((tree) => {
        data[0].children = tree
        return { data, fullPath }
      })
    })
  }

  // 非OA组织机构删除
  deleteGroup(params) {
    return axios({
      url: 'api/framework/v1/oa-base-address-unit/delete-by-ids',
      method: 'post',
      data: params,
    })
  }

  delGroupById(id) {
    return axios
      .delete(`api/framework/v1/oa-base-address-unit/delete-by-ids/${id}`)
      .then((res) => res)
  }

  // 上传头像
  uploadAvatar(param) {
    return axios
      .post(`api/framework/v1/oa-base-address-user/Base64`, param, {
        headers: {
          'Content-Type': 'application/json',
        },
      })
      .then(function(res) {
        return res
      })
  }

  //  获取 groupId
  getGroupCode() {
    return axios({
      url: 'api/framework/v1/attachment-extend/attachments-create-group-code',
      method: 'get',
    })
  }

  // 非OA用户通讯录导入
  notOaImport(params) {
    return axios({
      url: 'api/framework/v1/oa-base-address-user/not-OA/import-excel',
      method: 'post',
      data: params,
    })
  }

  // OA用户通讯录导入
  oaImport(params) {
    return axios({
      url: 'api/framework/v1/oa-base-address-user/OA/import-excel',
      method: 'post',
      data: params,
    })
  }

  // 获取当前节点的props相关内容
  getNodeProps(treeId) {
    return axios({
      url: `api/framework/v1/oa-base-address-unit/groups/node-props/${treeId}`,
      method: 'get',
    })
  }

  groupIsCanDelete(params) {
    return axios({
      url: 'api/framework/v1/address-manager/addresses/isCanDelete',
      method: 'get',
      params,
    })
  }

  // 初始化数据
  initialization() {
    return axios({
      url: `api/we-open/v1/address-data/data-sync`,
      method: 'get',
    })
  }

  // 初始化数据
  getJobOptions() {
    return axios({
      url: `api/xcoa-mobile/v1/oa-base-address-user/level`,
      method: 'get',
    })
  }
}

export default new AddressbookService()
