import { reactive, toRefs, onUnmounted } from 'vue'
import { orderListAll } from '@/services/api/common'

export function useMarket() {
    const state = reactive({
        loading: true,
        markets: <Model.OrderListAllRsp[]>[]
    })

    const controller = new AbortController()
    const readyCallbackMap = new Map<symbol, () => void>()

    const getMarketById = (marketId?: number) => {
        return state.markets.find((e) => e.marketid === marketId)
    }

    // 获取市场列表
    const getMarketOptions = (filtered: number | number[] = [], reverse = false) => {
        const valuesSet = new Set(Array.isArray(filtered) ? filtered : [filtered])
        if (valuesSet.size === 0) {
            return state.markets.map((e) => ({
                label: e.marketname,
                value: e.marketid
            }))
        }
        const result = state.markets.filter((e) => {
            if (reverse) {
                // 排除市场
                return !valuesSet.has(e.trademode) && !valuesSet.has(e.marketid)
            } else {
                // 匹配市场
                return valuesSet.has(e.trademode) || valuesSet.has(e.marketid)
            }
        })
        return result.map((e) => ({
            label: e.marketname,
            value: e.marketid
        }))
    }

    // 注册成功回调
    const registerMarketReadyCallback = (callback: () => void) => {
        if (state.loading) {
            const key = Symbol()
            readyCallbackMap.set(key, callback)
        } else {
            callback()
        }
    }

    // 获取市场列表
    orderListAll({ controller }).then((res) => {
        state.markets = res.data
        readyCallbackMap.forEach((callback) => callback())
        readyCallbackMap.clear()
    }).finally(() => {
        state.loading = false
    })

    onUnmounted(() => {
        controller.abort()
        readyCallbackMap.clear()
    })

    return {
        ...toRefs(state),
        getMarketOptions,
        getMarketById,
        registerMarketReadyCallback
    }
}