package com.example.math.mqtt.consumer;



import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.sts20150401.Client;
import com.aliyun.sts20150401.models.AssumeRoleRequest;
import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.example.math.constants.CommonConstants;
import com.example.math.constants.DJIMethonConstants;
import com.example.math.controller.OperateController;
import com.example.math.enums.TakeOffToPointEnum;
import com.example.math.mqtt.MqttConfig;
import com.example.math.mqtt.SendMsg;
import com.example.math.mqtt.SpringUtil;
//import com.example.math.task.FirstTask;
import com.example.math.mqtt.SpringUtils;
//import com.example.math.utils.DJIUtils;
import com.example.math.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Component
public class MqttConsumerCallBack implements MqttCallback {


    public static List<SendMsg> sendList = new ArrayList<>();




    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    @Value("${spring.mqtt.url}")
    private String address;

//    @Value("${spring.mqtt.newUrl}")
//    private String newAddress;

    @Value("${spring.mqtt.client.id}")
    private String clientId;

    @Autowired
    private RedisUtils redisUtils;

    //机场推流地址
    private static String airportRtmpUrl =  "rtmp://live.push.t-aaron.com/dji/hyslj002";
    //无人机推流地址
    private static String droneRtmpUrl =  "rtmp://live.push.t-aaron.com/dji/hyslj001";




    //topic固定参数
    private static String someTopic = "thing/product/%s/services";

    //机场sn号
    private static String airPortSn = "8UUXN3500A02BE";

