package com.mortals.xhx.daemon.applicationservice;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.springcloud.service.IApplicationStartedService;
import com.mortals.framework.util.ThreadPool;
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.queue.DefaultTbQueueMsg;
import com.mortals.xhx.queue.TbQueueMsg;
import com.mortals.xhx.queue.TbQueueMsgHeaders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.Date;

import static com.mortals.xhx.common.key.RedisKey.KEY_DEVICE_DOWN_MSG_QUEUE;

/**
 * 下发消息
 *
 * @author: zxfei
 * @date: 2023/11/8 23:45
 */
//@Component
@Slf4j
public class DeviceDownMsgService implements IApplicationStartedService {

    protected Boolean stopped = false;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceLogService deviceLogService;
    @Autowired
    private MessageProducer messageProducer;

    @Override
    public void start() {
        log.info("DeviceDownMsgService start");

        ThreadPool.getInstance().init(10);



        Thread sendThread = new Thread(new Runnable() {
            @Override
            public void run() {
                int waitTime = 1;
                while (!stopped) {
                    try {
                        DeviceMsgReq deviceMsgReq = cacheService.blpop(KEY_DEVICE_DOWN_MSG_QUEUE,10, DeviceMsgReq.class);
                        if (!ObjectUtils.isEmpty(deviceMsgReq)) {
                            log.info("下发消息:{}",deviceMsgReq.getDeviceCode());
                            //根据设备编码查询设备
                            DeviceEntity deviceEntity = null;
                            try {
                                deviceEntity = deviceService.getExtCache(deviceMsgReq.getDeviceCode());
                            } catch (Exception e) {
                                log.error("redis 获取设备异常！", e);
                                continue;
                            }
                            if (!ObjectUtils.isEmpty(deviceEntity)) {
                                TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
                                header.put(MessageHeader.MESSAGETYPE, deviceMsgReq.getMessageType());
                                header.put(MessageHeader.DEVICECODE, deviceMsgReq.getDeviceCode());
                                header.put(MessageHeader.TIMESTAMP, deviceMsgReq.getTimestamp().toString());

                                TbQueueMsg queueMsg = new DefaultTbQueueMsg(IdUtil.fastUUID(), deviceMsgReq.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(deviceMsgReq.getMessageType());
                                deviceLogEntity.setContent(deviceMsgReq.getData());
                                deviceLogEntity.setLogType(LogTypeEnum.下发服务.getValue());
                                deviceLogEntity.setCreateUserId(1L);
                                deviceLogEntity.setCreateTime(new Date());
                                deviceLogService.save(deviceLogEntity, null);
                            } else {
                                log.info("未找到设备，deviceCode:{}", deviceMsgReq.getDeviceCode());
                            }
                        }

                        try {
                            Thread.sleep(waitTime);
                        } catch (InterruptedException e2) {
                        }

                    } catch (Exception e) {
                        log.error("异常", e);

                        try {
                            Thread.sleep(waitTime);
                        } catch (InterruptedException e2) {
                        }
                    }
                }
            }
        });

        ThreadPool.getInstance().execute(sendThread);

      //  sendThread.start();
    }

    @Override
    public void stop() {
        log.info("停止服务..");
        this.stopped = true;
    }

    @Override
    public int getOrder() {
        return 50;
    }

}
