package com.lightinit.hsdataportal.WXsdk;

import com.lightinit.hsdataportal.dictionary.DicWXPayInfo;
import com.lightinit.hsdataportal.entity.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class MyWXUtils {

    private static Logger logger = LoggerFactory.getLogger(MyWXUtils.class);

    //获取当前自己ip
    public static String getRemoteHost(javax.servlet.http.HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }

    //微信合成参数验证签名是否正确
    public static Map<String, String> getPrepayid(String orderNumber, Order order, String ip) throws Exception {
        logger.info("-------------验证签名开始-----------------------");
        Map<String, String> map = new HashMap<String, String>();
        map.put("appid", DicWXPayInfo.APPID);
        map.put("mch_id", DicWXPayInfo.MCHID);
        map.put("nonce_str", WXPayUtil.generateNonceStr());
        map.put("body", "衡水大数据开放平台");
        map.put("out_trade_no", orderNumber);
       String str  = order.getOrderAmount().multiply(BigDecimal.valueOf(100)).intValue()+"" ;
        map.put("total_fee",str) ;
//        map.put("total_fee", "1");
        map.put("spbill_create_ip", ip);
        map.put("notify_url", DicWXPayInfo.NOTIFYURL);
        map.put("trade_type", "NATIVE");
        String sign = WXPayUtil.generateSignature(map, DicWXPayInfo.KEY);
        map.put("sign", sign);
        logger.info("sign={}", sign);
        logger.info("-------------结束-----------------------");
        return map;
    }

}
