package com.yeejoin.amos.video.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.video.dao.IVideoOriginalRepository;
import com.yeejoin.amos.video.dto.VideoOriginalDto;
import com.yeejoin.amos.video.entity.EsVideoOriginal;
import com.yeejoin.amos.video.entity.VideoOriginal;
import com.yeejoin.amos.video.mapper.VideoOriginalMapper;
import com.yeejoin.amos.video.service.IVideoOriginalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * 模板表服务实现类
 *
 * @author system_generator
 * @date 2021-09-01
 */
@Service
public class VideoOriginalServiceImpl extends BaseService<VideoOriginalDto, VideoOriginal, VideoOriginalMapper> implements IVideoOriginalService  {
	
	private static final Logger logger = LoggerFactory.getLogger(VideoOriginalServiceImpl.class);
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private IVideoOriginalRepository iVideoOriginalRepository;
	@Value("${biz.hk.video.url}")
	private String hkVideoUrl;
	@Value("${biz.hk.video.APPkey}")
	private String hkVideoAPPkey;
	@Value("${biz.hk.video.APPsecret}")
	private String hkVideoAPPsecret;
	@Value("${biz.hk.video.csv}")
	private String hkVideoCsv;
	@Value("${biz.hk.video.status.csv}")
	private String hkVideoStatusCsv;
	private final String protocol="hls";
	private final static String HK = "HK";
	@PostConstruct
	public void init() {
	}

	/**
	 * 重建索引
	 * @param db 
	 */
	public Boolean initEs(String userId,String userName, Boolean db) {
		iVideoOriginalRepository.deleteAll();
		String objectStr = new StringBuilder().append(
				"{\"httpMethod\":\"GET\",\"path\":\"/api/resource/v1/csv/downloadcsv/{csvFileName}\",\"headers\":{},\"query\":{},\"parameter\":{\"csvFileName\":\"")
				.append(hkVideoCsv).append("\"},\"mock\":false,\"appKey\":\"").append(hkVideoAPPkey)
				.append("\",\"appSecret\":\"").append(hkVideoAPPsecret).append("\"}").toString();
		ResponseEntity<String> response = getVideoData(objectStr);
		String ss = response.getBody();
		JSONObject obj1 = JSONObject.parseObject(ss);
		String sss = obj1.get("response").toString();
		logger.info("完成海康视频数据查询：长度："+sss.length());
		String[] str = sss.split("\n");
		List<EsVideoOriginal> resultData = new ArrayList<EsVideoOriginal>();
		for (String originalStr : str) {
			String[] strstr = originalStr.split(",");
			String cn = strstr[0];
			String indexCode = strstr[1];
			String ip = strstr[9];
			String port = strstr[10];
			if (!cn.equals("cn") && !indexCode.equals("indexCode")) {
				EsVideoOriginal videoOriginal = new EsVideoOriginal();
				videoOriginal.setCn(cn);
				videoOriginal.setIndexCode(indexCode);
				videoOriginal.setOriginalData(originalStr);
				videoOriginal.setRecUserId(userId);
				videoOriginal.setRecUserName(userName);
				videoOriginal.setIp(ip);
				videoOriginal.setPort(port);
				videoOriginal.setType(HK);
				videoOriginal.setRecDate(DateUtils.getDateNowString());
				resultData.add(videoOriginal);
			}
		}
		logger.info("开始搜索引擎中存储"+resultData.size());
		iVideoOriginalRepository.saveAll(resultData);
		logger.info("完成搜索引擎中存储");
		boolean isSuccess = this.saveToDB(str, userId, userName, db);
		if(!isSuccess) {
			logger.info("搜索引擎存储视频原始数据失败");
		}
		return true;
	}

