package com.miaxis.wx.service.impl;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.miaxis.common.config.WxPayConfigImpl;
import com.miaxis.common.config.WxpayConfig;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.RSAUtils;
import com.miaxis.common.utils.XmlUtil;
import com.miaxis.wx.dto.WxExtractBankDTO;
import com.miaxis.wx.service.IWxExtractService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.TreeMap;

import static com.miaxis.common.utils.OrderCodeFactory.getOrderCode;

@Service
@Slf4j
public class WxExtreactServiceImpl implements IWxExtractService {


    @Autowired
    private WxpayConfig wxpayConfig;

    @Autowired
    private RSAUtils rsaUtils;

    @Override
    public String wxwithbankdrawal(WxExtractBankDTO dto) throws Exception {

        Map<String, String> sortMap = new TreeMap<String, String>();
        sortMap.put("mch_id",wxpayConfig.getMerchantId());
        sortMap.put("nonce_str", RandomStringUtils.randomAlphanumeric(32));
        sortMap.put("partner_trade_no",getOrderCode(null));
        sortMap.put("amount",String.valueOf(dto.getAmount()));
        sortMap.put("desc","用户银行卡提现");


        // 进行签名服务
        sortMap.put("enc_true_name",rsaUtils.encryptData(dto.getEncTrueName()) );
        sortMap.put("enc_bank_no",rsaUtils.encryptData(dto.getEncBankNo()));
        sortMap.put("bank_code",dto.getBankCode().toString());


        WXPayConfig config = new WxPayConfigImpl();
        String sign = WXPayUtil.generateSignature(sortMap, config.getKey(), WXPayConstants.SignType.MD5);
        sortMap.put("sign", sign);
        WXPay pay = new WXPay(config);

        String url = "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank";
       //Map<String, String> resMap;
        String xmlStr = pay.requestWithCert(url, sortMap, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs());
        Map<String, String> resMap = XmlUtil.xmlToMap(xmlStr);
        if (!"SUCCESS".equals(resMap.get("return_code"))||!"SUCCESS".equals(resMap.get("result_code"))){
            throw new CustomException(resMap.get("return_msg"));
        }


        return resMap.get("return_msg");
    }
}
