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

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.service.ICacheService;
import com.mortals.xhx.common.code.*;
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.SendTask;
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.key.Constant.PARAM_SERVER_PHP_IN_HTTP_URL;
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;


    @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 {
            DeviceEntity deviceEntity = deviceService.getExtCache(deviceCode);
            if (!ObjectUtils.isEmpty(deviceEntity)) {
                cacheService.set(RedisKey.KEY_DEVICE_ONLINE_CACHE + deviceEntity.getDeviceCode(), "", GlobalSysInfo.getParamIntValue(Constant.HEARTBEAT_TIMEOUT, 120));
                if (deviceEntity.getDeviceStatus() == DeviceStatusEnum.离线.getValue()) {
                    deviceEntity.setOnlineTime(new Date());
                    deviceEntity.setDeviceStatus(DeviceStatusEnum.在线.getValue());
                    deviceService.update(deviceEntity);

                    PlatformEntity platformEntity = platformService.get(deviceEntity.getPlatformId());
                    ProductEntity productEntity = productService.get(deviceEntity.getProductId());
                    if (!ObjectUtils.isEmpty(platformEntity) && !ObjectUtils.isEmpty(productEntity)) {
                        //新增设备通知第三方平台
                        deviceService.sendThirdParty(deviceEntity, productEntity, platformEntity, DeviceMethodEnum.ONLINE);
                    }
                }
                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.get(deviceEntity.getPlatformId());

                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 + "队列消息消费成功");
    }
}
