package com.cftech.pay.api.preid;

import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.cftech.pay.weixin.kit.HttpUtilKit;
import com.cftech.pay.weixin.kit.PaymentKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by user on 2017/5/11.
 */
@Controller
@RequestMapping("/weixin")
@Slf4j
public class WeiXinPreIdController {





    @RequestMapping("/pay/payparm")
    @ResponseBody
    public void payparm(String openId,HttpServletRequest request, HttpServletResponse response){
        try {
            // 获取openid
           //String openId ="oM-EVs39oF027oyR1R9DLlr_Jxzg";//刘凌 oM-EVs3Pz8NEFnM3vmO8sXvjaXjU 老邢 oM-EVs39oF027oyR1R9DLlr_Jxzg HKL oM-EVs-XBSReg8TS5C-K7LKoWOxs
            String appid = "wx82576a6142b4e6ee";// WXConfig.APP_ID;
            String paternerKey = "a7bcea04af0b472facc95153de2c1234";// WXConfig.PERTNER_KEY;
            String mch_id = "1268622101";
            String out_trade_no = createNonceStr();
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put("appid", appid);
            paraMap.put("attach", "测试");
            paraMap.put("body", "测试购买支付");
            paraMap.put("mch_id", mch_id);
            paraMap.put("nonce_str", out_trade_no);
            paraMap.put("openid", openId);
            paraMap.put("out_trade_no", out_trade_no);
            paraMap.put("spbill_create_ip", getIpAddress(request));
            paraMap.put("total_fee", "1");
            paraMap.put("trade_type", "JSAPI");
            paraMap.put("notify_url", "http://faye5.iask.in/pay/weixin/callback/billcheck");// 此路径是微信服务器调用支付结果通知路径
            String sign = PaymentKit.createSign(paraMap, paternerKey);
            paraMap.put("sign", sign);
            // 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

            String xml =PaymentKit.toXml(paraMap);

            String xmlStr = HttpUtilKit.doPost(url, xml);

            // 预付商品id
            String prepay_id = "";

            if (xmlStr.indexOf("SUCCESS") != -1) {
                Map<String, String> map =  PaymentKit.xmlToMap(xmlStr);
                prepay_id = (String) map.get("prepay_id");
            }

          String timeStamp = createTimeStamp();
            String nonceStr = out_trade_no;
            Map<String, String> payMap = new HashMap<String, String>();
            payMap.put("appId", appid);
          payMap.put("timeStamp", timeStamp);
            payMap.put("nonceStr", nonceStr);
            payMap.put("package",  "prepay_id="+prepay_id);
            payMap.put("signType", "MD5");

            String paySign =  PaymentKit.createSign(payMap, paternerKey);

          //  payMap.put("pg", prepay_id);
            payMap.put("paySign", paySign);

            // 拼接并返回json
            StringBuilder sBuilder = new StringBuilder("{");
            sBuilder.append("appId:'").append(appid).append("',")
                    .append("timeStamp:'").append(timeStamp).append("',")
                    .append("nonceStr:'").append(nonceStr).append("',")
                    .append("package:'").append("prepay_id="+prepay_id).append("',")
                    .append("signType:'MD5',")
                    .append("paySign:'").append(paySign).append("'");
            sBuilder.append("}");
            System.out.println(sBuilder.toString());
            response.getWriter().print(sBuilder.toString());
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String createNonceStr()
    {
       return UUID.randomUUID().toString().replace("-","");
    }

    private String createTimeStamp()
    {
        return String.valueOf(System.currentTimeMillis());
    }

    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 参考文章： http://developer.51cto.com/art/201111/305181.htm
     *
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     *
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
     * 192.168.1.100
     *
     * 用户真实IP为： 192.168.1.110
     *
     * @param request
     * @return
     */
    public static String getIpAddress(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.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        int index = ip.indexOf(",");
        if(index!=-1)
        {
            ip = ip.substring(0,index);
        }
        return ip;
    }



}
