/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.smartapplication.vcdevice.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.smartapplication.vcdevice.beans.VideoCloudPageInfo;
import org.springblade.smartapplication.vcdevice.beans.VideoCloudResult;
import org.springblade.smartapplication.vcdevice.conf.VideoCloudConfig;
import org.springblade.smartapplication.vcdevice.conf.ZlmConfig;
import org.springblade.smartapplication.vcdevice.entity.VideoCloudAccount;
import org.springblade.smartapplication.vcdevice.entity.VideoCloudDevice;
import org.springblade.smartapplication.vcdevice.service.IVideoCloudAccountService;
import org.springblade.smartapplication.vcdevice.util.VideoCloudUtil;
import org.springblade.smartapplication.vcdevice.vo.VideoCloudDeviceVO;
import org.springblade.smartapplication.vcdevice.mapper.VideoCloudDeviceMapper;
import org.springblade.smartapplication.vcdevice.service.IVideoCloudDeviceService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2020-11-12
 */
@Service
@Slf4j
public class VideoCloudDeviceServiceImpl extends BaseServiceImpl<VideoCloudDeviceMapper, VideoCloudDevice> implements IVideoCloudDeviceService {

	@Autowired
	private IVideoCloudAccountService videoCloudAccountService;
	@Autowired
	private VideoCloudConfig videoCloudConfig;
	@Autowired
	private ZlmConfig zlmConfig;

	@Override
	public IPage<VideoCloudDeviceVO> selectVideoCloudDevicePage(IPage<VideoCloudDeviceVO> page, VideoCloudDeviceVO videoCloudDevice) {
		return page.setRecords(baseMapper.selectVideoCloudDevicePage(page, videoCloudDevice));
	}

	@Override
	public List<VideoCloudDevice> likeByResidentialName(String residentialName) {
		return baseMapper.likeByResidentialName(residentialName);
	}

	@Override
	public List<String> getAllVCDeviceAccountName() {
		return baseMapper.getAllVCDeviceAccountName();
	}

	@Override
	public VideoCloudDevice getByOldId(String oldId) {
		QueryWrapper<VideoCloudDevice> wrapper = new QueryWrapper<>();
		wrapper.eq("old_id", oldId);
		return this.baseMapper.selectOne(wrapper);
	}

	@Override
	public R syncByAccount(String accountName) {
		VideoCloudAccount videoCloudAccount = videoCloudAccountService.getOne(new QueryWrapper<>(new VideoCloudAccount()).lambda().eq(VideoCloudAccount::getAccountName, accountName));
		Map<String, Object> map = VideoCloudUtil.getSysParams(videoCloudAccount.getAppKey(), videoCloudConfig.getFormat(), "device/list", videoCloudConfig.getSignMethod(), videoCloudConfig.getV(), videoCloudAccount.getToken());
		map.put("resultType", "0");
		map.put("numPerPage", 200 + "");
		String sign = VideoCloudUtil.getSign(map, videoCloudConfig.getSecret());
		map.put("sign", sign);
		String urlParamsLink = VideoCloudUtil.getUrlParamsLink(map, "&");
		String url = videoCloudConfig.getServerIp() + ":" + videoCloudConfig.getServerPort() + "/api/v2/device/list"  + "?" + urlParamsLink;
		log.info("=================视频云设备列表同步请求数据【" + videoCloudAccount.getAccountName() + "】=====================");
		log.info(url);
		String response = HttpUtil.post(url, new String());
		log.info("=================视频云设备列表同步响应数据【" + videoCloudAccount.getAccountName() + "】=====================");
		log.info(response);
		JSONObject responseObj = JSON.parseObject(response);
		if(responseObj.getString("returnCode").equals("1")){
			JSONObject pageInfoObj = responseObj.getJSONObject("pageInfo");
			JSONArray videoCloudDeviceArray = pageInfoObj.getJSONArray("list");
			if(videoCloudDeviceArray == null || videoCloudDeviceArray.size() <= 0){
				return R.success("无设备同步返回");
			}else{
				List<VideoCloudDevice> targetList = new ArrayList<>();
				for(int i = 0; i < videoCloudDeviceArray.size(); i++){
					JSONObject index = videoCloudDeviceArray.getJSONObject(i);
					VideoCloudDevice source = JSONObject.toJavaObject(index, VideoCloudDevice.class);
					LambdaQueryWrapper<VideoCloudDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
					lambdaQueryWrapper.eq(VideoCloudDevice::getDeviceNum, source.getDeviceNum());
					VideoCloudDevice target = this.getOne(lambdaQueryWrapper);
					if(target == null){
						target = new VideoCloudDevice();
					}else{
						source.setId(target.getId());
						//经纬度只保存有值的时候
						if(StringUtil.isBlank(source.getLatitude())){
							source.setLatitude(target.getLatitude());
						}
						if(StringUtil.isBlank(source.getLongitude())){
							source.setLongitude(target.getLongitude());
						}
					}
					BeanUtil.copyProperties(source, target);
					target.setAccountName(accountName);
					targetList.add(target);
				}
				boolean saveOrUpdateBatch = this.saveOrUpdateBatch(targetList);
				if(saveOrUpdateBatch){
					return R.success("同步设备成功");
				}else{
					return R.fail( "同步设备成功，但保存失败");
				}
			}
		}else{
			if(responseObj.getString("subCode").equals("-2")){ //未登录或者token过期了
				R login = this.videoCloudAccountService.login(accountName);
				if(login.isSuccess()){
					return R.fail("获取设备信息失败，请重新点击获取");
				}else{
					return login;
				}
			}
			return R.fail(responseObj.getString("msg") + ":" + responseObj.getString("subMsg"));
		}
	}

