package com.yiqi.common.utils.pay;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiaohei
 * @date 2024/1/28
 */
public class WXPayV2Utils {

    private WXPayV2Utils(){}

    private static Log log = LogFactory.getLog(WXPayV2Utils.class);

    /**
     * 扫码支付
     * @throws Exception
     */
    public static String scanCodeToPay(String auth_code) throws Exception {
        WxPayV2Config config = new WxPayV2Config();
        WXPay wxpay = new WXPay(config);
        String out_trade_no = "";
        Map<String, String> map = new HashMap<>(16);
        map.put("attach", "订单额外描述");
        map.put("auth_code", auth_code);
        map.put("body", "付款码支付测试");
        map.put("device_info", "1000");
        map.put("nonce_str", WXPayUtil.generateNonceStr());
        map.put("out_trade_no", out_trade_no);
        map.put("spbill_create_ip", "14.17.22.52");
        map.put("total_fee", "2");
        //生成签名
        String sign = WXPayUtil.generateSignature(map, config.getKey());
        map.put("sign", sign);
        String mapToXml = null;
        try {
            //调用微信的扫码支付接口
            Map<String, String> resp = wxpay.microPay(map);
            mapToXml = WXPayUtil.mapToXml(resp);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("微信支付失败"+ e);
        }
        //判断支付是否成功
        String return_code = null;
        String result_code = null;
        String err_code_des = null;
        String err_code = null;
        //获取Document对象（主要是获取支付接口的返回信息）
        Document doc = DocumentHelper.parseText(mapToXml);
        //获取对象的根节点<xml>
        Element rootElement = doc.getRootElement();
        //获取对象的子节点
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            if(element.getName().equals("return_code")){
                return_code = element.getTextTrim();
            } else if(element.getName().equals("result_code")){
                result_code = element.getTextTrim();
            } else if(element.getName().equals("err_code_des")){
                err_code_des = element.getTextTrim();
            } else if(element.getName().equals("err_code")){
                err_code = element.getTextTrim();
            }
        }
        if(WxPayV2Config.PAY_SUCCESS.equals(return_code) && WxPayV2Config.PAY_SUCCESS.equals(result_code)){
            log.info("微信免密支付成功！");
            return WxPayV2Config.PAY_SUCCESS;
        } else if (WxPayV2Config.PAY_USERPAYING.equals(err_code)){
            for(int i = 0; i < 4; i++){
                Thread.sleep(3000);
                Map<String, String> data = new HashMap<>(16);
                data.put("out_trade_no", out_trade_no);
                //调用微信的查询接口
                Map<String, String> orderQuery = wxpay.orderQuery(data);
                String orderResp = WXPayUtil.mapToXml(orderQuery);
                String trade_state = null;
                //获取Document对象
                Document orderDoc = DocumentHelper.parseText(orderResp);
                //获取对象的根节点<xml>
                Element rootElement1 = orderDoc.getRootElement();
                //获取对象的子节点
                List<Element> elements1 = rootElement1.elements();
                for (Element element : elements1) {
                    if(element.getName().equals("trade_state")){
                        trade_state = element.getTextTrim();
                    }
                }
                if(WxPayV2Config.PAY_SUCCESS.equals(trade_state)){
                    log.info("微信加密支付成功！");
                    return WxPayV2Config.PAY_SUCCESS;
                }
                log.info("正在支付" + orderResp);
            }
        }
        log.error("微信支付失败！");
        return err_code_des;
    }
}
