package com.yeejoin.amos.boot.module.cylinder.biz.listener;

import com.alibaba.fastjson.JSONArray;
import com.yeejoin.amos.boot.module.cylinder.flc.api.dto.CylinderFillingRecordDto;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.component.emq.EmqxListener;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class CylinderFillingInsertEventListener extends EmqxListener {

    @Value("${cylinder.filling.insert.msg.custom.thread.number:3}")
    private int threadNumber;

    @Value("${cylinder.filling.insert.topic:cylinder/filling/insert/topic}")
    private String insertTopic;

    @Value("${spring.application.name:TZS-CYLINDER}")
    private String applicationName;

    private EmqKeeper emqKeeper;

    private List<ICylinderFillingInsertListener> cylinderFillingInsertListeners;

    private BlockingQueue<CylinderFillingRecordDto> blockingQueue = new LinkedBlockingQueue<>();

    public CylinderFillingInsertEventListener(EmqKeeper emqKeeper,
                                              List<ICylinderFillingInsertListener> cylinderFillingInsertListeners) {
        this.emqKeeper = emqKeeper;
        this.cylinderFillingInsertListeners = cylinderFillingInsertListeners;
    }


    @PostConstruct
    public void init() throws Exception {
        emqKeeper.subscript(this.getShareTopic(), 2, this);
        consumeTheQueue();
    }

    private void consumeTheQueue() {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber);
        for (int i = 0; i < threadNumber; i++) {
            executorService.execute(() -> {
                while (true) {
                    try {
                        CylinderFillingRecordDto cylinderFillingRecordDto = blockingQueue.take();
                        this.createCylinderFillingQuestion(cylinderFillingRecordDto);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });

        }
    }

    private String getShareTopic() {
        return String.format("%s/%s/%s", "$share", applicationName, insertTopic);
    }

    private void createCylinderFillingQuestion(CylinderFillingRecordDto cylinderFillingRecordDto) {
        cylinderFillingInsertListeners.forEach(listener -> {
            listener.handle(cylinderFillingRecordDto);
        });
    }

    @Override
    public void processMessage(String topic, MqttMessage message) {
        String msg = new String(message.getPayload(), StandardCharsets.UTF_8);
        log.info("1.收到充装信息插入消息:{}", msg);
        List<CylinderFillingRecordDto> cylinderFillingRecordDtos = JSONArray.parseArray(msg, CylinderFillingRecordDto.class);
        blockingQueue.addAll(cylinderFillingRecordDtos);
    }
}