	@Override
	public List<VideoCloudDevice> listByAccountName(String accountName) {
		LambdaQueryWrapper<VideoCloudDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(VideoCloudDevice::getAccountName, accountName);
		return this.baseMapper.selectList(lambdaQueryWrapper);
	}

	@Override
	public R syncByDevice(String accountName, String deviceNum) {
		VideoCloudAccount videoCloudAccount = videoCloudAccountService.getOne(new QueryWrapper<>(new VideoCloudAccount()).lambda().eq(VideoCloudAccount::getAccountName, accountName));
		Map<String, Object> map = VideoCloudUtil.getSysParams(videoCloudAccount.getAppKey(), videoCloudConfig.getFormat(), "device/list", videoCloudConfig.getSignMethod(), videoCloudConfig.getV(), videoCloudAccount.getToken());
		map.put("deviceNum", deviceNum);
		String sign = VideoCloudUtil.getSign(map, videoCloudConfig.getSecret());
		map.put("sign", sign);
		String urlParamsLink = VideoCloudUtil.getUrlParamsLink(map, "&");
		String url = videoCloudConfig.getServerIp() + ":" + videoCloudConfig.getServerPort() + "/api/v2/device/list"  + "?" + urlParamsLink;
		log.info("=================视频云设备同步请求数据【" + videoCloudAccount.getAccountName() + "】=====================");
		log.info(url);
		String response = HttpRequest.post(url).header(Header.CONTENT_TYPE, "application/json").execute().body();
		log.info("=================视频云设备同步响应数据【" + videoCloudAccount.getAccountName() + "】=====================");
		log.info(response);
		JSONObject responseObj = JSON.parseObject(response);
		if(responseObj.getString("returnCode").equals("1")){
			JSONObject pageInfoObj = responseObj.getJSONObject("pageInfo");
			JSONArray videoCloudDeviceArray = pageInfoObj.getJSONArray("list");
			if(videoCloudDeviceArray == null || videoCloudDeviceArray.size() <= 0){
				return R.success("无设备同步返回");
			}else{
				JSONObject index = videoCloudDeviceArray.getJSONObject(0);
				VideoCloudDevice source = JSONObject.toJavaObject(index, VideoCloudDevice.class);
				LambdaQueryWrapper<VideoCloudDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
				lambdaQueryWrapper.eq(VideoCloudDevice::getDeviceNum, source.getDeviceNum());
				VideoCloudDevice target = this.getOne(lambdaQueryWrapper);
				if(target == null){
					target = new VideoCloudDevice();
					target.setAccountName(accountName);
				}else{
					source.setId(target.getId());
					//经纬度只保存有值的时候
					if(StringUtil.isBlank(source.getLatitude())){
						source.setLatitude(target.getLatitude());
					}
					if(StringUtil.isBlank(source.getLongitude())){
						source.setLongitude(target.getLongitude());
					}
				}
				BeanUtil.copyProperties(source, target);
				target.setAccountName(accountName);
				boolean b = this.saveOrUpdate(target);
				if(b){
					return R.success("同步设备信息成功");
				}else{
					return R.fail("同步设备信息成功，但保存失败");
				}
			}
		}else{
			if(responseObj.getString("subCode").equals("-2")){ //未登录或者token过期了
				R login = this.videoCloudAccountService.login(accountName);
				if(login.isSuccess()){
					return R.fail("获取设备信息失败，请重新点击获取");
				}else{
					return login;
				}
			}
			return R.fail(responseObj.getString("msg") + ":" + responseObj.getString("subMsg"));
		}
	}

