package com.yeejoin.amos.boot.module.jxiop.biz.emqx;

import com.alibaba.fastjson.JSONArray;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
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.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Component
@Slf4j
public class StationYardMessage extends EmqxListener {


    @Autowired
    protected EmqKeeper emqKeeper;

    @Autowired
    private StationBasicMapper stationBasicMapper;


    /**
     * 江西电建接收红黄绿码主题
     */
    private static final String JXIOP_STATION_YARD = "jxIop/station/yard";

    private static final BlockingQueue<List<Map<String, String>>> blockingQueue = new LinkedBlockingQueue<List<Map<String, String>>>();

    @PostConstruct
    void init() throws Exception {
        new Thread(taskRunnable).start();
        emqKeeper.subscript(JXIOP_STATION_YARD, 2, this);
    }

    @Override
    public void processMessage(String topic, MqttMessage message) throws Exception {

        JSONArray ja = JSONArray.parseArray(new String(message.getPayload()));
        List<Map<String, String>> liMap = JSONArray.toJavaObject(ja, List.class);
        blockingQueue.add(liMap);

    }

    Runnable taskRunnable = new Runnable() {
        @Override
        public void run() {
            boolean isRun = true;
            int k = 0;
            while (isRun) {
                k++;
                isRun = k < Integer.MAX_VALUE;
                try {
                    List<Map<String, String>> analysisResult = blockingQueue.take();
//                    RequestContext.setAppKey(amosAuth.getAppKey());
//                    RequestContext.setProduct(amosAuth.getProduct());
//                    RequestContext.setToken(amosAuth.getToken());
                    jxIopUpdate(analysisResult);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public void jxIopUpdate(List<Map<String, String>> analysisResult) {
        log.info("场站红黄绿码数据：{}", analysisResult);
        stationBasicMapper.updateYardByProjectOrgCode(analysisResult);
    }
}
