package com.imdroid.beidou_fwd.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.GnssCalcData;
import com.imdroid.secapi.dto.GnssStatusMsg;
import com.imdroid.secapi.dto.GnssStatusMsgMapper;
import org.springframework.beans.factory.annotation.Autowired;
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();

    @Autowired
    GnssStatusMsgMapper statusMsgMapper;

    @PostConstruct
    void registerMe(){
        init(FORWARDER_NAME, data_host,3,FWD_DEVICE_ALIAS_NAME,60);
    }
    /**
     * 每半小时转发GNSS解算结果
     */
    @Scheduled(cron = "0 0 0/1 * * ?") // 每小时执行一次
    //@Scheduled(cron = "0 0/5 * * * ?") // 每30分钟执行一次
    private void forwardGnss() {
        logger.debug("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.debug("update token failed!");
                    return 0;
                }
            }
            catch (Exception e){
                logger.debug("update token failed!");
                return 0;
            }
            lastTokenTime = nowTime;
        }

        // 获取最近一小时的状态消息
        // 获取温湿度
        QueryWrapper<GnssStatusMsg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenantid",tenantId);
        queryWrapper.le("createtime",sentTime);
        queryWrapper.ge("createtime",sentTime.minusMinutes(fwdCycleMinutes));
        queryWrapper.orderByDesc("createtime");
        List<GnssStatusMsg> statusMsgs = statusMsgMapper.selectList(queryWrapper);

        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)));
            for(GnssStatusMsg msg:statusMsgs){
                if(msg.getDeviceid().equals(locationRecord.getDeviceid())){
                    if(msg.getVoltage()!=null && msg.getRssi()!=null && msg.getTemperature()!=null) {
                        data.getPhys().setSensorData(
                                NumberUtils.scale((double) (msg.getVoltage() / 1000), 1),
                                NumberUtils.scale((double) (msg.getRssi()), 0),
                                NumberUtils.scale((double) (msg.getTemperature()), 1));
                    }
                    break;
                }
            }
            dataList.add(data);
            sendNum++;
        }
        String json = GsonUtil.toJson(dataList);
        logger.debug(json);
        String result = HttpUtils.postJson(data_host,header,json);
        logger.debug("project " + projectId + ": push calculation result to Kingma");
        logger.debug("result: "+result);
        JSONObject obj = (JSONObject) JSONObject.parse(result);
        String msg = obj.getString("message");
        if(msg.equals("Success")) return sendNum;
        else return 0;
        //return sendNum;
    }

}
