package cn.com.taiji.video.service.impl;


import cn.com.taiji.video.mapper.HtDpVideoMapper;
import cn.com.taiji.video.model.*;
import cn.com.taiji.video.service.IHtDpVideoAnalysisService;
import cn.com.taiji.video.service.IVideoUrlService;
import cn.com.taiji.video.utils.DataUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 *
 * @Author  yangyue
 * @Date 2021/11/18
 */
@Service
@Slf4j
public class VideoUrlServiceImpl implements IVideoUrlService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private HtDpVideoMapper videoMapper;

    @Autowired
    private IHtDpVideoAnalysisService videoAnalysisService;

    @Value("${taiji.clientId}")
    private String clientId;

    @Value("${taiji.clientSecret}")
    private String clientSecret;

    @Value("${taiji.faceTaskId}")
    private String faceTaskId;

    @Value("${taiji.carTaskId}")
    private String carTaskId;

    @Value("${taiji.url}")
    private String analysisUrl;

    @Value("${taiji.ak}")
    private String ak;

    @Value("${taiji.sk}")
    private String sk;

    String url = "http://10.110.80.31:8888";

    @Override
    public void httpsPost(String deviceids) {
        MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
        params.add("client_id",clientId);
        params.add("client_secret",clientSecret);
        params.add("grant_type","client_credentials");

        String tokenUrl = url + "/tglserver/token";
        log.info(tokenUrl);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity httpEntity = new HttpEntity(params,headers);
        ResponseEntity<Map> result2 = restTemplate.postForEntity(tokenUrl, httpEntity, Map.class);
        log.info(result2.getBody().toString());
        String token = result2.getBody().get("token_type") + " " + result2.getBody().get("access_token");
        log.info(token);

        //登录接口
        String deviceUrl = url + "/api/Common/GeMonitorListByDeviceId?client_id="+clientId+"&deviceids="+deviceids;

        headers.clear();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Authorization", token);
        HttpEntity reqEntity = new HttpEntity(headers);
        log.info(deviceUrl);
        ResponseEntity<List> mainServiceEntity = restTemplate.exchange(deviceUrl, HttpMethod.GET, reqEntity,List.class);
        // log.info(JSON.toJSONString(mainServiceEntity.getBody()));
        // return mainServiceEntity.getBody();
        List<Map> datas = (List<Map>) mainServiceEntity.getBody();
        if (null != datas && datas.size() > 0) {
            datas.forEach(o -> {
                videoMapper.update(
                        null,
                        Wrappers.<HtDpVideo>lambdaUpdate()
                                .set(HtDpVideo::getRtspUrl, o.get("RtspUrl"))
                                .set(HtDpVideo::getRtmpUrl, o.get("RtmpUrl"))
                                .set(HtDpVideo::getHlsUrl, o.get("HLSUrl"))
                                .eq(HtDpVideo::getCode, o.get("DeviceID"))
                );
            });
        }
    }

    @Override
    public List<VideoDTO> queryVideoList() {
        return videoMapper.selectVideoList();
    }

    @Override
    public List<VideoRecord> queryVideoRecord() {
        return videoMapper.selectVideoRecord();
    }

    @Override
    public void queryTestPie(Integer type, LocalDate startDate, LocalDate endDate) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM");
        ArtemisConfig.host=analysisUrl;
        ArtemisConfig.appKey=ak;
        ArtemisConfig.appSecret=sk;
        final String artemispath = "/artemis";
        List<LocalDate> localDates = DataUtils.getAllDatesInTheDateRange(startDate, endDate);
        if (null != localDates && localDates.size() > 0) {
            localDates.forEach(item -> {
                long startTimestamp = LocalDateTime.of(item, LocalTime.MIN).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
                long endTimestamp = LocalDateTime.of(item, LocalTime.MAX).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
                log.info("开始时间：{} ；结束时间：{}",startTimestamp,endTimestamp);
                HtDpVideoAnalysis videoAnalysis = new HtDpVideoAnalysis();
                videoAnalysis.setYear(String.valueOf(item.getYear()));
                videoAnalysis.setYearMonth(item.format(fmt));
                videoAnalysis.setStatDate(item);
                videoAnalysis.setType(type);
                String taskId = carTaskId;
                if (1 == type) {
                    taskId = faceTaskId;
                }
                videoAnalysis.setTaskId(taskId);
                String previewurlsapi = artemispath + "/api/v2/tasks/picture/statistics/"+taskId+"/"+ startTimestamp +"/"+endTimestamp;
                log.info(previewurlsapi);

                Map<String, String> path = new HashMap<String, String>(2) {
                    {
                        put("https://", previewurlsapi);//根据现场环境部署确认是http还是https
                    }
                };
                String contentType = "application/json";
                // post请求application/json类型参数
                String result = ArtemisHttpUtil.doGetArtemis(path, null, null, contentType, null);
                log.info(result);
                JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("data");
                videoAnalysis.setPicAnalysisTotal(jsonObject.getInteger("picAnalysisTotal"));
                videoAnalysis.setPicAnalysisFailCount(jsonObject.getInteger("picAnalysisFailCount"));
                videoAnalysis.setPicAnalysisSuccessCount(jsonObject.getInteger("picAnalysisSuccessCount"));
                videoAnalysis.setPicCaptureTotal(jsonObject.getInteger("picCaptureTotal"));
                videoAnalysis.setPicFilterCount(jsonObject.getInteger("picFilterCount"));
                videoAnalysis.setPicSubmitFailCount(jsonObject.getInteger("picSubmitFailCount"));
                videoAnalysis.setPicSubmitSuccessCount(jsonObject.getInteger("picSubmitSuccessCount"));
                videoAnalysisService.saveOrUpdate(
                        videoAnalysis,
                        Wrappers.<HtDpVideoAnalysis>lambdaUpdate()
                                .eq(HtDpVideoAnalysis::getType,type)
                                .eq(HtDpVideoAnalysis::getStatDate,item));

            });
        }
    }

    @Override
    public Integer queryPieRecordAll() {
        return videoAnalysisService.queryAllFilter();
    }

    @Override
    public VideoAnalysisPieDTO queryPieRecord(Integer type) {
        LocalDate localDate = LocalDate.now();
        String year = String.valueOf(localDate.getYear());
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM");
        String yearMonth = localDate.format(fmt);
        List<AnalysisDTO> analysisDTO;
        if (1 == type) {
            analysisDTO = videoAnalysisService.queryFilter(year, null);
        } else {
            analysisDTO = videoAnalysisService.queryFilter(null,yearMonth);
        }
        VideoAnalysisPieDTO videoAnalysisPieDTO = new VideoAnalysisPieDTO();
        // videoAnalysisPieDTO.setAnalysis(analysisDTO);
        int total = 0;
        int face = 0;
        int car = 0;
        int body = 0;
        if (null != analysisDTO && analysisDTO.size() > 0) {
            for (AnalysisDTO dto: analysisDTO) {
                total += dto.getCount();
                if (dto.getType() == 1) {
                    face = dto.getCount();
                }
                if (dto.getType() == 2) {
                    car = dto.getCount();
                }
                if (dto.getType() == 3) {
                    body = dto.getCount();
                }
            }
        }
        videoAnalysisPieDTO.setTotal(total);
        if (total != 0) {
            log.info(String.valueOf(face));
            log.info(String.valueOf(car));
            videoAnalysisPieDTO.setFace((new BigDecimal((float)face/total).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue())*100);
            videoAnalysisPieDTO.setCar((new BigDecimal((float)car/total).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue())*100);
            videoAnalysisPieDTO.setBody((new BigDecimal((float)body/total).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue())*100);
        } else {
            videoAnalysisPieDTO.setFace(0.00);
            videoAnalysisPieDTO.setCar(0.00);
            videoAnalysisPieDTO.setBody(0.00);
        }

        return videoAnalysisPieDTO;
    }

    @Override
    public List<VideoAnalysisLineDTO> queryLineRecord(Integer type) {

        LocalDate localDate = LocalDate.now();
        String year = String.valueOf(localDate.getYear());
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM");
        String yearMonth = localDate.format(fmt);
        List<VideoAnalysisLineDTO> analysisLineDTO;
        if (1 == type) {
            analysisLineDTO = videoAnalysisService.querytotal(year, null);
        } else {
            analysisLineDTO = videoAnalysisService.querytotal(null,yearMonth);
        }

        return analysisLineDTO;
    }
}
