package com.fuyuanshen.global.mqtt.rule;

import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.ImageToCArrayConverter;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static com.fuyuanshen.common.core.utils.ImageToCArrayConverter.convertHexToDecimal;

/**
 * 人员信息命令处理
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class DeviceBootLogoRule implements MqttMessageRule {
    
    private final MqttGateway mqttGateway;

    @Override
    public String getCommandType() {
        return LightingCommandTypeConstants.BOOT_LOGO;
    }

    @Override
    public void execute(MqttRuleContext context) {
        try {
            Byte val2 = (Byte) context.getConvertArr()[1];
            if (val2 == 100) {
                return;
            }

            String data = RedisUtils.getCacheObject(GlobalConstants.GLOBAL_REDIS_KEY+"app_logo_data:" + context.getDeviceImei());
            if (StringUtils.isEmpty(data)) {
                return;
            }
            
            byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
            byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, (val2 - 1), 512);
            System.out.println("第" + val2 + "块数据大小: " + specificChunk.length + " 字节");
//            System.out.println("第" + val2 + "块数据: " + Arrays.toString(specificChunk));

            ArrayList<Integer> intData = new ArrayList<>();
            intData.add(3);
            intData.add((int) val2);
            ImageToCArrayConverter.buildArr(convertHexToDecimal(specificChunk), intData);
            intData.add(0);
            intData.add(0);
            intData.add(0);
            intData.add(0);
            
            Map<String, Object> map = new HashMap<>();
            map.put("instruct", intData);
            
            mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + context.getDeviceImei(), 1, JsonUtils.toJsonString(map));
            log.info("发送开机LOGO点阵数据到设备消息=>topic:{},payload:{}",
                    MqttConstants.GLOBAL_PUB_KEY + context.getDeviceImei(),
                    JsonUtils.toJsonString(map));
        } catch (Exception e) {
            log.error("处理人员信息命令时出错", e);
        }
    }
}
