package com.bohuikeji.delivery.backstage.controller.api.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.constants.WxAppEm;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.listener.pay.WeChartListener;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.sys.SysError;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.utils.wx.wxPayUtil;
import com.bohuikeji.frame.module.admin.wxpay.WXPayUtil;
import com.bohuikeji.frame.module.admin.wxpayv3.WxPayV3Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;


/**
 * @author zhouliwu
 * 支付相关接口
 * 注：所以接口类必须继承 ApiController，否则无法被接口文档识别
 */
@Api(tags = {"微信v3版本支付相关接口"})
@RestController
@Slf4j
@RequestMapping("/api/v2/wxPay")
public class WxPayV2Api extends ApiController {
    @Autowired
    ITOrderService itOrderService;
    @Autowired
    ITPayService payService;
    @Autowired
    ITCourierPayService courierPayService;
    @Autowired
    ITCustomerWalletService customerWalletService;
    @Autowired
    ITCustomerPayService customerPayService;
    @Autowired
    ITRefundService refundService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ISysConfigService configService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    MqTool mqTool;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 微信/支付宝收款码付款
     * （客户出示付款码，商家扫码后支付成功）
     *
     * @param tOrder
     * @return
     * @throws AlipayApiException
     */
    @ApiOperation("微信扫码支付补充支付（补充支付）")
    @PostMapping("/wxCodePay")
    public APIEntity aliPay(@RequestBody TOrder tOrder, HttpServletRequest request) {
        log.info("订单补付金额=[{}]", tOrder.getOrderFactPrice());
        TCourier courier = courierService.getById(tOrder.getCourierId());
        if (courier == null) {
            log.error("支付失败，未找到该订单的骑手信息。");
            return APIEntity.fail("支付失败，未找到该订单的骑手信息，请派送员重新登陆！").setStatus(412);
        }
        String CODE = tOrder.getPayWay();
        TPay pay = payService.getOne(new QueryWrapper<TPay>().eq("order_id", tOrder.getOrderId()).in("pay_status", "待付款"));
        if (pay != null) {
            if (payService.wxAlipay(pay, tOrder, request) == true) {
                return APIEntity.success("支付成功");
            } else {
                return APIEntity.fail("支付失败，请联系管理员！");
            }
        }
        //微信付款码
        if (wxPayUtil.contain(CODE.substring(0, 2))) {
            pay = payService.createBeforePay(tOrder, "补充支付", "客户支付", "微信");
            if (payService.wxAlipay(pay, tOrder, request) == true) {
                return APIEntity.success("支付成功");
            } else {
                return APIEntity.fail("支付失败，请联系管理员！");
            }
        }
        //支付宝付款吗
        else if ("28".equals(CODE.substring(0, 2))) {
            pay = payService.createBeforePay(tOrder, "补充支付", "客户支付", "支付宝");
            //发起支付请求
            AlipayTradePayResponse response = AliPay.alipaycode(tOrder.getPayWay(), pay.getPayNum(), tOrder.getOrderFactPrice().toString(), "同城急送");
            return response == null ? APIEntity.fail("支付失败，请联系管理员！") : APIEntity.success();
        } else {
            return APIEntity.fail("无法识别的付款码");
        }
    }

