package com.xinda.gkb;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xinda.common.annotation.SysProtocol;
import com.xinda.common.constant.XinDaConstant;
import com.xinda.common.core.mq.DeviceReport;
import com.xinda.common.core.mq.MQSendMessageBo;
import com.xinda.common.core.mq.message.DeviceData;
import com.xinda.common.core.mq.message.FunctionCallBackBo;
import com.xinda.common.core.redis.RedisCache;
import com.xinda.common.core.redis.RedisKeyBuilder;
import com.xinda.common.core.thingsModel.ThingsModelSimpleItem;
import com.xinda.common.exception.ServiceException;
import com.xinda.common.utils.DateUtils;
import com.xinda.common.utils.gateway.mq.TopicsUtils;
import com.xinda.iot.domain.Device;
import com.xinda.iot.model.ThingsModels.ThingsModelValueItem;
import com.xinda.iot.model.ThingsModels.ValueItem;
import com.xinda.iot.service.IDeviceService;
import com.xinda.protocol.base.protocol.IProtocol;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.math.BigDecimal;
import java.util.stream.Collectors;

/**
 * @author gsb
 * @date 2023/8/14 16:04
 */
@Slf4j
@Component
@SysProtocol(name = "IECF6113-JSON协议",protocolCode = XinDaConstant.PROTOCOL.IECF6113,description = "IECF6113-JSON协议")
public class IECF6113ProtocolService implements IProtocol {


    @Resource
    private RedisCache redisCache;
    @Resource
    private TopicsUtils topicsUtils;
    @Resource
    private IDeviceService deviceService;

    /**
     * 上报数据格式:              <p>
     *     {
     *   "AD6": 0.27333333333333,
     *   "AD15": 0.27333333333333,
     *   "AD14": 0.27333333333333,
     *   "AD7": 0.27333333333333,
     *   "AD11": 0.26,
     *   "AD1": 0.27333333333333,
     *   "AD4": 0.26,
     *   "AD3": 0.26,
     *   "AD10": 0.27333333333333,
     *   "AD8": 0.26,
     *   "AD16": 0.27333333333333,
     *   "AD12": 0.26,
     *   "AD13": 0.27333333333333,
     *   "AD9": 0.27333333333333,
     *   "AD2": 0.27333333333333,
     *   "AD5": 0.27333333333333
     * }
     *
     * {
     *   "I0.1": 0,
     *   "I0.3": 0,
     *   "I0.4": 0,
     *   "I0.6": 0,
     *   "I0.5": 0,
     *   "I0.2": 0
     * }
     *
     * {
     *   "lng": "104.0902886",
     *   "lat": "030.8176553"
     * }
     *
     * {
     *   "PAD": 3905
     * }
     *
     *
     *
     * 下发报文格式<p>
     * device   从机编号  <p>
     * name     标识符    <p>
     * value    值        <p>
     * serNo    流水号    <p>
     * {
     * 	"device": 1,
     * 	"name": "template",
     * 	"value": 111,
     * 	"serNo": "213245489543789"
     * }
     * </p>
     *
     * 下发指令回复格式<p>
     * serNo   平台的流水号，用于对应回复消息   <p>
     * ack     下发指令状态 0是失败 1是成功    <p>
     *   {
     *  "serNo": "213245489543789",
     *  "ack": 1
     * }
     * </p>
     *
     */
    @Override
    public DeviceReport decode(DeviceData deviceData, String clientId) {
        try {
            DeviceReport reportMessage = new DeviceReport();
            String data = new String(deviceData.getData(),StandardCharsets.UTF_8);
            List<ThingsModelSimpleItem> result = new ArrayList<>();
            if(data.trim().equals("ok")||data.trim().equals("ERROR")){
                log.info(data);
            }else{
                Map<String,Object> values = JSON.parseObject(data, Map.class);
                if (values.containsKey("AD1") || values.containsKey("lng") || values.containsKey("I0.1")||values.containsKey("PAD")){
                    // 初始化纬度变量，使用BigDecimal来存储高精度值
                    BigDecimal latitude = new BigDecimal("39.9042");
                    // 初始化经度变量，同样使用BigDecimal
                    BigDecimal longitude = new BigDecimal("116.4074");
                    for (Map.Entry<String, Object> entry : values.entrySet()) {
//                        JSONArray value = (JSONArray) entry.getValue();
                        ThingsModelSimpleItem simpleItem = new ThingsModelSimpleItem();
                        simpleItem.setTs(DateUtils.getNowDate());
                        simpleItem.setId(entry.getKey());
                        simpleItem.setValue(entry.getValue()+"");
                        result.add(simpleItem);
                        if(values.containsKey("lng")) {
                            if (entry.getKey().equals("lng")) {
                                longitude = new BigDecimal(entry.getValue() + "");
                            }
                            if (entry.getKey().equals("lat")) {
                                latitude = new BigDecimal(entry.getValue() + "");
                                //更新设备经纬度信息
                                Device device = new Device();
                                device.setSerialNumber(deviceData.getSerialNumber());
                                device.setLatitude(latitude);
                                device.setLongitude(longitude);
                                deviceService.updateDeviceStatus(device);
                            }
                        }
                    }
                }
            }


            reportMessage.setThingsModelSimpleItem(result);
            reportMessage.setClientId(clientId);
            reportMessage.setSerialNumber(clientId);
            return reportMessage;
        }catch (Exception e){
            throw new ServiceException("数据解析异常"+e.getMessage());
        }
    }

