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

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

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 com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
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;

/**
 * 模板表服务实现类
 *
 * @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;
	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();
//		HttpHeaders headers = new HttpHeaders();
//		headers.add("Content-Type", "application/json");
//		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//		factory.setConnectTimeout(30000);
//		factory.setReadTimeout(30000);
//		restTemplate.setRequestFactory(factory);
		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();
//		JSONObject obj = JSONObject.parseObject(objectStr);
//		HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers); // 组装
//		logger.info("开始查询海康视频数据"+objectStr);
//		ResponseEntity<String> response = restTemplate.exchange(hkVideoUrl, HttpMethod.POST, request, String.class);
		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];
			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.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();
			for (EsVideoOriginal videoOriginal : it) {
				videoOriginalDtoList.add(transDto(videoOriginal));
			}	
		}else {
			List<EsVideoOriginal> videoOriginalList = iVideoOriginalRepository.findByCnLike(cn);	
			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.setType(HK);
			return videoOriginalDto;
	}
	public String qeueryByIndexCode(String indexCode) {
//		// TODO Auto-generated method stub
//		HttpHeaders headers = new HttpHeaders();
//		headers.add("Content-Type", "application/json");
//		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//		factory.setConnectTimeout(30000);
//		factory.setReadTimeout(30000);
//		restTemplate.setRequestFactory(factory);
		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();
//		JSONObject obj = JSONObject.parseObject(objectStr);
//		HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers); // 组装
//		logger.info("开始查询海康视频播放地址"+objectStr);
//		ResponseEntity<String> response = restTemplate.exchange(hkVideoUrl, HttpMethod.POST, request, String.class);
		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;
	}
}