package cn.com.ty.lift.ud.pay.wxpay;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;

import cn.com.ty.lift.ud.chat.mapper.entity.LiftCaseEntity;
import cn.com.ty.lift.ud.chat.service.ILiftCaseService;
import cn.com.ty.lift.ud.operation.mapper.entity.UserLevelRuleEntity;
import cn.com.ty.lift.ud.operation.mapper.entity.VipFeeSettingEntity;
import cn.com.ty.lift.ud.operation.service.IUserLevelRuleService;
import cn.com.ty.lift.ud.operation.service.IVipFeeSettingService;
import cn.com.ty.lift.ud.pay.controller.req.PassbackParamsDTO;
import cn.com.ty.lift.ud.pay.controller.req.PayDTO;
import cn.com.ty.lift.ud.pay.enums.PassbackEnum;
import cn.com.ty.lift.ud.pay.service.WxpayService;
import cn.com.ty.lift.ud.payment.mapper.entity.UserRechargeDetailEntity;
import cn.com.ty.lift.ud.payment.service.IUserRechargeDetailService;
import cn.com.ty.lift.ud.question.mapper.QuestionBankMapper;
import cn.com.ty.lift.ud.question.mapper.entity.QuestionBankEntity;
import cn.com.ty.lift.ud.schoolVideo.mapper.entity.SchoolVideoEntity;
import cn.com.ty.lift.ud.schoolVideo.service.ISchoolVideoService;
import cn.com.ty.lift.ud.tableDict.service.ITableDictService;
import cn.com.ty.lift.ud.userInfo.mapper.UserInfoMapper;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserInfoEntity;
import cn.com.ty.lift.ud.utils.UUIDUtil;
import cn.com.xwy.boot.web.dto.RestResponse;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

/**
 * app微信支付
 * @author Administrator
 *
 */
@Slf4j
@Api(tags = "微信支付- 魏瑞锋")
@RestController
@RequestMapping("/api")
//@CrossOrigin
public class PayResponseResource {

    private Logger logger = LoggerFactory.getLogger(PayResponseResource.class);

    // 微信appid
    @Value("${wx.pay.appId}")
    private String wxAppId;

    // 微信商户ID
    @Value("${wx.pay.mchId}")
    private String wxMchId;

    // 微信商户key
    @Value("${wx.pay.mchKey}")
    private String wxMchKey;
    
    @Value("${wx.pay.notifyUrl}")
    private String notifyUrl;

    @Autowired
    private WxPayService wxService;

    private @Autowired ILiftCaseService liftCaseService;

    @Autowired
    private WxpayService wxpayService;

    private @Autowired ITableDictService tableDictService;

    private @Autowired UserInfoMapper userInfoMapper;

    private @Autowired IUserLevelRuleService iUserLevelRuleService;

    private @Autowired IVipFeeSettingService vipFeeSettingService;

    private @Autowired ISchoolVideoService schoolVideoService;

    private @Autowired QuestionBankMapper questionBankMapper;

    private @Autowired IUserRechargeDetailService userRechargeDetailService;

