package com.mortals.xhx.common.utils;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.xhx.base.system.message.impl.MessageProducer;
import com.mortals.xhx.busiz.req.DeviceMsgReq;
import com.mortals.xhx.common.code.LogTypeEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.key.QueueKey;
import com.mortals.xhx.common.model.DefaultTbQueueMsgHeaders;
import com.mortals.xhx.common.model.MessageHeader;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.model.DeviceLogEntity;
import com.mortals.xhx.module.device.service.DeviceLogService;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.module.platform.service.PlatformService;
import com.mortals.xhx.module.product.service.ProductService;
import com.mortals.xhx.queue.DefaultTbQueueMsg;
import com.mortals.xhx.queue.TbQueueMsg;
import com.mortals.xhx.queue.TbQueueMsgHeaders;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 接收消息
 *
 * @author: zxfei
 * @date: 2022/4/28 10:56
 * @description:
 **/
@Slf4j
@AllArgsConstructor
public class DownMsgTask implements Runnable {
    private List<DeviceMsgReq> list;
    private PlatformService platformService;
    private ProductService productService;
    private DeviceService deviceService;
    private DeviceLogService deviceLogService;

    private MessageProducer messageProducer;

    @Override
    public void run() {
        try {
            list.stream().sorted(Comparator.comparing(DeviceMsgReq::getTimestamp)).forEach(item -> {
                //根据设备编码查询设备
                DeviceEntity deviceEntity = deviceService.getExtCache(item.getDeviceCode());
                if (!ObjectUtils.isEmpty(deviceEntity)) {
                    //将上报信息转发到mq中
      /*              PlatformEntity platformEntity = platformService.get(deviceEntity.getPlatformId());
                    if (ObjectUtils.isEmpty(platformEntity)) {
                        log.error("当前设备未配置所属系统平台，请在后台配置后再激活！");
                        return;
                    }
                    ProductEntity productEntity = productService.get(deviceEntity.getProductId());
                    if (ObjectUtils.isEmpty(productEntity)) {
                        log.error("当前设备未配置所属产品，请在后台配置后再激活！");
                        return;
                    }*/
                   // String exchangeName = platformEntity.getPlatformSn() + Constant.EXCHANGE_SPLIT + productEntity.getProductCode();
                   // TopicPartitionInfo info = TopicPartitionInfo.builder().exchangeName(exchangeName).topic(Constant.DOWN_TOPIC + deviceEntity.getDeviceMac()).build();
                    TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
                    header.put(MessageHeader.MESSAGETYPE, item.getMessageType());
                    header.put(MessageHeader.DEVICECODE, item.getDeviceCode());
                    header.put(MessageHeader.TIMESTAMP, item.getTimestamp().toString());


                    TbQueueMsg queueMsg = new DefaultTbQueueMsg(IdUtil.fastUUID(), item.getData(), header);
                    messageProducer.sendMsg(QueueKey.DEFAULT_EXCHANGE,Constant.DOWN_TOPIC + deviceEntity.getDeviceCode(),JSON.toJSONString(queueMsg));

                    DeviceLogEntity deviceLogEntity = new DeviceLogEntity();
                    deviceLogEntity.initAttrValue();
                    deviceLogEntity.setTraceID(IdUtil.fastSimpleUUID());
                    deviceLogEntity.setSiteId(deviceEntity.getSiteId());
                    deviceLogEntity.setDeviceId(deviceEntity.getId());
                    deviceLogEntity.setDeviceName(deviceEntity.getDeviceName());
                    deviceLogEntity.setDeviceCode(deviceEntity.getDeviceCode());
                    deviceLogEntity.setMessageHead(item.getMessageType());
                    deviceLogEntity.setContent(item.getData());
                    deviceLogEntity.setLogType(LogTypeEnum.下发服务.getValue());
                    deviceLogEntity.setCreateUserId(1L);
                    deviceLogEntity.setCreateTime(new Date());
                    deviceLogService.save(deviceLogEntity,null);
                /*
                    TbQueueCallback callback = new TbQueueCallback() {
                        @Override
                        public void onSuccess(TbQueueMsgMetadata metadata) {
                            //下行业务消息保存日志
                            if (!Constant.MESSAGETYPE_HEARTBEAT.equalsIgnoreCase(item.getMessageType())) {
                                DeviceLogEntity deviceLogEntity = new DeviceLogEntity();
                                deviceLogEntity.initAttrValue();
                                deviceLogEntity.setTraceID(metadata.getMessageId());
                                deviceLogEntity.setSiteId(deviceEntity.getSiteId());
                                deviceLogEntity.setDeviceId(deviceEntity.getId());
                                deviceLogEntity.setDeviceName(deviceEntity.getDeviceName());
                                deviceLogEntity.setDeviceCode(deviceEntity.getDeviceCode());
                                deviceLogEntity.setMessageHead(item.getMessageType());
                                deviceLogEntity.setContent(item.getData());
                                deviceLogEntity.setLogType(LogTypeEnum.下发服务.getValue());
                                deviceLogEntity.setCreateUserId(1L);
                                deviceLogEntity.setCreateTime(new Date());
                                deviceLogService.save(deviceLogEntity);
                            }
                            log.info("消息投递成功,设备通道编码:" + deviceEntity.getDeviceMac());
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            DeviceLogEntity deviceLogEntity = new DeviceLogEntity();
                            deviceLogEntity.initAttrValue();
                            String traceID = IdUtil.fastSimpleUUID();
                            deviceLogEntity.setTraceID(traceID);
                            deviceLogEntity.setDeviceId(deviceEntity.getId());
                            deviceLogEntity.setSiteId(deviceEntity.getSiteId());
                            deviceLogEntity.setDeviceName(deviceEntity.getDeviceName());
                            deviceLogEntity.setDeviceCode(deviceEntity.getDeviceCode());
                            deviceLogEntity.setMessageHead(item.getMessageType());
                            deviceLogEntity.setContent(item.getData());
                            deviceLogEntity.setLogType(LogTypeEnum.消息异常.getValue());
                            deviceLogEntity.setCreateUserId(1L);
                            deviceLogEntity.setCreateTime(new Date());
                            deviceLogService.save(deviceLogEntity);
                            log.error("traceID:"+traceID,"消息投递失败,设备通道编码:" + deviceEntity.getDeviceMac(), t);
                        }
                    };

                    deviceService.sendDeviceMessage(deviceEntity, info, header, item.getData(),callback, null);

*/
                } else {
                    log.info("未找到设备，deviceCode:{}", item.getDeviceCode());
                }
            });
        } catch (Exception e) {
            log.error("异常：", e);
        }
    }
}
