package com.yc.ship.module.trade.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class InsuranceRequestHelper {

    /**
     * 请求参数加密加签
     *
     * @param jsonObject 请求公共参数对象
     * @param publicKey   渠道管理方颁发的公钥
     */
    public static void encryptAndSign(JSONObject jsonObject, String publicKey, String privateKey) throws Exception {
        //业务数据加密
        String bizContent = jsonObject.getStr("bizContent");
        String encryptBizContent = SecurityUtils.rsaEncrypt(bizContent, publicKey);
        jsonObject.set("bizContent",encryptBizContent);
        //数据加签
        //要加签的字符串
        String toSignStr = getSortedStr(jsonObject);
        //获得签文 TODO 如果渠道接入方未生成密钥对，则调用 SecurityUtils.md5Sign() 方法进行MD5加签
        String signStr = SecurityUtils.rsaSign(toSignStr, privateKey);
        jsonObject.set("signValue",signStr);
    }

    /**
     * 响应数据验签解密
     * @param insuranceResponse 响应数据对象
     * @param publicKey 渠道管理方颁发的公钥
     * @throws Exception e
     */
    public static void checkSignAndDecrypt(JSONObject insuranceResponse, String publicKey,String privateKey) throws Exception {
        //要验签的字符串
        JSONObject base = JSONUtil.parseObj(JSONUtil.toJsonStr(insuranceResponse));
        base.set("signValue",null);
        String toCheckSignStr = getSortedStr(base);
        //签文
        String signStr = insuranceResponse.getStr("signValue");
        //验签 TODO 如果渠道接入方未生成密钥对，则调用 SecurityUtils.md5CheckSign() 方法进行MD5验签
        boolean checkSign = SecurityUtils.rsaCheckSign(toCheckSignStr, signStr, publicKey);
        if (!checkSign) {
            log.error("[保险]验签失败");
            throw new RuntimeException("验签失败！");
        }
        //解密
        String decrypt = SecurityUtils.rsaDecrypt((String) insuranceResponse.get("data"), privateKey);
        insuranceResponse.set("data",decrypt);
    }

    /**
     * 对属性字典排序输出key:value形式的json
     *
     * @param obj 要排序的对象
     * @return json串
     * @throws Exception e
     */
    private static String getSortedStr(Object obj) throws Exception {
        Map<String, Object> map= JSONUtil.toBean(JSONUtil.toJsonStr(obj),Map.class);
//        })
//        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(obj), new TypeReference<Map<String, Object>>() {
//        });
        TreeMap<String, Object> treeMap = new TreeMap<>(map);
        return JSONUtil.toJsonStr(treeMap);
    }

    public static void main(String[] args) throws Exception{
        String s = "{\"code\":\"200\",\"message\":\"成功\",\"data\":\"co+0XRGrDQawU50G5gN0RfCqh2rKNISB9JspUW+ZlHpc7minRTsepCnjoszycTCM6xgg7mycQS+OK8yLsFPDSpupT2LAlaw7SVeKp2KkWsPMkJdY/ax5NwjCdVW0h9rdQGo3zD4ABxYPD7RE1TDif27DMyX4JECn9hcP2+Swt1qVQIcHixoZD6fvx6/gslgHqu5lCUgYIx9Qrlwr2Oro86qPN1prMlAeasYnxzpb3l74Lg21XE1/rZCKwngPpmgF+ET30vr7IA9DS+haPeqlWuHNwB+QtNLXYz2hjYl7TwP5GbCfo6udGo0BnNT+JaKJzlpzRbesR8SHwZMp1ejY5AIbQWTXdsW53zkzwMPtocm6Jb9pGg/wAYeHr4n5y7r+HlEtAvuFKaXNjvZTDDmwKtIOAXlcuKvadoxN3/6jepz0IBO19zvkbtv2BOTvcg7qqtKNp6/Kiomkxld02czWxYUU+HM4Mh9GNT3r/dGl9TTfi5LeoXp+OL8iT7WvkCugbFNrboVYBmlMw/+QVrURG8eu1i7lz/66YjEiwbfZ8Tc6h/zEMLVxU6jnenzWHjIikzZrQkQCgmOYWszszl+ZRdqzjdqf0YEtDhAbikV6O6oc0UnqobCBnJMNx+9jPzKKUzgrl5KLZjVYNPW7GZ5megYe9JUl6rv0gywYptdcuUuf4sWEP4qSAOY+837K1saCJ9FVT1r57XQCrDxERAg/dvYk+OogFg8HZ8V4T+6GFo9cv02v/pC64KsfuJLnGchBEBp8k5Qj4xJgiN9SkcXi3KR2M49K+cb0Y4kCIlJ03TluOcLuUYzg51VSiOHkucdeEGLxQlsBesnthehXXhhTbA==\",\"signValue\":\"b4HQ8qQxhsybnMLlGTg4eK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klFeqihPIP4FyQJAAXTigPBI/JvjpBc0uckcUbOfniJD6rzfQzF6ZWOKjZrEU+RJtkmEwGk4ZXet6ywzQe33I5n3GfDJ+DkiESLZ0QJANsc2a9daLx4L5eQ06MDf4Li5f03leonnfZlnnPaM9nLY1FXn/r9r+50BjL+e15bkPF7tnoaf0fRo9FeLWd0tjA==");
        //{"head":{"sysFlag":"TK006","taCode":"HCC000316","sendTime":"20250102065113","version":"1.0.0","type":"INPUT","rationType":"P260000207","riskCode":"2700"},"hccResults":[{"policyNo":"STI142700QB46M9W2V00","proposalNo":"TTI142700QB46M9W2V00","premium":"551940.00","orderNo":"BX2501025073791R0P6T","amount":"551940.00","code":"success","msg":"That's great! The Insurance Policy Is Insured successfuly","status":"success","startDate":"2025-01-03 00:00:00","endDate":"2025-01-03 23:59:59","underwriteFlag":"4"}]}
    }
}
