import { computed, reactive, ref, unref } from 'vue'

export function useCoupon() {
    const couponId = ref()
    const setCouponId = (id: number) => {
        couponId.value = id
    }
    return {
        couponId,
        setCouponId
    }
}

export function useZPaging(payload: any, requestApi: (params: any) => Promise<any>) {
    const paging = ref()
    const state = reactive({
        totalParam: {}
    })

    /**获取列表数据 */
    const queryList = async (page_no: number, page_size: number, config = {}) => {
        if (typeof requestApi !== 'function') return
        try {
            uni.showLoading({
                title: '加载中...'
            })
            const params = {
                ...payload,
                ...state.totalParam,
                ...config,
                pageNo: page_no,
                pageSize: page_size
            }
            const res = await requestApi?.(params)
            paging.value.complete(res?.lists || res || [])
        } catch (e) {
            paging?.value?.complete(false)
        }
        uni.hideLoading()
    }
    /**更新参数 */
    const updateTotalParam = (params: any) => {
        let nowParam: Record<string, any> = {}
        for (const key in params) {
            nowParam[key] = params[key]
        }
        Object.assign(state.totalParam, nowParam)
    }
    /**刷新列表 */
    const refresh = (params: any) => {
        updateTotalParam(params)
        paging.value.reload()
    }

    return {
        paging,
        queryList,
        refresh
    }
}

export function useTabs() {
    const tabStatus = ref(1) //tab状态
    const setTabIndex = computed(() => unref(tabStatus) - 1) //当前点击的tab索引

    /**切换tab */
    const handleChangeTab = (index: number) => {
        tabStatus.value = index + 1
    }
    return {
        tabStatus,
        setTabIndex,
        handleChangeTab
    }
}
