package com.ruoyi.dj.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.dj.mqtt.client.DJICloudMQTTClient;
import com.ruoyi.dj.mqtt.cmd.CmdConstant;
import com.ruoyi.dj.mqtt.common.CommonFieldsVo;
import com.ruoyi.dj.mqtt.dto.VideoInfoChangeVo;
import com.ruoyi.dj.mqtt.dto.VideoInfoQualityVo;
import com.ruoyi.dj.mqtt.dto.liveCameraChangeDto;
import com.ruoyi.dj.mqtt.utils.*;
import com.ruoyi.system.domain.vo.VideoInfoVo;
import com.ruoyi.system.service.IGatewayOperationLogService;
import com.ruoyi.system.service.IVideoInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther 周志雄
 * @date 2024/7/9 9:48
 */
@Slf4j
@RestController
@Api(tags = "直播相关")
@RequestMapping("/dj")
public class LiveController {
    private static final String SERVICES_TOPIC = "thing/product/?/services";

    @Resource
    private DJICloudMQTTClient djiCloudMQTTClient;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private IVideoInfoService videoInfoService;
    @Resource
    private IGatewayOperationLogService gatewayOperationLogService;


    /**
     * 开启直播
     *
     * @param videoInfoVo
     * @return
     */
    @ApiOperation(value = "开启直播")
    @PostMapping("/live/start")
    public AjaxResult startLive(@RequestBody VideoInfoVo videoInfoVo) {
        String topic = SERVICES_TOPIC.replace("?", videoInfoVo.getGateway());
        CommonFieldsVo commonFieldVo = CommonFieldsVo.createCommonFieldVo(CmdConstant.LIVE_START_PUSH, videoInfoVo.getGateway());
        // 把数据进行MD5
        String key = videoInfoVo.getGateway() + "," + videoInfoVo.getSn() + "," + videoInfoVo.getCameraIndex() + "," + videoInfoVo.getVideoIndex();
        String encrypt = AESUtil.encrypt(key);
        // 准备参数
        Map<String, Object> data = new HashMap<>();
        data.put("url_type", 1); // 设置格式为 RTMP
        String rtmpUrl = "rtmp://" + videoInfoVo.getHost() + ":" + videoInfoVo.getRtmpPort() + "/live/" + key.replaceAll(",", "");
        data.put("url", rtmpUrl);
        data.put("video_id", videoInfoVo.getSn() + "/" + videoInfoVo.getCameraIndex() + "/" + videoInfoVo.getVideoIndex());
        data.put("video_quality", videoInfoVo.getDefinition()); // 设置直播质量
        String payload = PayloadUtil.generatePayload(commonFieldVo, data);
        String response = djiCloudMQTTClient.publishMessage(topic, payload, commonFieldVo);
        // 记录操作日志
        GatewayOperationLogUtil.generateLog(videoInfoVo.getGateway(), CmdConstant.LIVE_START_PUSH, payload, response);
        Map<String, Object> resultData = new HashMap<>();
        String webrtcUrl = "http://" + videoInfoVo.getHost() + ":" + videoInfoVo.getRtcPort() + "/rtc/v1/whep/?app=live&stream=" + key.replaceAll(",", "");
        resultData.put("url", webrtcUrl);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将字符串解析为 JSON 对象
            ObjectNode jsonNode = null;
            jsonNode = (ObjectNode) objectMapper.readTree(response);
            JsonNode resultNode = jsonNode.path("data").path("result");
            Integer result = Integer.valueOf(resultNode.asText());
            // 根据 result 值判断是否成功
            if (result == 0 || (result != 0 && result == 513003)) {
                return AjaxResult.success("开启直播成功").put("data", resultData);
            } else {
                return HandleResultUtil.handleResult(response, resultData, "开启直播失败");
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭直播
     */
    @ApiOperation(value = "关闭直播")
    @PostMapping("/live/stop")
    public AjaxResult stopLive(@RequestBody VideoInfoVo videoInfoVo) {
        String topic = SERVICES_TOPIC.replace("?", videoInfoVo.getGateway());
        CommonFieldsVo commonFieldVo = CommonFieldsVo.createCommonFieldVo(CmdConstant.LIVE_STOP_PUSH, videoInfoVo.getGateway());
        // 准备参数
        Map<String, Object> data = new HashMap<>();
        data.put("video_id", videoInfoVo.getSn() + "/" + videoInfoVo.getCameraIndex() + "/" + videoInfoVo.getVideoIndex());
        String payload = PayloadUtil.generatePayload(commonFieldVo, data);
        String response = djiCloudMQTTClient.publishMessage(topic, PayloadUtil.generatePayload(commonFieldVo, data), commonFieldVo);
        // 记录操作日志
        GatewayOperationLogUtil.generateLog(videoInfoVo.getGateway(), CmdConstant.LIVE_STOP_PUSH, payload, response);
        AjaxResult ajaxResult = HandleResultUtil.handleResult(response, null, "关闭直播成功");
        return ajaxResult;
    }

    /**
     * 镜头切换
     */
    @ApiOperation(value = "镜头切换")
    @PostMapping("/live/change")
    public AjaxResult liveLensChange(@RequestBody VideoInfoChangeVo videoInfoChangeVo) {
        String topic = SERVICES_TOPIC.replace("?", videoInfoChangeVo.getGateway());
        CommonFieldsVo commonFieldVo = CommonFieldsVo.createCommonFieldVo(CmdConstant.LIVE_LENS_CHANGE, videoInfoChangeVo.getGateway());
        // 准备参数
        Map<String, Object> data = new HashMap<>();
        data.put("video_id", videoInfoChangeVo.getSn() + "/" + videoInfoChangeVo.getCameraIndex() + "/" + videoInfoChangeVo.getVideoIndex());
        data.put("video_type", videoInfoChangeVo.getVideoType());
        String payload = PayloadUtil.generatePayload(commonFieldVo, data);
        String response = djiCloudMQTTClient.publishMessage(topic, PayloadUtil.generatePayload(commonFieldVo, data), commonFieldVo);
        // 记录操作日志
        GatewayOperationLogUtil.generateLog(videoInfoChangeVo.getGateway(), CmdConstant.LIVE_LENS_CHANGE, payload, response);
        AjaxResult ajaxResult = HandleResultUtil.handleResult(response, null, "镜头切换成功");
        return ajaxResult;
    }

    /**
     * 设置直播质量
     */
    @ApiOperation(value = "设置直播质量")
    @PostMapping("/live/quality")
    public AjaxResult liveSetQuality(@RequestBody VideoInfoQualityVo videoInfoQualityVo) {
        String topic = SERVICES_TOPIC.replace("?", videoInfoQualityVo.getGateway());
        CommonFieldsVo commonFieldVo = CommonFieldsVo.createCommonFieldVo(CmdConstant.LIVE_SET_QUALITY, videoInfoQualityVo.getGateway());
        // 准备参数
        Map<String, Object> data = new HashMap<>();
        data.put("video_id", videoInfoQualityVo.getSn() + "/" + videoInfoQualityVo.getCameraIndex() + "/" + videoInfoQualityVo.getVideoIndex());
        data.put("video_quality", videoInfoQualityVo.getVideoQuality());
        String payload = PayloadUtil.generatePayload(commonFieldVo, data);
        String response = djiCloudMQTTClient.publishMessage(topic, PayloadUtil.generatePayload(commonFieldVo, data), commonFieldVo);
        // 记录操作日志
        GatewayOperationLogUtil.generateLog(videoInfoQualityVo.getGateway(), CmdConstant.LIVE_SET_QUALITY, payload, response);

        String videoQuality = null;
        switch (videoInfoQualityVo.getVideoQuality()) {
            case 0:
                videoQuality = "自适应";
                break;
            case 1:
                videoQuality = "流畅";
                break;
            case 2:
                videoQuality = "标清";
                break;
            case 3:
                videoQuality = "高清";
                break;
            default:
                videoQuality = "超清";
        }
        String message = "已为您切换" + videoQuality + "摄像头";

        AjaxResult ajaxResult = HandleResultUtil.handleResult(response, null, message);
        return ajaxResult;
    }

    /**
     * 直播相机切换
     */
    @ApiOperation(value = "直播相机切换")
    @PostMapping("/live/camera/change")
    public AjaxResult liveCameraChange(@RequestBody liveCameraChangeDto linkedCameraChangeDto) {
        String topic = SERVICES_TOPIC.replace("?", linkedCameraChangeDto.getGateway());
        CommonFieldsVo commonFieldVo = CommonFieldsVo.createCommonFieldVo(CmdConstant.LIVE_CAMERA_CHANGE, linkedCameraChangeDto.getGateway());
        // 准备参数
        Map<String, Object> data = new HashMap<>();
        data.put("video_id", linkedCameraChangeDto.getSn() + "/" + linkedCameraChangeDto.getCameraIndex() + "/" + linkedCameraChangeDto.getVideoIndex());
        data.put("camera_position", linkedCameraChangeDto.getCameraPosition());
        String payload = PayloadUtil.generatePayload(commonFieldVo, data);
        log.info("直播相机切换请求参数：" + payload);
        String response = djiCloudMQTTClient.publishMessage(topic, PayloadUtil.generatePayload(commonFieldVo, data), commonFieldVo);
        // 记录操作日志
        GatewayOperationLogUtil.generateLog(linkedCameraChangeDto.getGateway(), CmdConstant.LIVE_CAMERA_CHANGE, payload, response);
        String value = linkedCameraChangeDto.getCameraPosition() == 0 ? "舱内" : "舱外";
        String msg = "已为您切换" + value + "摄像头";
        AjaxResult ajaxResult = HandleResultUtil.handleResult(response, null, msg);
        return ajaxResult;
    }
}



