package com.ics.controller.mobile.pay.wx;

import com.google.gson.Gson;
import com.ics.controller.mobile.pay.wx.constant.WxApiConstants;
import com.ics.controller.mobile.pay.wx.dto.WxChatBasePayDto;
import com.ics.controller.mobile.pay.wx.dto.WxChatPayDto;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.Signature;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class WxPayCommon {

    @Autowired
    WxPayConfig wxPayConfig;


    /**
     * 封装基础通用请求数据
     *
     * @param basePayData 微信支付基础请求数据
     * @return 封装后的map对象
     */
    public Map<String, Object> getBasePayParams(WxChatBasePayDto basePayData) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("appid", wxPayConfig.getAppid());
        paramsMap.put("mchid", wxPayConfig.getMchId());
        // 如果商品名称过长则截取
        String title = basePayData.getDescription().length() > 120 ? basePayData.getDescription().substring(0, 120) : basePayData.getDescription();
        paramsMap.put("description", title);
        paramsMap.put("out_trade_no", basePayData.getOrderId());
        paramsMap.put("notify_url", wxPayConfig.getNotifyDomain().concat(basePayData.getNotify()));
        Map<String, Integer> amountMap = new HashMap<>();
        amountMap.put("total", basePayData.getPrice().multiply(new BigDecimal("100")).intValue());
        paramsMap.put("amount", amountMap);
        return paramsMap;
    }

    /**
     * 获取请求对象（Post请求）
     *
     * @param paramsMap 请求参数
     * @return Post请求对象
     */
    public HttpPost getHttpPost(String url, Map<String, Object> paramsMap) {
        // 1.设置请求地址
        HttpPost httpPost = new HttpPost(wxPayConfig.getDomain().concat(url));

        // 2.设置请求数据
        Gson gson = new Gson();
        String jsonParams = gson.toJson(paramsMap);

        // 3.设置请求信息
        StringEntity entity = new StringEntity(jsonParams, "utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        return httpPost;
    }

    /**
     * 获取请求对象（Get请求）
     *
     * @return Get请求
     */
    public HttpGet getHttpGet(String url) {
        // 1.设置请求地址
        HttpGet httpGet = new HttpGet(wxPayConfig.getDomain().concat(url));
        // 3.设置请求信息
        httpGet.setHeader("Accept", "application/json");
        return httpGet;
    }


    /**
     * 解析响应数据
     *
     * @param response 发送请求成功后，返回的数据
     * @return 微信返回的参数
     */
    public HashMap<String, String> resolverResponse(CloseableHttpResponse response) {
        try {
            // 1.获取请求码
            int statusCode = response.getStatusLine().getStatusCode();
            // 2.获取返回值 String 格式
            final String bodyAsString = EntityUtils.toString(response.getEntity());

            Gson gson = new Gson();
            if (statusCode == 200) {
                // 3.如果请求成功则解析成Map对象返回
                HashMap<String, String> resultMap = gson.fromJson(bodyAsString, HashMap.class);
                return resultMap;
            } else {
                if (StringUtils.isNoneBlank(bodyAsString)) {
                    System.out.println("微信支付请求失败，提示信息:{}" + bodyAsString);
                    // 4.请求码显示失败，则尝试获取提示信息
                    HashMap<String, String> resultMap = gson.fromJson(bodyAsString, HashMap.class);
                    throw new RuntimeException(resultMap.get("message"));
                }
                System.out.println("微信支付请求失败，未查询到原因，提示信息:{}" + response.toString());
                // 其他异常，微信也没有返回数据，这就需要具体排查了
                throw new IOException("request failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取签名
     *
     * @param nonceStr  随机数
     * @param appId     微信公众号或者小程序等的appid
     * @param prepay_id 预支付交易会话ID
     * @param timestamp 时间戳 10位
     * @return String 新签名
     */
    String getSign(String nonceStr, String appId, String prepay_id, long timestamp) {

        //从下往上依次生成
        String message = buildMessage(appId, timestamp, nonceStr, prepay_id);
        //签名
        try {
            return sign(message.getBytes("utf-8"));
        } catch (IOException e) {
            throw new RuntimeException("签名异常,请检查参数或商户私钥");
        }
    }

    String sign(byte[] message) {
        try {
            //签名方式
            Signature sign = Signature.getInstance("SHA256withRSA");
            //私钥，通过MyPrivateKey来获取，这是个静态类可以接调用方法 ，需要的是_key.pem文件的绝对路径配上文件名
            sign.initSign(PemUtil.loadPrivateKey(new FileInputStream(wxPayConfig.getPrivateKeyPath())));
            sign.update(message);
            return Base64.getEncoder().encodeToString(sign.sign());
        } catch (Exception e) {
            throw new RuntimeException("签名异常,请检查参数或商户私钥");
        }
    }

    /**
     * 按照前端签名文档规范进行排序，\n是换行
     *
     * @param nonceStr  随机数
     * @param appId     微信公众号或者小程序等的appid
     * @param prepay_id 预支付交易会话ID
     * @param timestamp 时间戳 10位
     * @return String 新签名
     */
    String buildMessage(String appId, long timestamp, String nonceStr, String prepay_id) {
        return appId + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + prepay_id + "\n";
    }


    /**
     * 创建微信支付订单-jsapi方式
     *
     * @param basePayData 基础请求信息，商品标题、商家订单id、订单价格
     * @return 微信支付二维码地址
     */
    public String wxJsApiPay(WxChatBasePayDto basePayData) {
        // 1.获取请求参数的Map格式
        Map<String, Object> paramsMap = getBasePayParams(basePayData);
        // 1.1 添加支付者信息
        Map<String, String> payerMap = new HashMap();
        payerMap.put("openid", basePayData.getOpenId());
        paramsMap.put("payer", payerMap);

        // 2.获取请求对象
        HttpPost httpPost = getHttpPost(WxApiConstants.JSAPI_PAY, paramsMap);

        // 3.完成签名并执行请求
        CloseableHttpResponse response = null;
        try {
            response = wxPayConfig.getWxPayClient().execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("微信支付请求失败");
        }

        // 4.解析response对象
        HashMap<String, String> resultMap = resolverResponse(response);
        if (resultMap != null) {
            // 【预支付交易会话标识】 预支付交易会话标识。用于后续接口调用中使用，该值有效期为2小时
            return resultMap.get("prepay_id");
        }
        return null;
    }

    /**
     * 微信用户调用微信支付
     */
    public WxChatPayDto wxPayCall(String prepayId) {
        WxChatPayDto wxChatPayDto = new WxChatPayDto();
        wxChatPayDto.setAppid(wxPayConfig.getAppid());
        wxChatPayDto.setTimeStamp(String.valueOf(System.currentTimeMillis() / 1000));
        wxChatPayDto.setNonceStr(UUID.randomUUID().toString().replaceAll("-", ""));
        wxChatPayDto.setPrepayId("prepay_id=" + prepayId);
        wxChatPayDto.setSignType("RSA");
        wxChatPayDto.setPaySign(getSign(wxChatPayDto.getNonceStr(), wxChatPayDto.getAppid(), wxChatPayDto.getPrepayId(), Long.parseLong(wxChatPayDto.getTimeStamp())));

        return wxChatPayDto;
    }


    /**
     * 商户订单号查询订单
     */
    public HashMap<String, String> wxMerchantOrderQuery(String outTradeNo) {
        // 创建请求
        HttpGet httpGet = getHttpGet(WxApiConstants.MERCHANT_ORDER_NUMBER_QUERY + "/" + outTradeNo + "?mchid=" + wxPayConfig.getMchId());
        // 完成签名并执行请求
        CloseableHttpResponse response = null;
        try {
            response = wxPayConfig.getWxPayClient().execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("商户订单号查询订单请求失败");
        }
        // 解析response对象
        HashMap<String, String> resultMap = resolverResponse(response);
        return resultMap;
    }


}
