package com.imdroid.beidou_fwd.task;

import com.alibaba.fastjson.JSONObject;
import com.imdroid.beidou_fwd.entity.KingMaData;
import com.imdroid.common.util.GsonUtil;
import com.imdroid.common.util.HttpUtils;
import com.imdroid.common.util.NumberUtils;
import com.imdroid.secapi.dto.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Configuration
@EnableScheduling
public class KingMaForwarder extends Forwarder{
    static final String FORWARDER_NAME = "KingMa";
    @Value("${kingma.server.login_user}")
    private String login_user;

    @Value("${kingma.server.login_pwd}")
    private String login_pwd;

    @Value("${kingma.server.login_host}")
    private String login_host;

    @Value("${kingma.server.data_host}")
    private String data_host;
    Map<String, String> header;
    LocalDateTime lastTokenTime = LocalDateTime.now();

    @PostConstruct
    void registerMe(){
        init(FORWARDER_NAME, data_host,3,true,60);
    }
    /**
     * 每半小时转发GNSS解算结果
     */
    @Scheduled(cron = "0 0 0/1 * * ?") // 每小时执行一次
    private void forwardGnss() {
        logger.info("kingma forwardGnss");
        forwardCurrentGnss();
    }

    boolean updateToken() throws Exception{
        String jsonLogin = "{\"username\":\""+login_user+"\"," +
                "\"password\":\""+login_pwd+"\"}";

        String result = HttpUtils.postJson(login_host, jsonLogin);
        if(result == null) return false;

        String token = null;
        JSONObject obj = (JSONObject) JSONObject.parse(result);
        obj = obj.getJSONObject("data");
        token = obj.getString("token");
        if(token == null) return false;

        if(header == null){
            header = new HashMap<>();
        }
        header.put("Authorization", token);
        return true;
    }

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

        // 检查token是否过期
        LocalDateTime nowTime = LocalDateTime.now();
        if(header == null || nowTime.isAfter(lastTokenTime.plusMinutes(59))){
            try {
                if (!updateToken()) {
                    logger.info("update token failed!");
                    return 0;
                }
            }
            catch (Exception e){
                logger.info("update token failed!");
                return 0;
            }
            lastTokenTime = nowTime;
        }

        List<KingMaData> dataList = new ArrayList<>(records.size());

        for(GnssCalcData locationRecord: records) {
            KingMaData data = new KingMaData();
            data.setDataTime(locationRecord.getCreatetime().toString());
            data.setProjectId(projectId);
            data.setDeviceId(locationRecord.getDeviceid());
            data.setFlag(0);
            data.setPhys(new KingMaData.Phys(
                    NumberUtils.scale(locationRecord.getRpose(), 2),
                    NumberUtils.scale(locationRecord.getRposn(), 2),
                    NumberUtils.scale(locationRecord.getRposd(), 2)));
            dataList.add(data);
            sendNum++;
        }
        String json = GsonUtil.toJson(dataList);
        String result = HttpUtils.postJson(data_host,header,json);
        logger.info("project " + projectId + ": push calculation result to Kingma");
        logger.info(json);
        logger.info("result: "+result);
        JSONObject obj = (JSONObject) JSONObject.parse(result);
        String msg = obj.getString("message");
        if(msg.equals("Success")) return sendNum;
        else return 0;
    }

}