    /**
     * 客户端断开连接的回调
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.info("与服务器断开连接，可重连");
        MqttConfig client = SpringUtil.getBean(MqttConfig.class);
        client.connect();
//        if (!client.isconnect()) {
//            client.connect();
//            log.info("重连成功！");
//        }
    }


    private static int qos = 2;
    private static boolean retained = true;

//    @Autowired
//    private MqttConfig providerClient;

    private static final String DJIAIRPORT_SN = "7CTDM7H00BXZD1";

    private static final String DJIDRONE_SN = "1581F6Q8D243100C605L";

    private static final String AIRLINE = "airline";

    private static final String CAMERA_INDEX = "81-0-0";





    /**
     * 消息到达的回调
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {

//
//        if (true){
//            return;
//        }

//        System.out.println();
//        System.out.println(String.format("接收消息主题 : %s", topic));
////        System.out.println(String.format("接收消息Qos : %d", message.getQos()));
//        System.out.println(String.format("接收消息内容 : %s", new String(message.getPayload())));
////        System.out.println(String.format("接收消息retained : %b", message.isRetained()));
//        System.out.println();
//        if(topic.length() > 0){
////            return;
//        }

//        if(true){
//            if (Objects.isNull(redisUtils)){
//                redisUtils = SpringUtils.getBean(RedisUtils.class);
//            }
//            redisUtils.set(AIRLINE + DJIDRONE_SN, 11111, 60 * 60 * 24);
//            Object o = redisUtils.get(AIRLINE + DJIDRONE_SN);
//        }

        String payload = new String(message.getPayload());
        JSONObject jsonObject = JSONObject.parseObject(payload);
        Object tid = jsonObject.getString("tid");
        Object bid = jsonObject.getString("bid");
        Object timestamp = jsonObject.getLong("timestamp");
        Object method = jsonObject.getString("method");
        Object gateway = jsonObject.getString("gateway");


        //获取设备可上传的文件列表
        if (topic.contains("7CTDM7H00BXZD1/services_reply") && method.equals("fileupload_list")){

        }


        //获取设备可上传的文件列表
        if (topic.contains("7CTDM7H00BXZD1/events") && method.equals("fileupload_progress")){



            System.out.println();
            System.out.println();
        }

        //获取设备可上传的文件列表
        if (topic.contains("/events") && method.equals("fileupload_list")){

        }


        if (topic.contains("/events") && method.equals("ota_progress")){

        }




        //媒体文件上报的处理
        RedisUtils redisUtils = SpringUtils.getBean(RedisUtils.class);
        if (Objects.nonNull(method) && method.equals("fly_to_point_progress")){
            String airPprtSn = "8UUXN3500A02BE";
            String data = jsonObject.getString("data");
            String string = com.alibaba.fastjson.JSONObject.parseObject(data).getString("status");
            //查询是否处于飞行控制模式

            Object o = redisUtils.get(airPprtSn + DJIMethonConstants.DRC_STATUS);

            if (TakeOffToPointEnum.WAYLINE_CANCEL.getCode().equals(string)){
                System.out.println("++++++++++++++++++ 指点失败了！！！！");
            }


            if (TakeOffToPointEnum.WAYLINE_PROGRESS.getCode().equals(string)){
                redisUtils.hset(CommonConstants.FLY_TOPOINT_PROGRESS, airPprtSn, TakeOffToPointEnum.WAYLINE_PROGRESS.getCode(), 5);

                if (Objects.nonNull(o) && o.equals(true)){
                    log.info("指点飞行退出控制模式 is {}", airPprtSn);
                    drcModeExit();
                    redisUtils.set(airPprtSn + DJIMethonConstants.DRC_STATUS, false);
                }
            }else if (TakeOffToPointEnum.WAYLINE_OK.getCode().equals(string) || TakeOffToPointEnum.WAYLINE_CANCEL.getCode().equals(string) || TakeOffToPointEnum.WAYLINE_FAILED.getCode().equals(string)){
                redisUtils.hset(CommonConstants.FLY_TOPOINT_PROGRESS, airPprtSn, TakeOffToPointEnum.WAYLINE_OK.getCode(), 2);
                //不处于
                if (Objects.nonNull(o) && (Boolean)o.equals(false)){
                    log.info("指点飞行进入控制模式 msg is {}", jsonObject);
//                    Thread.sleep(1000);
                    drcModeEnter();
                    redisUtils.set(airPprtSn + DJIMethonConstants.DRC_STATUS, true);
                }
            }
        }






//        String string = jsonObject.getString("data");
//        com.alibaba.fastjson.JSONObject data = com.alibaba.fastjson.JSONObject.parseObject(string);
//        Map map = new HashMap();
//        if (Objects.nonNull(data.getString("longitude"))) {
//            //空调模式
//            JSONObject airConditioner =  JSONObject.parseObject(data.getString("air_conditioner"));
//            //获取空调模式 air_conditioner_state {"0":"空闲模式(无制冷、制热、除湿等)","1":"制冷模式","2":"制热模式","3":"除湿模式","4":"制冷退出模式","5":"制热退出模式","6":"除湿退出模式","7":"制冷准备模式","8":"制热准备模式","9":"除湿准备模式"10":"风冷准备中"11":"风冷中"12":"风冷退出中"13":"除雾准备中"14":"除雾中"15":"除雾退出中"}
//            String airConditionerState = airConditioner.getString("air_conditioner_state");
//            map.put("airConditionerState", airConditionerState);
//            System.out.println(LocalDateTime.now() + "    " +  "airConditionerState is " + airConditionerState + "              ");
//            //获取空调模式可切换时间 为0时才可切换其他空调模式 单位为秒
//            String switchTime = airConditioner.getString("switch_time");
//            map.put("switchTime", switchTime);
//            System.out.println(LocalDateTime.now() + "    " +  "switchTime is " + switchTime);
//        }


        String data = jsonObject.getString("data");


        if (topic.equals("thing/product/1581F6Q83254100BD0UV/osd")){
            String string = jsonObject.getString("data");
            JSONObject newJson = JSONObject.parseObject(string);
//            String modeCode = newJson.getString("mode_code");
//            if (Objects.nonNull(modeCode)){
//                System.out.printf("+++++" + modeCode + "       ");
//            }
//            redisUtils.set("8UUXN3500A02BE" + DJIMethonConstants.DRC_STATUS, false);

//            if (modeCode.equals("1")){
//                log.info("drone msg is {}", jsonObject.getString("modeCode"));
//                //先获取飞行控制权
//                Object flightAuthority = redisUtils.get("8UUXN3500A02BE" + DJIMethonConstants.FLIGHT_AUTHORITY_GRAB);
//                if (Objects.isNull(flightAuthority)){
//                    flightAuthorityGrab("8UUXN3500A02BE");
//                    redisUtils.set("8UUXN3500A02BE" + DJIMethonConstants.FLIGHT_AUTHORITY_GRAB, 1);
//                }
//                //再获取负载控制权
//                Object payloadAuthority = redisUtils.get("8UUXN3500A02BE" + DJIMethonConstants.PAYLOAD_AUTHORITY_GRAB);
//                if (Objects.isNull(payloadAuthority)){
//                    payloadAuthorityGrab("99-0-0", "8UUXN3500A02BE");
//                    redisUtils.set("8UUXN3500A02BE" + DJIMethonConstants.PAYLOAD_AUTHORITY_GRAB, 1);
//                }
//                //如果是返航或者降落 退出飞行控制模式 并停止心跳发送
//                if (modeCode.equals("9") || modeCode.equals("10")){
//                    drcModeExit();
//                }
//            }


            String positionState = newJson.getString("position_state");
            if (Objects.nonNull(positionState)){
                String gpsNumber = com.alibaba.fastjson.JSONObject.parseObject(positionState).getString("gps_number");
                System.out.printf("gpsNumber is " + gpsNumber + System.getProperty("line.separator"));

                String quality = com.alibaba.fastjson.JSONObject.parseObject(positionState).getString("quality");
                System.out.printf("quality is " + quality + System.getProperty("line.separator"));

                String rtk_number = com.alibaba.fastjson.JSONObject.parseObject(positionState).getString("rtk_number");
                System.out.printf("rtk_number is " + rtk_number + System.getProperty("line.separator"));
            }

        }


//        if (!topic.equals("thing/product/8UUXN2T00A01RU/events")){
//            return;
//        }


        if(topic.equals("thing/product/7CTXMC900B054P/osd")){
            JSONObject newJson = JSONObject.parseObject(data);
//            String drcState = newJson.getString("drc_state");
//            if (Objects.nonNull(drcState)){
//                System.out.printf("网络状态 is " + drcState + System.getProperty("line.separator") );
//            }


            String network_state = newJson.getString("network_state");
            if (Objects.nonNull(network_state)){
                System.out.printf("网络状态 is " + network_state + System.getProperty("line.separator") );
            }

            Object o = newJson.get("wireless_link");
            if (Objects.nonNull(o)){
                JSONObject wireless_link = (JSONObject) o;
                String sdr_quality = wireless_link.getString("sdr_quality");
                System.out.printf("图传信号 " + sdr_quality + System.getProperty("line.separator") );
            }


//            String modeCode = jsonObject.getString("modeCode");
//            log.info("drone msg is {}", modeCode);
//            if (Objects.nonNull(modeCode)){
//                //先获取飞行控制权
//                String airportSn = "8UUXN2T00A01R1";
//                RedisUtils redisUtils = SpringUtils.getBean(RedisUtils.class);
//                DJIUtils djiUtils = SpringUtils.getBean(DJIUtils.class);
//                Object flightAuthority = redisUtils.get(airportSn + DJIMethonConstants.FLIGHT_AUTHORITY_GRAB);
//                if (Objects.isNull(flightAuthority)){
//                    djiUtils.flightAuthorityGrab(airportSn);
//                    redisUtils.set(airportSn + DJIMethonConstants.FLIGHT_AUTHORITY_GRAB, 1);
//                }
//                //再获取负载控制权
//                Object payloadAuthority = redisUtils.get(airportSn + DJIMethonConstants.PAYLOAD_AUTHORITY_GRAB);
//                if (Objects.isNull(payloadAuthority)){
//                    djiUtils.payloadAuthorityGrab("99-0-0", airportSn);
//                    redisUtils.set(airportSn + DJIMethonConstants.PAYLOAD_AUTHORITY_GRAB, 1);
//                }
//            }
        }

//        if (method.equals("fly_to_point_progress")){
//            takeoffToPointProgress(oldJsonObject, data, sn);
//        }


//
//        if (Objects.isNull(method)){
//            return;
//        }
//
//
//        //DRC-飞行控制无效原因通知
//        if (method.equals("joystick_invalid_notify")){
//            JSONObject dataJson = JSONObject.parseObject(data);
//            String reason = dataJson.getString("reason");
//            log.info("joystick_invalid_notify is {}" ,reason);
//
//        }
//        //DRC 链路状态通知
//        if (method.equals("drc_status_notify")){
//            JSONObject dataJson = JSONObject.parseObject(data);
//            String drcState = dataJson.getString("drc_state");
//            String result = dataJson.getString("result");
//            log.info("drc_status_notify is {}, is {} ", drcState  , result);
//        }


//        if(Objects.nonNull(method) && method.equals("fileupload_progress")){
//            Map<String,Object> content = new HashMap<>();
//            content.put("tid",tid);
//            content.put("bid",bid);
//            content.put("gateway", gateway);
//            content.put("timestamp",System.currentTimeMillis());
//            content.put("method",method);
//            Map<String,Object> data1 = new HashMap<>();
//            data1.put("result", 0);
//            content.put("data",data1);
//            String msg = com.alibaba.fastjson.JSONObject.toJSONString(content);
//            topic += "_reply";
//            MqttConfig providerClient = SpringUtil.getBean(MqttConfig.class);
//            MqttDeliveryToken publish = providerClient.publish(1, false, topic, msg);
//        }


//
//        log.info("tid is {},bid is {},method is {}, gateway is {}, timestamp is {}",
//                tid,bid,method,gateway,timestamp);


//        if ("thing/product/7CTDM7H00BXZD1/events".equals(topic)){
//            Map<String,Object> data = new HashMap<>();
//            data.put("result",0);
//            Map<String,Object> content = new HashMap<>();
//            content.put("tid",tid);
//            content.put("bid",bid);
//            content.put("gateway", DJIAIRPORT_SN);
//            content.put("timestamp",System.currentTimeMillis());
//            content.put("method","flighttask_progress");
//            content.put("data",data);
//            String msg = JSONObject.toJSONString(content);
//            topic += "_reply";
//            SendMsg sendMsg = new SendMsg();
//            sendMsg.setQos(qos);
//            sendMsg.setRetained(retained);
//            sendMsg.setTopic(topic);
//            sendMsg.setMessage(msg);
//            sendList.add(sendMsg);
//
//        }


//        if ("file_upload_callback".equals(method)){
//            System.out.printf("媒体文件上传结果上报" + topic);
//            System.out.printf("媒体文件上传结果上报2" + method);
//        }
//
//        if ("thing/product/7CTDM7H00BXZD1/events".equals(topic) && "file_upload_callback".equals(method)){
//            System.out.printf("媒体文件上传结果上报" + topic);
//            System.out.printf("媒体文件上传结果上报2" + method);
//        }
//
//        try{
//            if (topic.equals("thing/product/7CTDM7H00BXZD1/osd")){
//                //此处处理 无人机osd 回调处理气象 状态等信息 airportStatus
//                log.info("topic is {}", topic);
//                airportStatus(jsonObject, "7CTDM7H00BXZD1", tid , bid);
//
//                Object data = jsonObject.getString("data");
//                JSONObject newJson = JSONObject.parseObject(data.toString());
//                String string = newJson.getString("drc_state");
//                if (Objects.nonNull(string)){
//                    System.out.printf("osd中的drc_state" + string);
////                    if (string.equals("2") || string.equals(2)){
////                        log.info("一键起飞命令 drc_mode_enter is start");
////                        FirstTask.seq = 0;
////
////                        Integer qos = 2;
////                        Boolean retained = true;
////                        //topic主题 sn是机场sn号  thing/product/%s/services
////                        //TODO 此处用的是无人的SN号 待测试
////                        String newtopic = String.format(someTopic, airPortSn);
////                        //封装数据
////                        Map<String,Object> content = new HashMap<>();
////                        Map<String,Object> newdata = new HashMap<>();
////                        //负载枚举值 镜头负载
////                        newdata.put("hsi_frequency", 1);
////
////                        //Broker 连接信息
////                        Map<String,Object> mqttBroker = new HashMap<>();
////                        //服务器连接地址
////                        mqttBroker.put("address", newAddress);
////                        //客户端ID
////                        mqttBroker.put("client_id", clientId += "drc");
////                        //enable_tls
////                        mqttBroker.put("enable_tls", false);
////                        //expire_time 当前时间+3000秒
////                        mqttBroker.put("expire_time", System.currentTimeMillis()/1000 + 3600);
////                        //密码
////                        mqttBroker.put("password", password);
////                        //用户名
////                        mqttBroker.put("username", username);
////                        newdata.put("mqtt_broker", mqttBroker);
////                        //设置 OSD 上报频率  {"max":30,"min":1,"unit_name":"赫兹 / Hz"}
////                        newdata.put("osd_frequency", 21);
////
////                        content.put("tid", UUID.randomUUID().toString());
////                        content.put("bid", UUID.randomUUID().toString());
////                        content.put("timestamp",System.currentTimeMillis());
////                        content.put("method", DJIMethonConstants.DRC_MODE_ENTER);
////                        content.put("data", newdata);
////                        String message1 = JSONObject.toJSONString(content);
////                        System.out.println(message);
////                        MqttDeliveryToken publish = providerClient.publish(qos, retained, newtopic, message1);
////                        log.info("一键起飞命令 drc_mode_enter is end topic is {}, message is {}, token is {} ", newtopic, message1, publish);
////                    }
//
//
//                }
//
//
//            }else if (topic.equals("thing/product/1581F6Q8D243100C605L/osd")){
//                //此处处理 机场osd 回调处理气象 状态等信息
//                log.info("处理机场osd回调信息 topic is {}", topic);
//                droneStatus(jsonObject, "1581F6Q8D243100C605L", tid , bid);
//            }else if (topic.equals("sys/product/7CTDM7H00BXZD1/status")){
//                log.info("收到无人机osd失效 sys/product/7CTDM7H00BXZD1/status");
//                Map<String,Object> data = new HashMap<>();
//                data.put("result",0);
//                Map<String,Object> content = new HashMap<>();
//                content.put("tid",tid);
//                content.put("bid",bid);
//                content.put("timestamp",System.currentTimeMillis());
//                content.put("method","update_topo");
//                content.put("data",data);
//                MqttConfig providerClient = SpringUtil.getBean(MqttConfig.class);
//                String msg = com.alibaba.fastjson.JSONObject.toJSONString(content);
//                topic += "_reply";
//                MqttDeliveryToken publish = providerClient.publish(qos, retained, topic, msg);
//                log.info("处理无人机osd失效的回复 topic is {}, msg is {}, publish is {}", topic, msg, publish);
//            }else if (topic.equals("sys/product/7CTDM7H00BXZD1/status")){
//                log.info("收到无人机osd失效 sys/product/7CTDM7H00BXZD1/status");
//                Map<String,Object> data = new HashMap<>();
//                data.put("result",0);
//                Map<String,Object> content = new HashMap<>();
//                content.put("tid",tid);
//                content.put("bid",bid);
//                content.put("timestamp",System.currentTimeMillis());
//                content.put("method","update_topo");
//                content.put("data",data);
//                MqttConfig providerClient = SpringUtil.getBean(MqttConfig.class);
//                String msg = com.alibaba.fastjson.JSONObject.toJSONString(content);
//                topic += "_reply";
//                MqttDeliveryToken publish = providerClient.publish(qos, retained, topic, msg);
//                log.info("处理无人机osd失效的回复 topic is {}, msg is {}, publish is {}", topic, msg, publish);
//            }else if (topic.equals("thing/product/7CTDM7H00BXZD1/events") && method.equals("drc_status_notify") ) {
//                //此处drc链路通知状态
//                Object data = jsonObject.getString("data");
//                log.info("drc_status_notify topic is {}, data is {}", topic, data);
//                JSONObject newJson = JSONObject.parseObject(data.toString());
//                log.info("drc链路消息", newJson);
//            }else if (topic.equals("thing/product/7CTDM7H00BXZD1/events") && method.equals("takeoff_to_point_progress") ) {
//                //处理一键起飞结果
//                log.info("topic is {}", topic);
//            } else if ( topic.equals("thing/product/7CTDM7H00BXZD1/drc/up") && method.equals("drone_control")  ){
//                System.out.printf("控制指令报错了" + jsonObject);
//                Object data = jsonObject.getString("data");
//                JSONObject newJson = JSONObject.parseObject(data.toString());
//                String string = newJson.getString("result");
//                if (!string.equals(0)){
////                    OperateController.seq = 0;
//                }
//            }
//        }catch (Exception e){
//
//        }
//
//
//        if (topic.equals("thing/product/8UUXN2T00A01QB/requests")) {
//            System.out.println("enter...............");
//            if (method.equals("config")) {
//                System.out.println("enter config..........");
//                //需要回复
//
//                Map<String, Object> data = new HashMap<>();
//                data.put("ntp_server_host", "172.16.251.26");
//                data.put("app_id", "148774");
//                data.put("app_key", "a3ba3e9934f43b82bd52428b26e695b");
//                data.put("app_license", "Cm+BDccW/auc1L5Fixy59JrudnnXxguksAfGNPRjaDDqf3ESlHJt4JYaYBlXJ/rkkSPREF/MIg5FZV3MSwPVcXQ2ioOahFH0OEHx0fhxLnrS2uUVXaXcDkDxLRfDuOTvkmojS3KFZIgPOjt6hdF9Madi/WC+EsnZzpA5RvTD/u4=");
//                data.put("ntp_server_port", "172.16.251.26");
//
//
//                Map<String, Object> content = new HashMap<>();
//                content.put("tid", tid);
//                content.put("bid", bid);
//                content.put("timestamp", System.currentTimeMillis());
//                content.put("method", "config");
//                content.put("data", data);
//
//                String msg = JSONObject.toJSONString(content);
////                log.info("will send msg is {}" ,msg);
//
//                topic += "_reply";
//
//                SendMsg sendMsg = new SendMsg();
//                sendMsg.setQos(qos);
//                sendMsg.setRetained(retained);
//                sendMsg.setTopic(topic);
//                sendMsg.setMessage(msg);
//                sendList.add(sendMsg);
//
//
//                if (Objects.isNull(providerClient)){
//                    providerClient = SpringUtil.getBean(MqttConfig.class);
//                }
//                providerClient.publish(qos, retained, topic, msg);
//                return;
//            }
//
//            else if(method.equals("airport_bind_status")){
////            }else
// if(method.equals("storage_config_get")){
//                System.out.println("enter airport_bind_status..........");
//                //需要回复
//
//                Map<String,Object> deviceInfo = new HashMap<>();
//                deviceInfo.put("sn" ,"7CTDM7H00BXZD1");
//                deviceInfo.put("device_callsign" ,"");
//                deviceInfo.put("is_device_bind_organization" ,true);
//                deviceInfo.put("organization_id" ,"w");
//                deviceInfo.put("organization_name" ,"Test Group One");
//
//
//
//                List<Map<String,Object>> bindStatusList = new ArrayList<>();
//                bindStatusList.add(deviceInfo);
//
//                Map<String,Object> bindItem = new HashMap<>();
//                bindItem.put("bind_status" ,bindStatusList);
//
//                Map<String,Object> data = new HashMap<>();
//                data.put("output",bindItem);
//                data.put("result",0);
//
//                Map<String,Object> content = new HashMap<>();
//                content.put("tid",tid);
//                content.put("bid",bid);
//                content.put("timestamp",System.currentTimeMillis());
//                content.put("method","airport_bind_status");
//                content.put("data",data);
//
//                String msg = JSONObject.toJSONString(content);
////                log.info("will send msg is {}" ,msg);
//
//                topic += "_reply";
//                SendMsg sendMsg = new SendMsg();
//                sendMsg.setQos(qos);
//                sendMsg.setRetained(retained);
//                sendMsg.setTopic(topic);
//                sendMsg.setMessage(msg);
//
//                if (Objects.isNull(providerClient)){
//                    providerClient = SpringUtil.getBean(MqttConfig.class);
//                }
//                providerClient.publish(qos, retained, topic, msg);
//            }


// else if(method.equals("airport_organization_get")){
////            }else
// if(method.equals("storage_config_get")){
//                System.out.println("enter airport_organization_get..........");
//                //需要回复
//
//                Map<String,Object> outputItem = new HashMap<>();
//                outputItem.put("organization_name" ,"Test Group One");
//
//                Map<String,Object> data = new HashMap<>();
//                data.put("output",outputItem);
//                data.put("result",0);
//
//                Map<String,Object> content = new HashMap<>();
//                content.put("tid",tid);
//                content.put("bid",bid);
//                content.put("timestamp",System.currentTimeMillis());
//                content.put("method","airport_organization_get");
//                content.put("data",data);
//
//                String msg = JSONObject.toJSONString(content);
////                log.info("will send msg is {}" ,msg);
//
//                topic += "_reply";
//                SendMsg sendMsg = new SendMsg();
//                sendMsg.setQos(qos);
//                sendMsg.setRetained(retained);
//                sendMsg.setTopic(topic);
//                sendMsg.setMessage(msg);
//
//                sendList.add(sendMsg);
////                if (Objects.isNull(providerClient)){
////                    providerClient = SpringUtil.getBean(MqttConfig.class);
////                }
////                providerClient.publish(qos, retained, topic, msg);
//                return;
//            }
//
//
//            else if(method.equals("airport_organization_bind")){
////            }else if(method.equals("storage_config_get")){
//                System.out.println("enter airport_organization_get..........");
//                //需要回复
//
//
//                Map<String,Object> err_info = new HashMap<>();
//                err_info.put("sn" ,"7CTDM7H00BXZD1");
//                err_info.put("err_code" ,0);
//
//                List<Map<String,Object>> err_infos = new ArrayList<>();
//                err_infos.add(err_info);
//
//                Map<String,Object> outputItem = new HashMap<>();
//                outputItem.put("err_infos" ,err_infos);
//
//                Map<String,Object> data = new HashMap<>();
//                data.put("output",outputItem);
//                data.put("result",0);
//
//                Map<String,Object> content = new HashMap<>();
//                content.put("tid",tid);
//                content.put("bid",bid);
//                content.put("timestamp",System.currentTimeMillis());
//                content.put("method","airport_organization_bind");
//                content.put("data",data);
//
//                String msg = JSONObject.toJSONString(content);
////                log.info("will send msg is {}" ,msg);
//
//                topic += "_reply";
//                SendMsg sendMsg = new SendMsg();
//                sendMsg.setQos(qos);
//                sendMsg.setRetained(retained);
//                sendMsg.setTopic(topic);
//                sendMsg.setMessage(msg);
//
//                sendList.add(sendMsg);
////                if (Objects.isNull(providerClient)){
////                    providerClient = SpringUtil.getBean(MqttConfig.class);
////                }
////                providerClient.publish(qos, retained, topic, msg);
//                return;
//            }else
//
//
//            if(method.equals("storage_config_get")){
//                System.out.println("enter storage_config_get..........");
//                //需要回复
//                System.out.printf("jsonObject" + jsonObject);
//                Map<String,Object> credentials = new HashMap<>();
//                //获取阿里云 OSS对应文件夹的token
//                Map<String, String> ossMap = ossToken();
//                if (!CollectionUtils.isEmpty(ossMap)){
//                    credentials.put("access_key_id" , ossMap.get("access_key_id"));
//                    credentials.put("access_key_secret" , ossMap.get("access_key_secret"));
//                    credentials.put("expire" ,3600);
//                    credentials.put("security_token" , ossMap.get("security_token"));
//                    log.info("获取阿里云上传凭证成功");
//                }else {
//                    log.info("获取阿里云上传凭证失败");
//                }
//                Map<String,Object> outputItem = new HashMap<>();
//                outputItem.put("bucket" ,"dji-dev");
//                outputItem.put("endpoint" ,"https://oss-cn-shanghai.aliyuncs.com");
//                outputItem.put("object_key_prefix" ,"hyslj");
//                outputItem.put("provider" ,"ali");
//                outputItem.put("region" ,"sh");
//                outputItem.put("credentials" ,credentials);
//
//                Map<String,Object> data = new HashMap<>();
//                data.put("output",outputItem);
//                data.put("result",0);
//
//                Map<String,Object> content = new HashMap<>();
//                content.put("tid",tid);
//                content.put("bid",bid);
//                content.put("timestamp",System.currentTimeMillis());
//                content.put("method","storage_config_get");
//                content.put("data",data);
//
//                String msg = JSONObject.toJSONString(content);
////                log.info("will send msg is {}" ,msg);
//
//                topic += "_reply";
//                SendMsg sendMsg = new SendMsg();
//                sendMsg.setQos(qos);
//                sendMsg.setRetained(false);
//                sendMsg.setTopic(topic);
//                sendMsg.setMessage(msg);
//
//                sendList.add(sendMsg);
//                //消息回复
//                if (Objects.isNull(providerClient)){
//                    providerClient = SpringUtil.getBean(MqttConfig.class);
//                }
//                providerClient.publish(qos, retained, topic, msg);
//                return;
//            }
//
//
//            else if(method.equals("flighttask_resource_get")){
//
////                System.out.println("enter flighttask_resource_get..........");
////                //需要回复
////
////                Map<String,Object> file = new HashMap<>();
////                file.put("fingerprint","AA9D2EF80BBE544B3C7B97C9087E640F");
////                file.put("url","xxxxxx");
////
////                Map<String,Object> output = new HashMap<>();
////                output.put("file" ,file);
////
////                Map<String,Object> data = new HashMap<>();
////                data.put("output",output);
////                data.put("result",0);
////
////                Map<String,Object> content = new HashMap<>();
////                content.put("tid",tid);
////                content.put("bid",bid);
////                content.put("timestamp",System.currentTimeMillis());
////                content.put("method","flighttask_resource_get");
////                content.put("data",data);
////
////                String msg = JSONObject.toJSONString(content);
//////                log.info("will send msg is {}" ,msg);
////
////                topic += "_reply";
////                SendMsg sendMsg = new SendMsg();
////                sendMsg.setQos(qos);
////                sendMsg.setRetained(false);
////                sendMsg.setTopic(topic);
////                sendMsg.setMessage(msg);
////
////                sendList.add(sendMsg);
////                //消息回复
////                if (Objects.isNull(providerClient)){
////                    providerClient = SpringUtil.getBean(MqttConfig.class);
////                }
////                providerClient.publish(qos, retained, topic, msg);
//                return;
//            }
//        }
//
//
//        System.out.println("finish...");

        }

//    /**
//     * 消息发布成功的回调
//     */
//    @Override
//    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//
//    }


//    /**
//     * 气温 状态等数据
//     * @param oldjsonObject
//     */
//    private void droneStatus(JSONObject oldjsonObject, String sn , Object tid, Object bid) {
//        Map map = new HashMap();
//        //发送的坐标信息
//        String string = oldjsonObject.getString("data");
//        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(string);
//        //当前位置经度 longitude
//        String longitude = jsonObject.getString("longitude");
//        map.put("longitude", longitude);
//        //当前位置纬度 latitude
//        String latitude = jsonObject.getString("latitude");
//        map.put("latitude", latitude);
//        //飞行器状态
//        String modeCode = jsonObject.getString("mode_code");
//        map.put("modeCode", modeCode);
//        //相对起飞点高度 elevation
//        String elevation = jsonObject.getString("elevation");
//        map.put("elevation", elevation);
//        //风速 wind_speed
//        String windSpeed = jsonObject.getString("wind_speed");
//        map.put("windSpeed", windSpeed);
//        //当前风向 wind_direction
//        String windDirection = jsonObject.getString("wind_direction");
//        map.put("windDirection", windDirection);
//        //低电量告警 low_battery_warning_threshold
//        String lowBatteryWarningThreshold = jsonObject.getString("low_battery_warning_threshold");
//        map.put("lowBatteryWarningThreshold", lowBatteryWarningThreshold);
//        //飞行器电池信息 battery  {
//        // capacity_percent电池的总剩余电量  remain_flight_time剩余飞行时间  return_home_power返航所需电量百分比 landing_power强制降落电量百分比capacity_percent电池剩余电量
//        // voltage电压  temperature温度  wind_direction风向   }
//        String battery = jsonObject.getString("battery");
//        map.put("battery", battery);
//        RedisUtils redisUtils = SpringUtil.getBean(RedisUtils.class);
//        redisUtils.hmset("DJIDrone" + sn, map, 300);
//
//        Map<String,Object> content = new HashMap<>();
//        content.put("longitude",longitude);
//        content.put("latitude",latitude);
//        String msg = com.alibaba.fastjson.JSONObject.toJSONString(content);
//    }
//
//
//    /**
//     * 无人机气温 状态等数据
//     * @param oldjsonObject
//     */
//    private void airportStatus(JSONObject oldjsonObject, String sn, Object tid, Object bid) {
//        Map map = new HashMap();
//        //发送的坐标信息
//        String string = oldjsonObject.getString("data");
//        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(string);
//        //当前位置经度 longitude
//        String longitude = jsonObject.getString("longitude");
//        if (Objects.isNull(longitude)){
//            return;
//        }
//        map.put("longitude", longitude);
//        //当前位置纬度 latitude
//        String latitude = jsonObject.getString("latitude");
//        map.put("latitude", latitude);
//        //工作电流 working_current
//        String workingCurrent = jsonObject.getString("working_current");
//        map.put("workingCurrent", workingCurrent);
//        //工作电压 working_voltage
//        String workingVoltage = jsonObject.getString("working_voltage");
//        map.put("workingVoltage", workingVoltage);
//        //舱内湿度 humidity
//        String humidity = jsonObject.getString("humidity");
//        map.put("humidity", humidity);
//        //舱内温度 temperature
//        String temperature = jsonObject.getString("temperature");
//        map.put("temperature", temperature);
//        //environment_temperature	环境温度
//        String environmentTemperature = jsonObject.getString("environment_temperature");
//        map.put("environmentTemperature", environmentTemperature);
//        //wind_speed	风速
//        String windSpeed = jsonObject.getString("wind_speed");
//        map.put("windSpeed", windSpeed);
//        //rainfall	降雨量
//        String rainfall = jsonObject.getString("rainfall");
//        map.put("rainfall", rainfall);
//        //drone_in_dock	飞行器是否在舱{"0":"舱外","1":"舱内"}
//        String droneInDock = jsonObject.getString("drone_in_dock");
//        map.put("droneInDock", droneInDock);
//        //cover_state	舱盖状态"0":"关闭","1":"打开","2":"半开","3":"舱盖状态异常"
//        String coverState = jsonObject.getString("cover_state");
//        map.put("coverState", coverState);
//        //flighttask_step_code  机场任务状态"0":"作业准备中","1":"飞行作业中","2":"作业后状态恢复","3":"自定义飞行区更新中","4":"地形障碍物更新中","5":"任务空闲","255":"飞行器异常","256":"未知状态"
//        String flighttaskStepCode = jsonObject.getString("flighttask_step_code");
//        map.put("flighttaskStepCode", flighttaskStepCode);
//        //mode_code	机场状态
//        String modeCode = jsonObject.getString("mode_code");
//        map.put("modeCode", modeCode);
//        //当前位置经度 longitude
//        String airPortLongitude = jsonObject.getString("longitude");
//        map.put("airPortLongitude", airPortLongitude);
//        //当前位置纬度 latitude
//        String airPortLatitude = jsonObject.getString("latitude");
//        map.put("airPortLatitude", airPortLatitude);
//        RedisUtils redisUtils = SpringUtil.getBean(RedisUtils.class);
//        redisUtils.hmset("DJIAirport"+ sn, map, 30);
//    }
//
//
//
//    /**
//     * 获取
//     */
//    private Map<String, String> ossToken() {
//        Map<String, String> ossMap = new HashMap<>();
//        String policy = "{\n" +
//                "    \"Version\": \"1\", \n" +
//                "    \"Statement\": [\n" +
//                "        {\n" +
//                "            \"Action\": [\n" +
//                "                \"oss:PutObject\"\n" +
//                "            ], \n" +
//                "            \"Resource\": [\n" +
//                "                \"acs:oss:*:*:dji-dev/*\" \n" +
//                "            ], \n" +
//                "            \"Effect\": \"Allow\"\n" +
//                "        }\n" +
//                "    ]\n" +
//                "}";
//
//        String roleARN = "acs:ram::1399733914954856:role/ramosstest";
//        String sessionName = "SessionTest";
//        java.util.List<String> args = Arrays.asList();
//        Client client = null;
//        try {
//            client = MqttConsumerCallBack.createClient();
//        } catch (Exception e) {
//            log.info("获取阿里云token失败");
//        }
//        AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest()
//                .setDurationSeconds(3600L)
//                .setPolicy(policy)
//                .setRoleArn(roleARN)
//                .setRoleSessionName(sessionName);
//        try {
//            // 复制代码运行请自行打印 API 的返回值
//            AssumeRoleResponse assumeRoleResponse = client.assumeRoleWithOptions(assumeRoleRequest, new RuntimeOptions());
//            String arn = assumeRoleResponse.getBody().getAssumedRoleUser().getArn();
//            String assumedRoleId = assumeRoleResponse.getBody().getAssumedRoleUser().getAssumedRoleId();
//            String accessKeyId = assumeRoleResponse.getBody().getCredentials().getAccessKeyId();
//            String accessKeySecret = assumeRoleResponse.getBody().getCredentials().getAccessKeySecret();
//            String securityToken = assumeRoleResponse.getBody().getCredentials().getSecurityToken();
//            String expiration = assumeRoleResponse.getBody().getCredentials().getExpiration();
//            log.info(arn);
//            log.info(assumedRoleId);
//            log.info(accessKeyId);
//            log.info(accessKeySecret);
//            log.info(securityToken);
//            log.info(expiration);
//            log.info("a");
//
//            ossMap.put("access_key_id", accessKeyId);
//            ossMap.put("access_key_secret", accessKeySecret);
//            ossMap.put("security_token", securityToken);
//            return ossMap;
//        } catch (TeaException error) {
//            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
//            // 错误 message
//            log.info(error.getMessage());
//            // 诊断地址
//            log.info(error.getData().get("Recommend")+"");
//            com.aliyun.teautil.Common.assertAsString(error.message);
//        } catch (Exception _error) {
//            TeaException error = new TeaException(_error.getMessage(), _error);
//            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
//            // 错误 message
//            log.info(error.getMessage());
//            // 诊断地址
//            log.info(error.getData().get("Recommend")+"");
//            com.aliyun.teautil.Common.assertAsString(error.message);
//        }
//        return ossMap;
//    }
//
//    /**
//     * <b>description</b> :
//     * <p>使用AK&amp;SK初始化账号Client</p>
//     * @return Client
//     *
//     * @throws Exception
//     */
//    public static Client createClient() throws Exception {
//        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
//        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
//        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
//                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
//                .setAccessKeyId("LTAI5tFmaJHU7ywvBH2j12Gp")
//                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
//                .setAccessKeySecret("mX6rS1xYTgZgFAgpOrQHyc6jLXv0AV");
//        // Endpoint 请参考 https://api.aliyun.com/product/Sts
//        config.endpoint = "sts.cn-shanghai.aliyuncs.com";
//        return new Client(config);
//    }

//    }