    /**
     * 微信支付-诊单支付
     * 
     * @param pay
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/wxpay/case")
    public RestResponse appPay(@RequestBody PayDTO pay, HttpServletRequest httpServletRequest) {
        String ip = httpServletRequest.getRemoteAddr();
        if (StringUtils.isBlank(pay.getOrders())) {
            log.error("订单号不能为空。");
            return RestResponse.fail("0", "订单号不能为空。");
        }

        if (null == pay.getLiftCaseType()) {
            log.error("出诊问诊类型不能为空。");
            return RestResponse.fail("0", "出诊问诊类型不能为空。");
        }

        QueryWrapper<LiftCaseEntity> queryWrapper = new QueryWrapper<LiftCaseEntity>();
        queryWrapper.eq("order_no", pay.getOrders());
        LiftCaseEntity orders = liftCaseService.getOne(queryWrapper);

        if (null == orders) {
            log.error("该支付订单不存在请检查！");
            return RestResponse.fail("0", "该支付订单不存在请检查！");
        }

        BigDecimal totalAmount = orders.getPayCost().multiply(new BigDecimal(100));
        if (totalAmount.compareTo(new BigDecimal("0.01")) == -1) {
            log.info("所需支付金额为：{}元,无需调用支付宝。走余额支付回调", totalAmount);
            return RestResponse.fail("0", "该订单支付金额小于0.01元，请使用余额支付！");
        }
        double moneyDou = totalAmount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        // 调用微信统一下单接口
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        String passbackParams = "";
        try {
            if (pay.getLiftCaseType() == 1) {
                passbackParams = assemblePassbackParams(PassbackEnum.LIFT_CASE_PAY.getCode(), "问诊订单回调", null, null);
            } else if (pay.getLiftCaseType() == 2) {
                passbackParams = assemblePassbackParams(PassbackEnum.LIFT_CALL_PAY.getCode(), "出诊订单回调", null, null);
            } else {
                log.error("出诊问诊类型有误。");
                return RestResponse.fail("0", "出诊问诊类型有误。");
            }
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        request.setAttach(passbackParams);
        request.setAppid(wxAppId);
        request.setMchId(wxMchId);
        request.setDeviceInfo("APP");
        // 调用统一下单接口时，会自动设置nonceStr、sign
        String subject = "微信支付";
        request.setBody(subject);
        // 订单号
        request.setOutTradeNo(pay.getOrders());
        // 订单总金额，单位分
        int totalfee = (int)moneyDou;
        // 沙箱环境测试时，金额直接设置为官方测试用例中的301才行。
        request.setTotalFee(totalfee);
        request.setSpbillCreateIp(ip);
        // 配置属性中已设置回调URL，http://gfapi.whlhcx.com/USER/api/wxpayNotify
        // 支付类型，APP表示APP支付
        request.setTradeType("APP");
        request.setNotifyUrl(notifyUrl);

        try {
            WxPayUnifiedOrderResult wxPayUnifiedOrderResult = wxService.unifiedOrder(request);
            if (wxPayUnifiedOrderResult.getReturnCode().equalsIgnoreCase("SUCCESS")) {
                // 当resultCode="SUCCESS"，才会返回prepayId。
                if (wxPayUnifiedOrderResult.getResultCode().equalsIgnoreCase("SUCCESS")) {
                    String prepayId = wxPayUnifiedOrderResult.getPrepayId();
                    String packageInfo = "Sign=WXPay";
                    long currentTimeMillis = System.currentTimeMillis();
                    String noncestr = String.valueOf(currentTimeMillis);
                    String timestamp = String.valueOf(currentTimeMillis / 1000);
                    WxPayAppUnifiedOrderResult result =
                        new WxPayAppUnifiedOrderResult(wxAppId, wxMchId, prepayId, packageInfo, noncestr, timestamp);
                    // 创建并设置签名值。
                    result.createSign(wxMchKey);
                    return RestResponse.success(result, "success");
                }
            }
        } catch (WxPayException e) {
            logger.error("微信预支付交易单创建异常，原因：{}", e.getMessage());
            // throw new ParamException("微信预支付交易单创建过程异常");
        }
        return RestResponse.fail("调用APP支付接口时发生异常");
    }

    /**
     * 微信支付-打赏支付
     * 
     * @param pay
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/wxpay/reward")
    public RestResponse reward(@RequestBody PayDTO pay, HttpServletRequest httpServletRequest) {
        String ip = httpServletRequest.getRemoteAddr();
        if (StringUtils.isBlank(pay.getOrders())) {
            log.error("订单号参数不能为空。");
            return RestResponse.fail("0", "订单号不能为空。");
        }

        if (null == pay.getUserId()) {
            log.error("打赏用户id不能为空。");
            return RestResponse.fail("0", "打赏用户id不能为空。");
        }

        if (null == pay.getRewardType()) {
            log.error("打赏类型不能为空。");
            return RestResponse.fail("0", "打赏类型能为空。");
        }

        if (null == pay.getReawrdMoney()) {
            log.error("打赏代号不能为空。");
            return RestResponse.fail("0", "打赏代号能为空。");
        }

        // 打赏金额
        String totalAmount =
            tableDictService.findOneByTableAndColumnAndCode("reward_setting", "reward", pay.getReawrdMoney().getCode());
        if (StringUtils.isBlank(totalAmount)) {
            log.error("打赏代号有误。");
            return RestResponse.fail("0", "打赏代号有误。");
        }

        String passbackParams = "";
        if (1 == pay.getRewardType()) {
            QueryWrapper<QuestionBankEntity> queryWrapper = new QueryWrapper<QuestionBankEntity>();
            queryWrapper.eq("id", pay.getOrders());
            QuestionBankEntity orders = questionBankMapper.selectOne(queryWrapper);
            if (null == orders) {
                log.error("打赏题库不存在请检查！");
                return RestResponse.fail("0", "打赏题库不存在请检查！");
            }
            // totalAmount = orders.getReward();
            try {
                passbackParams =
                    assemblePassbackParams(PassbackEnum.REWARD_PAY.getCode(), "题库打赏", pay.getUserId(), pay.getOrders());
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if (2 == pay.getRewardType()) {
            QueryWrapper<SchoolVideoEntity> queryWrapper = new QueryWrapper<SchoolVideoEntity>();
            queryWrapper.eq("id", pay.getOrders());
            SchoolVideoEntity orders = schoolVideoService.getOne(queryWrapper);

            if (null == orders) {
                log.error("打赏视频不存在请检查！");
                return RestResponse.fail("0", "打赏视频不存在请检查！");
            }
            // totalAmount = orders.getReward();
            try {
                passbackParams =
                    assemblePassbackParams(PassbackEnum.VIDEO_PAY.getCode(), "视频打赏", pay.getUserId(), pay.getOrders());
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            log.error("打赏类型有误。");
            return RestResponse.fail("0", "打赏类型有误。");
        }

        // 调用微信统一下单接口
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        BigDecimal b = new BigDecimal(totalAmount).multiply(new BigDecimal(100));
        double doubleValue = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        request.setAttach(passbackParams);
        request.setAppid(wxAppId);
        request.setMchId(wxMchId);
        request.setDeviceInfo("APP");
        // 调用统一下单接口时，会自动设置nonceStr、sign
        String subject = "微信支付";
        request.setBody(subject);
        // 订单号
        request.setOutTradeNo(UUIDUtil.getUuidByTime(8));
        // 订单总金额，单位分
        int totalfee = (int)doubleValue;
        // 沙箱环境测试时，金额直接设置为官方测试用例中的301才行。
        request.setTotalFee(totalfee);
        request.setSpbillCreateIp(ip);
        // 配置属性中已设置回调URL，http://gfapi.whlhcx.com/USER/api/wxpayNotify
        // 支付类型，APP表示APP支付
        request.setTradeType("APP");
        request.setNotifyUrl(notifyUrl);

        try {
            WxPayUnifiedOrderResult wxPayUnifiedOrderResult = wxService.unifiedOrder(request);
            if (wxPayUnifiedOrderResult.getReturnCode().equalsIgnoreCase("SUCCESS")) {
                // 当resultCode="SUCCESS"，才会返回prepayId。
                if (wxPayUnifiedOrderResult.getResultCode().equalsIgnoreCase("SUCCESS")) {
                    String prepayId = wxPayUnifiedOrderResult.getPrepayId();
                    String packageInfo = "Sign=WXPay";
                    long currentTimeMillis = System.currentTimeMillis();
                    String noncestr = String.valueOf(currentTimeMillis);
                    String timestamp = String.valueOf(currentTimeMillis / 1000);
                    WxPayAppUnifiedOrderResult result =
                        new WxPayAppUnifiedOrderResult(wxAppId, wxMchId, prepayId, packageInfo, noncestr, timestamp);
                    // 创建并设置签名值。
                    result.createSign(wxMchKey);
                    return RestResponse.success(result, "success");
                }
            }
        } catch (WxPayException e) {
            logger.error("微信预支付交易单创建异常，原因：{}", e.getMessage());
            // throw new ParamException("微信预支付交易单创建过程异常");
        }
        return RestResponse.fail("调用APP支付接口时发生异常");
    }

    /**
     * 微信支付-app充值
     * 
     * @param pay
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/wxpay/recharge")
    public RestResponse recharge(@RequestBody PayDTO pay, HttpServletRequest httpServletRequest) {
        String ip = httpServletRequest.getRemoteAddr();
        if (StringUtils.isBlank(pay.getOrders())) {
            log.error("请输入订单号.");
            return RestResponse.fail("0", "请输入订单号.");
        }

        QueryWrapper<UserRechargeDetailEntity> queryWrapper = new QueryWrapper<UserRechargeDetailEntity>();
        queryWrapper.eq("order_sn", pay.getOrders());
        UserRechargeDetailEntity rechargeDetail = userRechargeDetailService.getOne(queryWrapper);

        if (null == rechargeDetail) {
            return RestResponse.fail("0", "无效的充值，请重试");
        }

        if (1 != rechargeDetail.getPayStatus()) {
            return RestResponse.fail("0", "充值状态有误，请重试");
        }

        // 充值金额
        BigDecimal rechargeAmount = rechargeDetail.getProductPrice().multiply(new BigDecimal(100));

        String passbackParams = "";
        try {
            passbackParams =
                assemblePassbackParams(PassbackEnum.RECHARGE_PAY.getCode(), "用户充值", rechargeDetail.getUserId(), null);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // 调用微信统一下单接口
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        double doubleValue = rechargeAmount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        request.setAttach(passbackParams);
        request.setAppid(wxAppId);
        request.setMchId(wxMchId);
        request.setDeviceInfo("APP");
        // 调用统一下单接口时，会自动设置nonceStr、sign
        String subject = "微信支付";
        request.setBody(subject);
        // 订单号
        request.setOutTradeNo(pay.getOrders());
        // 订单总金额，单位分
        int totalfee = (int)doubleValue;
        // 沙箱环境测试时，金额直接设置为官方测试用例中的301才行。
        request.setTotalFee(totalfee);
        request.setSpbillCreateIp(ip);
        // 配置属性中已设置回调URL，http://gfapi.whlhcx.com/USER/api/wxpayNotify
        // 支付类型，APP表示APP支付
        request.setTradeType("APP");
        request.setNotifyUrl(notifyUrl);

        try {
            WxPayUnifiedOrderResult wxPayUnifiedOrderResult = wxService.unifiedOrder(request);
            if (wxPayUnifiedOrderResult.getReturnCode().equalsIgnoreCase("SUCCESS")) {
                // 当resultCode="SUCCESS"，才会返回prepayId。
                if (wxPayUnifiedOrderResult.getResultCode().equalsIgnoreCase("SUCCESS")) {
                    String prepayId = wxPayUnifiedOrderResult.getPrepayId();
                    String packageInfo = "Sign=WXPay";
                    long currentTimeMillis = System.currentTimeMillis();
                    String noncestr = String.valueOf(currentTimeMillis);
                    String timestamp = String.valueOf(currentTimeMillis / 1000);
                    WxPayAppUnifiedOrderResult result =
                        new WxPayAppUnifiedOrderResult(wxAppId, wxMchId, prepayId, packageInfo, noncestr, timestamp);
                    // 创建并设置签名值。
                    result.createSign(wxMchKey);
                    return RestResponse.success(result, "success");
                }
            }
        } catch (WxPayException e) {
            logger.error("微信预支付交易单创建异常，原因：{}", e.getMessage());
            // throw new ParamException("微信预支付交易单创建过程异常");
        }
        return RestResponse.fail("调用APP支付接口时发生异常");
    }

    /**
     * 微信支付-app充值成为vip
     * 
     * @param pay
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/wxpay/rechargeVIP")
    public RestResponse rechargeVIP(@RequestBody PayDTO pay, HttpServletRequest httpServletRequest) {
        String ip = httpServletRequest.getRemoteAddr();
        if (StringUtils.isBlank(pay.getOrders())) {
            log.error("订单号不能为空。");
            return RestResponse.fail("0", "订单号不能为空。");
        }

        if (null == pay.getUserId()) {
            log.error("打赏用户id不能为空。");
            return RestResponse.fail("0", "打赏用户id不能为空。");
        }

        QueryWrapper<VipFeeSettingEntity> queryWrapper = new QueryWrapper<VipFeeSettingEntity>();
        queryWrapper.eq("id", pay.getOrders());
        VipFeeSettingEntity orders = vipFeeSettingService.getOne(queryWrapper);

        if (null == orders) {
            log.error("该项会费不存在请检查！");
            return RestResponse.fail("0", "该项会费不存在请检查！");
        }

        /** 0 待审核 1 审核通过 2 驳回 3 待提交 */
        final int flag = 1;
        if (flag != orders.getExamineFlag()) {
            log.error("该项会费不支持使用请检查！");
            return RestResponse.fail("0", "该项会费不支持使用请检查！");
        }

