package com.ningdatech.carapi.irs.service.impl;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Objects;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.ningdatech.cache.model.cache.CacheKey;
import com.ningdatech.cache.repository.CachePlusOps;
import com.ningdatech.carapi.irs.service.CarService;
import com.ningdatech.carapi.irs.service.RefreshKeyService;
import com.ningdatech.carapi.irs.utils.Md5Utils;
import com.ningdatech.carapi.scheduler.contants.TaskConstant;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author CMM
 * @since 2023/04/23 15:21
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CarServiceImpl implements CarService {

    private final RestTemplate restTemplate;
    private final RefreshKeyService refreshKeyService;
    private final CachePlusOps cachePlusOps;

    @Override
    public String vehicleIllegalQuery() {
        // 应用appKey
        String appKey = "A330000100000202105003941";
        String appSecret = "e07fd4471e92410d9860282d939b1217";
        String innerAppKey = "210a2657177f478c808381deb13a4dac";
        // 刷新密钥
        String requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret);

        // 请求签名
        Long requestTime  = System.currentTimeMillis();
        String sign = Md5Utils.hash(appKey + requestSecret + requestTime);
        String url = "https://interface.zjzwfw.gov.cn/gateway/api/proxy/001003007/dataSharing/Czp71c3856d9gf1a.htm";
        //// 车辆分类
        //String clfl = "abc";
        //// 当事人 --
        //String dsr = "abc";
        //// 号牌号码 --
        //String hphm = "abc";
        //// 号牌种类
        //String hpzl = "abc";
        //// 决定书编号 --
        //String jdsbh = "abc";
        // 驾驶证号 --
        String jszh = "330382198711014059";
        //// 违法编号 --
        //String wfbh = "abc";
        //// 机动车使用性质
        //String syxz = "abc";

        MultiValueMap<String, Object> map = new LinkedMultiValueMap();
        // 附加信息
        map.add("additional","{\"powerMatters\":\"许可-0000-00\",\"subPowerMatters\":\"许可-0000-0101\",\"accesscardId\":\"33071918111111784523\"}");
        map.add("appKey",appKey);
        map.add("requestTime",requestTime);
        map.add("sign",sign);
        //map.add("dsr",dsr);
        //map.add("hphm",hphm);
        //map.add("jdsbh",jdsbh);
        map.add("jszh",jszh);
        //map.add("wfbh",wfbh);
        //map.add("hpzl",hpzl);
        //map.add("syxz",syxz);
        //map.add("clfl",clfl);
        String res = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("innerAppKey",innerAppKey);
            HttpEntity<Object> httpEntity = new HttpEntity<>(map,headers);
            log.info("请求参数 :{}", JSON.toJSONString(map));
            res = restTemplate.postForObject(url, httpEntity ,String.class);
            log.info("[RestTemplateTest-车辆违法查询] http request :{}", res);
        } catch (Exception e) {
            log.error("[RestTemplateTest-车辆违法查询] http request error", e);
        }
        return res;
    }

    @Override
    public String vehicleIllegalQuery(String hphm) {
        // 应用appKey
        String appKey = "A330000100000202105003941";
        String appSecret = "e07fd4471e92410d9860282d939b1217";
        String innerAppKey = "210a2657177f478c808381deb13a4dac";
        // 根据传入的时间判断是否需要刷新密钥
        // 刷新密钥
        String requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret);
        // 号牌种类
        String hpzl = "01";

        // 请求签名
        Long requestTime  = System.currentTimeMillis();
        String sign = Md5Utils.hash(appKey + requestSecret + requestTime);
        String url = "https://interface.zjzwfw.gov.cn/gateway/api/proxy/001003007/dataSharing/Czp71c3856d9gf1a.htm";

        MultiValueMap<String, Object> map = new LinkedMultiValueMap();
        // 附加信息
        map.add("additional","{\"powerMatters\":\"许可-0000-00\",\"subPowerMatters\":\"许可-0000-0101\",\"accesscardId\":\"33071918111111784523\"}");
        map.add("appKey",appKey);
        map.add("requestTime",requestTime);
        map.add("sign",sign);
        map.add("hphm",hphm);
        map.add("hpzl",hpzl);
        String res = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("innerAppKey",innerAppKey);
            HttpEntity<Object> httpEntity = new HttpEntity<>(map,headers);
            log.info("请求参数 :{}", JSON.toJSONString(map));
            res = restTemplate.postForObject(url, httpEntity ,String.class);
            log.info("[RestTemplateTest-车辆违法查询] http request :{}", res);
        } catch (Exception e) {
            log.error("[RestTemplateTest-车辆违法查询] http request error", e);
        }
        return res;
    }

    @Override
    public String vehicleIllegalQuery(String hphm, Integer index) {
        // 应用appKey
        String appKey = "A330000100000202105003941";
        String appSecret = "e07fd4471e92410d9860282d939b1217";
        String innerAppKey = "210a2657177f478c808381deb13a4dac";

        // 请求秘钥
        CacheKey requestKey = new CacheKey(TaskConstant.RedisKey.IRS_VEHICLE_ILLEGAL_REQUEST_SECRET);
        // 刷新密钥
        CacheKey refreshKey = new CacheKey(TaskConstant.RedisKey.IRS_VEHICLE_ILLEGAL_REFRESH_SECRET);
        // 根据key获取缓存中的请求秘钥和刷新密钥
        String requestSecret = cachePlusOps.get(requestKey);
        String refreshSecret = cachePlusOps.get(refreshKey);
        if (index == 0) {
            // 任务第一次调用接口，获取刷新秘钥和请求秘钥,并保存到redis中
            try {
                if (Objects.nonNull(refreshSecret)){
                    requestSecret = refreshKeyService.refreshRequestSecret(appKey, requestKey, refreshKey, refreshSecret);
                    if (requestSecret == null) {
                        requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret, requestKey, refreshKey);
                    }
                }else {
                    requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret, requestKey, refreshKey);
                }
            } catch (Exception e) {
                log.error("获取刷新密钥失败:{},此次车辆违法查询车牌号为{}", e.getMessage(), hphm);
                return null;
            }
        }
        // 如果获取不到刷新密钥，重新生成
        else if (Objects.isNull(refreshSecret)) {
            try {
                requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret, requestKey, refreshKey);
                if (requestSecret == null) {
                    return null;
                }
            } catch (Exception e) {
                log.error("获取刷新密钥失败:{},此次车辆违法查询车牌号为{}", e.getMessage(), hphm);
                return null;
            }
        }
        // 不是第一次调用,看请求秘钥是否过期
        // 刷新密钥有效期两天，而定时任务每天都会执行一次，每次任务执行又会更新刷新密钥，所以刷新密钥不会过期
        // 只需判断请求秘钥是否过期
        else if (Objects.isNull(requestSecret)) {
            try {
                // 调用IRS刷新秘钥接口，更新刷新密钥和请求秘钥
                requestSecret = refreshKeyService.refreshRequestSecret(appKey, requestKey, refreshKey, refreshSecret);
                if (requestSecret == null) {
                    requestSecret = refreshKeyService.getRequestSecret(appKey, appSecret, requestKey, refreshKey);
                }
            } catch (Exception e) {
                log.error("刷新请求密钥失败:{},此次车辆违法查询车牌号为{}", e.getMessage(), hphm);
                return null;
            }
        }
        
        // 号牌种类
        String hpzl = "01";

        // 请求签名
        Long requestTime  = System.currentTimeMillis();
        log.info("请求参数中请求秘钥为：" + requestSecret);
        String sign = Md5Utils.hash(appKey + requestSecret + requestTime);
        String url = "https://interface.zjzwfw.gov.cn/gateway/api/proxy/001003007/dataSharing/Czp71c3856d9gf1a.htm";

        MultiValueMap<String, Object> map = new LinkedMultiValueMap();
        // 附加信息
        map.add("additional","{\"powerMatters\":\"许可-0000-00\",\"subPowerMatters\":\"许可-0000-0101\",\"accesscardId\":\"33071918111111784523\"}");
        map.add("appKey",appKey);
        map.add("requestTime",requestTime);
        map.add("sign",sign);
        map.add("hphm",hphm);
        map.add("hpzl",hpzl);
        HttpHeaders headers = new HttpHeaders();
        headers.add("innerAppKey", innerAppKey);
        HttpEntity<Object> httpEntity = new HttpEntity<>(map, headers);
        log.info("请求参数 :{}", JSON.toJSONString(map));
        String res = restTemplate.postForObject(url, httpEntity, String.class);
        log.info("[RestTemplateTest-车辆违法查询] http request :{}", res);
        return res;
    }

    public static void main(String[] args) {
        // 请求秘钥过期时间
        Long requestSecretEndTime = 1688746680035L;
        //Long requestSecretEndTime = 1688574780035L;
        // 将时间戳转换为Instant对象
        Instant instant = Instant.ofEpochMilli(requestSecretEndTime);
        // 将Instant对象转换为LocalDateTime对象
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        int minute = localDateTime.getMinute();
        System.out.println(minute);
        System.out.println(localDateTime);

        Duration duration = Duration.between(LocalDateTime.now(), localDateTime);
        // 获取相差的小时数
        long hours = duration.toHours();

        System.out.println("相差的小时数：" + hours);
    }
}