    /**
     * 获取
     */
    private Map<String, String> ossToken() {
        Map<String, String> ossMap = new HashMap<>();
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:PutObject\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:dji-dev/*\" \n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";

//        String roleARN = "acs:ram::1399733914954856:role/ramosstest";
        String roleARN = "acs:ram::1399733914954856:role/oss-role";
        String sessionName = "SessionTest";
        java.util.List<String> args = Arrays.asList();
        Client client = null;
        try {
            client = MqttConsumerCallBack.createClient();
        } catch (Exception e) {
            log.info("获取阿里云token失败");
        }
        AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest()
                .setDurationSeconds(3600L)
                .setPolicy(policy)
                .setRoleArn(roleARN)
                .setRoleSessionName(sessionName);
        try {
            // 复制代码运行请自行打印 API 的返回值
            AssumeRoleResponse assumeRoleResponse = client.assumeRoleWithOptions(assumeRoleRequest, new RuntimeOptions());
            String arn = assumeRoleResponse.getBody().getAssumedRoleUser().getArn();
            String assumedRoleId = assumeRoleResponse.getBody().getAssumedRoleUser().getAssumedRoleId();
            String accessKeyId = assumeRoleResponse.getBody().getCredentials().getAccessKeyId();
            String accessKeySecret = assumeRoleResponse.getBody().getCredentials().getAccessKeySecret();
            String securityToken = assumeRoleResponse.getBody().getCredentials().getSecurityToken();
            String expiration = assumeRoleResponse.getBody().getCredentials().getExpiration();
            log.info(arn);
            log.info(assumedRoleId);
            log.info(accessKeyId);
            log.info(accessKeySecret);
            log.info(securityToken);
            log.info(expiration);
            log.info("a");

            ossMap.put("access_key_id", accessKeyId);
            ossMap.put("access_key_secret", accessKeySecret);
            ossMap.put("security_token", securityToken);
            return ossMap;
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.info(error.getMessage());
            // 诊断地址
            log.info(error.getData().get("Recommend") + "");
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.info(error.getMessage());
            // 诊断地址
            log.info(error.getData().get("Recommend") + "");
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return ossMap;
    }

    /**
     * <b>description</b> :
     * <p>使用AK&amp;SK初始化账号Client</p>
     *
     * @return Client
     * @throws Exception
     */
    public static Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId("LTAI5tFmaJHU7ywvBH2j12Gp")
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret("mX6rS1xYTgZgFAgpOrQHyc6jLXv0AV");
        // Endpoint 请参考 https://api.aliyun.com/product/Sts
        config.endpoint = "sts.cn-shanghai.aliyuncs.com";
        return new Client(config);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }


