package com.yfd.platform.modules.robotapi.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yfd.platform.annotation.Log;
import com.yfd.platform.component.WebSocketServer;
import com.yfd.platform.component.nettyclient.BootNettyClientChannel;
import com.yfd.platform.component.nettyclient.BootNettyClientChannelCache;
import com.yfd.platform.component.nettyclient.HeartBeatTask;
import com.yfd.platform.component.nettyserver.NettyServer;
import com.yfd.platform.component.nettyudpclient.NettyUdpClient;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.modules.robotapi.service.IStationRobotService;
import com.yfd.platform.utils.FileUtil;
import com.yfd.platform.utils.FtpClient;
import com.yfd.platform.utils.HttpRESTfulUtils;
import io.netty.channel.Channel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.awt.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/stationnode")
@Api(tags = "与边缘节点TCP通信")
public class StationRobotController {

    @Resource
    private IStationRobotService staionNodeService;
    @Resource
    private HeartBeatTask heartBeatTask;
    @Resource
    private FtpClient ftpClient;
    @Resource
    private HttpRESTfulUtils httpRESTfulUtils;

    double x = 0;
    double y = 0;
    double z = 10.5;
    double a = -1.57;
    int type = 0;

    @PostMapping("/sendRobotCommand")
    @ApiOperation("发送机器人控制指令")
    public ResponseResult sendRobotCommand(String jsonStr) {
        staionNodeService.sendRobotCommand(jsonStr);
        return ResponseResult.success();
    }

    @PostMapping("/sendRobotModel")
    @ApiOperation("发送机器人模型同步")
    public ResponseResult sendRobotModel(String robotId) {
        staionNodeService.sendRobotModel(robotId);
        return ResponseResult.success();
    }


    @PostMapping("/testCreateCimfile")
    @ApiOperation("测试生成cimfile")
    public boolean testCreateCimfile() throws Exception {
        long eventtime = DateUtil.parse("2023-07-21 12:23:15.321", "yyyy-MM-dd HH:mm:ss.SSS").getTime();
        staionNodeService.createVideocfmresult("0001", "1-" + eventtime, "1");
        return true;
    }

    @Log(module = "巡视任务", value = "上报上级系统")
    @PostMapping("/reportTaskById")
    @ApiOperation("上报上级系统")
    public ResponseResult reportParentById(String ids, String type) throws IOException {
        staionNodeService.reportParentById(ids, type);
        return ResponseResult.success();
    }

    @PostMapping("/testSendLinkComand")
    @ApiOperation("发送一键顺控任务")
    public ResponseResult testSendLinkComand(String ip, String no, String index, String port) throws Exception {
        NettyUdpClient.testSendLinkComand(ip, no, index, port);
        return ResponseResult.success();
    }

    @PostMapping("/testSendLinkComand1")
    @ApiOperation("发送智能联动任务")
    public ResponseResult testSendLinkComand1() throws Exception {
        NettyUdpClient.testSendLinkComand1();
        return ResponseResult.success();
    }

    @PostMapping("/markImageRectangle")
    @ApiOperation("画框（支持多个）")
    public ResponseResult markImageRectangle(String originfilename, String jsonStr, String markedfilename) {
        FileUtil.MarkImageRectangle(originfilename, jsonStr, markedfilename);
        return ResponseResult.success();
    }

    @PostMapping("/addWaterMark")
    @ApiOperation("画水印")
    public ResponseResult addWaterMark(String originfilename, String alertinfo, String markedfilename, int pos_x,
                                       int pos_y) {
        Color color2 = new Color(226, 7, 24);
        Font font = new Font("微软雅黑", Font.PLAIN, 40);
        FileUtil.addWaterMark(originfilename, markedfilename, alertinfo, pos_x, pos_y, color2, font);
        return ResponseResult.success();
    }

    @PostMapping("/sendRegisterToSuper")
    @ApiOperation("发送注册信息到上级系统")
    public ResponseResult sendRegisterToSuper() {
//        staionNodeService.sendRegisterToSuper();
        return ResponseResult.success();
    }