    /**
     * 1.查询模拟量 GKB29810,ADC,8
     * 2.查询 485 上报 GKB29810,command,1
     * 3.查询输入开关量 GKB29810,IPUT,
     * 4.更改上报时间 GKB29810,JCZ,{"TIME":20}
     * 5.通 信 控制 GKB29810,MODBUS, {"KO":12}
     * 6.开关量输出控制 GKB29810,OUT,{"Q0.1":0,"Q0.2":0,"Q0.3":0,"Q0.4":0,"Q0.5":0,"Q0.6":0}GKB29810,0UT,{"Q0.1":1 ,"Q0.2":1,"Q0.3":1,"Q0.4":1,"Q0.5":1 "Q0.6":1)
     * @param message
     * @return
     */
    @Override
    public FunctionCallBackBo encode(MQSendMessageBo message) {
        try {
            FunctionCallBackBo callBack = new FunctionCallBackBo();
            JSONObject params = message.getParams();
//            Map<String,Object> values = JSON.parseObject(data, Map.class);
            ValueItem valueItem = new ValueItem();
           if(params.containsKey("select")) {
               String msg = params.get("select") + "";
               callBack.setSources(msg);
               callBack.setMessage(msg.getBytes());
           }
           if(params.containsKey("MODBUS")){
               String msg ="GKB29810,MODBUS," + params.get("MODBUS");
               callBack.setSources(msg);
               callBack.setMessage(msg.getBytes());
           }
           if(params.containsKey("OUT")){
               String msg = params.get("OUT") + "";
               callBack.setSources(msg);
               callBack.setMessage(msg.getBytes());
           }
           if(params.containsKey("TIME")){
               String msg = "GKB29810,JCZ,{\"TIME\":" + params.get("TIME")+ "}";
               callBack.setSources(msg);
               callBack.setMessage(msg.getBytes());
           }
            // 调用方法检查并获取以前缀开头的键和值
            Map<String, Object> result = getKeysAndValuesWithPrefix(params, "Q0.");
            // 输出结果
            if (!result.isEmpty()) {
                StringBuilder msg = new StringBuilder("GKB29810,OUT,{\"");
                result.forEach((k, v) -> {
                    msg.append(k).append("\":").append(v).append(",");
                });
                // 删除最后一个逗号
                if (msg.charAt(msg.length() - 1) == ',') {
                    msg.deleteCharAt(msg.length() - 1);
                }
                // 添加结尾的双引号和大括号
                msg.append("}");
                callBack.setSources(msg.toString());
                callBack.setMessage(msg.toString().getBytes());
            }
            return callBack;
        } catch (Exception e) {
            log.error("=>指令编码异常,device={},data={}", message.getSerialNumber(),
                    message.getParams());
            return null;
        }
    }


    /**
     * 获取JSONObject中以指定前缀开头的键和值
     *
     * @param jsonObject 要检查的JSONObject
     * @param prefix     要匹配的前缀
     * @return 一个包含匹配键和值的Map，如果没有匹配的键，则返回一个空的Map
     */
    public static Map<String, Object> getKeysAndValuesWithPrefix(JSONObject jsonObject, String prefix) {
        Map<String, Object> result = new HashMap<>();

        // 遍历JSONObject的所有键值对
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            String key = entry.getKey();
            // 检查当前键是否以指定前缀开头
            if (key.startsWith(prefix)) {
                // 如果匹配，将键和值添加到结果Map中
                result.put(key, entry.getValue());
            }
        }

        return result;
    }

}
