package com.mortals.xhx.daemon.applicationservice;

import cn.hutool.core.net.NetUtil;
import com.mortals.framework.springcloud.service.IApplicationStartedService;
import com.mortals.xhx.base.framework.listener.DirectDynamicListener;
import com.mortals.xhx.base.system.message.impl.MessageProducer;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.key.QueueKey;
import com.mortals.xhx.common.utils.SendTaskThreadPool;
import com.mortals.xhx.module.device.model.DeviceEntity;
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.thread.DeviceDownMsgThread;
import com.mortals.xhx.thread.DeviceUpdateComsumerThread;
import com.mortals.xhx.thread.SendThirdPartyThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.LinkedHashSet;

/**
 * 初始化设备消费者注册
 *
 * @author: zxfei
 * @date: 2022/9/2 9:17
 */
@Component
@Slf4j
public class DeviceComsumersRegisterService implements IApplicationStartedService {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ProductService productService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private DirectMessageListenerContainer container;
    @Autowired
    private MessageProducer messageProducer;
    @Autowired
    private SendTaskThreadPool sendTaskThreadPool;
    @Autowired
    private DirectDynamicListener directDynamicListener;
    @Autowired
    private DeviceUpdateComsumerThread deviceUpdateComsumerThread;
    @Autowired
    private SendThirdPartyThread sendThirdPartyThread;
    @Autowired
    private DeviceDownMsgThread deviceDownMsgThread;

    @Value("${deviceUpdateComsumerIp:}")
    public String deviceUpdateComsumerIp;

    @Override
    public void start() {
        log.info("初始化发送线程数量");
        sendTaskThreadPool.init(6);

        //判断是否为
        if (!ObjectUtils.isEmpty(deviceUpdateComsumerIp)) {
            //判断指定了ip是否与启动节点的ip一致，如果一致则启动当前节点
           // final String localIp = NetUtil.getLocalhostStr();
            log.info("deviceUpdateComsumerIp :{}",deviceUpdateComsumerIp);
            LinkedHashSet<String> ipSet = NetUtil.localIpv4s();
            if(!ObjectUtils.isEmpty(ipSet)){
                for (String localIp : ipSet) {
                    log.info("get Ip...-->" + localIp);
                    if (deviceUpdateComsumerIp.trim().equalsIgnoreCase(localIp)) {
                        log.info("设备更新消费线程启动");
                        deviceUpdateComsumerThread.start();
                        break;
                    }
                }
            }
        } else {
            log.info("设备更新消费线程启动");
            deviceUpdateComsumerThread.start();
        }
        log.info("第三方发送线程启动");
        sendThirdPartyThread.start();
        //log.info("消息下发发送线程启动");
       // deviceDownMsgThread.start();
        log.info("服务端消息队列初始化服务开始..");

        deviceService.find(new DeviceEntity())
                .stream()
                .filter(f -> !ObjectUtils.isEmpty(platformService.getCache(f.getPlatformId() == null ? "0" : f.getPlatformId().toString())))
                .filter(f -> !ObjectUtils.isEmpty(productService.getCache(f.getProductId() == null ? "0" : f.getProductId().toString()))).forEach(item -> {
                    String uploadQueue = Constant.UPLOAD_TOPIC + item.getDeviceCode();
                    String downQueue = Constant.DOWN_TOPIC + item.getDeviceCode();
                    messageProducer.queueAddAndBinds(QueueKey.DEFAULT_EXCHANGE, uploadQueue, uploadQueue);
                    messageProducer.queueAddAndBinds(QueueKey.DEFAULT_EXCHANGE, downQueue, downQueue);
                });

        String[] queues = deviceService.find(new DeviceEntity())
                .stream()
                .filter(f -> !ObjectUtils.isEmpty(platformService.getCache(f.getPlatformId() == null ? "-1" : f.getPlatformId().toString())))
                .filter(f -> !ObjectUtils.isEmpty(productService.getCache(f.getProductId() == null ? "-1" : f.getProductId().toString())))
                .filter(f -> !ObjectUtils.isEmpty(f.getDeviceCode()))
                .map(item -> Constant.UPLOAD_TOPIC + item.getDeviceCode())
                .toArray(String[]::new);

        log.info("服务端消费消息注册服务开始..");
        container.addQueueNames(queues);
        container.start();
        container.setMessageListener(directDynamicListener);
    }

    @Override
    public void stop() {
        log.info("停止服务..");
        container.stop();

    }

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


}
