import { ref, nextTick } from 'vue'
import { setQueryValue } from '@/utils/requestWrappers'
import type { CheckboxValueType } from 'element-plus'

interface PageParams {
    page: number
    pageSize: number
    total?: number
}

interface SearchOptions<T = any> {
    // params引用
    params: {
        pageBean: PageParams
        querys: []
        [key: string]: any
    }
    // 数据加载函数
    loadData: () => Promise<void>
    columnsList: T[]
    currentColumnsKeys: string[]
}

export function useSearch({ params, loadData, columnsList, currentColumnsKeys }: SearchOptions) {
    const tableHeaderSettingRef = ref(null)
    const isShowSearch = ref(true)
    const isShowSearchAll = ref(false)
    const isShowSetting = ref(false)
    let currentDataDel = ref<string[]>([])
    const isIndeterminate = ref(true)
    const checkAll = ref(false)

    // 显示隐藏搜索
    const toggleSearch = () => {
        isShowSearch.value = !isShowSearch.value
    }
    const handleShowAll = () => {
        isShowSearchAll.value = !isShowSearchAll.value
    }
    const toggleSetting = () => {
        isShowSetting.value = !isShowSetting.value

        if (isShowSetting.value) {
            nextTick(() => {
                tableHeaderSettingRef.value?.focus()
            })
        }
    }

    // 优化的表头设置面板焦点处理
    const handleSettingFocusOut = (event: FocusEvent) => {
        // 延迟检查，确保新的焦点元素已经设置
        setTimeout(() => {
            const settingPanel = tableHeaderSettingRef.value
            if (!settingPanel) return

            // 检查新的焦点元素是否在设置面板内
            const activeElement = document.activeElement
            if (!settingPanel.contains(activeElement)) {
                // 焦点移出了设置面板，关闭面板
                isShowSetting.value = false
            }
        }, 0)
    }

    // 菜单弹出层失焦时间
    const tableHeaderSettingBlur = () => {
        nextTick(() => {
            isShowSetting.value = false
        })
    }

    // 表格选中
    const handleSelectionChange = (val: []) => {
        currentDataDel.value = val.map((item: { id: string }) => item.id)
    }

    // 表格刷新
    const refresh = () => {
        currentDataDel.value = []
        params.pageBean.page = 1
        loadData()
    }

    const handleClearQuery = (data: any) => {
        setParams(data)
    }

    // 搜索处理
    const handleSearch = (data: string) => {
        params.pageBean.page = 1
        setParams(data)
        loadData()
    }

    // 重置处理
    const handleReset = (data: any) => {
        handleSearch(data)
    }

    // 设置参数
    function setParams(data: any) {
        data.forEach((item: any) => {
            if (item.queryHandler && typeof item.queryHandler === 'function') {
                item.queryHandler(item.value)
            } else if (Array.isArray(item.prop) && item.prop.length) {
                item.prop.forEach((prop: string) =>
                    setQueryValue(params, prop, item.value, item.operation)
                )
            } else if (typeof item.prop === 'string') {
                setQueryValue(params, item.prop, item.value, item.operation)
            }
        })
    }

    const handleCheckedChange = (val: []) => {
        let checkedCount = val.length
        checkAll.value = checkedCount === columnsList.length
        isIndeterminate.value = checkedCount > 0 && checkedCount < columnsList.length
    }
    const handleCheckAllChange = (val: CheckboxValueType) => {
        isIndeterminate.value = false
        currentColumnsKeys.value = val ? columnsList.map((item) => item.prop) : []
    }

    return {
        tableHeaderSettingRef,
        isShowSetting,
        isShowSearch,
        isShowSearchAll,
        currentDataDel,
        toggleSearch,
        isIndeterminate,
        checkAll,
        handleShowAll,
        toggleSetting,
        handleSettingFocusOut,
        tableHeaderSettingBlur,
        handleSelectionChange,
        refresh,
        handleClearQuery,
        handleReset,
        handleSearch,
        handleCheckedChange,
        handleCheckAllChange
    }
}
