package com.yeejoin.amos.boot.module.jcs.biz.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertNewsDto;
import com.yeejoin.amos.component.rule.config.ClazzUtils;
import com.yeejoin.amos.component.rule.config.RuleConfig;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.List;

/**
 * @description:
 * @author: tw
 * @createDate: 2021/9/16
 */
@Component
public class StartLoader implements ApplicationRunner {
    private final Logger logger = LoggerFactory.getLogger(StartLoader.class);


    @Autowired
    private EmqKeeper emqKeeper;
    @Value("${mqtt.topic.alert.iot}")
    private String topic;
    @Value("${mqtt.topic.alert.iot.web}")
    private String topicweb;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("開始監聽物聯警情======================================");
        loadSysParams();
    }

    public void loadSysParams(){
        try {
            emqKeeper.getMqttClient().subscribe(topic, (s, mqttMessage) -> {
                byte[] payload = mqttMessage.getPayload();
                try {
                    String obj = new String(payload);
                    if (!ValidationUtil.isEmpty(obj)) {
                        JSONObject json = JSON.parseObject(obj);
                        AlertNewsDto alertNewsDto = new AlertNewsDto( "物联警情", json.get("unitInvolvedName")+","+json.get("address")+"，发生警情，请处理。", json.get("id").toString(),  json);
                        emqKeeper.getMqttClient().publish(topicweb, JSONObject.toJSON(alertNewsDto).toString().getBytes("UTF-8"), 1, false);
                 }
                } catch (Exception e) {
                    logger.error("系统异常", e);
                }
            });
        } catch (MqttException e) {
            logger.info("订阅物联警情异常", e);
        }
    }

}
