package com.imdroid.beidou_fwd.task;

import com.alibaba.fastjson.JSONObject;
import com.imdroid.beidou_fwd.entity.DefoData;
import com.imdroid.common.util.GsonUtil;
import com.imdroid.common.util.HttpUtils;
import com.imdroid.common.util.NumberUtils;
import com.imdroid.secapi.dto.GnssCalcData;
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.time.format.DateTimeFormatter;
import java.util.*;

@Component
@Configuration
@EnableScheduling
public class ZNYForwarder extends Forwarder{
    static final String FORWARDER_NAME = "武汉中南设计院";

    @Value("${zny.server.host}")
    private String data_host;
    final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @PostConstruct
    void registerMe(){
        init(FORWARDER_NAME, data_host,4,true,30);
    }
    /**
     * 每半小时转发GNSS解算结果
     */
    @Scheduled(cron = "0 0/10 * * * ?") // 每30分钟执行一次
    private void checkDevice() {
        logger.info("zny checkDevice");
        checkOfflineDevice("2345072","2345076","2345064");
    }

    @Scheduled(cron = "0 0/30 * * * ?") // 每30分钟执行一次
    private void forwardGnss() {
        logger.info("zny forwardGnss");
        forwardCurrentGnss();
    }

    @Override
    int send(String projectId, List<GnssCalcData> records, LocalDateTime sentTime){
        int sendNum = 0;
        // 单位：米
        DefoData defoData = new DefoData(projectId, sentTime.format(dateFormatter), records.size());
        for(GnssCalcData locationRecord:records) {
            double n = NumberUtils.scale(locationRecord.getRposn() * 0.001, 5);
            double e = NumberUtils.scale(locationRecord.getRpose() * 0.001, 5);
            double d = NumberUtils.scale(locationRecord.getRposd() * 0.001, 5);
            DefoData.Data data = new DefoData.Data(locationRecord.getDeviceid(), String.format("%.5f", n),
                    String.format("%.5f", e), String.format("%.5f", d));
            defoData.getData().add(data);
            sendNum++;
        }
        String json = GsonUtil.toJson(defoData);
        logger.info("发送数据到武汉中南设计院平台：{}", json);
        //return sendNum;

        try {
            String result = HttpUtils.postJson(data_host, json);
            logger.info("发送数据到武汉中南设计院平台返回结果：{}", result);
            JSONObject obj = (JSONObject) JSONObject.parse(result);
            String msg = obj.getString("msg");
            if (msg.contains("成功")) return sendNum;
            else return 0;
        }
        catch (Exception e){
            logger.error(e.toString());
            return 0;
        }
    }

}
