import { ref, onUnmounted, UnwrapRef } from 'vue'
import { FetchTypes, CommonFetchOptions, CommonResult } from '@/services/http/types'
import { useDataTable } from '../datatable'

interface RequestOptions<T extends FetchTypes> {
    params?: {
        pageNum?: number; // 当前页码
        pageSize?: number; // 每页条数
    } & T['request'];
    localPagination?: boolean;
    manual?: boolean; // 是否手动触发
    onSuccess?: (res: CommonResult<T['response']>) => void;
    onError?: (err: string) => void;
    onFinally?: () => void;
}

export function useRequest<T extends FetchTypes>(fetcher: (options: CommonFetchOptions<T>) => Promise<CommonResult<T['response']>>, options?: RequestOptions<T>) {
    type RequestType = T['request']
    type ResponseType = T['response'] extends (infer U)[] ? U : T['response'] // 如果 U 是数组，取 U 的类型

    const { params, localPagination, manual, onSuccess, onError, onFinally } = options ?? {}

    const { dataList, filters, total, pageIndex, pageSize, pageCount } = useDataTable<ResponseType>({
        localPagination,
        pageIndex: params?.pageNum,
        pageSize: params?.pageSize,
    })

    const data = ref<ResponseType>()
    const loading = ref(false)
    const controller = new AbortController()

    // 异步函数
    const runAsync = async (payload: Partial<RequestType> = {}) => {
        if (params && params.pageSize) {
            params.pageNum = pageIndex.value
            params.pageSize = pageSize.value
        }

        const res = await fetcher({
            controller,
            data: typeof params === 'object' ? { ...(params as object), ...payload } : payload
        })

        total.value = res.total

        if (Array.isArray(res.data)) {
            dataList.value = res.data
        } else {
            data.value = res.data as ResponseType
        }

        return res
    }

    // 同步函数
    const run = (payload: Partial<RequestType> = {}) => {
        loading.value = true
        runAsync(payload).then((res) => {
            onSuccess && onSuccess(res)
        }).catch((err) => {
            onError && onError(err)
        }).finally(() => {
            loading.value = false
            onFinally && onFinally()
        })
    }

    const cancel = () => {
        //controller.abort()
    }

    if (!manual) {
        run() // 自动执行
    }

    onUnmounted(() => {
        cancel()
    })

    return {
        loading,
        data,
        dataList,
        total,
        pageIndex,
        pageSize,
        pageCount,
        filters,
        runAsync,
        run,
        cancel,
    }
}

// 未完善
export function useDataList<T>(pageSize: number) {
    const dataList = ref<T[]>([])
    const currentPage = ref(1) // 当前点击所在的页码
    const startIndex = ref(0) // 当前页码的起始位置，用于数组 splice 替换或删除

    const getItem = (index: number) => {
        currentPage.value = Math.ceil((index + 1) / pageSize)
        startIndex.value = (currentPage.value - 1) * pageSize
        return dataList.value[index]
    }

    // 向列表中追加数据
    const appendData = (data: UnwrapRef<T[]>, empty = false) => {
        if (empty) {
            dataList.value = []
        }
        dataList.value.push(...data)
    }

    // 页面返回刷新列表
    const updateData = (data: UnwrapRef<T[]>) => {
        dataList.value.splice(startIndex.value, pageSize, ...data)
        // 去重
    }

    return {
        dataList,
        currentPage,
        getItem,
        appendData,
        updateData,
    }
}