	@Override
	public R syncByAccountV3(String accountName) {
		JSONObject paramdata = new JSONObject(true);
		paramdata.put("memberkey", videoCloudConfig.getV3MemberKey());
		paramdata.put("resulttype", "1");
		paramdata.put("pagesize", "100");
		paramdata.put("pagenum", "1");
		String paramStr = paramdata.toJSONString();
		String beforeSign = videoCloudConfig.getV3Secret() + "&&" + paramStr;
		String sign = StringUtils.upperCase(SecureUtil.md5(beforeSign));
		String url = videoCloudConfig.getV3ApiHost() + "device/select?appkey=" + videoCloudConfig.getV3AppKey();
		JSONObject body = new JSONObject();
		body.put("parmdata", paramdata);
		body.put("sign", sign);
		log.info("================加密体字符串============");
		log.info(paramStr);
		log.info("================加密体加密前字符串============");
		log.info(beforeSign);
		log.info("====================SIGN==================");
		log.info(sign);
		log.info("=================获取视频流地址==================");
		log.info(url);
		log.info("================请求体字符串============");
		log.info(body.toJSONString());
		String response = HttpRequest.post(url).body(body.toJSONString()).header(Header.CONTENT_TYPE, "application/json").execute().body();
		log.info("================响应数据============");
		log.info(response);
		JSONObject responseData = JSONObject.parseObject(response);
		if(responseData.getString("code").equals("1")){
			JSONArray videoCloudDeviceArray = responseData.getJSONArray("result");
			if(videoCloudDeviceArray == null || videoCloudDeviceArray.size() <= 0){
				return R.success("无设备同步返回");
			}else{
				videoCloudDeviceArray.forEach(item -> {
					JSONObject source = (JSONObject) item;
					LambdaQueryWrapper<VideoCloudDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
					lambdaQueryWrapper.eq(VideoCloudDevice::getDeviceNum, source.getString("deviceid"));
					VideoCloudDevice target = this.getOne(lambdaQueryWrapper);
					if(target == null){
						target = new VideoCloudDevice();
					}
					target.setDeviceId(source.getString("deviceid"));
					target.setDeviceNum(source.getString("deviceid"));
					target.setDeviceName(source.getString("devicename"));
					target.setIsOnline(source.getInteger("online"));
					target.setStatus(source.getInteger("status"));
					boolean b = this.saveOrUpdate(target);
				});
				if(true){
					return R.success("同步设备信息成功");
				}else{
					return R.fail("同步设备信息成功，但保存失败");
				}
			}
		} else{
			return R.fail("同步设备信息失败");
		}
	}

