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.common.utils.SendTaskThreadPool;
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 SendTaskThreadPool sendTaskThreadPool;
    @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());
//                    DeviceEntity entity = new DeviceEntity();
//                    entity.setOnlineTime(new Date());
//                    entity.setDeviceStatus(DeviceStatusEnum.在线.getValue());
//                    DeviceEntity condition = new DeviceEntity();
//                    condition.setId(deviceEntity.getId());
                    //int update = deviceService.getDeviceDao().update(entity, condition);
                    // deviceService.update(deviceEntity);
                     //deviceService.putCache(deviceEntity.getId().toString(),deviceEntity);

                     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);
                }
            /*    //获取exchange,
                PlatformEntity platformEntity = platformService.getCache(deviceEntity.getPlatformId().toString());

                String phpInUrl = GlobalSysInfo.getParamValue(PARAM_SERVER_PHP_IN_HTTP_URL, "http://172.15.28.116:8090");
                if (!Constant.MESSAGETYPE_HEARTBEAT.equalsIgnoreCase(messageType)
                        && !ObjectUtils.isEmpty(platformEntity)
                        && platformEntity.getSendSwitch() == YesNoEnum.YES.getValue()) {
                    if (platformEntity.getSendMsgType() == SendMsgTypeEnum.http.getValue()) {
                        SendTask sendTask = new SendTask(phpInUrl, queueMsg.getData());
                        sendTaskThreadPool.execute(sendTask);
                    }
                }*/
            }
        } catch (Exception e) {
            log.error("消费消息异常", e);
        }

//        log.info("接收到：" + queue + "，消息内容为：" + new String(body));
//        //channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//        log.info(queue + "队列消息消费成功");
    }
}
