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 dataList = computed<UnwrapRef<T[]>>({
        get() {
            const result = dataSource.value.filter((row) => {
                // 过滤所有查询条件
                return filterData.value.every((e) => {
                    return e.fields.some((field) => {
                        const value = row[field]
                        if (typeof value === 'number') {
                            return e.values.includes(value as T[keyof T])
                        }
                        return e.values.some((text) => {
                            return String(value).toLowerCase().indexOf(String(text)) >= 0
                        })
                    })
                })
            })
            // 本地分页
            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 = () => {
        const { filters } = _.cloneDeep(defaultOption)

        const items = filters.map((defaultItem, index) => {
            const currentItem = filterOption.filters[index]
            return currentItem.locked ? currentItem : defaultItem
        })

        filterOption.filters = items
    }

    // 获取过滤参数，支持多条件查询
    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> = Object.create({})

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

        return params
    }

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