package com.imdroid.beidou_fwd.task;


import com.imdroid.beidou_fwd.entity.GXJKData;
import com.imdroid.beidou_fwd.service.MQTTClient;
import com.imdroid.common.util.GsonUtil;
import com.imdroid.common.util.NumberUtils;
import com.imdroid.secapi.dto.GnssCalcData;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
@Configuration
@EnableScheduling
public class GXJKForwarder extends Forwarder {
    static final String FORWARDER_NAME = "广西交科";
    @Value("${gxjk.mqtt.server.brokerUrl}")
    private String brokerUrl;
    @Value("${gxjk.mqtt.server.username}")
    private String username;
    @Value("${gxjk.mqtt.server.password}")
    private String password;
    @Value("${gxjk.mqtt.server.clientid}")
    private String clientid;

    MQTTClient mqttClient;

    @PostConstruct
    void registerMe() throws MqttException {
        init(FORWARDER_NAME, "MQTT "+brokerUrl,7,FWD_DEVICE_NAME,10);
        mqttClient = new MQTTClient(brokerUrl, username, password,clientid);
        try{
            mqttClient.connect();
        }
        catch (Exception e){
            logger.error("gxjk mqtt connect failed: {}",e.toString());
        }
    }

    /**
     * 每半小时转发GNSS解算结果
     */
    @Scheduled(cron = "0 0/30 * * * ?") // 每30分钟执行一次
    private void forwardGnss() {
        logger.debug("gxjk forwardGnss");
        if(mqttClient.isConnected()) forwardCurrentGnss();
        else{
            try{
                mqttClient.connect();
            }
            catch (Exception e){
                logger.error("gxjk mqtt connect failed: {}",e.toString());
            }
        }
    }

    @Override
    int send(String projectId, List<GnssCalcData> records, LocalDateTime sentTime) {
        int sendNum = 0;
        if(records.size() == 0) return 0;

        GXJKData sendData = new GXJKData();

        List<GXJKData.Data> dataList = new ArrayList<>(records.size());
        sendData.setData(dataList);

        for(GnssCalcData locationRecord: records) {
            GXJKData.Data data = new GXJKData.Data();
            dataList.add(data);
            data.setDataTime(locationRecord.getCreatetime().format(formatter));
            data.setDevNum(locationRecord.getDeviceid());
            data.setDevtype("GNSS");
            // 单位由mm转化为m
            data.setX(NumberUtils.scale(locationRecord.getRpose() * 0.001, 5));
            data.setY(NumberUtils.scale(locationRecord.getRposn() * 0.001, 5));
            data.setZ(NumberUtils.scale(locationRecord.getRposd() * 0.001, 5));
            // 经纬度
            data.setDevLng(locationRecord.getR9250e());
            data.setDevLat(locationRecord.getR9250n());
            sendNum++;
        }
        String json = "#" + GsonUtil.toJson(sendData) + "!";
        logger.debug("project " + projectId + ": push calculation result to GXJK");
        logger.debug(json);
        // /slope/项目号-all/gnss/all/publish
        String topic = "/slope/"+projectId+"-all/gnss/all/publish";
        try {
            if(!mqttClient.publish(topic, json)) {
                sendNum = 0;
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return sendNum;
    }

}
