package com.keystar.plane.inspection.mqtt;

import cn.hutool.core.util.ReUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.keystar.mqtt.annotation.MqttHandlerType;
import com.keystar.mqtt.annotation.MqttSubScribe;
import com.keystar.mqtt.handler.AbstractMqttHandler;
import com.keystar.plane.inspection.constant.PlaneStatusConstant;
import com.keystar.plane.inspection.constant.UrlConstant;
import com.keystar.plane.inspection.dao.LoginVo;
import com.keystar.plane.inspection.dao.PlanePhotoVo;
import com.keystar.plane.inspection.utils.HttpUtils;
import com.keystar.plane.inspection.utils.RedisUtils;
import com.keystar.plane.inspection.utils.Utils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

@MqttHandlerType(
        {
                @MqttSubScribe(topic = "/70ddc6e4-1b3e-4da9-9952-16c04ec5c415/status/media", qos = 0)
        }
)
@Slf4j
public class PlaneMqttHandler implements AbstractMqttHandler {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @SneakyThrows
    @Override
    public void handle(MqttMessage message) {

        String key = "PlaneInspection:status";

        String messageContent = new String(message.getPayload());

        Map<String, String> map;
        try{
            map = OBJECT_MAPPER.readValue(messageContent,Map.class);
        }catch (IOException ioex){
            return;
        }

        if (map.containsKey("currentState")){

            String currentState = map.get("currentState");
            // 如果无人机当前状态是一边上传一边下载
            if (currentState.equals(PlaneStatusConstant.DOWNLOAD_UPLOAD_MEANWHILE)){
                RedisUtils.set(key,currentState);
            }

            // 如果无人机是处于空闲状态
            if (currentState.equals(PlaneStatusConstant.IDLE)){
                // 上一个状态还是上传下载
                if (RedisUtils.hasKey(key) && RedisUtils.get(key).equals(PlaneStatusConstant.DOWNLOAD_UPLOAD_MEANWHILE)){
                    String token = planeLogin();


                    if (token != null){
                        // todo 拿取最新的无人机图片

                    }
                }

                RedisUtils.set(key,currentState);
            }

        }
    }


    /**
     *  根据无人机登录接口返回token
     **/
    public static String planeLogin() throws Exception {

        String password = "Keystar@2022";
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDrKWklonbo4ZFgwLgE63wt+sHiB4Uq0Tl6V6g2Aoj5IPRd4TL8mJlMkaJu/c3G212jhjbUjYkWn5HOnrUwrVN1q+mJGGUCED6ruTNMiAc1Oe5gbLwGIeyk4IMuZFUVwq7XdTgVfFo9cVRAM8jIWftJrCm63ZrqqU/AdBoU4FSTQIDAQAB";
        String encrypt = Utils.encrypt(password, publicKey);

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("account","keystar");
        paramMap.put("password",encrypt);
        paramMap.put("type","1");
        paramMap.put("platform","0");

        String response = HttpUtils.doPost(UrlConstant.PLANE_LOGIN, paramMap, null);
        log.debug("======无人机登录接口返回结果： " + response);
        // 通过无人机的登录接口获取token
        Map<String, Object> responseMap = null;
        try {
            responseMap = OBJECT_MAPPER.readValue(response, Map.class);
        }catch (Exception e) {
            log.debug("通过无人机登录接口获取异常");
        }
        if (responseMap != null){

            Object param = responseMap.get("param");
            LoginVo loginVo = JSON.parseObject(JSON.toJSONString(param), LoginVo.class);
            return loginVo.getToken();
        }
        return null;
    }

    /**
     *  获取最新的无人机图片
     **/
    public static String getPlanePhoto() throws Exception {

        String token = planeLogin();
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", token);
        String response = HttpUtils.doGet(UrlConstant.PLANE_PHOTO, headers);
        log.debug("======获取无人机图片返回结果： " + response);

        return response;
    }


}