	@Override
	public R syncByDeviceV3(String accountName, String deviceNum) {
		JSONObject paramdata = new JSONObject(true);
		paramdata.put("memberkey", videoCloudConfig.getV3MemberKey());
		if(StringUtil.isNotBlank(deviceNum)){
			paramdata.put("deviceids", deviceNum);
		}
		paramdata.put("resulttype", "1");
		paramdata.put("pagesize", "20");
		paramdata.put("pagenum", "1");
		String paramStr = paramdata.toJSONString();
		String beforeSign = videoCloudConfig.getV3Secret() + "&&" + paramStr;
		String sign = StringUtils.upperCase(SecureUtil.md5(beforeSign));
		String url = videoCloudConfig.getV3ApiHost() + "device/select?appkey=" + videoCloudConfig.getV3AppKey();
		JSONObject body = new JSONObject();
		body.put("parmdata", paramdata);
		body.put("sign", sign);
		log.info("================加密体字符串============");
		log.info(paramStr);
		log.info("================加密体加密前字符串============");
		log.info(beforeSign);
		log.info("====================SIGN==================");
		log.info(sign);
		log.info("=================获取视频流地址==================");
		log.info(url);
		log.info("================请求体字符串============");
		log.info(body.toJSONString());
		String response = HttpRequest.post(url).body(body.toJSONString()).header(Header.CONTENT_TYPE, "application/json").execute().body();
		log.info("================响应数据============");
		log.info(response);
		JSONObject responseData = JSONObject.parseObject(response);
		if(responseData.getString("code").equals("1")){
			JSONArray videoCloudDeviceArray = responseData.getJSONArray("result");
			if(videoCloudDeviceArray == null || videoCloudDeviceArray.size() <= 0){
				return R.success("无设备同步返回");
			}else{
				videoCloudDeviceArray.forEach(item -> {
					JSONObject source = videoCloudDeviceArray.getJSONObject(0);
					LambdaQueryWrapper<VideoCloudDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
					lambdaQueryWrapper.eq(VideoCloudDevice::getDeviceNum, source.getString("deviceid"));
					VideoCloudDevice target = this.getOne(lambdaQueryWrapper);
					if(target == null){
						target = new VideoCloudDevice();
					}
					target.setDeviceId(source.getString("deviceid"));
					target.setDeviceNum(source.getString("deviceid"));
					target.setDeviceName(source.getString("devicename"));
					target.setIsOnline(source.getInteger("online"));
					target.setStatus(source.getInteger("status"));
					boolean b = this.saveOrUpdate(target);
				});
				if(true){
					return R.success("同步设备信息成功");
				}else{
					return R.fail("同步设备信息成功，但保存失败");
				}
			}
		} else{
			return R.fail("同步设备信息失败");
		}
	}

	/**
	 *
	 * @param accountName
	 * @param deviceNum
	 * @param networkType 1表示TCP
	 * @return
	 */
	@Override
	public R<String> getVideoUrlV2(String accountName, String deviceNum, String networkType) {
		VideoCloudAccount videoCloudAccount = videoCloudAccountService.getOne(new QueryWrapper<>(new VideoCloudAccount()).lambda().eq(VideoCloudAccount::getAccountName, accountName));
		Map<String, Object> map = VideoCloudUtil.getSysParams(videoCloudAccount.getAppKey(), videoCloudConfig.getFormat(), "/device/getDevUrl", videoCloudConfig.getSignMethod(), videoCloudConfig.getV(), videoCloudAccount.getToken());
		map.put("deviceNum", deviceNum);
		String sign = VideoCloudUtil.getSign(map, videoCloudConfig.getSecret());
		map.put("sign", sign);
		String urlParamsLink = VideoCloudUtil.getUrlParamsLink(map, "&");
		String url = videoCloudConfig.getServerIp() + ":" + videoCloudConfig.getServerPort() + "/api/v2/device/getDevUrl"  + "?" + urlParamsLink;
		log.info("=================视频云获取设备播放地址请求数据【" + videoCloudAccount.getAccountName() + "】=====================");
		log.info(url);
		String response = HttpRequest.post(url).header(Header.CONTENT_TYPE, "application/json").execute().body();
		VideoCloudResult videoCloudResult = JsonUtil.parse(response, VideoCloudResult.class);
		log.info("=================视频云获取设备播放地址响应数据【" + videoCloudAccount.getAccountName() + "】=====================");
		log.info(JsonUtil.toJson(videoCloudResult));
		if(videoCloudResult.getReturnCode().equals("1")){
			VideoCloudDevice target = this.getByDeviceNum(deviceNum);
			if(target != null){
				target.setRtspUrl(videoCloudResult.getRtspUrl());
				this.saveOrUpdate(target);
			}
			return R.data(videoCloudResult.getRtspUrl(), "同步设备播放地址成功");
		} else{
			if(videoCloudResult.getSubCode().equals("-2")){ //未登录或者token过期了
				R login = this.videoCloudAccountService.login(accountName);
				if(login.isSuccess()){
					return R.fail("获取播放地址失败，请重新点击获取");
				}else{
					return login;
				}
			}
			return R.fail(videoCloudResult.getMsg() + ":" + videoCloudResult.getSubMsg());
		}
	}

