package org.springblade.community.pay.wx.util;

import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.model.UnifiedOrderModel;
import lombok.extern.slf4j.Slf4j;
import org.springblade.community.pay.wx.config.WxPayConfig;
import org.springblade.community.pay.wx.exception.WxPayException;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class WxPayUtil {
	/**
	 * 微信支付配置
	 */
	private static WxPayConfig wxPayConfig;

	/**
	 * 初始化
	 * @param wxPayConfig
	 */
	public WxPayUtil(WxPayConfig wxPayConfig) {
		WxPayUtil.wxPayConfig = wxPayConfig;
	}

	/**
	 * 创建微信支付H5模式
	 * @param unifiedOrderModel
	 * @return
	 * @throws WxPayException
	 */
	public static Map<String,String> createWxPayOfH5(UnifiedOrderModel unifiedOrderModel) throws WxPayException {
		unifiedOrderModel.setTrade_type(TradeType.MWEB.getTradeType());
		return createWxPay(unifiedOrderModel);
	}

	/**
	 * 创建微信支付小程序或公众号模式
	 * @param unifiedOrderModel
	 * @return
	 * @throws WxPayException
	 */
	public static Map<String,String> createJSAPI(UnifiedOrderModel unifiedOrderModel) throws WxPayException {
		unifiedOrderModel.setTrade_type(TradeType.JSAPI.getTradeType());
		return createWxPay(unifiedOrderModel);
	}

	/**
	 * 构建UnifiedOrderModel
	 * @return
	 */
	public static UnifiedOrderModel.UnifiedOrderModelBuilder buildUnifiedOrderModel(){
		return UnifiedOrderModel
			.builder()
			.appid(wxPayConfig.getAppId())
			.mch_id(wxPayConfig.getMchId())
			.nonce_str(WxPayKit.generateStr())
			.out_trade_no(WxPayKit.generateStr())
			.notify_url(wxPayConfig.getNotifyUrl())
			.trade_type(TradeType.MWEB.getTradeType());
	}

	/**
	 * 创建支付
	 * @param unifiedOrderModel
	 * @return
	 * @throws WxPayException
	 */
	private static Map<String,String> createWxPay(UnifiedOrderModel unifiedOrderModel) throws WxPayException {
		try {
			Map<String, String> params = unifiedOrderModel.createSign(wxPayConfig.getApiKey(), SignType.HMACSHA256);

			String xmlResult = WxPayApi.pushOrder(false, params);
			log.info(xmlResult);

			Map<String, String> result = WxPayKit.xmlToMap(xmlResult);

			String return_code = result.get("return_code");
			String return_msg = result.get("return_msg");
			if (!WxPayKit.codeIsOk(return_code)) {
				throw new RuntimeException(return_msg);
			}
			String result_code = result.get("result_code");
			if (!WxPayKit.codeIsOk(result_code)) {
				throw new RuntimeException(return_msg);
			}
			// 以下字段在return_code 和result_code都为SUCCESS的时候有返回

			String prepayId = result.get("prepay_id");
			String webUrl = result.get("mweb_url");

			log.info("prepay_id:" + prepayId + " mweb_url:" + webUrl);

			return result;
		} catch (Exception e) {
			log.error("微信支付错误信息: {}", e.getMessage());
			throw new WxPayException(e);
		}
	}
}
