package com.example.math.task;

import com.alibaba.fastjson.JSONObject;
import com.example.math.constants.DJIMethonConstants;
import com.example.math.mqtt.MqttConfig;
import com.example.math.mqtt.SendMsg;
import com.example.math.mqtt.consumer.MqttConsumerCallBack;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class FirstTask {

    private static Integer seq = 0;

    private static Boolean aBoolean = false;

    @Autowired
    private MqttConfig providerClient;


//    @Scheduled(cron = "0/1 * * * * ?")
//    //或直接指定时间间隔，例如：5秒
//    //@Scheduled(fixedRate=5000)
//    private void configureTasks() {
//        System.err.println("执行静态定时任务时间: " + System.currentTimeMillis());
//
//        List<SendMsg> sendList = MqttConsumerCallBack.sendList;
//
//        while(sendList.size()>0) {
//            SendMsg sendMsg = sendList.remove(0);
//            log.info("sendmsg qos is {},retained is {}, topic is {}, msg is {}",
//                    sendMsg.retained = false;Qos(),sendMsg.isRetained(),sendMsg.getTopic(),sendMsg.getMessage());
//            providerClient.publish(sendMsg.getQos(),sendMsg.isRetained(),sendMsg.getTopic(),sendMsg.getMessage());
//
//        }
//    }


    @Scheduled(cron = "0/2 * * * * ?")
    private void aaaa() {
        if (true){
            Map<String,Object> content = new HashMap<>();
            HashMap<String, Long> data
                    = new HashMap<>();
            data.put("timestamp", System.currentTimeMillis());
            seq++;
            content.put("method", "heart_beat");
            content.put("data", data);
            content.put("seq", 0);
            String message = com.alibaba.fastjson.JSONObject.toJSONString(content);
//            System.out.println(message);
            MqttDeliveryToken publish = providerClient.publish(1, false, "thing/product/8UUXN3500A02BE/drc/down", message);
        }
    }



//    @Scheduled(cron = "0/1 * * * * ?")
//    //或直接指定时间间隔，例如：5秒
//    //@Scheduled(fixedRate=5000)
//    private void configureTasks() {
//
//        flightAuthorityGrab("7CTXMC500B052Q");
//
//        payloadAuthorityGrab("81-0-0", "7CTXMC500B052Q");
//    }


    private static String someTopic = "thing/product/%s/services";

    /**
     * 飞行控制权抢夺 /flightAuthorityGrab
     * @param airPortSn 机场sn号
     * @return JsonResult
     */
    public String flightAuthorityGrab(String airPortSn){
        try {
            log.info("飞行控制权抢夺 flight_authority_grab is start");
            Integer qos = 1;
            Boolean retained = false;
            //topic主题 sn是机场sn号  thing/product/%s/services
            //TODO 此处用的是无人的SN号 待测试
            String topic = String.format(someTopic, airPortSn);
            //封装数据
            Map<String,Object> content = new HashMap<>();
            Map<String,Object> data = new HashMap<>();
            String tid = UUID.randomUUID().toString();
            content.put("tid", tid);
            content.put("bid", UUID.randomUUID().toString());
            content.put("timestamp",System.currentTimeMillis());
            content.put("method", DJIMethonConstants.FLIGHT_AUTHORITY_GRAB);
            content.put("data", data);
            String message = JSONObject.toJSONString(content);
            System.out.println(message);
            MqttDeliveryToken publish = providerClient.publish(qos, retained, topic, message);
            log.info("飞行控制权抢夺 flight_authority_grab is end topic is {}, message is {}, token is {} ", topic, message, publish);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "发送失败";
        }
    }

    /**
     * 负载控制权抢夺 /payloadAuthorityGrab
     * @param airPortSn 机场sn号
     * @param cameraIndex 镜头参数
     * @return JsonResult
     */
    public String payloadAuthorityGrab(String cameraIndex, String airPortSn){
        try {
            Integer qos = 2;
            Boolean retained = false;
            //topic主题 sn是机场sn号  thing/product/%s/services
            //TODO 此处用的是无人的SN号 待测试
            String topic = String.format(someTopic, airPortSn);
            //封装数据
            Map<String,Object> content = new HashMap<>();
            Map<String,Object> data = new HashMap<>();
            //负载枚举值 镜头负载
            data.put("payload_index", cameraIndex);
            content.put("tid", UUID.randomUUID().toString());
            content.put("bid", UUID.randomUUID().toString());
            content.put("timestamp",System.currentTimeMillis());
            content.put("method", DJIMethonConstants.PAYLOAD_AUTHORITY_GRAB);
            content.put("data", data);
            String message = com.alibaba.fastjson.JSONObject.toJSONString(content);
            System.out.println(message);
            MqttDeliveryToken publish = providerClient.publish(qos, retained, topic, message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "发送失败";
        }
    }



}
