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.HashMap;
import java.util.Objects;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ningdatech.cache.model.cache.CacheKey;
import com.ningdatech.cache.repository.CachePlusOps;
import com.ningdatech.carapi.irs.service.RefreshKeyService;
import com.ningdatech.carapi.irs.utils.HttpUtil;
import com.ningdatech.carapi.irs.utils.Md5Utils;

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

/**
 * @Classname RefreshServieImpl
 * @Description
 * @Date 2023/3/1 16:58
 * @Author PoffyZhang
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RefreshServieImpl implements RefreshKeyService {
    private final CachePlusOps cachePlusOps;
    @Override
    public String refresh() {
        String appkey = "A330000100000202105003941"; // appkey
        Long requestTime = System.currentTimeMillis ();
        HttpUtil httpUtil = HttpUtil.getInstance();
        String requstSecret = "e07fd4471e92410d9860282d939b1217"; // app密钥
        log.info("请求密钥" + requstSecret);
        String sign = Md5Utils.hash (appkey + requstSecret + requestTime);
        String url = String.format ("http://59.202.38.178/gateway/app/refreshTokenByKey.htm" +
                "?appKey=%s&requestTime=%s&sign=%s",appkey,requestTime+"",sign);
        log.info(url);
        String result = httpUtil.sendHttpGet(url);
        log.info(result);
        JSONObject dataJson = JSON.parseObject(result).getJSONObject("datas");
        if(Objects.nonNull(dataJson)){
            return dataJson.getString("requestSecret");
        }
        return result;
    }

    @Override
    public String getRequestSecret(String appKey, String appSecret) {
        Long requestTime  = System.currentTimeMillis();
        // 刷新秘钥
        HttpUtil httpUtil = HttpUtil.getInstance();
        log.info("请求密钥" + appSecret);
        String refreshSign = Md5Utils.hash (appKey + appSecret + requestTime);
        String refreshUrl = String.format ("http://59.202.38.178/gateway/app/refreshTokenByKey.htm" +
                "?appKey=%s&requestTime=%s&sign=%s", appKey, requestTime +"",refreshSign);
        log.info(refreshUrl);
        String result = httpUtil.sendHttpGet(refreshUrl);
        log.info(result);
        JSONObject dataJson = JSON.parseObject(result).getJSONObject("datas");
        if(Objects.nonNull(dataJson)){
            return dataJson.getString("requestSecret");
        }
        return result;
    }

    /**
     * 获取应用的刷新密钥和请求秘钥
     * @param appKey
     * @param appSecret
     * @return
     */
    @Override
    public String getRefreshSecret(String appKey, String appSecret) {
        Long requestTime  = System.currentTimeMillis();
        // 刷新秘钥
        HttpUtil httpUtil = HttpUtil.getInstance();
        log.info("请求密钥" + appSecret);
        String sign = Md5Utils.hash (appKey + appSecret + requestTime);
        HashMap<String, String> params = new HashMap<>();
        //String refreshUrl = String.format ("http://59.202.38.178/gateway/app/refreshTokenByKey.htm" +
        //        "?appKey=%s&requestTime=%s&sign=%s", appKey, requestTime +"",refreshSign);

        String refreshUrl = "https://interface.zjzwfw.gov.cn/gateway/app/refreshTokenByKey.htm";
        params.put("appKey",appKey);
        params.put("sign",sign);
        params.put("requestTime",requestTime + "");
        String result = httpUtil.sendHttpPost(refreshUrl,params);
        log.info(result);
        JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
        if(Objects.nonNull(jsonObject)){
            return jsonObject.getString("datas");
        }
        return result;
    }

    @Override
    public String refreshSecret(String appKey, String refreshSecret) {
        Long requestTime  = System.currentTimeMillis();
        // 刷新秘钥
        HttpUtil httpUtil = HttpUtil.getInstance();
        log.info("刷新密钥" + refreshSecret);
        String refreshSign = Md5Utils.hash (appKey + refreshSecret + requestTime);
        HashMap<String, String> params = new HashMap<>();

        String refreshUrl = "https://interface.zjzwfw.gov.cn/gateway/app/refreshTokenBySec.htm";
        params.put("appKey",appKey);
        params.put("sign",refreshSign);
        params.put("requestTime",requestTime + "");
        String result = httpUtil.sendHttpPost(refreshUrl,params);
        log.info(result);
        JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
        if(Objects.nonNull(jsonObject)){
            return jsonObject.getString("datas");
        }
        return result;
    }

    @Override
    public String getRequestSecret(String appKey, String appSecret, CacheKey requestKey, CacheKey refreshKey) {
        String requestSecret;
        String refreshSecret;
        String result = getRefreshSecret(appKey, appSecret);
        JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
        if (Objects.nonNull(jsonObject)) {
            refreshSecret = jsonObject.getString("refreshSecret");
            requestSecret = jsonObject.getString("requestSecret");
            // 请求秘钥过期时间
            Long requestSecretEndTime = jsonObject.getLong("requestSecretEndTime");
            // 刷新密钥过期时间
            Long refreshSecretEndTime = jsonObject.getLong("refreshSecretEndTime");

            LocalDateTime requestEndTime = getEndTime(requestSecretEndTime);
            LocalDateTime refreshEndTime = getEndTime(refreshSecretEndTime);
            LocalDateTime startTime = LocalDateTime.now();
            // 请求秘钥有效期(分钟),提前1分钟刷新
            Duration minuteDuration = Duration.between(startTime, requestEndTime);
            long minute = minuteDuration.toMinutes() - 1;
            // 刷新密钥有效期(小时),提前1小时刷新
            Duration hourDuration = Duration.between(startTime, refreshEndTime);
            // 获取相差的小时数,并提前1小时刷新
            long hour = hourDuration.toHours() - 1;
            log.info("刷新秘钥有效期：" + hour);
            if (Objects.nonNull(requestSecret)) {
                // 请求秘钥,有效期15分钟
                requestKey.setExpire(Duration.ofMinutes(minute));
                cachePlusOps.set(requestKey, requestSecret, Boolean.TRUE);
            }else {
                return null;
            }
            if (Objects.nonNull(refreshSecret)) {
                // 刷新密钥,有效期48小时
                refreshKey.setExpire(Duration.ofHours(hour));
                cachePlusOps.set(refreshKey, refreshSecret, Boolean.TRUE);
            }else {
                return null;
            }
        }else {
            return null;
        }
        return requestSecret;
    }

    private LocalDateTime getEndTime(Long requestSecretEndTime) {
        // 将时间戳转换为Instant对象
        Instant instant = Instant.ofEpochMilli(requestSecretEndTime);
        // 将Instant对象转换为LocalDateTime对象
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    @Override
    public String refreshRequestSecret(String appKey, CacheKey requestKey, CacheKey refreshKey, String refreshSecret) {
        String requestSecret;
        String result = refreshSecret(appKey, refreshSecret);
        JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
        if (Objects.nonNull(jsonObject)) {
            refreshSecret = jsonObject.getString("refreshSecret");
            requestSecret = jsonObject.getString("requestSecret");
            // 请求秘钥过期时间
            Long requestSecretEndTime = jsonObject.getLong("requestSecretEndTime");
            // 刷新密钥过期时间
            Long refreshSecretEndTime = jsonObject.getLong("refreshSecretEndTime");

            LocalDateTime requestEndTime = getEndTime(requestSecretEndTime);
            LocalDateTime refreshEndTime = getEndTime(refreshSecretEndTime);
            LocalDateTime startTime = LocalDateTime.now();
            // 请求秘钥有效期(分钟),提前1分钟刷新
            Duration minuteDuration = Duration.between(startTime, requestEndTime);
            long minute = minuteDuration.toMinutes() - 1;
            log.info("请求秘钥有效期：" + minute);
            // 刷新密钥有效期(小时),提前1小时刷新
            Duration duration = Duration.between(startTime, refreshEndTime);
            // 获取相差的小时数,并提前1小时刷新
            long hour = duration.toHours() - 1;
            log.info("刷新秘钥有效期：" + hour);
            if (Objects.nonNull(requestSecret)) {
                // 请求秘钥,有效期15分钟
                requestKey.setExpire(Duration.ofMinutes(minute));
                cachePlusOps.set(requestKey, requestSecret, Boolean.TRUE);
            }else {
                return null;
            }
            if (Objects.nonNull(refreshSecret)) {
                // 刷新密钥,有效期48小时
                refreshKey.setExpire(Duration.ofHours(hour));
                cachePlusOps.set(refreshKey, refreshSecret, Boolean.TRUE);
            }else {
                return null;
            }
        }else {
            return null;
        }
        return requestSecret;
    }

    public static void main(String[] args) {
//        String appkey = "A330000100000202105003941"; // appkey
//        Long requestTime = System.currentTimeMillis ();
//        System.out.println(requestTime);
//        String requstSecret = "e07fd4471e92410d9860282d939b1217"; // app密钥
//        String sign = Md5Utils.hash (appkey + requstSecret + requestTime);
//        System.out.println(sign);

        System.out.println("7520d721086111e7985b008cfaeb3d74".length());
    }
}