    @ApiOperation("微信小程序/App补充支付（派送员代缴——暂未接通）")
    @GetMapping("/pay/behalf")
    public APIEntity payBehalf(@RequestAttribute("JwtUserId") Integer id, Integer orderId, String price,String type, HttpServletRequest request) throws Exception {
        if (!StringUtils.isPrice(price)) {
            return APIEntity.fail("无法识别订单金额，请检查格式是否正确！！");
        }
        log.info("参数：[{}],[{}]", id, orderId);
        TOrder order = itOrderService.getById(orderId);
        if (order == null) {
            log.error("未找到该订单信息");
            return APIEntity.fail("未找到该订单信息！");
        }
        if (order.getCourierId() == null) {
            log.error("【派送员订单代缴接口异常】，无法找到派送员信息！");
            SysError.saveError("【派送员订单代缴接口异常】，无法找到派送员信息！，当前订单实体={0}", order);
            return APIEntity.fail("无法找到派送员信息，请尝试重新登陆或者，联系平台核实！");
        }
        if (!order.getCourierId().equals(id)) {
            log.error("订单与派送员不批配，无法完成支付");
            return APIEntity.fail("订单与派送员不批配，无法完成支付");
        }
        TPay pay = payService.getOne(new QueryWrapper<TPay>().eq("order_id", order.getOrderId()).in("pay_status", "待付款"));
        log.info("派送员代缴，是否有支付记录的查询:[{}]", pay);
        JSONObject object = null;
        if("APP".equals(type)){
            if ("取件中".equals(order.getOrderStatus())) {
                pay = payService.createBeforePay(order, "补充支付", "骑手代付", "微信");
                String prepayId = WxPayV3Util.V3couAppPay("v3/pay/transactions/app", pay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(new BigDecimal(price))), "业务订单支付", request);
                object = JSONObject.parseObject(WxPayV3Util.couAppTuneUp(prepayId).toString());
            }
        }
        if("JSAPI".equals(type)){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id", id).eq("wx_app_id", WxAppEm.MP_COURIER.getAppId()).eq("wx_app_name", WxAppEm.MP_COURIER.getName()));
            if (wxUser == null) {
                return APIEntity.fail("未绑定微信，无法获取openId");
            }
            if ("取件中".equals(order.getOrderStatus())) {
                pay = payService.createBeforePay(order, "补充支付", "骑手代付", "微信");
                String prepayId = WxPayV3Util.V3MpPay("v3/pay/transactions/jsapi", pay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(new BigDecimal(price))), wxUser.getWxUserOpenid(), "业务订单支付", request);
                object = JSONObject.parseObject(WxPayV3Util.WxCusLet(prepayId).toString());
            }
        }

        return object == null ? APIEntity.fail("APP调起支付错误！") : APIEntity.success(object);
    }


    /**
     * 微信app支付
     *
     * @param id
     * @param orderId
     * @param price
     * @return
     */
    @ApiOperation("微信app支付（派送员代缴）")
    @GetMapping("/tcjscoucus/Behalf")
    public APIEntity tcjsCouCusBehalf(@RequestAttribute("JwtUserId") Integer id, Integer orderId, String price, HttpServletRequest request) {
        if (!StringUtils.isPrice(price)) {
            return APIEntity.fail("无法识别订单金额，请检查格式是否正确！！");
        }
        log.info("参数：[{}],[{}]", id, orderId);
        TOrder order = itOrderService.getById(orderId);
        if (order == null) {
            log.error("未找到该订单信息");
            return APIEntity.fail("未找到该订单信息！");
        }
        if (order.getCourierId() == null) {
            log.error("【派送员订单代缴接口异常】，无法找到派送员信息！");
            SysError.saveError("【派送员订单代缴接口异常】，无法找到派送员信息！，当前订单实体={0}", order);
            return APIEntity.fail("无法找到派送员信息，请尝试重新登陆或者，联系平台核实！");
        }
        if (!order.getCourierId().equals(id)) {
            log.error("订单与派送员不批配，无法完成支付");
            return APIEntity.fail("订单与派送员不批配，无法完成支付");
        }
        TPay pay = payService.getOne(new QueryWrapper<TPay>().eq("order_id", order.getOrderId()).in("pay_status", "待付款"));
        log.info("派送员代缴，是否有支付记录的查询:[{}]", pay);
        JSONObject object = null;
        if (pay != null) {
            if ("待付款".equals(pay.getPayStatus())) {
                String prepayId = WxPayV3Util.V3couAppPay("v3/pay/transactions/app", pay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(new BigDecimal(price))), "业务订单支付", request);
                object = JSONObject.parseObject(WxPayV3Util.couAppTuneUp(prepayId).toString());
                return object == null ? APIEntity.fail("APP调起支付错误！") : APIEntity.success(object);
            }
        }
        if ("取件中".equals(order.getOrderStatus())) {
            pay = payService.createBeforePay(order, "补充支付", "骑手代付", "微信");
            String prepayId = WxPayV3Util.V3couAppPay("v3/pay/transactions/app", pay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(new BigDecimal(price))), "业务订单支付", request);
            object = JSONObject.parseObject(WxPayV3Util.couAppTuneUp(prepayId).toString());
        }
        return object == null ? APIEntity.fail("APP调起支付错误！") : APIEntity.success(object);
    }

    /**
     * 微信小程序支付
     *
     * @param id
     * @param orderId
     * @param price
     * @return
     */
    @ApiOperation("微信小程序支付（派送员代缴）")
    @GetMapping("/tcjscoucus/applet")
    public APIEntity tcjsApplet(@RequestAttribute("JwtUserId") Integer id, Integer orderId, String price, HttpServletRequest request) throws Exception {
        if (!StringUtils.isPrice(price)) {
            return APIEntity.fail("无法识别订单金额，请检查格式是否正确！！");
        }
        log.info("参数：[{}],[{}]", id, orderId);
        TOrder order = itOrderService.getById(orderId);
        if (order == null) {
            log.error("未找到该订单信息");
            return APIEntity.fail("未找到该订单信息！");
        }
        if (order.getCourierId() == null) {
            log.error("【派送员订单代缴接口异常】，无法找到派送员信息！");
            SysError.saveError("【派送员订单代缴接口异常】，无法找到派送员信息！，当前订单实体={0}", order);
            return APIEntity.fail("无法找到派送员信息，请尝试重新登陆或者，联系平台核实！");
        }
        if (!order.getCourierId().equals(id)) {
            log.error("订单与派送员不批配，无法完成支付");
            return APIEntity.fail("订单与派送员不批配，无法完成支付");
        }
        TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id", id).eq("wx_app_id", WxAppEm.MP_COURIER.getAppId()).eq("wx_app_name", WxAppEm.MP_COURIER.getName()));
        if (wxUser == null) {
            return APIEntity.fail("未绑定微信，无法获取openId");
        }
        TPay pay = payService.getOne(new QueryWrapper<TPay>().eq("order_id", order.getOrderId()).in("pay_status", "待付款"));
        log.info("派送员代缴，是否有支付记录的查询:[{}]", pay);
        JSONObject object = null;
        if (pay != null) {
            if ("待付款".equals(pay.getPayStatus())) {
                pay.setPayNum(NumberUtils.get("C"));
                payService.updateById(pay);
                String prepayId = WxPayV3Util.V3MpPay("v3/pay/transactions/jsapi", pay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(new BigDecimal(price))), wxUser.getWxUserOpenid(), "业务订单支付", request);
                object = JSONObject.parseObject(WxPayV3Util.WxCusLet(prepayId).toString());
                return object == null ? APIEntity.fail("小程序调起支付错误！") : APIEntity.success(object);
            }
        }
        if ("取件中".equals(order.getOrderStatus())) {
            pay = payService.createBeforePay(order, "补充支付", "骑手代付", "微信");
            String prepayId = WxPayV3Util.V3MpPay("v3/pay/transactions/jsapi", pay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(new BigDecimal(price))), wxUser.getWxUserOpenid(), "业务订单支付", request);
            object = JSONObject.parseObject(WxPayV3Util.WxCusLet(prepayId).toString());
        }
        return object == null ? APIEntity.fail("小程序调起支付错误！") : APIEntity.success(object);
    }


    /**
     * 微信App支付（派送员入住缴费）
     *
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation("微信App支付入住缴费（派送员入住缴费）")
    @GetMapping("/wxCourierPay")

    public APIEntity wxAppPay(@RequestAttribute("JwtUserId") Integer id, HttpServletRequest request) throws Exception {
        TCourier courier = courierService.getById(id);
        if (courier == null) {
            return APIEntity.fail("无法找到客户信息，请重新登陆！", 412);
        }
        TCourierPay oldPay = courierPayService.getOne(new QueryWrapper<TCourierPay>().eq("player_id", id).in("pay_status", "已支付", "待付款"), false);
        //如果有已支付的订单则提示用户刷新客户端
        if (oldPay != null) {
            if ("已支付".equals(oldPay.getPayStatus())) {
                courierService.update(new UpdateWrapper<TCourier>().set("courier_pay_status", "已缴费").eq("courier_id", id));
                return APIEntity.fail("您已经支付过了，请重新打开APP再试！");
            }
            if ("待付款".equals(oldPay.getPayStatus())) {
                courierPayService.updateById(oldPay.setPayWay("微信"));
                String prepayId = WxPayV3Util.V3couAppPay("v3/pay/transactions/app", oldPay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(oldPay.getPayExpectPrice())), "派送员入住支付", request);
                JSONObject object = JSONObject.parseObject(WxPayV3Util.couAppTuneUp(prepayId).toString());
                log.info("统一下单调起支付的参数 [{}]", object);
                return object == null ? APIEntity.fail("APP调起支付错误！") : APIEntity.success(object);
            }
        }
        //获取预付款TPay对象
        TCourierPay beforePay = courierPayService.courierCreatePay(id, courierService.getCourierPrice(id).getConfigValue(), "微信", "入驻缴费");
        String prepayId = WxPayV3Util.V3couAppPay("v3/pay/transactions/app", beforePay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(beforePay.getPayExpectPrice())), "派送员入住支付", request);
        JSONObject object = JSONObject.parseObject(WxPayV3Util.couAppTuneUp(prepayId).toString());
        log.info("统一下单调起支付的参数 [{}]", object);
        return object == null ? APIEntity.fail("APP调起支付错误！") : APIEntity.success(object);
    }

    /**
     * 微信小程序支付入住缴费（派送员入住缴费）
     *
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    /*@ApiOperation("微信小程序支付入住缴费（派送员入住缴费）")
    @GetMapping("/wx/courier/mp/pay")
    public APIEntity wxMpPay(@RequestAttribute("JwtUserId") Integer id, HttpServletRequest request) throws Exception {
        TCourier courier = courierService.getById(id);
        if (courier == null) {
            return APIEntity.fail("无法找到客户信息，请重新登陆！", 412);
        }
        WxAppEm app= WxAppEm.MP_COURIER;
        TWxUser wxUser=wxUserService.getUserByType(id,WxAppEm.WX_USER_TYPE_COURIER,app);
        if (wxUser==null){
            return APIEntity.fail("小程序没有授权绑定！");
        }
        TCourierPay oldPay = courierPayService.getOne(new QueryWrapper<TCourierPay>().eq("player_id", id).in("pay_status", "已支付", "待付款"), false);
        //如果有已支付的订单则提示用户刷新客户端
        if (oldPay != null) {
            if ("已支付".equals(oldPay.getPayStatus())) {
                courierService.update(new UpdateWrapper<TCourier>().set("courier_pay_status", "已缴费").eq("courier_id", id));
                return APIEntity.fail("您已经支付过了，请重新打开APP再试！");
            }
            if ("待付款".equals(oldPay.getPayStatus())) {
                courierPayService.updateById(oldPay.setPayWay("微信"));
                String prepayId = WxPayV3Util.V3MpPay("v3/pay/transactions/jsapi", oldPay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(oldPay.getPayExpectPrice())), wxUser.getWxUserOpenid(), "派送员入住支付", request);
                JSONObject object = JSONObject.parseObject(WxPayV3Util.WxTuneUp(prepayId).toString());
                return object == null ? APIEntity.fail("APP调起支付错误！") : APIEntity.success(object);
            }
        }
        //获取预付款TPay对象
        TCourierPay beforePay = courierPayService.courierCreatePay(id, courierService.getCourierPrice(id).getConfigValue(), "微信", "入驻缴费");
        String prepayId = WxPayV3Util.V3MpPay("v3/pay/transactions/jsapi", beforePay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(beforePay.getPayExpectPrice())), wxUser.getWxUserOpenid(), "派送员入住支付", request);
        JSONObject object = JSONObject.parseObject(WxPayV3Util.couAppTuneUp(prepayId).toString());
        log.info("统一下单调起支付的参数 [{}]", object);
        return object == null ? APIEntity.fail("APP调起支付错误！") : APIEntity.success(object);
    }*/

    /**
     * 派送员根据等级缴纳入驻费用
     *
     * @param id
     * @return
     * @throws AlipayApiException
     */
    @ApiOperation("派送员根据等级缴纳入驻费用 [微信小程序]")
    @GetMapping("/wx/recharge/pay")
    public APIEntity courierRechargeWxPay(@ApiIgnore @RequestAttribute("JwtUserId") Integer id, String price, HttpServletRequest request) throws Exception {
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@:{}",price);
        TCourier courier = courierService.getById(id);
        if (courier == null) {
            return APIEntity.fail("无法找到骑手信息，请重新登陆！", 412);
        }
        WxAppEm app= WxAppEm.MP_COURIER;
        TWxUser wxUser=wxUserService.getUserByType(id,WxAppEm.WX_USER_TYPE_COURIER,app);
        if (wxUser==null){
            return APIEntity.fail("小程序没有授权绑定！");
        }
        /*SysConfig sysConfig = configService.getOne(new QueryWrapper<SysConfig>().eq("config_group", "cost_set").eq("config_data_one", courier.getCourierSettledMoney().add(new BigDecimal(price))));
        if (sysConfig ==null) {
            log.error("当前缴纳费用没有相应的匹配等级，缴纳费用:[{}]", courier.getCourierSettledMoney().intValue());
            SysError.saveError("当前缴纳费用没有相应的匹配等级，骑手入驻支付单：{0}元，{1}", courier.getCourierSettledMoney().intValue(), courier.getCourierName());
            return APIEntity.fail("当前缴纳费用没有相应的匹配等级,如有疑问请联系客服！", 412);
        }*/
        TCourierPay oldPay = courierPayService.getOne(new QueryWrapper<TCourierPay>().eq("player_id", id).eq("pay_way", "微信").in("pay_status", "待付款"));
        log.info("!!!!!!!!!!!!!微信预支付订单信息：[{}]", oldPay);
        //如果有已支付的订单则提示用户刷新客户端
        if (oldPay != null) {
            String prepayId = WxPayV3Util.V3MpPay("v3/pay/transactions/jsapi", oldPay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(oldPay.getPayExpectPrice())), wxUser.getWxUserOpenid(), "派送员入住支付", request);
            JSONObject object = JSONObject.parseObject(WxPayV3Util.WxCusLet(prepayId).toString());
            log.info("统一下单调起支付的参数 [{}]", object);
            return object == null ? APIEntity.fail("小程序调起支付错误！") : APIEntity.success(object);
        }
        //获取预付款TPay对象
        TCourierPay beforePay = courierPayService.courierCreatePay(id, price, "微信", "入驻缴费");
        String prepayId = WxPayV3Util.V3MpPay("v3/pay/transactions/jsapi", beforePay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(beforePay.getPayExpectPrice())), wxUser.getWxUserOpenid(), "派送员入住支付", request);
        JSONObject object = JSONObject.parseObject(WxPayV3Util.WxCusLet(prepayId).toString());
        log.info("统一下单调起支付的参数 [{}]", object);
        return object == null ? APIEntity.fail("小程序调起支付错误！") : APIEntity.success(object);

    }

    /**
     * 派送员根据等级缴纳入驻费用
     *
     * @param id
     * @return
     * @throws AlipayApiException
     */
    @ApiOperation("派送员根据等级缴纳入驻费用 [微信App]")
    @GetMapping("/aliCourierRecharge")
    public APIEntity courierRecharge(@ApiIgnore @RequestAttribute("JwtUserId") Integer id, String price, HttpServletRequest request) throws Exception {
        TCourier courier = courierService.getById(id);
        if (courier == null) {
            return APIEntity.fail("无法找到骑手信息，请重新登陆！", 412);
        }
        SysConfig sysConfig = configService.getOne(new QueryWrapper<SysConfig>().eq("config_group", "cost_set").eq("config_data_one", courier.getCourierSettledMoney().add(new BigDecimal(price))));
        if (StringUtils.isBlank(sysConfig.toString())) {
            log.error("当前缴纳费用没有相应的匹配等级，缴纳费用:[{}]", courier.getCourierSettledMoney().intValue());
            SysError.saveError("当前缴纳费用没有相应的匹配等级，骑手入驻支付单：{0}元，{1}", courier.getCourierSettledMoney().intValue(), courier.getCourierName());
            return APIEntity.fail("当前缴纳费用没有相应的匹配等级,如有疑问请联系客服！", 412);
        }
        TCourierPay oldPay = courierPayService.getOne(new QueryWrapper<TCourierPay>().eq("player_id", id).eq("pay_way", "微信").in("pay_status", "待付款"));
        log.info("!!!!!!!!!!!!!微信预支付订单信息：[{}]", oldPay);
        //如果有已支付的订单则提示用户刷新客户端
        if (oldPay != null) {
            String prepayId = WxPayV3Util.V3couAppPay("v3/pay/transactions/app", oldPay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(oldPay.getPayExpectPrice())), "派送员入驻支付", request);
            JSONObject object = JSONObject.parseObject(WxPayV3Util.couAppTuneUp(prepayId).toString());
            log.info("统一下单调起支付的参数 [{}]", object);
            return object == null ? APIEntity.fail("APP调起支付错误！") : APIEntity.success(object);
        }
        //获取预付款TPay对象
        TCourierPay beforePay = courierPayService.courierCreatePay(id, price, "微信", "入驻缴费");
        String prepayId = WxPayV3Util.V3couAppPay("v3/pay/transactions/app", beforePay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(beforePay.getPayExpectPrice())), "派送员入驻支付", request);
        JSONObject object = JSONObject.parseObject(WxPayV3Util.couAppTuneUp(prepayId).toString());
        log.info("统一下单调起支付的参数 [{}]", object);
        return object == null ? APIEntity.fail("APP调起支付错误！") : APIEntity.success(object);

    }

    /**
     * 客户钱包充值缴费缴费
     *
     * @param id
     * @return
     * @throws AlipayApiException
     */
    @ApiOperation("客户钱包充值缴费缴费（微信App）")
    @PostMapping("/wxpay/wallet")
    public APIEntity wxpayWallet(@RequestAttribute("JwtUserId") Integer id, String price, String type, String location, HttpServletRequest request) throws Exception {
        TCustomer customer = customerService.getById(id);
        if (customer == null) {
            return APIEntity.fail("无法找到客户信息，请重新登陆！", 412);
        }
        /*if(new BigDecimal(price).compareTo(new BigDecimal(100)) < 0){
            return APIEntity.fail("钱包充值金额不得小于100.00元");
        }*/
        TCustomerWallet tCustomerWallet = customerWalletService.getOne(new QueryWrapper<TCustomerWallet>().eq("customer_id",customer.getCustomerId()).eq("wallet_state","提现中"));
        if(tCustomerWallet != null){
            return APIEntity.fail("您的钱包余额正在提现中，请稍候充值。");
        }
        TCustomerPay customerPay = customerPayService.getOne(new QueryWrapper<TCustomerPay>().eq("player_id", customer.getCustomerId()).eq("pay_status", "待付款"));
        JSONObject object = null;
        if ("APP".equals(type)) {
            if (customerPay != null) {
                if ("待付款".equals(customerPay.getPayStatus()) && customerPay.getPayExpectPrice().compareTo(new BigDecimal(price)) == 0) {
                    customerPayService.updateById(customerPay.setPayWay("微信"));
                    String prepayId = WxPayV3Util.V3cusAppPay("v3/pay/transactions/app", customerPay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(customerPay.getPayExpectPrice())), "钱包充值支付", request);
                    object = JSONObject.parseObject(WxPayV3Util.WxAppTuneUp(prepayId).toString());
                    return object == null ? APIEntity.fail("APP调起支付错误") : APIEntity.success(object);
                }
            }
            //获取预付款TPay对象
            customerPay = customerPayService.createWalletPay(customer, price, "微信", "钱包充值", location);
            String prepayId = WxPayV3Util.V3cusAppPay("v3/pay/transactions/app", customerPay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(customerPay.getPayExpectPrice())), "钱包充值支付", request);
            object = JSONObject.parseObject(WxPayV3Util.WxAppTuneUp(prepayId).toString());
        }
        if ("JSAPI".equals(type)) {
            if (customerPay != null) {
                if ("待付款".equals(customerPay.getPayStatus()) && customerPay.getPayExpectPrice().compareTo(new BigDecimal(price)) == 0) {
                    customerPayService.updateById(customerPay.setPayWay("微信"));
                    String prepayId = WxPayV3Util.V3JsapiPay("v3/pay/transactions/jsapi", customerPay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(customerPay.getPayExpectPrice())), customer.getOpenId(), "钱包充值支付", request);
                    object = JSONObject.parseObject(WxPayV3Util.WxTuneUp(prepayId).toString());
                    return object == null ? APIEntity.fail("APP调起支付错误") : APIEntity.success(object);
                }
            }
            //获取预付款TPay对象
            customerPay = customerPayService.createWalletPay(customer, price, "微信", "钱包充值", location);
            String prepayId = WxPayV3Util.V3JsapiPay("v3/pay/transactions/jsapi", customerPay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(customerPay.getPayExpectPrice())), customer.getOpenId(), "钱包充值支付", request);
            object = JSONObject.parseObject(WxPayV3Util.WxTuneUp(prepayId).toString());
        }
        return object == null ? APIEntity.fail("APP调起支付错误") : APIEntity.success(object);
    }

    /**
     * 微信v3版本订单业务支付退款
     * @param orderId
     * @return
     */
   /* @ApiOperation("微信V3版本支付退款(新版暂未使用)")
    @PostMapping("/wxRefund")
    public APIEntity wxRefund(Integer orderId) throws Exception {
        TOrder tOrder = itOrderService.getById(orderId);
        TPay tPay = payService.getOne(new QueryWrapper<TPay>().eq("pay_id",tOrder.getPayId()));
        if(tOrder == null){
            log.info("未找到该订单");
            return APIEntity.fail("该订单不存在");
        }
        TRefund refund= null;
        wxPayUtil payUtil = new wxPayUtil();
        String refunds = WxPayV3Util.V3wxRefund("v3/refund/domestic/refunds",tPay.getPayChannelNum(),tPay.getPayFactPrice(),tPay.getPayFactPrice(),"测试新版退款");
        log.info("微信付款码支付退款返回结果 [{}]",refunds);
        return APIEntity.fail(refunds);
    }*/

    /**
     * 微信支付异步回调
     * 将回调的订单信息放到消息队列里，监听消息队列进行业务处理
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @ApiOperation("微信小程序异步回调接口，前端不需要接入")
    @PostMapping("/wxnoty")
    public String wxnoty(HttpServletRequest request, HttpServletResponse response) throws Exception {
        JSONObject jsonObject = WxPayV3Util.notify(request, response);
        log.info("小程序调起支付回调消息：[{}]", jsonObject);
        mqTool.sendMsg(jsonObject, WeChartListener.class);
        return "success";
    }


}