	public List<VideoOriginalDto> qeueryByKeys(String cn) {
		List<VideoOriginalDto> videoOriginalDtoList = new ArrayList<VideoOriginalDto>();
		if(cn.equals("all")) {
			Iterable<EsVideoOriginal> it = iVideoOriginalRepository.findAll();
			logger.info("查询所有HK视频："+it.iterator().hashCode());
			for (EsVideoOriginal videoOriginal : it) {
				videoOriginalDtoList.add(transDto(videoOriginal));
			}	
		}else {
			List<EsVideoOriginal> videoOriginalList = iVideoOriginalRepository.findByCnLike(cn);
			logger.info("查询'"+cn+"'HK视频："+videoOriginalList.size());
			for (EsVideoOriginal videoOriginal : videoOriginalList) {
				videoOriginalDtoList.add(transDto(videoOriginal));
			}
		}
		return videoOriginalDtoList;
	}
	private VideoOriginalDto  transDto(EsVideoOriginal videoOriginal){
			VideoOriginalDto videoOriginalDto = new VideoOriginalDto();
			videoOriginalDto.setCn(videoOriginal.getCn());
			videoOriginalDto.setIndexCode(videoOriginal.getIndexCode());
			videoOriginalDto.setIp(videoOriginal.getIp());
			videoOriginalDto.setPort(videoOriginal.getPort());
			videoOriginalDto.setType(HK);
			return videoOriginalDto;
	}
	public String qeueryByIndexCode(String indexCode) {
		String objectStr = new StringBuilder().append("{\"httpMethod\":\"POST\",\"path\":\"/api/video/v1/cameras/previewURLs\",\"headers\":{},\"query\":{},\"parameter\":{},\"body\":{\"indexCode\":\"")
				.append(indexCode).append("\",\"netZoneCode\":\"0\",\"transmode\":1,\"streamType\":0,\"protocol\":\"").append(protocol).append("\"},\"contentType\":\"application/json;charset=UTF-8\",\"mock\":false,\"appKey\":\"").append(hkVideoAPPkey)
				.append("\",\"appSecret\":\"").append(hkVideoAPPsecret).append("\"}").toString();
		ResponseEntity<String> response = getVideoData(objectStr);
		String ss = response.getBody();
		JSONObject obj1 = JSONObject.parseObject(ss);
		String sss = obj1.get("response").toString();
		String ssss = JSONObject.parseObject(sss).get("data").toString();
		String sssss =JSONObject.parseObject(ssss).get("url").toString();
		logger.info("完成海康视频播放地址查询：长度："+sss.length());
		return sssss;
	}
	private ResponseEntity<String> getVideoData(String urlParam){
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setConnectTimeout(30000);
		factory.setReadTimeout(30000);
		restTemplate.setRequestFactory(factory);
		JSONObject obj = JSONObject.parseObject(urlParam);
		HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers); // 组装
		logger.info("开始查询海康视频数据"+urlParam);
		ResponseEntity<String> response = restTemplate.exchange(hkVideoUrl, HttpMethod.POST, request, String.class);
		return response;
	}

	private boolean saveToDB(String[] str,String userId,String userName,boolean db) {
		List<VideoOriginal> resultData = new ArrayList<VideoOriginal>();
		for (String originalStr : str) {
			String[] strstr = originalStr.split(",");
			String cn = strstr[0];
			String indexCode = strstr[1];
			if (!cn.equals("cn") && !indexCode.equals("indexCode")) {
				VideoOriginal videoOriginal = new VideoOriginal();
				videoOriginal.setCn(cn);
				videoOriginal.setIndexCode(indexCode);
				videoOriginal.setOriginalData(originalStr);
				videoOriginal.setRecUserId(userId);
				videoOriginal.setRecUserName(userName);
				videoOriginal.setType(HK);
				videoOriginal.setRecDate(DateUtils.getDateNow());
				resultData.add(videoOriginal);
			}
		}
		boolean result = false;
		if(db) {
			try {
				QueryWrapper<VideoOriginal> wrapper = new QueryWrapper<VideoOriginal>();
				wrapper.eq("type", HK);
				boolean isTrue = this.remove(wrapper);
				if(isTrue) {
				 result = this.saveBatch(resultData);			
				}				
			} catch (Exception e) {
				// TODO: handle exception
				logger.error("HK原始视频数据删除失败："+e);
				e.printStackTrace();
			}
		}
		return result;
	}

	public List<EsVideoOriginal> qeueryStatusByIndexCode(String indexCode) {
		// TODO Auto-generated method stub
		String objectStr = new StringBuilder().append(
				"{\"httpMethod\":\"GET\",\"path\":\"/api/resource/v1/csv/downloadcsv/{csvFileName}\",\"headers\":{},\"query\":{},\"parameter\":{\"csvFileName\":\"")
				.append(hkVideoStatusCsv).append("\"},\"mock\":false,\"appKey\":\"").append(hkVideoAPPkey)
				.append("\",\"appSecret\":\"").append(hkVideoAPPsecret).append("\"}").toString();
		ResponseEntity<String> response = getVideoData(objectStr);
		String ss = response.getBody();
		JSONObject obj1 = JSONObject.parseObject(ss);
		String sss = obj1.get("response").toString();
		logger.info("完成海康视频状态数据查询：长度："+sss.length());
		String[] str = sss.split("\n");
		List<EsVideoOriginal> resultData = new ArrayList<EsVideoOriginal>();
		for (String originalStr : str) {
			System.out.println(originalStr);
			String[] strstr = originalStr.split(",");
			String cn = strstr[8];
			String indexCodes = strstr[0];
			String status = strstr[2];
			if (!cn.equals("cn") && !indexCodes.equals("indexCode")&&indexCodes.equals(indexCode)) {
				EsVideoOriginal videoOriginal = new EsVideoOriginal();
				videoOriginal.setCn(cn);
				videoOriginal.setIndexCode(indexCodes);
				videoOriginal.setStatus(status);
				logger.info("返回海康视频状态："+status);
				videoOriginal.setType(HK);
				videoOriginal.setRecDate(DateUtils.getDateNowString());
				resultData.add(videoOriginal);
			}
		}
		logger.info("返回海康视频状态对象长度："+resultData.size());
		return resultData;
	}
}