    /**
     * flyto 执行结果事件通知
     * @param
     * @param data
     */
//    private void flyToPointProgress(String data, String airPprtSn) {
//        RedisUtils redisUtils = SpringUtils.getBean(RedisUtils.class);
//        DJIUtils djiUtils = SpringUtils.getBean(DJIUtils.class);
//        String string = com.alibaba.fastjson.JSONObject.parseObject(data).getString("status");
//        //查询是否处于飞行控制模式
//        Object o = redisUtils.get(airPprtSn + DJIMethonConstants.DRC_STATUS);
//        if (TakeOffToPointEnum.WAYLINE_PROGRESS.getCode().equals(string)){
//            redisUtils.hset(CommonConstants.FLY_TOPOINT_PROGRESS, airPprtSn, TakeOffToPointEnum.WAYLINE_PROGRESS.getCode(), 5);
//
//            if (Objects.nonNull(o) && o.equals(true)){
//                log.info("指点飞行退出控制模式 is {}", airPprtSn);
////                dJIUtils.drcModeExit(airPprtSn);
//                redisUtils.set(airPprtSn + DJIMethonConstants.DRC_STATUS, false);
//            }
//        }else if (TakeOffToPointEnum.WAYLINE_OK.getCode().equals(string) || TakeOffToPointEnum.WAYLINE_CANCEL.getCode().equals(string) || TakeOffToPointEnum.WAYLINE_FAILED.getCode().equals(string)){
//            redisUtils.hset(CommonConstants.FLY_TOPOINT_PROGRESS, airPprtSn, TakeOffToPointEnum.WAYLINE_OK.getCode(), 2);
//            //不处于
//            if (Objects.nonNull(o) && (Boolean)o.equals(false)){
//                log.info("指点飞行进入控制模式");
//                djiUtils.drcModeEnter(airPprtSn);
//                redisUtils.set(airPprtSn + DJIMethonConstants.DRC_STATUS, true);
//            }
//        }
//    }

