package com.ningdatech.kqapi.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Classname RefreshKeyUtil
 * @Description
 * @Date 2023/6/27 10:03
 * @Author PoffyZhang
 */
@Slf4j
public class RefreshKeyUtil {
    public static String getRequestSecret(String appKey, String appSecret,Long requestTime) throws IOException {
        // 刷新秘钥
        HttpUtil httpUtil = HttpUtil.getInstance();
        log.info("请求密钥" + appSecret);
        String sign = Md5Utils.hash (appKey + appSecret + requestTime);
        String refreshUrl = "http://interface.zjzwfw.gov.cn/gateway/app/refreshTokenByKey.htm";
        log.info(refreshUrl);
        Map<String,String> map = new HashMap<>();
        map.put("appKey",appKey);
        map.put("sign",sign);
        map.put("requestTime",requestTime + "");
        String result = httpUtil.sendHttpPost(refreshUrl,map);
        log.info(result);
        JSONObject dataJson = JSON.parseObject(result).getJSONObject("datas");
        if(Objects.nonNull(dataJson)){
            return dataJson.getString("requestSecret");
        }
        return result;
    }

    public static String refreshSecret(String appKey, String refreshSecret,Long requestTime) throws IOException {
        // 刷新秘钥
        HttpUtil httpUtil = HttpUtil.getInstance();
        log.info("刷新密钥" + refreshSecret);
        String refreshSign = Md5Utils.hash (appKey + refreshSecret + requestTime);
        String refreshUrl = "http://interface.zjzwfw.gov.cn/gateway/app/refreshTokenBySec.htm";
        log.info(refreshUrl);
        Map<String,String> map = new HashMap<>();
        map.put("appKey",appKey);
        map.put("sign",refreshSign);
        map.put("requestTime",requestTime + "");
        String result = httpUtil.sendHttpPost(refreshUrl,map);
        log.info(result);
        JSONObject dataJson = JSON.parseObject(result).getJSONObject("datas");
        if(Objects.nonNull(dataJson)){
            return dataJson.getString("requestSecret");
        }
        return result;
    }
}
