import APP from '@/services';
import { funCode } from '@/services/funcode/index';
import { buildSubscribePeq, parseSubscribeRsp } from '@/services/socket/quota/adapter/index';
import { Callback } from '@/utils/websocket/index';
import { SubscribeInfoType } from './interface';

const subscribeGoodsList = new Map<string, SubscribeInfoType[]>(); // 订阅商品数据中心池

/**
 * 重组订阅商品（包括去重，组合）
 */
function recombinationSubscribeGoods(): SubscribeInfoType[] {
    const result: SubscribeInfoType[] = [];
    const goodsCodeSet = new Set<string>();
    for (const item of subscribeGoodsList.values()) {
        item.forEach((e) => {
            if (!goodsCodeSet.has(e.goodsCode)) {
                result.push(e);
            }
        });
    }
    return result;
}

/**
 * 开始商品订阅
 * @param subscribeInfos
 */
function actionSubcribe() {
    const arr = recombinationSubscribeGoods();
    const req = buildSubscribePeq(arr);
    APP.sendQuoteServer(req, funCode.MainClassNumber_Quota_SubscriptRsp, {
        onSuccess: (res: any) => {
            parseSubscribeRsp(res)
                .then((value) => {
                    if (value) {
                        console.log('订阅成功！', value);
                    }
                })
                .catch((err) => {
                    console.log('订阅失败：', err);
                });
        },
        onFail: (err) => console.log('订阅失败：', err),
    } as Callback);
}

/**
 * 添加行情订阅
 * @param subscribeInfos
 */
export function addSubscribeQuotation(uuid: string, subscribeInfos: SubscribeInfoType[]) {
    APP.connectQuote().then(() => {
        subscribeGoodsList.set(uuid, subscribeInfos);
        actionSubcribe();
    });
}

/**
 * 删除订阅
 */
export function removeSubscribeQuotation(uuid: string) {
    if (subscribeGoodsList.has(uuid)) {
        subscribeGoodsList.delete(uuid);
        if (subscribeGoodsList.size) {
            actionSubcribe();
        } else {
            // 没有订阅商品时候，主动断开行情链路
            APP.closeQuote();
        }
    }
}
