package com.supplier.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.supplier.model.WxPay;
import com.supplier.model.WxRefund;
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.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 微信退款
 */
@RestController
@RequestMapping("wxRefund")
public class WxRefundContoller extends WxPayUtils {

    @Autowired
    private WxPayService wxPayService;
    //appid
    private static String APPID = "wxc2d9b6a59eccffe5";
    //商户号
    private static String MCHID = "1629374258";
    //秘钥
    private static String KEY = "ueYnFyZimfIkejHrags9grqvHyekdXGa";


    /**
     * 微信退款
     * @param money 金额
     * @param wxPay 报价单编号
     * @return 返回结果
     * @throws Exception 异常
     */
    @RequestMapping("refund")
    @ResponseBody
    public static Map<String, Object> refund(String money, WxPay wxPay) throws Exception {
        //提示信息
        Map<String, Object> mapReturn = new HashMap<>();
        //配置请求微信退款的参数
        SortedMap<String, String> map = new TreeMap<String, String>();
        //拼接参数
        WXPayUtil wxPayUtil = new WXPayUtil(); //微信工具类
        PayToolUtil payToolUtil = new PayToolUtil();//数据转换工具类
        String outTradeNo = wxPayUtil.getOrderNo();
        String nonce_str = wxPayUtil.generateNonceStr();
        map.put("appid", APPID);
        map.put("mch_id", MCHID);
        map.put("nonce_str", nonce_str);
        map.put("transaction_id", wxPay.getPrepayId());
        map.put("out_refund_no", outTradeNo);
        map.put("out_trade_no", wxPay.getOutTradeNo());
        map.put("total_fee", wxPayUtil.getMoney(wxPay.getTotalFee()));//这里必须是支付时候的下单金额，特别是分批次退款的时候注意这里，不然微信提示：订单金额或退款金额与之前请求不一致，请核实后再试
        map.put("refund_fee", wxPayUtil.getMoney(money));//这里是需要退款的金额

        // 签名
        String sign = payToolUtil.createSign("UTF-8", map, KEY);
        map.put("sign", sign);

        String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        WXPayConfig config = new WxPayConfigImpl();
        WXPay pay = new WXPay(config);
        String resXml = pay.requestWithCert(url, map, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs());
        //xml返回结果转换
        Map<String, String> mapVal = wxPayUtil.xmlToMap(resXml);
        System.out.println(mapVal);
        if ("SUCCESS".equalsIgnoreCase(mapVal.get("result_code"))) {
            mapReturn.put("msg", "200");
            mapReturn.put("data", "退款成功");
        } else {
            mapReturn.put("msg", "500");
            mapReturn.put("data", "退款失败");
        }
        return mapReturn;
    }

    /**
     * 查询待审核退款单
     * @param wxRefund 参数
     * @param request 参数
     * @return 返回结果
     */
    @GetMapping("getUserRefund")
    public Map<String, Object> getUserRefund(WxRefund wxRefund, HttpServletRequest request){
        //获取token
        Map<String, Object> userMap = ParsingToken.tokenParsing(request);
        wxRefund.setCode((String) userMap.get("code"));
        return wxPayService.getUserRefund(wxRefund);
    }

    /**
     * 查询已审核的退款单
     * @param wxRefund 参数
     * @param request 参数
     * @return 返回结果
     */
    @GetMapping("getAuditRefund")
    public Map<String, Object> getAuditRefund(WxRefund wxRefund, HttpServletRequest request){
        //获取token
        Map<String, Object> userMap = ParsingToken.tokenParsing(request);
        wxRefund.setCode((String) userMap.get("code"));
        return wxPayService.getAuditRefund(wxRefund);
    }

    /**
     * 退款审批
     * @param wxRefund 参数
     * @return 返回结果
     */
    @PutMapping("refusedRefund")
    public Map<String, Object> refusedRefund(WxRefund wxRefund){
        return wxPayService.refusedRefund(wxRefund);
    }
}
