import { TreeNodeData } from '@arco-design/web-vue'
import { Ref, ref } from 'vue'
import _, { isUndefined } from 'lodash'
/**
 * 根据ids搜索出nodes
 *
 * @param ids 选中的ids
 * @param tree 树所有节点数据
 */
const searchTree = (ids: string[], tree: any[]): any[] => {
  const finds: any[] = []
  if (tree) {
    tree.forEach((node) => {
      if (node) {
        if (ids.findIndex((id) => id === node.id) >= 0) {
          finds.push(node)
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const findChild = searchTree(ids, node.children)
        finds.push(...findChild)
      }
    })
  }
  return _.unionWith(finds, (arrVal, othVal) => {
    return arrVal.id === othVal.id
  })
}
export default (treeData: Ref<any[]>, limit: number) => {
  /**
   * 选中的ids
   */
  const checkedKeys = ref<string[]>([])
  /**
   * 选中的nodes
   */
  const checkedNodes = ref<any[]>([])
  const canCheck = computed(() => limit > checkedKeys.value.length)
  /**
   * 计算checkedKeys和checkedNodes
   * @param node 节点数据{id,name,...}
   */
  const checkChange = (node?: any) => {
    if (!isUndefined(node)) {
      const idx = checkedKeys.value.findIndex((item) => item === node.id)
      if (idx >= 0) {
        checkedKeys.value.splice(idx, 1)
        checkedNodes.value.splice(idx, 1)
      } else {
        if (!canCheck.value) {
          checkedKeys.value.splice(checkedKeys.value.length - 1, 1)
          checkedNodes.value.splice(checkedNodes.value.length - 1, 1)
        }
        checkedKeys.value.push(node.id)
        checkedNodes.value.push(node)
      }
    }
  }

  /**
   * 提供给a-tree的@select事件
   * @param keys 选择的keys,string[]
   * @param data 反馈数据
   */
  const handleSelect = (
    keys: (string | number)[],
    data: { selected?: boolean; selectedNodes: TreeNodeData[]; node?: TreeNodeData; e?: Event }
  ) => {
    if (data.node && data.node.checkable) {
      checkChange(data.node)
    }
  }

  /**
   * 提供给a-tree的@check事件
   * @param keys 选择的keys,string[]
   * @param data 反馈数据
   */
  const handleCheck = (
    keys: Array<string | number>,
    data: {
      checked?: boolean
      checkedNodes: TreeNodeData[]
      node?: TreeNodeData
      e?: Event
      halfCheckedKeys: (string | number)[]
      halfCheckedNodes: TreeNodeData[]
    }
  ) => {
    if (data.node && data.node.checkable) {
      checkChange(data.node)
    }
  }

  /**
   * 取消选择
   * @param node 节点数据{id,name,...}
   */
  const handleUncheck = (node: any) => {
    checkChange(node)
  }
  /**
   * 让checkedNodes根据checkedKeys同步数据
   */
  const synchronize = () => {
    checkedNodes.value = searchTree(checkedKeys.value, treeData.value)
  }
  return {
    checkedKeys,
    checkedNodes,
    handleSelect,
    handleUncheck,
    handleCheck,
    synchronize
  }
}
