// MCPB模块
// 秒寻科技
// zt 2024-11-11

package mcpb

import (
	"encoding/binary"
	"errors"
	"ipsomc/module/ps/psmodel"
	"ipsomc/module/ps/pspublic"
	"ipsomc/module/upgrade"
	"time"
)

type McpB struct {
	upgradeApi upgrade.Upgrade
}

// MCP-B配置响应，要将查询结果反馈给页面模型
// dataList:MCP层数据队列
// wLen:数据队列长度
func (obj *McpB) McpUlRespB(stHeadModel *psmodel.PS_HEAD_T, dataList []byte, wLen int) error {
	var wCurrentLen uint16 = 0
	var wLtvLen uint16 = 0
	var wCommand uint16 = 0

	//判断设备响应是否成功
	if stHeadModel.StMcpHead.Resp == psmodel.MCP_RESP_ERR {
		obj.upgradeApi.UpgradeDeinit()
		return errors.New("设备响应错误")
	}

	//组织一个ltv-b数据
	wLtvLen = uint16(binary.LittleEndian.Uint16(dataList[wCurrentLen : wCurrentLen+2]))    //长度
	wCommand = uint16(binary.LittleEndian.Uint16(dataList[wCurrentLen+2 : wCurrentLen+4])) //命令

	//长度判断
	if wLtvLen != uint16(wLen) {
		obj.upgradeApi.UpgradeDeinit()
		return errors.New("数据长度错误")
	}

	//软件模式切换响应
	if wCommand == pspublic.OAM_UPGRADE_SWITCH_SOFT_WORK_MODE {

		err := obj.upgradeApi.UpgradeNoticeFileSize(stHeadModel.StVpHead.ProjectID, stHeadModel.StVpHead.DeviceID)
		if err != nil {
			obj.upgradeApi.UpgradeDeinit()
			return err
		}
	} else if wCommand == pspublic.OAM_UPGRADE_NOTICE_FILE_SIZE_ { //通知文件信息
		err := obj.upgradeApi.UpgradeTransferFile(stHeadModel.StVpHead.ProjectID, stHeadModel.StVpHead.DeviceID)
		if err != nil {
			obj.upgradeApi.UpgradeDeinit()
			return err
		}
	} else if wCommand == pspublic.OAM_UPGRADE_SEND_UPGRADE_FILE { //传输文件
		// 创建一个在100毫秒后接收的通道
		ch := time.After(100 * time.Millisecond)
		<-ch // 阻塞直到通道接收到值

		err := obj.upgradeApi.UpgradeTransferFile(stHeadModel.StVpHead.ProjectID, stHeadModel.StVpHead.DeviceID)
		if err != nil {
			obj.upgradeApi.UpgradeDeinit()
			return err
		}
	} else if wCommand == pspublic.OAM_UPGRADE_NOTICE_UPGRADE_OVER { //升级结束
		obj.upgradeApi.UpgradeSuccess() //升级成功
	}

	return nil
}
