package com.uavps.framework.udp;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.uavps.common.utils.spring.SpringUtils;
import com.uavps.framework.config.UdpConfig;
import com.uavps.framework.udp.utils.UdpDataUtils;
import com.uavps.system.service.IUavpsAircraftService;
import com.uavps.system.udp.vo.Aircraft;
import com.uavps.system.udp.vo.AircraftFormation;
import com.uavps.system.udp.vo.UdpData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;


/**
 * @Author MBQ
 * @Date: 2025/1/9
 * @Description:
 * @Version: 1.0
 **/
@Component
public class UdpServerService {

    private static final Logger log = LoggerFactory.getLogger(UdpServerService.class);

    private UdpConfig udpConfig = SpringUtils.getBean(UdpConfig.class);


    private IUavpsAircraftService uavpsAircraftService = SpringUtils.getBean(IUavpsAircraftService.class);

    /*public void receive(Session session) {
        try {
            //创建一个服务端对象，注册端口
            DatagramSocket socket = new DatagramSocket(udpConfig.getPort());

            //创建一个数据包对象，用于接收数据，限制64kb
            byte[] data = new byte[1024 * 64];
            DatagramPacket packet = new DatagramPacket(data, data.length);

            String uavData = "";
            boolean exit = false;
            while (true) {
                //使用数据包接收客户端发送的数据
                socket.receive(packet);
                uavData = new String(data, 0, packet.getLength());
                //websocket 退出,关闭upd服务
                if (uavData.length() == 4 && "EXIT".equals(uavData)) {
                    socket.close();
                    break;
                }
                JSONArray dataAry = JSON.parseArray(uavData);
                if (dataAry != null) {
                    UavpsAircraft uavpsAircraft = null;
                    for (int i = 0; i < dataAry.size(); i++) {
                        UdpData udpData = JSON.parseObject(dataAry.getString(i), UdpData.class);
                        uavpsAircraft = new UavpsAircraft();
                        uavpsAircraft.setBizId(udpData.getBizId());
                        uavpsAircraft.setDataTime(BigDecimal.valueOf(udpData.getTime()));
                        uavpsAircraft.setAircraftData(dataAry.getString(i));
                        uavpsAircraft.setCreateBy("python");

                        //入库
                        //uavpsAircraftService.insertUavpsAircraft(uavpsAircraft);

                        //数据发送页面展示
                        session.getBasicRemote().sendText(dataAry.getString(i));
                        Thread.sleep(20);

                        //判断数据是否发送完毕
                        if ("true".equals(udpData.getFinished())) {
                            exit = true;
                            break;
                        }
                    }
                }
                if (exit) {
                    socket.close();
                    break;
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }*/

    public void receive(Session session) {
        try {
            //创建一个服务端对象，注册端口
            DatagramSocket socket = new DatagramSocket(udpConfig.getPort());
            Boolean isFirst = true;
            float initX = 0;
            float initY = 0;
            float level = 0.00001f;
            //创建一个数据包对象，用于接收数据
            byte[] data = new byte[1024];
            DatagramPacket packet = new DatagramPacket(data, data.length);

            String uavData = "";
            int i = 0;
            while (true) {
                //使用数据包接收客户端发送的数据
                socket.receive(packet);
                uavData = new String(data, 0, packet.getLength());
                //websocket 退出,关闭upd服务
                if (uavData.length() == 4 && "EXIT".equals(uavData)) {
                    socket.close();
                    break;
                }
                byte[] remoteData = UdpDataUtils.hexStringToBytes(uavData);
                //byte[] remoteData = packet.getData();
                if (remoteData != null && remoteData.length > 3) {
                    UdpData udpData = UdpDataUtils.parseFrame(remoteData);
                    //System.out.println(UdpDataUtils.bizId);
                    if (udpData != null) {
                        UdpDataUtils.time += 1;
                        udpData.setTime(UdpDataUtils.time);
//                        for (int i = 0; i < udpData.getTargetAircraft().size(); i++) {
//                            List<Aircraft> aircrafts = udpData.getTargetAircraft().get(i).getAircrafts();
//                            for (int j = 0; j < aircrafts.size(); j++) {
//                                Aircraft aircraft = aircrafts.get(j);
//                                if (aircraft.getAircraftNumber().equals("1")) {
//                                    if (UdpDataUtils.time > 100 && UdpDataUtils.time < 200) {
//                                        aircraft.setCoordinateX(aircraft.getCoordinateX() + UdpDataUtils.time);
//                                        aircraft.setCoordinateY(aircraft.getCoordinateY() + 100);
//                                    } else if (UdpDataUtils.time > 200 && UdpDataUtils.time < 300) {
//                                        aircraft.setCoordinateX(aircraft.getCoordinateX() + 200);
//                                        aircraft.setCoordinateY(aircraft.getCoordinateY() + UdpDataUtils.time);
//                                    } else {
//                                        aircraft.setCoordinateX(aircraft.getCoordinateX() + UdpDataUtils.time);
//                                        aircraft.setCoordinateY(aircraft.getCoordinateY() + UdpDataUtils.time);
//                                    }
//                                } else if (aircraft.getAircraftNumber().equals("2")) {
//                                    if (UdpDataUtils.time > 100 && UdpDataUtils.time < 200) {
//                                        aircraft.setCoordinateX(aircraft.getCoordinateX() + UdpDataUtils.time + 50);
//                                        aircraft.setCoordinateY(aircraft.getCoordinateY() + 150);
//                                    } else if (UdpDataUtils.time > 200 && UdpDataUtils.time < 300) {
//                                        aircraft.setCoordinateX(aircraft.getCoordinateX() + 250);
//                                        aircraft.setCoordinateY(aircraft.getCoordinateY() + UdpDataUtils.time + 50);
//                                    } else {
//                                        aircraft.setCoordinateX(aircraft.getCoordinateX() + UdpDataUtils.time + 50);
//                                        aircraft.setCoordinateY(aircraft.getCoordinateY() + UdpDataUtils.time + 50);
//                                    }
//                                }
//                            }
//                        }
                        if(udpData.getTargetAircraft() != null){
                            for (AircraftFormation aircraftFormation : udpData.getTargetAircraft()) {
                                for (Aircraft aircraft : aircraftFormation.getAircrafts()) {
                                    if(isFirst){
                                        initX=aircraft.getCoordinateX() - 500 * level;
                                        initY=aircraft.getCoordinateY() - 500 * level;
                                        isFirst = false;
                                    }
                                    getNewXYAircraftCoordinate(aircraft,initX,initY,level);
                                }
                            }
                        }
                        ObjectMapper mapper = new ObjectMapper();
                        String json = mapper.writeValueAsString(udpData);
                        session.getBasicRemote().sendText(json);
                        //System.out.println(json);
                    }
//                    log.info("loop:"+(i++)+":"+udpData.getTargetAircraftsString());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getNewXYAircraftCoordinate(Aircraft aircraft, float initX, float initY, float level) {
        aircraft.setCoordinateOX(aircraft.getCoordinateX());
        aircraft.setCoordinateOY(aircraft.getCoordinateY());
        aircraft.setCoordinateOZ(aircraft.getCoordinateZ());
        aircraft.setCoordinateX((aircraft.getCoordinateX()-initX)/level);
        aircraft.setCoordinateY((aircraft.getCoordinateY()-initY)/level);
    }
}
