import { modal } from '@/utils'
import { intersectionWith } from 'lodash-es'
import type { DataTableRowKey } from 'naive-ui'
import { computed, reactive, type Ref } from 'vue'

export default (rowKey: string, dataSource: Ref<any[]>) => {
  const tableSelect = reactive<Map<DataTableRowKey, any>>(new Map())

  const selectKeys = computed(() => {
    return [...tableSelect.keys()]
  })
  const selectRows = computed(() => {
    return [...tableSelect.values()]
  })

  /**
   * 每次数据源变化之后 通过【rowKey】生成键值map
   */
  const dataSourceMap = computed(() => {
    return new Map(
      dataSource.value.map((row) => {
        return [row[rowKey], row]
      })
    )
  })

  const onSelectRowKeysChange = (allSelectKeys: DataTableRowKey[]) => {
    const currentKeys = new Set(allSelectKeys)
    // 更新 tableSelect，只处理新增和移除的项
    for (let [key, row] of dataSourceMap.value) {
      if (currentKeys.has(key)) {
        // 添加或保持已选中的项
        tableSelect.set(key, row)
      } else {
        // 移除未被选中的项
        tableSelect.delete(key)
      }
    }
  }

  const clearSelect = () => {
    tableSelect.clear()
  }

  const selectDetail = () => {
    modal.create({
      title: '选中的数据',
      preset: 'card',
      draggable: true,
      content: () => (
        <>
          <ul>
            {selectRows.value.map((row) => {
              return <li>{JSON.stringify(row)}</li>
            })}
          </ul>
        </>
      ),
    })
  }

  return {
    selectKeys,
    selectRows,
    onSelectRowKeysChange,
    clearSelect,
    selectDetail,
  }
}