        UserInfoEntity userInfoEntity = userInfoMapper.getByUserId(pay.getUserId());
        if (null == userInfoEntity) {
            log.error("当前用户不存在");
            return RestResponse.fail("当前用户不存在");
        }
        UserLevelRuleEntity userLevelRole = iUserLevelRuleService.getById(orders.getUserLevelId());
        if (null == userLevelRole) {
            log.error("当前会员角色等级不存在，请检查");
            return RestResponse.fail("当前会员角色等级不存在，请检查");
        }

        // 充值金额
        BigDecimal totalAmount = orders.getPrice().multiply(new BigDecimal(100));

        String passbackParams = "";
        try {
             passbackParams = assemblePassbackParams(PassbackEnum.RECHARGE_VIP_PAY.getCode(), orders.getName(),
                pay.getUserId(), orders.getId().toString());
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // 调用微信统一下单接口
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        double doubleValue = totalAmount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        request.setAttach(passbackParams);
        request.setAppid(wxAppId);
        request.setMchId(wxMchId);
        request.setDeviceInfo("APP");
        // 调用统一下单接口时，会自动设置nonceStr、sign
        String subject = "微信支付";
        request.setBody(subject);
        // 订单号
        request.setOutTradeNo(UUIDUtil.getUuidByTime(8));
        // 订单总金额，单位分
        int totalfee = (int)doubleValue;
        // 沙箱环境测试时，金额直接设置为官方测试用例中的301才行。
        request.setTotalFee(totalfee);
        request.setSpbillCreateIp(ip);
        // 配置属性中已设置回调URL，http://gfapi.whlhcx.com/USER/api/wxpayNotify
        // 支付类型，APP表示APP支付
        request.setTradeType("APP");
        request.setNotifyUrl(notifyUrl);

        try {
            WxPayUnifiedOrderResult wxPayUnifiedOrderResult = wxService.unifiedOrder(request);
            if (wxPayUnifiedOrderResult.getReturnCode().equalsIgnoreCase("SUCCESS")) {
                // 当resultCode="SUCCESS"，才会返回prepayId。
                if (wxPayUnifiedOrderResult.getResultCode().equalsIgnoreCase("SUCCESS")) {
                    String prepayId = wxPayUnifiedOrderResult.getPrepayId();
                    String packageInfo = "Sign=WXPay";
                    long currentTimeMillis = System.currentTimeMillis();
                    String noncestr = String.valueOf(currentTimeMillis);
                    String timestamp = String.valueOf(currentTimeMillis / 1000);
                    WxPayAppUnifiedOrderResult result =
                        new WxPayAppUnifiedOrderResult(wxAppId, wxMchId, prepayId, packageInfo, noncestr, timestamp);
                    // 创建并设置签名值。
                    result.createSign(wxMchKey);
                    return RestResponse.success(result, "success");
                }
            }
        } catch (WxPayException e) {
            logger.error("微信预支付交易单创建异常，原因：{}", e.getMessage());
            // throw new ParamException("微信预支付交易单创建过程异常");
        }
        return RestResponse.fail("调用APP支付接口时发生异常");
    }
    
