package com.supplier.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.supplier.model.Supplier;
import com.supplier.model.WxWithdrawal;
import com.supplier.service.PersonalServce;
import com.supplier.service.WxPayService;
import com.supplier.service.impl.WxPayConfigImpl;
import com.supplier.util.ParsingToken;
import com.supplier.util.PayToolUtil;
import com.supplier.util.WXPayUtil;
import com.supplier.vx.pay.WxPayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

/**
 * 微信提现
 */
@RestController
@RequestMapping("appWithdrawal")
public class WxCashController extends WxPayUtils {

    @Autowired
    private PersonalServce personalServce;

    @Autowired
    private WxPayService wxPayService;

    /**
     * 微信提现
     * @param money 金额
     * @return 返回结果
     * @throws Exception 异常
     */
    @RequestMapping("wxCash")
    @ResponseBody
    public String cash(String money, HttpServletRequest request) throws Exception {
        SortedMap<String, String> paramMap = new TreeMap<String, String>();
        //获取token
        Map<String, Object> userMap = ParsingToken.tokenParsing(request);
        //获取用户openId
        Supplier supplier = personalServce.getPresonalMessage((String)userMap.get("code"));
        if(null != supplier){
            if(null == supplier.getWxOpenid()){
                return "用户未绑定微信";
            }
        } else {
            return "未找到该用户";
        }

        //随机字符
        WXPayUtil wxPayUtil = new WXPayUtil(); //微信工具类
        PayToolUtil payToolUtil = new PayToolUtil();//数据转换工具类
        String nonce_str = wxPayUtil.generateNonceStr();
        //拼接参数
        String outTradeNo = wxPayUtil.getOrderNo();
        paramMap.put("mch_appid", APPID);
        paramMap.put("mchid", MCHID);
        paramMap.put("nonce_str", nonce_str);
        //提现的订单，恶意刷的可以找回
        paramMap.put("partner_trade_no", outTradeNo);
        paramMap.put("openid", supplier.getWxOpenid());
        paramMap.put("check_name", "NO_CHECK");
        paramMap.put("amount", wxPayUtil.getMoney(money));
        paramMap.put("desc", "提现");
        paramMap.put("spbill_create_ip", NOTIFY_URL);
        // 签名
        String sign = payToolUtil.createSign("UTF-8", paramMap, KEY);
        paramMap.put("sign", sign);

        String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        WXPayConfig config = new WxPayConfigImpl();
        WXPay pay = new WXPay(config);
        String resXml = pay.requestWithCert(url, paramMap, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs());
        //提现对象
        //生成uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        WxWithdrawal wxWithdrawal = new WxWithdrawal()
                .setUuid(uuid)
                .setAmount((Double.parseDouble(money) * 100 + ""))
                .setOutTradeNo(outTradeNo)
                .setCode(supplier.getCode());
        System.out.println("--------------------------------");
        System.out.println(resXml);
        System.out.println("--------------------------------");
        //xml返回结果转换
        Map<String, String> mapVal = wxPayUtil.xmlToMap(resXml);
        if ("SUCCESS".equalsIgnoreCase(mapVal.get("result_code"))) {
            wxPayService.wxCash(wxWithdrawal);//存入提现记录
            return "提现成功";
        } else {
            String err_code = mapVal.get("err_code");
            if ("SYSTEMERROR".equalsIgnoreCase(err_code)) {
                return err_code + "";
            } else if ("NOTENOUGH".equalsIgnoreCase(err_code)) {
                return err_code + "";
            } else {
                //在这把两个常见的错提了出来，剩下的统一为未知错误了，如果做个更好一些可以直接传错误信息。
                return "调用微信提现接口未知错误，请联系管理员！";
            }
        }
    }
}
