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

import com.alibaba.fastjson.JSONArray;
import com.yeejoin.amos.boot.module.cylinder.api.dto.CylinderQuestionInfoDto;
import com.yeejoin.amos.boot.module.cylinder.api.enums.QuestionTypeEnum;
import com.yeejoin.amos.boot.module.cylinder.biz.event.CylinderQuestionCreateEvent;
import com.yeejoin.amos.boot.module.cylinder.biz.event.publisher.EventPublisher;
import com.yeejoin.amos.boot.module.cylinder.flc.api.dto.CylinderFillingRecordDto;
import com.yeejoin.amos.boot.module.cylinder.flc.api.enums.CyclinderStatus;
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 EventPublisher eventPublisher;

    private EmqKeeper emqKeeper;

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

    public CylinderFillingInsertEventListener(EventPublisher eventPublisher,
                                              EmqKeeper emqKeeper) {
        this.eventPublisher = eventPublisher;
        this.emqKeeper = emqKeeper;
    }


    @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) {
        if (CyclinderStatus.HEGE.getName().equals(cylinderFillingRecordDto.getFillingResult()) && CyclinderStatus.HEGE.getName().equals(cylinderFillingRecordDto.getCheckResult())) {
            log.info("气瓶充装信息前后全部合格，不创建问题！");
        } else {
            CylinderQuestionInfoDto questionInfo = new CylinderQuestionInfoDto();
            questionInfo.setQuestionType(QuestionTypeEnum.CZJCBHG.getCode());
            questionInfo.setQuestionTypeName(QuestionTypeEnum.CZJCBHG.getName());
            questionInfo.setQuestionAttributionId(cylinderFillingRecordDto.getAppId());
            questionInfo.setQuestionAttributionName(cylinderFillingRecordDto.getFillingUnitName());
            questionInfo.setRegionCode(cylinderFillingRecordDto.getRegionCode());
            questionInfo.setQuestionObjectId(cylinderFillingRecordDto.getSequenceCode());
            questionInfo.setHappenDate(cylinderFillingRecordDto.getSyncDate());
            eventPublisher.publish(new CylinderQuestionCreateEvent(this, questionInfo));
        }
    }

    @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);
    }
}
