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

import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.stream.StreamSupport;

import javax.annotation.PostConstruct;

import org.apache.commons.compress.utils.Lists;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
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.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
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 com.alibaba.fastjson.JSONObject;
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.VideoOriginal;

//import net.sf.json.JSONObject;

/**
 * 模板表服务实现类
 *
 * @author system_generator
 * @date 2021-09-01
 */
@Service
public class VideoOriginalServiceImpl {
	
	private static final Logger logger = LoggerFactory.getLogger(VideoOriginalServiceImpl.class);
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private IVideoOriginalRepository iVideoOriginalRepository;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

	@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";
	@PostConstruct
	public void init() {
		// 初始化ES，重建索引
//		initEs();
	}

	/**
	 * 重建索引
	 */
	public Boolean initEs(String userId,String userName) {
//		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 = "{\"httpMethod\":\"GET\",\"path\":\"/api/resource/v1/csv/downloadcsv/{csvFileName}\",\"headers\":{},\"query\":{},\"parameter\":{\"csvFileName\":\"otherDomainCameraFull_1.csv\"},\"mock\":false,\"appKey\":\"25907430\",\"appSecret\":\"RJj3WmSNdQuyX0yCR02b\"}";
		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);
		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<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.setRecDate(DateUtils.getDateNowString());
				resultData.add(videoOriginal);
//				iVideoOriginalRepository.save(videoOriginal);
			}
		}
		logger.info("开始搜索引擎中存储"+resultData.size());
		iVideoOriginalRepository.saveAll(resultData);
		logger.info("完成搜索引擎中存储");
		return true;
	}

	public List<VideoOriginalDto> qeueryByKeys(String cn) {
		// TODO Auto-generated method stub
//		List<VideoOriginal> videoOriginalList = new ArrayList<VideoOriginal>();
//		MatchQueryBuilder builder = QueryBuilders.matchQuery("cn", cn);
////		FuzzyQueryBuilder builder = QueryBuilders.fuzzyQuery("cn", cn);
//		NativeSearchQuery searchQuery = new NativeSearchQuery(builder);
//		SearchHits<VideoOriginal> searchHits = elasticsearchTemplate.search(searchQuery, VideoOriginal.class);
//		BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
//        BoolQueryBuilder qb4 = QueryBuilders.boolQuery()
//        		.should(QueryBuilders.termQuery("cn", cn));
//        boolMust.must(qb4);
//        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
//                //过滤条件
//                .withQuery(boolMust);
//		SearchHits<VideoOriginal> searchHits = elasticsearchTemplate.search(queryBuilder.build(), VideoOriginal.class);
//		for (SearchHit searchHit : searchHits.getSearchHits())
//		{
//			System.out.println(searchHit.getContent());
//			JSONObject jsonObject = (JSONObject) JSONObject.toJSON(searchHit.getContent());
//			VideoOriginal videoOriginals = (VideoOriginal) JSONObject.toJavaObject(jsonObject,VideoOriginal.class);
//			videoOriginalList.add(videoOriginals);
//		}
		List<VideoOriginalDto> videoOriginalDtoList = new ArrayList<VideoOriginalDto>();
		if(cn.equals("all")) {
			Iterable<VideoOriginal> it = iVideoOriginalRepository.findAll();
			for (VideoOriginal videoOriginal : it) {
				videoOriginalDtoList.add(transDto(videoOriginal));
			}	
		}else {
			List<VideoOriginal> videoOriginalList = iVideoOriginalRepository.findByCnLike(cn);	
			for (VideoOriginal videoOriginal : videoOriginalList) {
				videoOriginalDtoList.add(transDto(videoOriginal));
			}
		}
		return videoOriginalDtoList;
	}
	private VideoOriginalDto  transDto(VideoOriginal videoOriginal){
			VideoOriginalDto videoOriginalDto = new VideoOriginalDto();
			videoOriginalDto.setCn(videoOriginal.getCn());
			videoOriginalDto.setIndexCode(videoOriginal.getIndexCode());
			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);
		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;
	}
}