package com.yfd.platform.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yfd.platform.config.AlgorithmManufacturerConfig;
import com.yfd.platform.config.HttpServerConfig;
import com.yfd.platform.modules.basedata.domain.LinkageSignal;
import com.yfd.platform.modules.patroltask.service.IAlarmLogService;
import com.yfd.platform.modules.robotapi.service.IStationRobotService;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
public class HttpRESTfulUtils {

    private final static Logger logger = LoggerFactory.getLogger(HttpRESTfulUtils.class);

    private OkHttpClient client;

    @Resource
    private HttpServerConfig Config;
    @Resource
    private RtspToMP4 rtspToMP4;
    @Resource
    private AlgorithmManufacturerConfig algorithmManufacturerConfig;

    public interface RequestCallback {

        void run(JSONObject response);
    }

    private OkHttpClient getClient() {
        if (client == null) {
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
            //todo 暂时写死超时时间 均为5s
            // 设置连接超时时间
            httpClientBuilder.connectTimeout(30, TimeUnit.SECONDS);
            // 设置读取超时时间
            httpClientBuilder.readTimeout(20, TimeUnit.SECONDS);
            // 设置连接池
            httpClientBuilder.connectionPool(new ConnectionPool(16, 5, TimeUnit.MINUTES));
            if (logger.isDebugEnabled()) {
                HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> {
                    logger.debug("http请求参数：" + message);
                });
                logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
                // OkHttp進行添加攔截器loggingInterceptor
                httpClientBuilder.addInterceptor(logging);
            }
            client = httpClientBuilder.build();
        }
        return client;

    }

    public JSONObject sendHeaderHttpPost(String posttype, String ip, String port, String secret, String token,
                                         String api, Map<String, Object> param, RequestCallback callback) {
        OkHttpClient client = getClient();
        String url = String.format("http://%s:%s/%s", ip, port, api);
        JSONObject responseJSON = new JSONObject();
        //-2自定义流媒体 调用错误码
        responseJSON.put("code", -2);
        responseJSON.put("msg", "http请求调用失败！");

        RequestBody body = null;
        if (posttype.equals("json")) {
            body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(param));
        } else {
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("secret", secret);
            if (param != null && param.keySet().size() > 0) {
                for (String key : param.keySet()) {
                    if (param.get(key) != null) {
                        builder.add(key, param.get(key).toString());
                    }
                }
            }
            body = builder.build();
        }
        Request request = new Request.Builder()
                .addHeader("token", token)
                .post(body)
                .url(url)
                .build();
        if (callback == null) {
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        String responseStr = responseBody.string();
                        responseJSON = JSON.parseObject(responseStr);
                    }
                } else {
                    response.close();
                    Objects.requireNonNull(response.body()).close();
                }
            } catch (IOException e) {
                logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                //throw new RuntimeException(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                if (e instanceof SocketTimeoutException) {
                    //读取超时超时异常
                    //logger.error(String.format("读取Http服务器数据失败: %s, %s", url, e.getMessage()));
                    throw new RuntimeException(String.format("读取Http服务器数据失败: %s, %s", url, e.getMessage()));
                }
                if (e instanceof ConnectException) {
                    //判断连接异常，我这里是报Failed to connect to 10.7.5.144
                    logger.error(String.format("连接Http服务器失败: %s, %s", url, e.getMessage()));
                    throw new RuntimeException(String.format("连接Http服务器失败: %s, %s", url, e.getMessage()));
                }

            } catch (Exception e) {
                logger.error(String.format("访问Http服务器失败: %s, %s", url, e.getMessage()));
                throw new RuntimeException(String.format("访问Http服务器失败: %s, %s", url, e.getMessage()));
            }
        } else {
            client.newCall(request).enqueue(new Callback() {

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    if (response.isSuccessful()) {
                        try {
                            String responseStr = Objects.requireNonNull(response.body()).string();
                            callback.run(JSON.parseObject(responseStr));
                        } catch (IOException e) {
                            logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                        }

                    } else {
                        response.close();
                        Objects.requireNonNull(response.body()).close();
                    }
                }

                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    logger.error(String.format("连接Http服务器失败: %s, %s", call.request().toString(), e.getMessage()));

                    if (e instanceof SocketTimeoutException) {
                        //读取超时超时异常
                        logger.error(String.format("读取Http服务器数据失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                    if (e instanceof ConnectException) {
                        //判断连接异常，我这里是报Failed to connect to 10.7.5.144
                        logger.error(String.format("连接Http服务器失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                }
            });
        }

        return responseJSON;
    }

    public JSONObject sendHttpPost(String posttype, String ip, String port, String secret, String api, Map<String,
            Object> param, RequestCallback callback) {
        OkHttpClient client = getClient();
        String url = String.format("http://%s:%s/%s", ip, port, api);
        JSONObject responseJSON = new JSONObject();
        //-2自定义流媒体 调用错误码
        responseJSON.put("code", -2);
        responseJSON.put("msg", "http请求调用失败！");

        RequestBody body = null;
        if (posttype.equals("json")) {
            body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(param));
        } else {
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("secret", secret);
            if (param != null && param.keySet().size() > 0) {
                for (String key : param.keySet()) {
                    if (param.get(key) != null) {
                        builder.add(key, param.get(key).toString());
                    }
                }
            }
            body = builder.build();
        }
        Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        if (callback == null) {
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        String responseStr = responseBody.string();
                        responseJSON = JSON.parseObject(responseStr);
                    }
                } else {
                    response.close();
                    Objects.requireNonNull(response.body()).close();
                }
            } catch (IOException e) {
                logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                //throw new RuntimeException(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                if (e instanceof SocketTimeoutException) {
                    //读取超时超时异常
                    //logger.error(String.format("读取Http服务器数据失败: %s, %s", url, e.getMessage()));
                    throw new RuntimeException(String.format("读取Http服务器数据失败: %s, %s", url, e.getMessage()));
                }
                if (e instanceof ConnectException) {
                    //判断连接异常，我这里是报Failed to connect to 10.7.5.144
                    logger.error(String.format("连接Http服务器失败: %s, %s", url, e.getMessage()));
                    throw new RuntimeException(String.format("连接Http服务器失败: %s, %s", url, e.getMessage()));
                }

            } catch (Exception e) {
                logger.error(String.format("访问Http服务器失败: %s, %s", url, e.getMessage()));
                throw new RuntimeException(String.format("访问Http服务器失败: %s, %s", url, e.getMessage()));
            }
        } else {
            client.newCall(request).enqueue(new Callback() {

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    if (response.isSuccessful()) {
                        try {
                            String responseStr = Objects.requireNonNull(response.body()).string();
                            callback.run(JSON.parseObject(responseStr));
                        } catch (IOException e) {
                            logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                        }

                    } else {
                        response.close();
                        Objects.requireNonNull(response.body()).close();
                    }
                }

                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    logger.error(String.format("连接Http服务器失败: %s, %s", call.request().toString(), e.getMessage()));

                    if (e instanceof SocketTimeoutException) {
                        //读取超时超时异常
                        logger.error(String.format("读取Http服务器数据失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                    if (e instanceof ConnectException) {
                        //判断连接异常，我这里是报Failed to connect to 10.7.5.144
                        logger.error(String.format("连接Http服务器失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                }
            });
        }

        return responseJSON;
    }


    public JSONObject sendHttpUrlPost(String posttype,String url,  String secret, Map<String, Object> param, RequestCallback callback) {
        OkHttpClient client = getClient();
        JSONObject responseJSON = new JSONObject();
        //-2自定义流媒体 调用错误码
        responseJSON.put("code", -2);
        responseJSON.put("msg", "http请求调用失败！");

        RequestBody body = null;
        if (posttype.equals("json")) {
            body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(param));
        } else {
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("secret", secret);
            if (param != null && param.keySet().size() > 0) {
                for (String key : param.keySet()) {
                    if (param.get(key) != null) {
                        builder.add(key, param.get(key).toString());
                    }
                }
            }
            body = builder.build();
        }
        Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        if (callback == null) {
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        String responseStr = responseBody.string();
                        responseJSON = JSON.parseObject(responseStr);
                    }
                } else {
                    response.close();
                    Objects.requireNonNull(response.body()).close();
                }
            } catch (IOException e) {
                logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                //throw new RuntimeException(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                if (e instanceof SocketTimeoutException) {
                    //读取超时超时异常
                    //logger.error(String.format("读取Http服务器数据失败: %s, %s", url, e.getMessage()));
                    throw new RuntimeException(String.format("读取Http服务器数据失败: %s, %s", url, e.getMessage()));
                }
                if (e instanceof ConnectException) {
                    //判断连接异常，我这里是报Failed to connect to 10.7.5.144
                    logger.error(String.format("连接Http服务器失败: %s, %s", url, e.getMessage()));
                    throw new RuntimeException(String.format("连接Http服务器失败: %s, %s", url, e.getMessage()));
                }

            } catch (Exception e) {
                logger.error(String.format("访问Http服务器失败: %s, %s", url, e.getMessage()));
                throw new RuntimeException(String.format("访问Http服务器失败: %s, %s", url, e.getMessage()));
            }
        } else {
            client.newCall(request).enqueue(new Callback() {

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    if (response.isSuccessful()) {
                        try {
                            String responseStr = Objects.requireNonNull(response.body()).string();
                            callback.run(JSON.parseObject(responseStr));
                        } catch (IOException e) {
                            logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                        }

                    } else {
                        response.close();
                        Objects.requireNonNull(response.body()).close();
                    }
                }

                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    logger.error(String.format("连接Http服务器失败: %s, %s", call.request().toString(), e.getMessage()));

                    if (e instanceof SocketTimeoutException) {
                        //读取超时超时异常
                        logger.error(String.format("读取Http服务器数据失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                    if (e instanceof ConnectException) {
                        //判断连接异常，我这里是报Failed to connect to 10.7.5.144
                        logger.error(String.format("连接Http服务器失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                }
            });
        }

        return responseJSON;
    }

    public JSONObject sendHttpPostStr(String ip, String port, String api, Map<String, Object> param, RequestCallback callback) {
        OkHttpClient client = getClient();
        String url = String.format("http://%s:%s/%s", ip, port, api);
        JSONObject responseJSON = new JSONObject();
        //-2自定义流媒体 调用错误码
        responseJSON.put("code", -2);
        responseJSON.put("msg", "http请求调用失败！");
        RequestBody body = null;
        FormBody.Builder builder = new FormBody.Builder();
        if (param != null && param.keySet().size() > 0) {
            for (String key : param.keySet()) {
                if (param.get(key) != null) {
                    builder.add(key, param.get(key).toString());
                }
            }
        }
        body = builder.build();

        Request request = new Request.Builder()
                .post(body)
                .addHeader("Cookie", "Name=admin; Pass=Admin123; Type=Admin")
                .addHeader("Content-Type", "text/plain")
                .url(url)
                .build();
        if (callback == null) {
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        String responseStr = responseBody.string();
                        responseJSON.put("code", 200);
                        responseJSON.put("msg", "成功！");
                        responseJSON.put("data", URLDecoder.decode(responseStr, "utf-8"));
                    }
                } else {
                    response.close();
                    Objects.requireNonNull(response.body()).close();
                }
            } catch (IOException e) {
                logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                //throw new RuntimeException(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                if (e instanceof SocketTimeoutException) {
                    //读取超时超时异常
                    //logger.error(String.format("读取Http服务器数据失败: %s, %s", url, e.getMessage()));
                    throw new RuntimeException(String.format("读取Http服务器数据失败: %s, %s", url, e.getMessage()));
                }
                if (e instanceof ConnectException) {
                    //判断连接异常，我这里是报Failed to connect to 10.7.5.144
                    logger.error(String.format("连接Http服务器失败: %s, %s", url, e.getMessage()));
                    throw new RuntimeException(String.format("连接Http服务器失败: %s, %s", url, e.getMessage()));
                }

            } catch (Exception e) {
                logger.error(String.format("访问Http服务器失败: %s, %s", url, e.getMessage()));
                throw new RuntimeException(String.format("访问Http服务器失败: %s, %s", url, e.getMessage()));
            }
        } else {
            client.newCall(request).enqueue(new Callback() {

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    if (response.isSuccessful()) {
                        try {
                            String responseStr = Objects.requireNonNull(response.body()).string();
                            callback.run(JSON.parseObject(responseStr));
                        } catch (IOException e) {
                            logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                        }

                    } else {
                        response.close();
                        Objects.requireNonNull(response.body()).close();
                    }
                }

                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    logger.error(String.format("连接Http服务器失败: %s, %s", call.request().toString(), e.getMessage()));

                    if (e instanceof SocketTimeoutException) {
                        //读取超时超时异常
                        logger.error(String.format("读取Http服务器数据失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                    if (e instanceof ConnectException) {
                        //判断连接异常，我这里是报Failed to connect to 10.7.5.144
                        logger.error(String.format("连接Http服务器失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                }
            });
        }

        return responseJSON;
    }

    public JSONObject sendHttpGetStr(String ip, String port, String api, RequestCallback callback) {
        OkHttpClient client = getClient();
        String url = String.format("http://%s:%s/%s", ip, port, api);
        JSONObject responseJSON = new JSONObject();
        //-2自定义流媒体 调用错误码
        responseJSON.put("code", -2);
        responseJSON.put("msg", "http请求调用失败！");
        Request request = new Request.Builder()
                .addHeader("Cookie", "Name=admin; Pass=Admin123; Type=Admin")
                .addHeader("Content-Type", "text/plain")
                .url(url)
                .build();
        if (callback == null) {
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        String responseStr = responseBody.string();
                        responseJSON.put("code", 200);
                        responseJSON.put("msg", "成功！");
                        responseJSON.put("data", URLDecoder.decode(responseStr, "utf-8"));
                    }
                } else {
                    response.close();
                    Objects.requireNonNull(response.body()).close();
                }
            } catch (IOException e) {
                logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                //throw new RuntimeException(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                if (e instanceof SocketTimeoutException) {
                    //读取超时超时异常
                    //logger.error(String.format("读取Http服务器数据失败: %s, %s", url, e.getMessage()));
                    throw new RuntimeException(String.format("读取Http服务器数据失败: %s, %s", url, e.getMessage()));
                }
                if (e instanceof ConnectException) {
                    //判断连接异常，我这里是报Failed to connect to 10.7.5.144
                    logger.error(String.format("连接Http服务器失败: %s, %s", url, e.getMessage()));
                    throw new RuntimeException(String.format("连接Http服务器失败: %s, %s", url, e.getMessage()));
                }

            } catch (Exception e) {
                logger.error(String.format("访问Http服务器失败: %s, %s", url, e.getMessage()));
                throw new RuntimeException(String.format("访问Http服务器失败: %s, %s", url, e.getMessage()));
            }
        } else {
            client.newCall(request).enqueue(new Callback() {

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    if (response.isSuccessful()) {
                        try {
                            String responseStr = Objects.requireNonNull(response.body()).string();
                            callback.run(JSON.parseObject(responseStr));
                        } catch (IOException e) {
                            logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                        }

                    } else {
                        response.close();
                        Objects.requireNonNull(response.body()).close();
                    }
                }

                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    logger.error(String.format("连接Http服务器失败: %s, %s", call.request().toString(), e.getMessage()));

                    if (e instanceof SocketTimeoutException) {
                        //读取超时超时异常
                        logger.error(String.format("读取Http服务器数据失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                    if (e instanceof ConnectException) {
                        //判断连接异常，我这里是报Failed to connect to 10.7.5.144
                        logger.error(String.format("连接Http服务器失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                }
            });
        }

        return responseJSON;
    }

    public void sendGetForImg(String ip, String port, String secret, String api, Map<String, Object> params,
                              String targetPath, String fileName) {
        String url = String.format("http://%s:%s/%s", ip, port, api);
        logger.debug(url);
        HttpUrl parseUrl = HttpUrl.parse(url);
        if (parseUrl == null) {
            return;
        }
        HttpUrl.Builder httpBuilder = parseUrl.newBuilder();

        httpBuilder.addQueryParameter("secret", secret);
        if (params != null) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                httpBuilder.addQueryParameter(param.getKey(), param.getValue().toString());
            }
        }
        Request request = new Request.Builder()
                .url(httpBuilder.build())
                .build();
        logger.info(request.toString());
        try {
            OkHttpClient client = getClient();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                if (targetPath != null) {
                    File snapFolder = new File(targetPath);
                    if (!snapFolder.exists()) {
                        if (!snapFolder.mkdirs()) {
                            logger.warn("{}路径创建失败", snapFolder.getAbsolutePath());
                        }

                    }
                    File snapFile = new File(targetPath + File.separator + fileName);
                    FileOutputStream outStream = new FileOutputStream(snapFile);

                    outStream.write(Objects.requireNonNull(response.body()).bytes());
                    outStream.flush();
                    outStream.close();
                } else {
                    logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
                }
                Objects.requireNonNull(response.body()).close();
            } else {
                logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
            }
            response.close();
        } catch (ConnectException e) {
            logger.error(String.format("连接服务器失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
        } catch (IOException e) {
            logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
        }
    }

    //调用摄像头预置位
    public JSONObject callDevicePos(String devicecode, String channelcode, String poscode, RequestCallback callback) {
        String api = String.format("api/ptz/front_end_command/%s/%s", devicecode, channelcode);
        if (StrUtil.isNotEmpty(Config.getMonitorAppname())) {
            api = String.format("%s/api/ptz/front_end_command/%s/%s", Config.getMonitorAppname(), devicecode, channelcode);
        }
        logger.info(api);
        Map<String, Object> param = new HashMap<>();
        param.put("cmdCode", "130");
        param.put("parameter1", "0");
        param.put("parameter2", poscode);
        param.put("combindCode2", "0");
        return sendHttpPost("form", Config.getMonitorIp(), Config.getMonitorPort(), "", api, param, null);
    }

    //获取摄像头监控视频截图
    public synchronized String getMonitorVideoSnap(String ffmpegpath, String url, String filename) {
        //rtsp://admin:123456@192.168.1.60:554/stream1  可更换到直接拉取摄像机视频流（脱离流媒体服务器的限制）
        try {
            String imgPath = Config.getSnapFilePath() + filename;
            VideoToImageUtil.getVideoPicture(ffmpegpath, url, imgPath);
        } catch (Exception e) {
            throw new RuntimeException("获取摄像头截图失败");
        }
        return filename;
    }

    //获取摄像头监控视频截图
    public String getMonitorAudioSnap(String ffmpegpath, String url, String filename) {
        //rtsp://admin:123456@192.168.1.60:554/stream1  可更换到直接拉取摄像机视频流（脱离流媒体服务器的限制）
        try {
            String audioPath = Config.getSnapFilePath() + filename;
            VideoToImageUtil.saveCaptureAudioFile(ffmpegpath, url, audioPath);
        } catch (Exception e) {
            throw new RuntimeException("获取音频文件失败");
        }
        return filename;
    }

    // 截取10秒钟视频
    public String getMonitorVideo(String ffmpegpath, String url, String filename, String linkageType,
                                  String videoStream) {
        String videoPath = Config.getSnapFilePath() + filename;
        if ("遥控".equals(linkageType)) {
            String dir = StrUtil.subBefore(videoPath, "/", true);
            logger.info(dir);
            FileUtil.mkdir(dir);
            rtspToMP4.StartRecord(videoStream, ffmpegpath, url, videoPath.replace("\\", "/"));
        }
        if ("遥信".equals(linkageType)) {
            rtspToMP4.stopRecord(videoStream);
        }
        return filename;
    }

    //调用智能分析主机图像算法识别
    public JSONObject callPicAnalyse(String requestId, String objectId, String typeList, String customParams, String filename) throws Exception {
        String api = "picAnalyse";
        Map<String, Object> param = new HashMap<>();
        param.put("requestHostIp", Config.getPatrolIp()); //巡视主机IP
        param.put("requestHostPort", Config.getPatrolPort());//巡视主机端口
        param.put("requestHostAppname", Config.getPatrolAppname());//巡视主机应用名称
        param.put("requestId", requestId);//巡视结果记录ID
        JSONArray jsonArray = new JSONArray();
        cn.hutool.json.JSONObject jsonObject2 = JSONUtil.parseObj(customParams);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("objectId", objectId);
        jsonObject.put("typeList", JSONUtil.parseArray(typeList));
        jsonObject.put("customParams", jsonObject2);
        if (StrUtil.isNotBlank(jsonObject2.getStr("imageNormalUrlPath"))) {
            jsonObject.put("imageNormalPath", jsonObject2.getStr("imageNormalUrlPath"));
        } else {
            jsonObject.put("imageNormalPath", "");
        }
        JSONArray imageUrlArray = new JSONArray();
        String methodname = "snapfile";
        if (typeList.indexOf("sound") > 0) {
            methodname = "playAudioFile";
        }
        //        if ("3".equals(Config.getFilefromtype())) {
//            imageurl = filename;
//        } else {
//            imageurl = String.format("http://%s:%s/%s?filename=%s", Config.getPatrolIp(),
//                    Config.getPatrolPort(), methodname, filename);
//            if (StrUtil.isNotEmpty(Config.getPatrolAppname())) {
//                imageurl = String.format("http://%s:%s/%s/%s?filename=%s", Config.getPatrolIp(),
//                        Config.getPatrolPort(), Config.getPatrolAppname(), methodname, filename);
//            }
//        }

        imageUrlArray.add(filename);
        jsonObject.put("imagePathList", imageUrlArray);
        jsonArray.add(jsonObject);
        param.put("objectList", jsonArray);
        logger.info(JSON.toJSONString(jsonArray));
        logger.info("===================调用分析1===============");
        try {
            String analyseIp = Config.getAnalyseIp();
            String analysePort = Config.getAnalysePort11();
            List<Map<String, String>> manufacturerList = algorithmManufacturerConfig.getManufacturer();
            for (Map<String, String> manufacturer : manufacturerList) {
                String taskName = jsonObject2.getStr("taskName");
                if (StrUtil.isBlank(taskName)) {
                    continue;
                }
                String name = manufacturer.get("name");
                if (taskName.contains(name)) {
                    analyseIp = manufacturer.get("ip");
                    analysePort = manufacturer.get("port");
                    jsonObject2.remove("taskName");
                    break;
                }
            }
            cn.hutool.json.JSONObject jsonObject1 = JSONUtil.parseObj(param);
            logger.info("===================调用分析===============" + jsonObject1.toString());
            return sendHttpPost("json", analyseIp, analysePort, "", api, param, null);
        } catch (Exception e) {
            logger.error(e.getMessage());;
            logger.error("===================调用分析出错===============");
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("code", "-2");
            return jsonObject1;
        }
    }

    //调用智能分析主机图像算法识别
    public JSONObject callPicAnalyse(String requestId,String objectId,String typeList,String customParams,String filename,String manId) throws Exception {
        String api = "picAnalyse";
        Map<String, Object> param = new HashMap<>();
        param.put("requestHostIp", Config.getPatrolIp()); //巡视主机IP
        param.put("requestHostPort", Config.getPatrolPort());//巡视主机端口
        param.put("requestHostAppname", Config.getPatrolAppname());//巡视主机应用名称
        param.put("requestId", requestId);//巡视结果记录ID
        JSONArray jsonArray = new JSONArray();
        cn.hutool.json.JSONObject jsonObject2 = JSONUtil.parseObj(customParams);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("objectId", objectId);
        jsonObject.put("typeList", JSONUtil.parseArray(typeList));
        jsonObject.put("customParams", jsonObject2);
        if (StrUtil.isNotBlank(jsonObject2.getStr("imageNormalUrlPath"))) {
            jsonObject.put("imageNormalPath", jsonObject2.getStr("imageNormalUrlPath"));
        } else {
            jsonObject.put("imageNormalPath", "");
        }
        JSONArray imageUrlArray = new JSONArray();
        String methodname = "snapfile";
        if (typeList.indexOf("sound") > 0) {
            methodname = "playAudioFile";
        }
        //        if ("3".equals(Config.getFilefromtype())) {
        //            imageurl = filename;
        //        } else {
        //            imageurl = String.format("http://%s:%s/%s?filename=%s", Config.getPatrolIp(),
        //                    Config.getPatrolPort(), methodname, filename);
        //            if (StrUtil.isNotEmpty(Config.getPatrolAppname())) {
        //                imageurl = String.format("http://%s:%s/%s/%s?filename=%s", Config.getPatrolIp(),
        //                        Config.getPatrolPort(), Config.getPatrolAppname(), methodname, filename);
        //            }
        //        }

        imageUrlArray.add(filename);
        jsonObject.put("imagePathList", imageUrlArray);
        jsonArray.add(jsonObject);
        param.put("objectList", jsonArray);
        logger.info(JSON.toJSONString(jsonArray));
        try {
            String analyseIp = Config.getAnalyseIp();
            String analysePort = Config.getAnalysePort11();
            List<Map<String, String>> manufacturerList = algorithmManufacturerConfig.getManufacturer();
            for (Map<String, String> manufacturer : manufacturerList) {
                String taskName = jsonObject2.getStr("taskName");
                if (StrUtil.isBlank(taskName)) {
                    continue;
                }
                String name = manufacturer.get("name");
                if (taskName.contains(name)) {
                    analyseIp = manufacturer.get("ip");
                    analysePort = manufacturer.get("port");
                    jsonObject2.remove("taskName");
                    break;
                }
            }
            cn.hutool.json.JSONObject jsonObject1 = JSONUtil.parseObj(param);
            logger.info("===================调用分析===============" + jsonObject1.toString());
            return sendHttpPost("json", analyseIp, analysePort, "", api, param, null);
        } catch (Exception e) {
            logger.error(e.getMessage());;
            logger.error("===================调用分析出错===============");
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("code", "-2");
            return jsonObject1;
        }
    }

    public JSONObject callPicAnalyse(String requestId, String objectId, String resImage, String deviceName) throws Exception {
        String value = "";
        String conf = "0.9";
        String type = "";
        String pos = "";
        String desc = "";
        Random random = new Random();
        if ("W109".equals(deviceName)) {
            // 生成1到3之间的随机数（包括1和3）
            int randomNum = random.nextInt(3) + 1;
            type = "meter";
            value = "30." + 1;
            desc = "表计读取";
        } else if ("W103".equals(deviceName)) {
            // 生成1到3之间的随机数（包括1和3）
            int randomNum = random.nextInt(3) + 1;
            type = "meter";
            value = "25." + 2;
            desc = "表计读取";
        } else if ("W105".equals(deviceName)) {
            type = "fhz_h";
            value = "1";
            desc = "分合闸_合";
        } else if ("W108".equals(deviceName)) {
            // 生成1到3之间的随机数（包括1和3）
            int randomNum = random.nextInt(3) + 1;
            type = "meter";
            value = "31." + 3;
            desc = "表计读取";
        } else if ("W102".equals(deviceName)) {
            // 生成1到3之间的随机数（包括1和3）
            int randomNum = random.nextInt(3) + 1;
            type = "meter";
            value = "30." + 3;
            desc = "表计读取";
        } else if ("W110".equals(deviceName)) {
            // 生成1到3之间的随机数（包括1和3）
            int randomNum = random.nextInt(3) + 1;
            type = "meter";
            value = "31." + 9;
            desc = "表计读取";
        }
        Map<String, Object> map = new HashMap<>();
        map.put("requestId", requestId);
        JSONArray resultList = new JSONArray();
        JSONObject resultObject = new JSONObject();
        resultObject.put("objectId", objectId);
        JSONArray results = new JSONArray();
        JSONObject result = new JSONObject();
        result.put("type", type);
        result.put("value", value);
        result.put("code", "2000");
        result.put("resImagePath", resImage);
        result.put("pos", new ArrayList<>());
        result.put("conf", conf);
        result.put("desc", desc);
        results.add(result);
        resultObject.put("results", results);
        resultList.add(resultObject);
        map.put("resultList", resultList);
        return sendHttpPost("json", "192.168.1.7", "8082", "", "picAnalyseRetNotify", map, null);
    }

    //调用静默监视任务（暂不使用）
    public JSONObject callSilentMonitor(String patroldevice_id, String rtspurl, String monitortype,
                                        String customParams) throws Exception {
        String api = "/silentMonitor/start";
        Map<String, Object> param = new HashMap<>();
        param.put("requestHostIp", Config.getPatrolIp()); //巡视主机IP
        param.put("requestHostPort", Config.getPatrolPort());//巡视主机端口
        param.put("requestHostAppname", Config.getPatrolAppname());//巡视主机应用名称
        param.put("patroldeviceId", patroldevice_id);//摄像机ID
        param.put("rtspUrl", rtspurl);//视频流地址
        param.put("monitorType", monitortype);//监控类型
        param.put("customParams", customParams);//定制参数
        try {
            return sendHttpPost("json", Config.getAnalyseIp(), Config.getAnalysePort12(), "", api, param, null);
        } catch (Exception e) {
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("code", "-2");
            return jsonObject1;
        }
    }

    //停止静默监视任务（暂不使用）
    public JSONObject stopSilentMonitor(String monitor_id) throws Exception {
        String api = "/silentMonitor/stop/" + monitor_id;
        try {
            return sendHttpPost("json", Config.getAnalyseIp(), Config.getAnalysePort12(), "", api, null, null);
        } catch (Exception e) {
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("code", "-2");
            return jsonObject1;
        }
    }
}
