package com.mortals.xhx.base.framework.listener;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.model.BizLogPdu;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.IMessageProduceService;
import com.mortals.xhx.common.code.DeviceMethodEnum;
import com.mortals.xhx.common.code.DeviceStatusEnum;
import com.mortals.xhx.common.code.LogTypeEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.common.pdu.DefaultQueueMsg;
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.model.PlatformEntity;
import com.mortals.xhx.module.platform.service.PlatformService;
import com.mortals.xhx.module.product.model.ProductEntity;
import com.mortals.xhx.module.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;

import static com.mortals.xhx.common.model.MessageHeader.DEVICECODE;
import static com.mortals.xhx.common.model.MessageHeader.MESSAGETYPE;

/**
 * 设备上行消息处理
 *
 * @author: zxfei
 * @date: 2022/8/23 0:32
 * @description:
 **/
@Slf4j
@Service
public class DirectDynamicListener implements MessageListener {
    @Autowired
    private DeviceLogService deviceLogService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ProductService productService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private IMessageProduceService messageProducer;


    @Override
    public void onMessage(Message message) {
        String queue = message.getMessageProperties().getConsumerQueue();
        byte[] body = message.getBody();
        String data = new String(body);
        // log.info("接收到：{} ，\n消息内容为：{}", queue, data);
        DefaultQueueMsg queueMsg = JSON.parseObject(data, DefaultQueueMsg.class);
        //做相应业务,做日志操作
        String deviceCode = queueMsg.getHeaders().getData().get(DEVICECODE);
        String messageType = queueMsg.getHeaders().getData().get(MESSAGETYPE);
        try {
            if (ObjectUtils.isEmpty(deviceCode)) {
                log.info("onMessage deviceCode is null,receive data:{},queue:{}", data, queue);
                return;
            }

            DeviceEntity deviceEntity = deviceService.getExtCache(deviceCode);
            if (!ObjectUtils.isEmpty(deviceEntity)) {
                cacheService.set(RedisKey.KEY_DEVICE_ONLINE_CACHE + deviceEntity.getDeviceCode(), "", GlobalSysInfo.getParamIntValue(Constant.HEARTBEAT_TIMEOUT, 180));
                if (deviceEntity.getDeviceStatus() == DeviceStatusEnum.离线.getValue()) {
                    DeviceEntity condition = new DeviceEntity();
                    condition.setId(deviceEntity.getId());
                    condition.setOnlineTime(new Date());
                    condition.setDeviceStatus(DeviceStatusEnum.在线.getValue());
                    cacheService.lpush(RedisKey.KEY_DEVICE_UPDATE_QUEUE, condition);

                    PlatformEntity platformEntity = platformService.getCache(deviceEntity.getPlatformId().toString());
                    ProductEntity productEntity = productService.get(deviceEntity.getProductId());
                    if (!ObjectUtils.isEmpty(platformEntity) && !ObjectUtils.isEmpty(productEntity)) {
                        deviceService.sendThirdParty(deviceEntity, productEntity, platformEntity, DeviceMethodEnum.ONLINE);
                        //保存业务消息为离线
                        BizLogPdu bizLogPdu = new BizLogPdu();
                        bizLogPdu.initAttrValue();
                        //保存为产品名称
                        bizLogPdu.setAppName(productEntity.getProductCode());
                        bizLogPdu.setTraceID(IdUtil.objectId());
                        bizLogPdu.setUserCode("system");
                        bizLogPdu.setDeviceCode(deviceEntity.getDeviceCode());
                        bizLogPdu.setEventTopic("online");
                        bizLogPdu.setEventTopicName(LogTypeEnum.上报事件.name());
                        bizLogPdu.setMsg(Base64.encode("设备上线"));
                        bizLogPdu.setLogLevel("INFO");
                        bizLogPdu.setLogTime(new Date());
                        messageProducer.syncBizSend(bizLogPdu);
                    }
                    // log.info("id:{},deviceCode:{} deviceStatus:{}==>上线  ", deviceEntity.getId(), deviceEntity.getDeviceCode(), deviceEntity.getDeviceStatus());
                }
                if (!Constant.MESSAGETYPE_HEARTBEAT.equalsIgnoreCase(messageType)) {
                    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(messageType);
                    deviceLogEntity.setContent(queueMsg.getData());
                    deviceLogEntity.setLogType(LogTypeEnum.上报事件.getValue());
                    deviceLogEntity.setCreateUserId(1L);
                    deviceLogEntity.setCreateTime(new Date());
                    deviceLogService.save(deviceLogEntity);
                }
            }
        } catch (Exception e) {
            log.error("消费消息异常", e);
        }
    }
}