    @PostMapping("/stopSendHeartBeat")
    @ApiOperation("停止上级系统心跳发送")
    public ResponseResult stopSendHeartBeat(String code) throws InterruptedException {
        heartBeatTask.stop("HeartBeatTask");
        BootNettyClientChannel bootNettyClientChannel = BootNettyClientChannelCache.channelMapCache.get(code);
        if(bootNettyClientChannel!=null){
            bootNettyClientChannel.getChannel().close();
            BootNettyClientChannelCache.channelMapCache.remove(code);
        }
        //        bootNettyClientChannel.getChannel().closeFuture()

        return ResponseResult.success();
    }

    @PostMapping("/sendFile")
    @ApiOperation("上送文件")
    public ResponseResult sendFile(String ip, String port, String username, String password, String filePath,
                                   String roPath) throws KeyManagementException, NoSuchAlgorithmException {
        ftpClient.uploadFile(ip, port, username, password, filePath, roPath);
        return ResponseResult.success();
    }

    @PostMapping("/monitorVideoSnap")
    @ApiOperation("使用ffmpeg截图")
    public ResponseResult monitorVideoSnap(String url,String count) {
        java.util.List<Map<String, String>> mapList = new ArrayList<>();
        int size = Integer.parseInt(count);
        for (int i = 0; i < size; i++) {
            Map<String, String> map = new HashMap<>();
            map.put("rtsp", url);
            map.put("filename", "test" + i+".jpg");
            mapList.add(map);
        }
        ExecutorService executorService = Executors.newFixedThreadPool(size);
        for (Map<String, String> map : mapList) {
            executorService.submit(() -> {
                //                httpRESTfulUtils.getMonitorVideoSnap("E:\\ffmpeg\\bin\\", map.get("rtsp"), map.get
                //                ("filename"));
            });
        }
        return ResponseResult.success();
    }

    @PostMapping("/sendCoordinatePixel")
    @ApiOperation("回到原点")
    public ResponseResult sendCoordinatePixel() {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        x = 0;
        y = 10.5;
        z = 0;
        a = -1.57;
        type = 0;
        jsonObject.putOpt("patroldevice_code", "34020000002010000001");
        jsonObject.putOpt("patroldevice_name", "43020000001180003001");
        jsonObject.putOpt("coordinate_geography", "115.70374298095703,34.30839920043945");
        jsonObject.putOpt("time", "2024-11-08 09:11:13");
        String coordinate_pixel = x + "," + y + "," + z + "," + a;
        jsonObject.putOpt("coordinate_pixel", coordinate_pixel);
        jsonArray.add(jsonObject);
        WebSocketServer.sendInfo("robot_status_data", jsonArray.toString());
        new Thread(() -> {
            try {
                while (type >= 0) {
                    Thread.sleep(1000);
                    if (type == 0) {
                        continue;
                    }
                    if (type == 5) {
                        break;
                    }
                    switch (type) {
                        case 1:
                            y += 1;
                            break;
                        case 2:
                            y -= 1;
                            break;
                        case 3:
                            z -= 1;
                            a=0;
                            break;
                        case 4:
                            a=3.14;
                            z += 1;
                            break;
                        case 6:
                            x += 0.15;
                            break;
                        case 8:
                            x += 1;
                            z += 1;
                            break;
                        default:
                            z += 0.15;
                            break;
                    }

                    String pixel = x + "," + y + "," + z + "," + a;
                    JSONArray jsonArray1 = new JSONArray();
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.putOpt("patroldevice_code", "34020000002010000001");
                    jsonObject1.putOpt("patroldevice_name", "43020000001180003001");
                    jsonObject1.putOpt("coordinate_geography", "115.70374298095703,34.30839920043945");
                    jsonObject1.putOpt("time", "2024-11-08 09:11:13");
                    jsonObject1.putOpt("coordinate_pixel", pixel);
                    jsonArray1.add(jsonObject1);
                    WebSocketServer.sendInfo("robot_status_data", jsonArray1.toString());
                }
            } catch (Exception e) {
                log.error(e.getMessage());;
            }
        }).start();
        return ResponseResult.success();
    }

    @PostMapping("/setType")
    @ApiOperation("设置方向")
    public ResponseResult setType(String typeStr) {
        type = NumberUtil.parseInt(typeStr);
        return ResponseResult.success();
    }
}
