package com.izouma.nineth.utils.sandpay;

import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.config.SandpayProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 新支付平台客户端
 *
 */
@Slf4j
public class SandpayNewClient {

    private SandpayProperties sandpayProperties;


    public SandpayNewClient(SandpayProperties sandpayProperties) {
        this.sandpayProperties = sandpayProperties;
    }





    /**
     * 创建签名数据
     * @param allData
     * @return
     * @throws Exception
     */
    private String createSignData(JSONObject allData){
        Map<String,Object> sortedMap = new TreeMap<>();
        sortedMap.putAll(allData);
        //移除不参与签名的数据
        sortedMap.remove("expire_time");
        sortedMap.remove("goods_name");
        sortedMap.remove("product_code");
        sortedMap.remove("clear_cycle");
        sortedMap.remove("jump_scheme");
        sortedMap.remove("sign");
        sortedMap.remove("limit_pay");
        sortedMap.remove("extend_params");
        sortedMap.remove("meta_option");
        StringBuilder signData = new StringBuilder();
        sortedMap.forEach((key,value) -> {
            String valueStr = Objects.toString(value, "");
            if(StringUtils.isNotEmpty(valueStr)){
                signData.append(key + "=" + valueStr);
                signData.append("&");
            }

        });
        signData.append("key=" + sandpayProperties.getNewMd5Key());


        String signStr = DigestUtils.md5Hex(signData.toString()).toUpperCase();

        log.info("接口拼接签名原始字符串：{}, MD5:{} " , signData, signStr);
        return signStr;

    }



    /**
     * 组报文
     */
    private JSONObject createRequestData(JSONObject data){
        // 补充报文信息
        data.put("version", "10");//版本
        data.put("mer_no", sandpayProperties.getMid());
        data.put("mer_key",sandpayProperties.getNewMerKey());
        data.put("sign_type","MD5");

        //创建签名
        String sign = createSignData(data);
        data.put("sign",sign);


        return data;
    }


    /**
     * 拼接请求地址
     * @return
     * @throws Exception
     */
    public String generateUrl(String tradePath, JSONObject bodyJson){
        String url;
        if(tradePath.matches("^http(s?)://.+")){
            url  = tradePath;
        }else{
            url = StringUtils.stripEnd(sandpayProperties.getNewGateWay(), "/") + tradePath;
        }

        JSONObject data = createRequestData(bodyJson);
        log.info("接口请求数据，地址：{}， 数据：{}", url, data);

        String query = UrlQuery.of(data, true).build(StandardCharsets.UTF_8);
        String fullUrl = url + "?" + query;
        return fullUrl;
    }



}
