import { METHOD, request } from '@vue2-client/utils/request'
import { runLogic } from '@vue2-client/services/api/common'

function getLeafNodes(nodes) {
  // 确保 nodes 是数组
  const nodeArray = Array.isArray(nodes) ? nodes : [nodes]
  return nodeArray.reduce((leaves, node) => {
    if (node.children && node.children.length) {
      // 递归处理子节点并合并结果
      leaves.push(...getLeafNodes(node.children))
    } else {
      // 当前节点是叶子节点时，直接加入结果
      leaves.push(node)
    }
    return leaves
  }, [])
}

function getLeafNodesByCondition(type, nodes, parent = null) {
  // 确保 nodes 是数组
  const nodeArray = Array.isArray(nodes) ? nodes : [nodes]

  return nodeArray.reduce((leaves, node) => {
    const isValidNode = node.resourcetype === type && node.name !== '组织机构'
    const updatedParent = node.name === '组织机构' ? null : node.name

    if (node.children && node.children.length) {
      // 当前节点符合条件时，加入叶子节点列表
      if (isValidNode) {
        leaves.push({
          ...node,
          name: parent ? `${node.name}-${parent}` : node.name
        })
      }
      // 递归处理子节点
      leaves.push(...getLeafNodesByCondition(type, node.children, updatedParent))
    } else if (isValidNode) {
      // 无子节点但符合条件时，直接加入叶子节点列表
      leaves.push({
        ...node,
        name: parent ? `${node.name}-${parent}` : node.name
      })
    }

    return leaves
  }, [])
}

function transformData(inputData) {
  function transform(node) {
    return {
      label: node.name,
      value: node.id,
      f_organization_id: node.f_organization_id,
      parentid: node.parentid || node.parentId || node.parent_id,
      orgid: node.orgid,
      children: Array.isArray(node.children) ? node.children.map(transform) : []
    }
  }

  return inputData.map(transform)
}

// 复用策略配置：相同请求共享结果，避免重复网络请求
const REUSE_CONFIG = { dedupe: true, dedupeStrategy: 'reuse' }

function getResData(params, toCallback) {
  const data = {
    userId: params.userid,
    roleName: params.roleName,
    filter: params.filter,
    filterType: params.filterType
  }
  if (params.source === '获取分公司') {
    runLogic('getOrgBySearch', data, 'af-system', false, REUSE_CONFIG).then(res => toCallback(res))
  } else if (params.source === '获取部门') {
    runLogic('getDepBySearch', data, 'af-system', false, REUSE_CONFIG).then(res => toCallback(res))
  } else if (params.source === '获取人员') {
    runLogic('getUserBySearch', data, 'af-system', false, REUSE_CONFIG).then(res => toCallback(res))
  } else if (params.source === '根据角色获取人员') {
    runLogic('getUserBySearchRole', data, 'af-system', false, REUSE_CONFIG).then(res => toCallback(res))
  } else {
    return search(params).then(res => toCallback(res))
  }
}

export async function searchToOption(params, callback) {
  function toCallback(res) {
    if (res.length) {
      if (res[0].children && res[0].children.length) {
        if (res[0].children[0].children) {
          callback(transformData(res[0].children[0].children))
        } else {
          callback(transformData(res[0].children))
        }
      } else {
        callback(res[0].children)
      }
    } else {
      callback(res)
    }
  }

  await getResData(params, toCallback)
}

export async function searchToListOption(params, callback) {
  function toCallback(res) {
    if (params.source.includes('人员')) {
      callback(transformData(getLeafNodes(res)))
    } else {
      const type = params.source.includes('公司') ? 'organization' : 'department'
      callback(transformData(getLeafNodesByCondition(type, res)))
    }
  }

  await getResData(params, toCallback)
}

export async function search(params) {
  return request('/rs/search', METHOD.POST, params)
}

export default { searchToOption, search }