    /**
     * 微信回调接口
     * 
     * @param xmlData
     * @return
     * @throws Exception
     */
    @PostMapping("/wxpayNotify")
    public String wxpayNotify(@RequestBody String xmlData) {
        logger.info("come into wxpayNotify()");
        logger.info(xmlData);
        // xmlData 异步回调参数有outTradeNo商户订单号信息，需要使用WxPayOrderNotifyResult接收。
        WxPayOrderNotifyResult result = null;
        try {
            result = wxService.parseOrderNotifyResult(xmlData);
        } catch (WxPayException e) {
            logger.error("解析微信回调接口参数发生异常。");
            logger.error(e.getMessage());
            return WxPayNotifyResponse.fail("fail");
        }
        // 如果不成功，则直接告知微信
        String returnCode = result.getReturnCode();
        if (!"SUCCESS".equalsIgnoreCase(returnCode)) {
            return WxPayNotifyResponse.fail("fail");
        }
        // 如果业务结果不成功，则直接告知微信
        String resultCode = result.getResultCode();
        if (!"SUCCESS".equalsIgnoreCase(resultCode)) {
            return WxPayNotifyResponse.fail("fail");
        }
        boolean signFlag = false;
        try {
            // 使用微信SDK提供的验签方法。
            signFlag = WXPayUtil.isSignatureValid(xmlData, wxMchKey);
        } catch (Exception e) {
            logger.error("微信回调接口验签发生异常。");
            logger.error(e.getMessage());
            return WxPayNotifyResponse.fail("fail");
        }
        if (!signFlag) {
            logger.error("weixin check sign fail");
            return WxPayNotifyResponse.fail("fail");
        }

        // 校验APP_ID
        String appId = result.getAppid();
        if (!wxAppId.equals(appId)) {
            logger.error("weixin check appid fail");
            return WxPayNotifyResponse.fail("fail");
        }
        // 校验商户ID
        String mchId = result.getMchId();
        if (!wxMchId.equals(mchId)) {
            logger.error("weixin check mchid fail");
            return WxPayNotifyResponse.fail("fail");
        }
        WxPayOrderQueryResult orderResult = null;
        String outTradeNo = result.getOutTradeNo();
        try {
            orderResult = wxService.queryOrder(null, outTradeNo);
        } catch (WxPayException e) {
            logger.error("微信查询订单发生异常。");
            logger.error(e.getMessage());
            return WxPayNotifyResponse.fail("fail");
        }
        if (orderResult.getReturnCode().equals("SUCCESS")) {
            // 校验业务状态
            if (orderResult.getResultCode().equals("SUCCESS")) {
                String tradeState = orderResult.getTradeState();
                // 支付成功
                if ("SUCCESS".equals(tradeState)) {
                    String passbackParams = result.getAttach();
                    String totalAmount = result.getTotalFee().toString();
                    String tradeNo = result.getTransactionId();
                    PassbackParamsDTO dto = JSON.parseObject(passbackParams, PassbackParamsDTO.class);
                    if (dto.getType() == PassbackEnum.LIFT_CASE_PAY.getCode()) {
                        wxpayService.wxCasePaymentComplete(outTradeNo, totalAmount, tradeNo);
                    } else if (dto.getType() == PassbackEnum.RECHARGE_PAY.getCode()) {
                        wxpayService.wxrechargePay(outTradeNo, totalAmount, tradeNo, dto);
                    } else if (dto.getType() == PassbackEnum.LIFT_CALL_PAY.getCode()) {
                        wxpayService.wxCallPaymentComplete(outTradeNo, totalAmount, tradeNo);
                    } else if (dto.getType() == PassbackEnum.REWARD_PAY.getCode()) {
                        Long questionId = Long.valueOf(dto.getDataId());
                        wxpayService.wxQuestionPaymentComplete(questionId, dto.getUserId(), tradeNo, totalAmount, 1);
                    } else if (dto.getType() == PassbackEnum.VIDEO_PAY.getCode()) {
                        Long videoId = Long.valueOf(dto.getDataId());
                        wxpayService.wxVideoPaymentComplete(videoId, dto.getUserId(), tradeNo, totalAmount, 1);
                    } else if (dto.getType() == PassbackEnum.RECHARGE_VIP_PAY.getCode()) {
                        Long vipFeeSetting = Long.valueOf(dto.getDataId());
                        wxpayService.wxToVIPPaymentComplete(vipFeeSetting, dto.getUserId(), tradeNo, totalAmount);
                    } else {
                        log.error("好可惜，回调类型不存在：{}", dto.getType());
                    }
                    return WxPayNotifyResponse.success("OK");
                } else {
                    logger.error("微信订单{}支付不成功", outTradeNo);
                }
            } else {
                logger.error("微信订单{}业务状态FAIL", outTradeNo);
            }
        } else {
            logger.error("微信订单{}查询失败", outTradeNo);
        }

        return WxPayNotifyResponse.fail("fail");
    }

    /**
     * 公用回传参数如果请求时传递了该参数，则返回给商户时会回传该参数。
     *
     * @param type
     *            当前回调处理类型
     * @param memo
     *            一段描述
     * @param userId
     *            用户id
     * @param dataId
     *            操作数据id
     * @return
     * @throws UnsupportedEncodingException
     */
    private String assemblePassbackParams(Integer type, String memo, Long userId, String dataId)
        throws UnsupportedEncodingException {
        PassbackParamsDTO dto = new PassbackParamsDTO();
        dto.setType(type);
        dto.setMemo(memo);
        dto.setUserId(userId);
        dto.setDataId(dataId);
        return JSON.toJSONString(dto);
    }

}
