package com.fuyuanshen.global.mqtt.rule.hby100j;

import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.rule.hby100j.domin.FunctionType4PowerStatusReport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_STATUS_KEY_PREFIX;

/**
 * 获取设备电源状态（设备下发返回响应数据、设备定时主动上报）
 */
@Slf4j
@Component
public class FuncType4PowerStatus implements NewMqttMessageRule {

    @Override
    public String getCommandType() {
        return "HBY100_4";
    }

    @Override
    public void execute(NewMqttRuleContext context) {
        log.info("HBY100J获取设备电源状态，消息负载：{}", context.getPayloadDict());

        try {
            String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + context.getDeviceImei() + DEVICE_STATUS_KEY_PREFIX);
//            String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
//                             context.getDeviceImei() + ":powerStatus";
            
            Map<String, Object> payloadDict = context.getPayloadDict();
            if (payloadDict != null) {

                String str = JSONObject.toJSONString(payloadDict);
                FunctionType4PowerStatusReport powerStatusReport =JSONObject.parseObject(str,FunctionType4PowerStatusReport.class);

                FunctionType4PowerStatusReport.Data data = powerStatusReport.getData();
                if(data != null){
                    // 构造设备状态信息对象
                    Map<String, Object> deviceInfo = new LinkedHashMap<>();
                    deviceInfo.put("batteryPercentage", data.getLevel());
                    deviceInfo.put("chargeState", data.getCharge());
                    deviceInfo.put("batteryRemainingTime", data.getBatteryRemainingTime());

                    // 将设备状态信息存储到Redis中
                    String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+ DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + context.getDeviceImei() + DEVICE_STATUS_KEY_PREFIX;
                    String deviceInfoJson = JsonUtils.toJsonString(deviceInfo);

                    // 存储到Redis
                    RedisUtils.setCacheObject(deviceRedisKey, deviceInfoJson);
                }

            }
        } catch (Exception e) {
            log.error("HBY100J获取设备电源状态失败", e);
        }
    }
}