	public static void main(String[] args) {
		String memberKey = "联系视频云获取";
		String deviceid = "需要获取视频地址的设备编号";
		String appkey = "视频云3.0appkey，联系视频云获取";
		String secret = "视频云3.0秘钥，联系视频云获取";
		String apiHost = "http://36.103.241.111:19103/api/dict/";
		JSONObject paramdata = new JSONObject(true);
		paramdata.put("memberkey", memberKey);
		paramdata.put("deviceid", deviceid);
//		paramdata.put("networktype", "1");
		String paramStr = paramdata.toJSONString();
		String sign = StringUtils.upperCase(SecureUtil.md5(secret + "&&" + paramStr));
		String url = apiHost + "media/play?appkey=" + appkey;
		JSONObject body = new JSONObject();
		body.put("parmdata", paramdata);
		body.put("sign", sign);
		String response = HttpRequest.post(url).body(body.toJSONString()).header(Header.CONTENT_TYPE, "application/json").execute().body();
		JSONObject responseData = JSONObject.parseObject(response);
		if(responseData.getString("code").equals("1")){
			JSONObject result = responseData.getJSONObject("result");
			String flvurl = result.getString("flvuri");
			System.out.println("视频播放地址：" + flvurl);
		} else{
			System.out.println("获取设备播放地址失败");
		}
	}

	/**
	 * 视频云3.0获取视频地址接口
	 * @param accountName
	 * @param deviceNum
	 * @param networkType 1表示TCP
	 * @return
	 */
	@Override
	public R<String> getVideoUrlV3(String accountName, String deviceNum, String networkType) {
		JSONObject paramdata = new JSONObject(true);
		paramdata.put("memberkey", videoCloudConfig.getV3MemberKey());
		paramdata.put("deviceid", deviceNum);
		paramdata.put("networktype", "1");
		String paramStr = paramdata.toJSONString();
		String sign = StringUtils.upperCase(SecureUtil.md5(videoCloudConfig.getV3Secret() + "&&" + paramStr));
		String url = videoCloudConfig.getV3ApiHost() + "media/play?appkey=" + videoCloudConfig.getV3AppKey();
		JSONObject body = new JSONObject();
		body.put("parmdata", paramdata);
		body.put("sign", sign);
		log.info("================加密体字符串============");
		log.info(paramStr);
		log.info("====================SIGN==================");
		log.info(sign);
		log.info("=================获取视频流地址==================");
		log.info(url);
		log.info("================请求体字符串============");
		log.info(body.toJSONString());
		String response = HttpRequest.post(url).body(body.toJSONString()).header(Header.CONTENT_TYPE, "application/json").execute().body();
		log.info("================响应数据============");
		log.info(response);
		JSONObject responseData = JSONObject.parseObject(response);
		if(responseData.getString("code").equals("1")){
			VideoCloudDevice target = this.getByDeviceNum(deviceNum);
			if(target != null){
				JSONObject result = responseData.getJSONObject("result");
				target.setRtspUrl(result.getString("flvuri"));
				this.saveOrUpdate(target);
			}
			return R.data(target.getRtspUrl(), "获取设备播放地址成功");
		} else{
			return R.fail("获取设备播放地址失败");
		}
	}

	@Override
	public VideoCloudDevice getByDeviceNum(String deviceNum) {
		LambdaQueryWrapper<VideoCloudDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(VideoCloudDevice::getDeviceNum, deviceNum);
		return this.getOne(lambdaQueryWrapper);
	}

	@Override
	public R getVideoUrlBatch(List<Long> idList) {
		for(Long id : idList){
			VideoCloudDevice videoCloudDevice = this.getById(id);
			if(videoCloudDevice.getIsOnline()!= null && videoCloudDevice.getIsOnline() == 1){
				try{
					R result = this.getVideoUrlV2(videoCloudDevice.getAccountName(), videoCloudDevice.getDeviceNum(), null);
					if(result.isSuccess()){
						continue;
					}else{
						return result;
					}
				}catch (Exception e){
					return R.fail("系统异常");
				}
			}
		}
		return R.success("操作成功");
	}

