import { v4 } from 'uuid'
import { quoteServerRequest } from '@/services/socket/quote'
import { useLoginStore } from '@/stores'
import eventBus from '@/services/bus'
import socket from '@/services/socket'

/**
 * 订阅行情
 */
export default new (class {
    /** 行情订阅列表 */
    private quoteSubscribeMap = new Map<string, string[]>()

    constructor() {
        // 接收行情服务断线重连成功通知
        eventBus.$on('QuoteServerReconnectNotify', () => {
            this.quoteSubscribe();
        })
    }

    /**
     * 开始行情订阅
     */
    private quoteSubscribe = () => {
        const subscribeData: Proto.QuoteReq[] = []

        this.quoteSubscribeMap.forEach((value) => {
            const item = value.map((code) => ({
                goodsCode: code,
                exchangeCode: 250,
                subState: 0
            }))
            subscribeData.push(...item)
        })

        if (subscribeData.length) {
            console.log('开始行情订阅', subscribeData)
            quoteServerRequest({
                data: subscribeData,
                success: (res) => {
                    if (res.length) {
                        console.log('行情订阅成功', res)
                    } else {
                        console.error('行情订阅失败')
                    }
                },
                fail: (err) => {
                    console.error('行情订阅失败', err)
                }
            })
        } else {
            // 没有订阅商品的时候，断开连接
            socket.closeQuoteServer()
        }
    }

    /**
     * 添加行情订阅
     * @param goodsCodes 
     * @param key 
     * @returns 
     */
    addQuoteSubscribe = (goodsCodes: string[], key?: string) => {
        const { getToken } = useLoginStore()
        const uuid = key ?? v4()
        const value = this.quoteSubscribeMap.get(uuid) ?? []

        const start = () => {
            // 对相同 key 订阅的商品进行合并处理
            this.quoteSubscribeMap.set(uuid, [...value, ...goodsCodes])
            this.quoteSubscribe()
        }

        return {
            uuid,
            start,
            stop: () => {
                const flag = this.quoteSubscribeMap.delete(uuid)
                if (flag) {
                    console.log('删除订阅', uuid)
                }
                if (getToken()) {
                    this.quoteSubscribe()
                }
                return flag
            },
        }
    }

    /**
     * 删除行情订阅
     * @param keys 
     */
    removeQuoteSubscribe = (...keys: string[]) => {
        if (keys.length) {
            keys.forEach((key) => {
                if (this.quoteSubscribeMap.delete(key)) {
                    console.log('删除订阅', key)
                }
            })
        } else {
            console.log('取消订阅')
            this.quoteSubscribeMap.clear()
        }
        this.quoteSubscribe()
    }
})