package com.cpop.pay.framewok.handler.wxPay;

import com.cpop.core.utils.SpringUtils;
import com.cpop.pay.framewok.config.wxPay.WxPayConfiguration;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author DB
 * @version 1.0.0
 * @since 2024-02-22 20:10
 */
@Component
public class WxPayNormalHandler {

    @Autowired
    private WxUtils wxUtils;

    public <T> T createOrder(String orderId,String openId, BigDecimal price, String body, String ipAddress,String notifyUrl) throws IOException {
        SortedMap<String, Object> parameters = new TreeMap<String, Object>();
        parameters.put("appid", "wx20853d18c455e874");
        parameters.put("mch_id", "1618436087");
        parameters.put("openid", openId);
        // 默认 "WEB"
        parameters.put("device_info", "WEB");
        parameters.put("body", body);
        // 32 位随机字符串
        parameters.put("nonce_str", wxUtils.gen32RandomString());
        parameters.put("notify_url", notifyUrl);
        parameters.put("out_trade_no", orderId);
        parameters.put("total_fee", price.multiply(BigDecimal.valueOf(100)).intValue());
        // parameters.put("total_fee", 1); // 测试时，将支付金额设置为 1 分钱
        parameters.put("spbill_create_ip", ipAddress);
        parameters.put("trade_type", "JSAPI");
        // sign 必须在最后
        parameters.put("sign", wxUtils.createSign(parameters, "JamBox20220329174000000000000002"));
        // 执行 HTTP 请求，获取接收的字符串（一段 XML）
        String result = wxUtils.executeHttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder", parameters);
        return wxUtils.createSign2(result, "JamBox20220329174000000000000002");
    }

    public String fail() {
        return "<xml>\n" +
                "  <return_code><![CDATA[FAIL]]></return_code>\n" +
                "  <return_msg><![CDATA[]]></return_msg>\n" +
                "</xml>";
    }

    public String success() {
        return "<xml>\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>";
    }
}
