import { reactive, ref, shallowRef, computed, UnwrapRef } from 'vue'
import { FilterData, FilterOption, DataTableOptions } from './types'
import _ from 'lodash'

export function useDataTable<T>(options: DataTableOptions = {}) {
    // 数据源
    const dataSource = ref<T[]>([])
    // 总条数
    const total = shallowRef(0)
    // 每页条数
    const pageSize = shallowRef(options.pageSize ?? 20)
    // 当前页码
    const pageIndex = shallowRef(options.pageIndex ?? 1)
    // 总页数
    const pageCount = computed(() => Math.ceil(total.value / pageSize.value) || 1)
    // 过滤筛选值
    const filterData = shallowRef<FilterData<T>[]>([])

    const matchesFilter = (row: T, filter: FilterData<T>) => {
        return filter.fields.some((field) => {
            const value = row[field]
            if (typeof value === 'number') {
                return filter.values.includes(value)
            }
            return filter.values.some((text) => String(value).toLowerCase().includes(String(text).toLowerCase()))
        })
    }

    // 数据列表
    const dataList = computed<UnwrapRef<T[]>>({
        get() {
            const result = dataSource.value.filter((row) => {
                // 过滤所有查询条件
                return filterData.value.every((filter) => matchesFilter(row as T, filter))
            })
            // 本地分页
            if (options.localPagination) {
                total.value = result.length
                return result.slice((pageIndex.value - 1) * pageSize.value, pageIndex.value * pageSize.value)
            }
            return result
        },
        set(val) {
            dataSource.value = val
        }
    })

    return {
        dataList,
        pageIndex,
        pageSize,
        pageCount,
        total,
        filterData,
    }
}

export function useDataFilter<T>(defaultOption: FilterOption<T, keyof T>) {
    const defaultOptionCopy = _.cloneDeep(defaultOption)

    const filterOption: FilterOption<T, keyof T> = reactive(Object.create(defaultOptionCopy))

    const queryParams = computed(() => getQueryParams())

    // 重置过滤条件
    const resetFilters = (...fields: (keyof T)[]) => {
        defaultOption.filters.forEach((defaultItem, index) => {
            if (!defaultItem.locked) {
                const currentItem = filterOption.filters[index]
                if (!fields.length || fields.includes(defaultItem.field)) {
                    currentItem.value = defaultItem.value
                }
            }
        })
    }

    // 获取过滤参数，支持多条件查询
    const getFilterParams = (clear = false) => {
        if (clear) resetFilters()
        const options: FilterData<T>[] = []

        // filterOption.items.forEach((e) => {
        //     const { keys, value } = e
        //     if (value) {
        //         options.push({
        //             keys,
        //             filteredValue: [value],
        //         })
        //     }
        // })

        return options
    }

    // 获取查询参数，支持多条件查询
    const getQueryParams = (clear = false) => {
        if (clear) resetFilters()
        const params: Partial<T> = {}

        filterOption.filters.forEach((e) => {
            if (e.value !== undefined) {
                params[e.field] = e.value
            }
        })

        return params
    }

    return {
        queryParams,
        filterOption,
        getFilterParams,
        getQueryParams,
        resetFilters
    }
}