import { computed, ComputedRef, nextTick, Ref, ref, toRaw, unref, watch } from 'vue'
import { BasicTableProps, TableRowSelection } from '@/types/table'
import { ElTable } from 'element-plus'
export function useRowSelection(
  propsRef: ComputedRef<BasicTableProps>,
  tableData: Ref<Recordable[]>,
  emit: EmitType,
  tableElRef: Ref<InstanceType<typeof ElTable>>
) {
  //选中的keys
  const selectedRowKeysRef = ref<string[]>([])
  //选中的行
  const selectedRowRef = ref<Recordable[]>([])

  const getRowSelectionRef = computed((): TableRowSelection | null => {
    //找到配置没有就代表不需要多选
    const { rowSelection } = unref(propsRef)
    if (!rowSelection) {
      return null
    }

    return {
      selectedRowKeys: unref(selectedRowKeysRef),
      ...rowSelection
    }
  })

  //监听传入值变化重新选中要选的玩意
  watch(
    () => unref(propsRef).rowSelection?.selectedRowKeys,
    (v: string[]) => {
      setSelectedRowKeys(v)
    }
  )

  //监听对选中的变化并emit出去
  watch(
    () => unref(selectedRowKeysRef),
    () => {
      nextTick(() => {
        //const { rowSelection } = unref(propsRef)
        emit('selecet-key-change', {
          keys: getSelectRowKeys(),
          rows: tableElRef.value?.getSelectionRows()
        })
      })
    },
    { deep: true }
  )

  //设置选中值
  function setSelectedRowKeys(rowKeys: string[]) {

    selectedRowKeysRef.value = rowKeys
    let rowkey = unref(propsRef).rowKey
    //找到对应的节点 包含当前的table 和 历史比如说上一页下一页的row
    let trueList = unref(tableData).filter((item) => {
      return rowKeys.includes(item[rowkey as string])
    })
    if (trueList) {
      trueList.forEach((row) => {
        unref(tableElRef)!.toggleRowSelection(row, undefined)
      })
    }
    selectedRowRef.value = trueList
  }

  //获取选中行
  function getSelectRowKeys() {
    return unref(selectedRowKeysRef)
  }

  //手动设置选中行
  function setSelectedRows(rows: Recordable[]) {
    selectedRowRef.value = rows
  }

  //清空选中行
  function clearSelectedRowKeys() {
    selectedRowRef.value = []
    selectedRowKeysRef.value = []
    tableElRef.value.clearSelection()
  }

  function deleteSelectRowByKey(key: string) {
    const selectedRowKeys = unref(selectedRowKeysRef)
    const index = selectedRowKeys.findIndex((item) => item === key)
    if (index !== -1) {
      unref(selectedRowKeysRef).splice(index, 1)
    }
  }


  function getSelectRows<T = Recordable>() {
    // const ret = toRaw(unref(selectedRowRef)).map((item) => toRaw(item));
    return unref(selectedRowRef) as T[]
  }

  function getRowSelection() {
    return unref(getRowSelectionRef)!
  }



  return {
    getRowSelection,
    getRowSelectionRef,
    getSelectRows,
    getSelectRowKeys,
    setSelectedRowKeys,
    clearSelectedRowKeys,
    deleteSelectRowByKey,
    setSelectedRows
  }
}
