/**
* @Author  : zou.yingbin
* @Create  : 2022/3/26 14:52
* @Modify  : 2022/3/26 14:52
* @note    :
 */

package client

import (
	"fmt"
	"mtp20access/packet"
	"strconv"
)

// DispatchRealQuote 分发行情
func DispatchRealQuote(p *packet.MiQuotePacket, clinet *Client) {
	// TODO: 目前只实现了订阅发送模式, 未支持全部发送模式

	pending := make([]byte, 0)
	// 解析接收到的商品
	ware := parseWareInfo(p)
	// 获取已订阅行情商品列表
	quoteSubs := clinet.GetQuoteSubs()
	for _, sub := range quoteSubs {
		for i := range ware {
			w := &ware[i]
			if w.exchId == strconv.Itoa(sub.ExchangeId) && w.goodsCode == sub.GoodsCode {
				pending = append(pending, w.buf...)
			}
		}
	}
	if len(pending) > 0 {
		// 按商品重新打包
		quote := packet.MiQuotePacket{
			BigType:   p.BigType,
			SmallType: p.SmallType,
			SerialNum: p.SerialNum,
			Mode:      p.Mode,
		}
		quote.Msg = pending
		sendBuf := quote.EnPack()

		// 发送给客户端
		if clinet.quoteWriteChan != nil {
			clinet.quoteWriteChan <- sendBuf
		}
	}
}

// parseWareInfo 从报文中解析出所有报价商品
func parseWareInfo(p *packet.MiQuotePacket) []wareInfo {
	ware := make([]wareInfo, 0)

	// 0x42(66)是控制信息，要过滤掉
	if p.OriMsg[5] == 0x42 {
		return ware
	}

	data := p.OriMsg[14:]
	nPos1, nPos2 := -1, -1
	for i := 0; i < len(data); i++ {
		// 报价包开始
		if data[i] == 0x10 {
			nPos1 = i
		}
		// 报价包结束
		if data[i] == 0x11 {
			nPos2 = i + 1
		}
		if nPos1 >= 0 && nPos2 > 0 {
			// 处理闪退问题
			if nPos1 > nPos2 {
				fmt.Printf("接收到错误的行情记录(nPos1>nPos2): %v \n", p.OriMsg)

				// 重置nPos1, nPos2 继续查找下一个报价包
				nPos1, nPos2 = -1, -1
			}

			v := wareInfo{buf: data[nPos1:nPos2]}
			v.parseField()
			//v.printInfo()
			//v.debugPrintAllField()
			ware = append(ware, v)
			// 重置nPos1, nPos2 继续查找下一个报价包
			nPos1, nPos2 = -1, -1
		}
	}
	return ware
}