	@Override
	public R syncByDeviceBatch(List<Long> idList) {
		for(Long id : idList){
			VideoCloudDevice videoCloudDevice = this.getById(id);
			if(videoCloudDevice.getIsOnline()!= null && videoCloudDevice.getIsOnline() == 1){
				try{
					R result = this.syncByDevice(videoCloudDevice.getAccountName(), videoCloudDevice.getDeviceNum());
					if(result.isSuccess()){
						continue;
					}else{
						return result;
					}
				}catch (Exception e){
					return R.fail("系统异常");
				}
			}
		}
		return R.success("操作成功");
	}

	@Override
	public R zlmPlayProxy(String deviceNum) {
		VideoCloudDevice device = this.getByDeviceNum(deviceNum);
		Assert.notNull(device, "设备不存在");
		String addStreamProxyUrl = String.format("%s/index/api/addStreamProxy?secret=%s&vhost=%s&app=live&stream=%s&url=%s&timeout_sec=60", zlmConfig.getZlmUrl()+ ":" + zlmConfig.getZlmPort(), zlmConfig.getZlmSecret(), zlmConfig.getZlmDefaultVhost(), deviceNum, device.getRtspUrl());
		String response = HttpUtil.get(addStreamProxyUrl);
		JSONObject responseData = JSON.parseObject(response);
		if(responseData.getInteger("code") == 0){
			JSONObject data = responseData.getJSONObject("data");
			device.setStreamId(data.getString("key"));
			this.updateById(device);
			return R.success("推流成功");
		}else{
			return R.fail("推流失败");
		}
	}

	@Override
	public R zlmStopProxy(String deviceNum) {
		VideoCloudDevice device = this.getByDeviceNum(deviceNum);
		Assert.notNull(device, "设备不存在");
		String delStreamProxyUrl = String.format("%s/index/api/delStreamProxy?secret=%s&key=%s", zlmConfig.getZlmUrl()+ ":" + zlmConfig.getZlmPort(), zlmConfig.getZlmSecret(), device.getStreamId());
		String response = HttpUtil.get(delStreamProxyUrl);
		JSONObject responseData = JSON.parseObject(response);
		if(responseData.getInteger("code") == 0){
			JSONObject data = responseData.getJSONObject("data");
			if(data.getBoolean("flag")){
				device.setStreamId(null);
				this.updateById(device);
				return R.success("停止成功");
			}else{
				return R.success("停止成功");
			}
		}else{
			return R.success("停止成功");
		}
	}

	@Override
	public R zlmPlayFFmpeg(String deviceNum) {
		VideoCloudDevice device = this.getByDeviceNum(deviceNum);
		Assert.notNull(device, "设备不存在");
		String addStreamProxyUrl = String.format("%s/index/api/addFFmpegSource?secret=%s&src_url=%s&dst_url=%s&timeout_ms=30000&enable_hls=0&enable_mp4=0", zlmConfig.getZlmUrl()+ ":" + zlmConfig.getZlmPort(), zlmConfig.getZlmSecret(), device.getRtspUrl(), zlmConfig.getZlmDstUrl() + device.getDeviceNum());
		String response = HttpUtil.get(addStreamProxyUrl);
		JSONObject responseData = JSON.parseObject(response);
		if(responseData.getInteger("code") == 0){
			JSONObject data = responseData.getJSONObject("data");
			device.setStreamId(data.getString("key"));
			this.updateById(device);
			return R.success("推流成功");
		}else{
			return R.fail("推流失败");
		}
	}

	@Override
	public R zlmStopFFmpeg(String deviceNum) {
		VideoCloudDevice device = this.getByDeviceNum(deviceNum);
		Assert.notNull(device, "设备不存在");
		String delStreamProxyUrl = String.format("%s/index/api/delFFmpegSource?secret=%s&key=%s", zlmConfig.getZlmUrl()+ ":" + zlmConfig.getZlmPort(), zlmConfig.getZlmSecret(), device.getStreamId());
		String response = HttpUtil.get(delStreamProxyUrl);
		JSONObject responseData = JSON.parseObject(response);
		if(responseData.getInteger("code") == 0){
			JSONObject data = responseData.getJSONObject("data");
			if(data.getBoolean("flag")){
				device.setStreamId(null);
				this.updateById(device);
				return R.success("停止成功");
			}else{
				return R.success("停止成功");
			}
		}else{
			return R.success("停止成功");
		}
	}

}
