package com.ruoyi.device.mqtt.handler.decoder.json.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.device.mqtt.annotation.JsonCmdUpHandler;
import com.ruoyi.device.mqtt.domain.BaseJsonBody;
import com.ruoyi.device.mqtt.domain.decoder.TaxDataUp;
import com.ruoyi.device.mqtt.enums.CmdTypeEnum;
import com.ruoyi.device.mqtt.handler.decoder.json.IJsonCmdUpHandler;
import com.ruoyi.device.mqtt.vo.CommonHeader;
import com.ruoyi.device.mqtt.vo.CommonTopic;
import com.ruoyi.device.websocket.TsbWebSocketService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 报税口上行：common:tax:up
 * <p>
 * 解析设备页面数据并推送到 WebSocket（无 MQTT 下行应答）。
 *
 * @author lwm
 */
@JsonCmdUpHandler(cmdType = CmdTypeEnum.COMMON_TAX)
public class TaxDataUpService implements IJsonCmdUpHandler
{
    private static final Logger log = LoggerFactory.getLogger(TaxDataUpService.class);

    @Resource
    private TsbWebSocketService tsbWebSocketService;

    @Override
    public BaseJsonBody handle(CommonTopic topic, CommonHeader header, String bodyJson, CmdTypeEnum cmd)
    {
        // 1、JSON 反序列化（保留原始 key，避免未传字段被补成 null 推到前端）
        // 因为 只传几个字段，就改变几个字段：部分字段为null，就清空显示
        JSONObject bodyObj = JSON.parseObject(bodyJson);
        if (bodyObj == null)
        {
            log.info("报税口报文体解析失败, deviceSn={}", topic.getDeviceSn());
            return BaseJsonBody.fail(topic.getDeviceType(), topic.getDeviceSn(), cmd.getCmdDownType(), "报税口报文体解析失败");
        }
        TaxDataUp taxDataUp = bodyObj.to(TaxDataUp.class);
        if (taxDataUp == null)
        {
            log.info("报税口报文体解析失败, deviceSn={}", topic.getDeviceSn());
            return BaseJsonBody.fail(topic.getDeviceType(), topic.getDeviceSn(), cmd.getCmdDownType(), "报税口报文体解析失败");
        }

        // 2、推送 Web 端
        tsbWebSocketService.pushPageSyncFromDevice(cmd.getCmdType(), bodyObj);
        // 3、无需下行应答
        return null;
    }
}