    private static String bid = "1";

    private static String tid = "2";

    public String drcModeExit(){
        try {
            MqttConfig providerClient = SpringUtil.getBean(MqttConfig.class);
//            try {
//                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<>();
//                content.put("tid", UUID.randomUUID().toString());
//                content.put("bid", UUID.randomUUID().toString());
//                content.put("timestamp",System.currentTimeMillis());
//                content.put("method", DJIMethonConstants.FLIGHT_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);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            Thread.sleep(4000);




            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<>();
//            tid = UUID.randomUUID().toString();
            content.put("tid",tid );
//            bid = UUID.randomUUID().toString();
            content.put("bid", bid);
            content.put("timestamp", System.currentTimeMillis());
            content.put("method", DJIMethonConstants.DRC_MODE_EXIT);
            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 "发送失败";
        }
    }


    public String drcModeEnter(){
        try {
            MqttConfig providerClient = SpringUtil.getBean(MqttConfig.class);

//            try {
//                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<>();
//                content.put("tid", UUID.randomUUID().toString());
//                content.put("bid", UUID.randomUUID().toString());
//                content.put("timestamp",System.currentTimeMillis());
//                content.put("method", DJIMethonConstants.FLIGHT_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);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            Thread.sleep(4000);


            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<>();
            //负载枚举值 镜头负载
            data.put("hsi_frequency", 1);

            //Broker 连接信息
            Map<String,Object> mqttBroker = new HashMap<>();
            //服务器连接地址
            mqttBroker.put("address", "58.213.148.44:1883");
            //客户端ID
            mqttBroker.put("client_id", "DRC-8UUXN3500A02BE");
            //enable_tls
            mqttBroker.put("enable_tls", false);
            //expire_time 当前时间+3000秒
            mqttBroker.put("expire_time", System.currentTimeMillis()/1000 + 3600);
            //密码
            mqttBroker.put("password", "admin##123");
            //用户名
            mqttBroker.put("username", "admin");
            data.put("mqtt_broker", mqttBroker);
            //设置 OSD 上报频率  {"max":30,"min":1,"unit_name":"赫兹 / Hz"}
            data.put("osd_frequency", 1);

//            tid = UUID.randomUUID().toString();
            content.put("tid", tid);
//            bid = UUID.randomUUID().toString();
            content.put("bid", bid);
            content.put("timestamp",System.currentTimeMillis());
            content.put("method", DJIMethonConstants.DRC_MODE_ENTER);
            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 "发送失败";
        }
    }


    public String flightAuthorityGrab(String airPortSn){
        MqttConfig providerClient = SpringUtil.getBean(MqttConfig.class);
        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 = com.alibaba.fastjson.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){
        MqttConfig providerClient = SpringUtil.getBean(MqttConfig.class);
        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 "发送失败";
        }
    }

}