import Long from 'long'
import { Package40 } from '@/utils/websocket/package'
import { FunCode } from '@/constants/funcode'
import { QuoteRequest } from './interface'
import { subscribeListToByteArrary } from './build/encode'
import { parseSubscribeRsp } from './build/decode'
import { useLoginStore } from '@/stores'
import socket from '../index'

/**
 * 向行情服务器发送请求
 * @param params 
 */
function quoteServerMiddleware(params: QuoteRequest): Promise<Proto.QuoteRsp[]> {
    const { getLoginId, getToken } = useLoginStore();
    const content = subscribeListToByteArrary(params.data, getToken(), Long.fromNumber(getLoginId()));

    return new Promise((resolve, reject) => {
        socket.sendQuoteServer({
            data: {
                rspCode: FunCode.QuoteSubscribeRsp,
                payload: new Package40(FunCode.QuoteSubscribeReq, content)
            },
            success: (raw) => {
                if (raw.content) {
                    parseSubscribeRsp(raw.content).then((res) => {
                        resolve(res);
                    }).catch(() => {
                        console.warn('报文解析失败', raw);
                        reject('报文解析失败')
                    })
                } else {
                    reject('数据异常');
                }
            },
            fail: (err) => {
                console.error('服务器请求失败', err);
                reject(err);
            }
        })
    })
}

/**
 * 向行情服务器发送请求
 * @param params 
 */
export function quoteServerRequest(params: QuoteRequest) {
    const { success, fail, complete } = params;

    quoteServerMiddleware(params).then((res) => {
        success && success(res);
    }).catch((msg) => {
        fail && fail({ msg });
    }).finally(() => {
        complete && complete();
    })
}