package com.zksy.visualization.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zksy.common.core.domain.Result;
import com.zksy.visualization.config.IccConfigProperty;
import com.zksy.visualization.domain.request.*;
import com.zksy.visualization.domain.response.RtspUrlResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Administrator
 * @version 1.0
 * @project dh-server-micro
 * @description 视频实时预览
 * @date 2024/12/12 13:32:23
 */
@RestController
@Api(tags = "视频实时预览", description = "视频实时预览")
@RequestMapping("/realTimePreviewVideo")
@Slf4j
public class RealTimePreviewVideoController {
    @Autowired
    private IccConfigProperty iccConfigProperty;
    @Autowired
    private OkHttpClient httpClient;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    /**
     * TODO 视频路径
      * @param
     * @return void
     * @author Administrator
     * @date 2024/12/12 14:43:37
     */
    @ApiOperation(value = "获取视频路径")
    @PostMapping("/getRtspUrl")
    public Result getRtspUrl(RtspUrlRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/admin/API/MTS/Video/StartVideo")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if(success.isBoolean() && success.asBoolean()) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode.isObject()) {
                        RtspUrlResponse intelligentPanelResponse = objectMapper.treeToValue(dataNode, RtspUrlResponse.class);
                        return Result.ok(intelligentPanelResponse);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    JsonNode errMsgNode = rootNode.path("errMsg");
                    String errMsg = errMsgNode.isTextual() ? errMsgNode.asText() : "未知错误";
                    return Result.error(errMsg);
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }
    @ApiOperation(value = "HLS、FLV、RTMP实时预览接口方式")
    @PostMapping("/getHFRUrl")
    public Result getHFRUrl(VideoPlayRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/admin/API/video/stream/realtime")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        return Result.ok(dataNode);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    JsonNode code = rootNode.path("code");
                    if("1001".equals(code.asText())){
                        return Result.error("未查询到视频信息");
                    }else {
                        return Result.error("HLS、FLV、RTMP实时预览失败");
                    }
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "查询普通录像信息列表")
    @PostMapping("/queryOrdinaryList")
    public Result queryOrdinaryList(VideoRecordQueryListRequest request){
        String startTime = DateToTimeStamp(request.getData().getStartTime());
        String endTime = DateToTimeStamp(request.getData().getEndTime());
        request.getData().setStartTime(startTime);
        request.getData().setEndTime(endTime);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/admin/API/SS/Record/QueryRecords")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        JsonNode records = dataNode.path("records");
                        if(records != null){
                            return Result.ok(records);
                        }else{
                            return Result.error("无数据");
                        }
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    return Result.error("查询普通录像信息列表失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "查询报警录像信息列表")
    @PostMapping("/queryWarnList")
    public Result queryWarnList(AlarmInfoRequest request){
        String alarmDate = DateToTimeStamp(request.getData().getAlarmDate());
        request.getData().setAlarmDate(alarmDate);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/admin/API/SS/Record/GetAlarmRecords")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        JsonNode records = dataNode.path("records");
                        if(records != null){
                            return Result.ok(records);
                        }else{
                            return Result.error("无数据");
                        }
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    return Result.error("查询报警录像信息列表失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "rtsp以时间形式回放录像")
    @PostMapping("/getRTSPDateReplay")
    public Result getRTSPDateReplay(VideoRecordDateQueryRequest request){
        /*String startTime = DateToTimeStamp(request.getData().getStartTime());
        String endTime = DateToTimeStamp(request.getData().getEndTime());
        request.getData().setStartTime(startTime);
        request.getData().setEndTime(endTime);*/
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/admin/API/SS/Playback/StartPlaybackByTime")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        return Result.ok(dataNode);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    return Result.error("rtsp以时间形式回放录像失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }
    @ApiOperation(value = "HLS、RTMP录像回放（FLV不支持）")
    @PostMapping("/getHRReplay")
    public Result getHRReplay(VideoRecordHRQueryRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/admin/API/video/stream/record")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        return Result.ok(dataNode);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    JsonNode code = rootNode.path("code");
                    if("2239".equals(code.asText())){
                        return Result.error("未查询到录像");
                    }else {
                        return Result.error("HLS、RTMP录像回放（FLV不支持）失败");
                    }
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }
    @ApiOperation(value = "云台镜头控制",notes = "控制云台镜头的变焦、变倍及光圈大小\n" +
            "命令command=1时，云台会开启动作，不调command=0会一直转动\n" +
            "异步发送操作指令到设备端，需开启动作与停止动作间隔一定时间，保证顺序执行\n" +
            "不推荐多用户同时操作同一个设备，多用户操作以最后一次操作为准")
    @PostMapping("/getOperateCamera")
    public Result getOperateCamera(CameraControlRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/admin/API/DMS/Ptz/OperateCamera")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        return Result.ok(dataNode);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    JsonNode code = rootNode.path("code");
                    if("1001".equals(code.asText())){
                        return Result.error("返回失败");
                    }else {
                        return Result.error("云台镜头控制失败");
                    }
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }
    @ApiOperation(value = "云台镜头控制",notes = "控制云台进行上下左右等八个方向的移动 命令command=1时，云台会开启动作，不调command=0会一直转动\n" +
            "异步发送操作指令到设备端，需开启动作与停止动作间隔一定时间，保证顺序执行\n" +
            "不推荐多用户同时操作同一个设备，多用户操作以最后一次操作为准")
    @PostMapping("/getOperateDirect")
    public Result getOperateDirect(OperateDirectRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/admin/API/DMS/Ptz/OperateDirect")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        return Result.ok(dataNode);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    JsonNode code = rootNode.path("code");
                    if("1001".equals(code.asText())){
                        return Result.error("返回失败");
                    }else {
                        return Result.error("云台方向控制失败");
                    }
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }
    @ApiOperation(value = "云台功能控制",notes = "控制云台的巡航、循迹及灯光等功能 命令command=1时，云台会开启动作，不调command=0会一直转动\n" +
            "异步发送操作指令到设备端，需开启动作与停止动作间隔一定时间，保证顺序执行\n" +
            "不推荐多用户同时操作同一个设备，多用户操作以最后一次操作为准")
    @PostMapping("/getOperateFunction")
    public Result getOperateFunction(OperateDirectRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/admin/API/DMS/Ptz/OperateFunction")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        return Result.ok(dataNode);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    JsonNode code = rootNode.path("code");
                    if("1001".equals(code.asText())){
                        return Result.error("返回失败");
                    }else {
                        return Result.error("云台功能控制失败");
                    }
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }

    public String DateToTimeStamp(String dateTimeString){
        // 定义日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            // 解析字符串为Date对象
            Date date = dateFormat.parse(dateTimeString);
            // 将Date对象转换为时间戳（秒）
            long timestamp = date.getTime() / 1000;
            return String.valueOf(timestamp);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateTimeString;
    }
}
