package com.sqx.modules.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.address.dao.AddressDao;
import com.sqx.modules.address.entity.Address;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.coupon.dao.TbCouponUserDao;
import com.sqx.modules.coupon.entity.TbCouponUser;
import com.sqx.modules.coupon.service.TbCouponUserService;
import com.sqx.modules.datacentre.service.DataCentreService;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.errand.service.TbIndentService;
import com.sqx.modules.errand.util.LonLatUtil;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.dao.GoodsShopRelevancyDao;
import com.sqx.modules.goods.dao.GoodsSkuDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.goods.entity.GoodsShop;
import com.sqx.modules.goods.entity.GoodsShopRelevancy;
import com.sqx.modules.goods.service.GoodsService;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.order.dao.AppOrderDao;
import com.sqx.modules.order.dao.OrderGoodsDao;
import com.sqx.modules.order.entity.OrderGoods;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.order.service.AppOrderService;
import com.sqx.modules.pay.config.WXConfig;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.shop.service.ShopMessageService;
import com.sqx.modules.utils.AmountCalUtils;
import com.sqx.modules.utils.MD5Util;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.WXConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author fang
 * @date 2020/2/26
 */
@Service
@Slf4j
public class WxServiceImpl implements WxService {
    private static final String SPBILL_CREATE_IP = "127.0.0.1";
    private static final String TRADE_TYPE_APP = "APP";
    private static final String TRADE_TYPE_NATIVE = "NATIVE";
    private static final String TRADE_TYPE_JSAPI = "JSAPI";

    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private UserDao userDao;
    @Lazy
    @Autowired
    private AppOrderService appOrderService;
    @Autowired
    private AppOrderDao appOrderDao;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private TbCouponUserService tbCouponUserService;
    @Autowired
    private UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    private GoodsShopDao goodsShopDao;
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private GoodsSkuDao goodsSkuDao;
    @Autowired
    private OrderGoodsDao orderGoodsDao;
    @Autowired
    private TbCouponUserDao tbCouponUserDao;
    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private GoodsShopRelevancyDao goodsShopRelevancyDao;
    @Lazy
    @Autowired
    private DataCentreService dataCentreService;
    @Lazy
    @Autowired
    private AliPayController aliPayController;
    @Lazy
    @Autowired
    private TbIndentService indentService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Lazy
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ShopMessageService shopMessageService;

    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Result balanceOrder(Long userId, Long parentId, Integer orderType, Long addressId) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            return balanceOrders(userId, parentId, orderType, addressId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Transactional
    public Result balanceOrders(Long userId, Long parentId, Integer orderType, Long addressId) {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        TbOrder tbOrder2 = appOrderDao.selectById(parentId);
        Address address = addressDao.selectById(addressId);
        tbOrder2.setOrderType(orderType);
        //判断商品数量不能超过库存
        Long orderId1 = tbOrder2.getOrderId();
        List<OrderGoods> orderGoodsList1 = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId1));
        for (int b = 0; b < orderGoodsList1.size(); b++) {
            Long goodsId = orderGoodsList1.get(b).getGoodsId();
            OrderGoods orderGoods = orderGoodsList1.get(b);
            Goods goods = goodsService.getById(orderGoods.getGoodsId());
            if (goods == null || goods.getStatus().equals(1)) {
                orderGoodsDao.deleteById(orderGoods.getId());
                return Result.error("商品：" + orderGoods.getGoodsName() + ",不存在，请刷新后重试！");
            }

            GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                    .eq("goods_id", goodsId).eq("shop_id", tbOrder2.getShopId()));
            int i = goodsShopRelevancyDao.selectGoodsCount(orderId1, goodsId);
            if (goodsShopRelevancy.getInventory() < i) {
                return Result.error("库存不足");
            }
        }
        List<TbOrder> tbOrderList = appOrderService.selectOrderByParentId(parentId);
        BigDecimal goodsPack = BigDecimal.valueOf(0);
        BigDecimal payMoney = BigDecimal.valueOf(0);
        for (int i = 0; i < tbOrderList.size(); i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrderList.get(i).getOrderId()));
            for (int a = 0; a < orderGoodsList.size(); a++) {
                BigDecimal goodsNum = new BigDecimal(orderGoodsList.get(a).getGoodsNum());
                BigDecimal goodsPrice = orderGoodsList.get(a).getGoodsPrice();
                BigDecimal goodsPacks = orderGoodsList.get(a).getGoodsPack();
                BigDecimal sumGoodsPack = goodsNum.multiply(goodsPacks);
                BigDecimal multiply1 = goodsNum.multiply(goodsPrice);
                goodsPack = goodsPack.add(sumGoodsPack);
                payMoney = payMoney.add(multiply1);
                BigDecimal multiply2 = goodsNum.multiply(orderGoodsList.get(a).getGoodsPack());
                payMoney = payMoney.add(multiply2);
            }
        }
        //查该商户的配送费 和 减免配送费最小订单金额
        GoodsShop goodsShop2 = goodsShopDao.selectById(tbOrder2.getShopId());
        BigDecimal errandMoney = BigDecimal.ZERO;
        if (orderType == 2) {
            //计算用户位置到商户位置的距离，并判断是否在配送范围内
            double distance = distance(goodsShop2.getShopLat(), goodsShop2.getShopLng(), address.getLat(), address.getLng());
            if (distance > goodsShop2.getDistributionDistance()) {
                return Result.error("超出商家配送范围，无法点餐！");
            }
            if (goodsShop2.getExemptMinMoney() != null && payMoney.doubleValue() < goodsShop2.getExemptMinMoney().doubleValue() && goodsShop2.getErrandMoney() != null && goodsShop2.getErrandMoney().doubleValue() > 0) {
                //加跑腿费
                payMoney = payMoney.add(goodsShop2.getErrandMoney());
                errandMoney = goodsShop2.getErrandMoney();
                tbOrder2.setErrandMoneyIsShop("本单未达到商家满减金额，跑腿费由用户承担");
            } else {
                tbOrder2.setErrandMoneyIsShop("本单已达到商家满减金额，跑腿费由商家承担");
                if (goodsShop2.getAutoSendOrder() != null && goodsShop2.getAutoSendOrder() == 0) {
                    errandMoney = goodsShop2.getErrandMoney() == null ? BigDecimal.ZERO : goodsShop2.getErrandMoney();
                }
            }

            tbOrder2.setErrandMoney(goodsShop2.getErrandMoney() == null ? BigDecimal.ZERO : goodsShop2.getErrandMoney());
            //判断订单金额是否大于最低起送金额
            if (goodsShop2.getMinimumDelivery() == null) {
                goodsShop2.setMinimumDelivery(BigDecimal.valueOf(0));
            }
            if (goodsShop2.getMinimumDelivery() != null && payMoney.doubleValue() < goodsShop2.getMinimumDelivery().doubleValue()) {
                return Result.error("订单金额未满足最低起送金额！");
            }
        }
        if (tbOrder2.getCouponId() != null) {
            TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder2.getCouponId());
            //计算总支付金额
            if (!tbCouponUser.getUserId().equals(userId)) {
                return Result.error("优惠券与登录用户不匹配");
            }
            if (tbCouponUser.getStatus() != 0) {
                return Result.error("该优惠券已失效");
            }
            if (tbCouponUser.getMinMoney().doubleValue() > payMoney.doubleValue()) {
                return Result.error("订单金额不足，无法使用该优惠券");
            }
            if (!tbCouponUser.getShopId().equals(tbOrder2.getShopId()) && tbCouponUser.getShopId() != 0) {
                return Result.error("优惠券使用错误，请刷新后重试");
            }
            payMoney = payMoney.subtract(tbCouponUser.getMoney());
            //如果使用红包后，订单价格小于0，则改为0.01元
            if (payMoney.doubleValue() <= 0) {
                payMoney = new BigDecimal("0.01");
            }
        }
        if (tbOrderList.size() == 0) {
            return Result.error("订单不存在，请刷新后重试！");
        }
        if (orderType == 2 && addressId == null) {
            return Result.error("请填写地址地址！");
        }
        /*if(!tbOrderList.get(0).getOrderId().equals(tbOrderList.get(0).getParentId())){
            return Result.error("您不是订单发起人，无法支付该订单！");
        }*/
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        if (payMoney.doubleValue() > userMoney.getMoney().doubleValue()) {
            return Result.error("您的余额不足，请充值后再支付！");
        }
        tbOrder2.setPayMoney(payMoney);
        userMoneyService.updateMoney(2, userId, tbOrder2.getPayMoney().doubleValue());
        //支付成功，增加该商品和商铺的销量，减少该商品库存
        Long shopId1 = tbOrder2.getShopId();
        Long orderId = tbOrder2.getOrderId();
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId));
        for (int a = 0; a < orderGoodsList.size(); a++) {
            Integer goodsNum = orderGoodsList.get(a).getGoodsNum();
            Long goodsId = orderGoodsList.get(a).getGoodsId();
            GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                    .eq("shop_id", shopId1).eq("goods_id", goodsId));
            GoodsShopRelevancy goodsShopRelevancy1 = new GoodsShopRelevancy();
            goodsShopRelevancy1.setId(goodsShopRelevancy.getId());
            goodsShopRelevancy1.setSales(goodsShopRelevancy.getSales() + goodsNum);//加销量
            goodsShopRelevancy1.setInventory(goodsShopRelevancy.getInventory() - goodsNum);//减库存
            goodsShopRelevancyDao.updateById(goodsShopRelevancy1);
            goodsShopDao.updateShopSales(1, goodsNum, goodsShopRelevancy.getShopId());
        }

        //支付成功，修改订单状态

        TbOrder tbOrder = orderGoodsDao.selectByPayTime(format);
        String orderCode = null;
        if (tbOrder == null) {
            String a = new SimpleDateFormat("yyyyMMdd").format(new Date());
            orderCode = a + "001";
        } else {
            Long a = Long.parseLong(tbOrder.getOrderCode()) + 1;
            orderCode = a.toString();
        }
        tbOrder2.setOrderCode(orderCode);
        //tbOrder1.setOrderCode(orderCode);
        tbOrder2.setIsPay(1);
        tbOrder2.setErrandMoney(errandMoney);
        tbOrder2.setPackMoney(goodsPack);
        tbOrder2.setOrderType(orderType);
        tbOrder2.setStatus(7);
        tbOrder2.setPayMoney(payMoney);
        tbOrder2.setPayType(2);
        tbOrder2.setPayTime(format);
        if (orderType == 2) {
            //添加地址
            String addressJson = JSONObject.toJSONString(address);
            tbOrder2.setAddress(addressJson);
            tbOrder2.setAddressId(addressId);
        }
        Integer autoSendOrder = 1;
        //如果是外卖订单,则生成一个跑腿的订单
        if (orderType == 2) {
            tbOrder2.setAddressId(addressId);
            GoodsShop goodsShop = goodsShopDao.selectById(tbOrder2.getShopId());
            //商户开启自动推单再生成订单
            if (goodsShop.getAutoSendOrder() == 0) {
                autoSendOrder = 0;
            }
        }
        indentService.insertIndent(tbOrder2);
        tbOrder2.setAutoSendOrder(autoSendOrder);
        appOrderDao.updateById(tbOrder2);
        //将优惠券改为已使用状态
        if (tbOrder2.getCouponId() != null) {
            TbCouponUser tbCouponUser = new TbCouponUser();
            tbCouponUser.setId(tbOrder2.getCouponId());
            tbCouponUser.setStatus(1);
            tbCouponUserService.updateById(tbCouponUser);
        }
        //添加钱包消费记录
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setUserId(userId);
        userMoneyDetails.setTitle("余额支付");
        userMoneyDetails.setType(2);
        userMoneyDetails.setClassify(3);
        userMoneyDetails.setState(2);
        userMoneyDetails.setMoney(tbOrder2.getPayMoney());
        String money = String.format("%.2f", tbOrder2.getPayMoney());
        userMoneyDetails.setContent("使用余额支付：" + money + "元");
        userMoneyDetails.setCreateTime(sdf.format(new Date()));
        userMoneyDetailsDao.insert(userMoneyDetails);
        //添加消息记录
        MessageInfo messageInfo = new MessageInfo();
        UserEntity userEntity = userDao.selectById(userId);
        messageInfo.setTitle("下单");
        messageInfo.setContent("恭喜您，下单成功！");
        messageInfo.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        messageInfo.setUserId(tbOrder2.getUserId().toString());
        messageInfo.setUserName(userEntity.getUserName());
        messageInfoDao.insert(messageInfo);
        //店铺端添加消息记录
        MessageInfo messageInfo1 = new MessageInfo();
        messageInfo1.setTitle("有新订单");
        messageInfo1.setCreateAt(format);
        messageInfo1.setContent("有新订单，请及时处理！");
        messageInfo1.setShopId(tbOrder2.getShopId());
        messageInfo1.setReadFlag(2);
        messageInfo1.setIsSee("2");
        messageInfoDao.insert(messageInfo1);
        //设置小程序消息推送
        CommonInfo one2 = commonInfoService.findOne(269);
        List<String> msgList = new ArrayList<>();
        Long shopId = tbOrder2.getShopId();
        GoodsShop goodsShop = shopMessageService.selectShopId(shopId);
        String shopName = goodsShop.getShopName();
//        String goodsMoney = tbOrder2.getPayMoney().toString();
        String orderNum1 = tbOrder2.getOrderNumber();
//        String payTime = tbOrder2.getPayTime();
        msgList.add("下单成功");
        msgList.add(orderNum1);
        msgList.add(shopName);
        msgList.add(format);
        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one2.getValue(), msgList, 1);
        userService.pushToSingle("下单成功", "亲爱的用户您好，您已下单成功，请等待商家接单！", userEntity.getClientid());


        CommonInfo shopTemplate = commonInfoService.findOne(352);
        //商家通知
        List<String> msgShopList = new ArrayList<>();
        msgShopList.add(tbOrder2.getOrderNumber());
        msgShopList.add(tbOrder2.getPayMoney().toString());
        msgShopList.add(tbOrder2.getPayTime());
        msgShopList.add("生意来了，立即去接单>");
        UserEntity shopUser = userService.selectUserById(goodsShop.getUserId());
        if (StringUtils.isNotEmpty(shopUser.getShopOpenId())) {
            SenInfoCheckUtil.sendShopMsg(shopUser.getShopOpenId(), shopTemplate.getValue(), msgShopList, 7);
        }
        if (StringUtils.isNotEmpty(shopUser.getShopClientId())) {
            userService.pushToSingleShop("下单成功", "生意来了，立即去接单>", shopUser.getShopClientId());
        }


        //处理如果是设置了自动接单 判断是否自动接单
        //商户开启自动推单再生成订单
        BigDecimal shopRate = goodsShop.getShopRate();
        BigDecimal sumMoney = tbOrder2.getPayMoney();
        if (tbOrder2.getCouponId() != null) {
            TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder2.getCouponId());
            sumMoney = tbOrder2.getPayMoney().add(tbCouponUser.getMoney());
        }
        if (tbOrder2.getAutoSendOrder() == 0) {
            //再减去商户需要支付的配送费
//            sumMoney = sumMoney.subtract(tbOrder2.getErrandMoney());
            sumMoney = sumMoney.subtract(goodsShop2.getErrandMoney());
        }

        BigDecimal shopMoney = sumMoney.multiply(shopRate);
        shopMoney = (shopMoney.setScale(2, BigDecimal.ROUND_DOWN));
        tbOrder2.setShopIncomeMoney(shopMoney);
        if (goodsShop.getAutoAcceptOrder() != null && goodsShop.getAutoAcceptOrder() == 0) {
            tbOrder2.setStatus(6);
            appOrderService.updateOrder(tbOrder2);
        } else {
            appOrderService.updateOrder(tbOrder2);
        }
        return Result.success();
    }

    @Override
    public Result balanceBuyVip(Long userId) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            return balanceBuyVips(userId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Override
    public Result wxPayJsApiBuyVip(Long userId, Integer type) throws Exception {
        String generalOrder = getGeneralOrder();
        CommonInfo one = commonInfoService.findOne(313);
        if (type == 4 || type == 5) {
            return aliPayController.payVip(Double.valueOf(one.getValue()), type, userId, generalOrder, 4);
        }
        return pay(Double.valueOf(one.getValue()), type, userId, generalOrder, 4);
    }

    @Transactional
    public Result balanceBuyVips(Long userId) {
        CommonInfo one = commonInfoService.findOne(313);
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        if (userMoney.getMoney().doubleValue() < Double.valueOf(one.getValue())) {
            return Result.error("余额不足！");
        }
        userMoneyService.updateMoney(2, userId, Double.valueOf(one.getValue()));
        dataCentreService.presenterVip(userId);
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setUserId(userId);
        userMoneyDetails.setTitle("用户开通会员");
        userMoneyDetails.setState(2);
        userMoneyDetails.setType(2);
        userMoneyDetails.setClassify(3);
        userMoneyDetails.setMoney(BigDecimal.valueOf(Double.valueOf(one.getValue())));
        userMoneyDetails.setContent("用户开通会员，花费" + Double.valueOf(one.getValue()) + "元");
        userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        userMoneyDetailsDao.insert(userMoneyDetails);
        return Result.success();
    }

    public double distance(double ol, double od, double dl, double dd) {
        GlobalCoordinates source = new GlobalCoordinates(ol, od);
        GlobalCoordinates target = new GlobalCoordinates(dl, dd);
        return LonLatUtil.getDistanceMeter(source, target, Ellipsoid.Sphere);
    }


    @Override
    public Result shopCashDeposit(Long shopId, Double money, String openId, Integer type) throws Exception {
        GoodsShop goodsShop = goodsShopDao.selectById(shopId);
        if (goodsShop.getStatus() != 1) {
            return Result.error("管理端审核成功后才能交保证金");
        }
        String generalOrder = getGeneralOrder();
        return shopPay(money, generalOrder, openId, shopId, type);
    }

    @Override
    public Result payMoney(Long userId, BigDecimal money, Integer type) throws Exception {
        String generalOrder = getGeneralOrder();
        if (type == 4 || type == 5) {
            return aliPayController.aliPayMoney(money.doubleValue(), type, userId, generalOrder, 2);
        }
        return pay(money.doubleValue(), type, userId, generalOrder, 2);
    }

    @Override
    public Result payOrder(Long userId, Long parentId, Integer type, Long addressId, Integer orderType) throws Exception {
        TbOrder tbOrder2 = appOrderDao.selectById(parentId);
        Address address = addressDao.selectById(addressId);
        //判断商品数量不能超过库存
        Long orderId1 = tbOrder2.getOrderId();
        List<OrderGoods> orderGoodsList1 = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId1));
        for (int b = 0; b < orderGoodsList1.size(); b++) {
            Long goodsId = orderGoodsList1.get(b).getGoodsId();
            OrderGoods orderGoods = orderGoodsList1.get(b);
            Goods goods = goodsService.getById(orderGoods.getGoodsId());
            if (goods == null || goods.getStatus().equals(1)) {
                orderGoodsDao.deleteById(orderGoods.getId());
                return Result.error("商品：" + orderGoods.getGoodsName() + ",不存在，请刷新后重试！");
            }
            GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                    .eq("goods_id", goodsId).eq("shop_id", tbOrder2.getShopId()));
            int i = goodsShopRelevancyDao.selectGoodsCount(orderId1, goodsId);
            if (goodsShopRelevancy.getInventory() < i) {
                return Result.error("库存不足");
            }
        }
        List<TbOrder> tbOrder = appOrderService.selectOrderByParentId(parentId);
        BigDecimal goodsPack = BigDecimal.valueOf(0);
        BigDecimal payMoney = BigDecimal.valueOf(0);
        for (int i = 0; i < tbOrder.size(); i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.get(i).getOrderId()));
            for (int a = 0; a < orderGoodsList.size(); a++) {
                BigDecimal goodsNum = new BigDecimal(orderGoodsList.get(a).getGoodsNum());
                BigDecimal goodsPrice = orderGoodsList.get(a).getGoodsPrice();
                BigDecimal goodsPacks = orderGoodsList.get(a).getGoodsPack();
                BigDecimal sumGoodsPack = goodsNum.multiply(goodsPacks);
                BigDecimal multiply1 = goodsNum.multiply(goodsPrice);
                goodsPack = goodsPack.add(sumGoodsPack);
                payMoney = payMoney.add(multiply1);
                BigDecimal multiply2 = goodsNum.multiply(orderGoodsList.get(a).getGoodsPack());
                payMoney = payMoney.add(multiply2);
            }
        }
        //查该商户的配送费 和 减免配送费最小订单金额
        GoodsShop goodsShop2 = goodsShopDao.selectById(tbOrder2.getShopId());
        BigDecimal errandMoney = BigDecimal.ZERO;

        TbOrder tbOrder1 = new TbOrder();

        if (orderType == 2) {
            //计算用户位置到商户位置的距离，并判断是否在配送范围内
            double distance = distance(goodsShop2.getShopLat(), goodsShop2.getShopLng(), address.getLat(), address.getLng());
            if (distance > goodsShop2.getDistributionDistance()) {
                return Result.error("超出商家配送范围，无法点餐！");
            }

            if (goodsShop2.getExemptMinMoney() != null && payMoney.doubleValue() < goodsShop2.getExemptMinMoney().doubleValue()) {
                //加跑腿费
                errandMoney = goodsShop2.getErrandMoney() == null ? BigDecimal.ZERO : goodsShop2.getErrandMoney();
                payMoney = payMoney.add(errandMoney);
                tbOrder1.setErrandMoneyIsShop("本单未达到商家满减金额，跑腿费由用户承担");
            } else {
                tbOrder1.setErrandMoneyIsShop("本单已达到商家满减金额，跑腿费由商家承担");
                if (goodsShop2.getAutoSendOrder() != null && goodsShop2.getAutoSendOrder() == 0) {
                    errandMoney = goodsShop2.getErrandMoney() == null ? BigDecimal.ZERO : goodsShop2.getErrandMoney();
                }
            }
            tbOrder2.setErrandMoney(goodsShop2.getErrandMoney() == null ? BigDecimal.ZERO : goodsShop2.getErrandMoney());
            //判断订单金额是否大于最低起送金额
            if (goodsShop2.getMinimumDelivery() == null) {
                goodsShop2.setMinimumDelivery(BigDecimal.valueOf(0));
            }
            if (goodsShop2.getMinimumDelivery() != null && payMoney.doubleValue() < goodsShop2.getMinimumDelivery().doubleValue()) {
                return Result.error("订单金额未满足最低起送金额！");
            }
            if (addressId == null) {
                return Result.error("请填写地址地址！");
            }
        }
        if (tbOrder2.getCouponId() != null) {
            TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder2.getCouponId());
            //计算总支付金额
            if (!tbCouponUser.getUserId().equals(userId)) {
                return Result.error("优惠券与登录用户不匹配");
            }
            if (tbCouponUser.getStatus() != 0) {
                return Result.error("该优惠券已失效");
            }
            if (tbCouponUser.getMinMoney().doubleValue() > payMoney.doubleValue()) {
                return Result.error("订单金额不足，无法使用该优惠券");
            }
            if (!tbCouponUser.getShopId().equals(tbOrder2.getShopId()) && tbCouponUser.getShopId() != 0) {
                return Result.error("优惠券使用错误，请刷新后重试");
            }
            payMoney = payMoney.subtract(tbCouponUser.getMoney());
            if (payMoney.doubleValue() <= 0) {
                payMoney = new BigDecimal(0.01);
            }
        }
        /*if(tbOrder.get(0).getOrderId().equals(tbOrder.get(0).getParentId())){
            return Result.error("您不是订单发起人，无法支付该订单！");
        }*/

        tbOrder1.setOrderId(tbOrder.get(0).getOrderId());
        tbOrder1.setPayMoney(payMoney);
        tbOrder1.setPackMoney(goodsPack);
        tbOrder1.setErrandMoney(errandMoney);
        tbOrder1.setOrderType(orderType);
        tbOrder1.setPayType(1);
        String generalOrder = getGeneralOrder();
        tbOrder1.setOrderNumber(generalOrder);
        if (orderType == 2) {
            //添加地址
            String addressJson = JSONObject.toJSONString(address);
            tbOrder1.setAddress(addressJson);
            tbOrder1.setAddressId(addressId);
        }

        if (type == 4 || type == 5) {
            tbOrder1.setPayType(3);
            appOrderDao.updateById(tbOrder1);
            return aliPayController.payAppOrders(payMoney.doubleValue(), type, tbOrder2.getUserId(), generalOrder, 1);
        }
        appOrderDao.updateById(tbOrder1);
        return pay(payMoney.doubleValue(), type, tbOrder2.getUserId(), generalOrder, 1);
    }

    /**
     * 微信支付订单生成
     *
     * @param moneys     支付金额 带小数点
     * @param type       类型 1app  2 二维码支付  3小程序 公众号支付
     * @param userId     用户id
     * @param outTradeNo 单号
     * @param classify   支付类型  1支付订单  2充值
     * @return
     * @throws Exception
     */
    private Result pay(Double moneys, Integer type, Long userId, String outTradeNo, Integer classify) throws Exception {
        //h5服务域名配置
        CommonInfo oneu = commonInfoService.findOne(19);
        String url;
        if (type == 3) {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyJsApi";//小程序支付
        } else if (type == 2) {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyMp";//公众号支付
        } else {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notify";//app支付
        }
        String currentTimeMillis = (System.currentTimeMillis() / 1000) + "";
        //后台服务名称
        CommonInfo one = commonInfoService.findOne(12);
        log.info("回调地址：" + url);
        Double mul = AmountCalUtils.mul(moneys, 100);
        String money = String.valueOf(mul.intValue());
        String generateNonceStr = WXPayUtil.generateNonceStr();
        WXConfig config = new WXConfig();
        //微信小程序APPID        微信公众号APPID
        if (type == 1) {
            config.setAppId(commonInfoService.findOne(74).getValue());
        } else if (type == 2) {
            config.setAppId(commonInfoService.findOne(5).getValue());
        } else if (type == 3) {
            config.setAppId(commonInfoService.findOne(45).getValue());
        }
        //微信商户key
        config.setKey(commonInfoService.findOne(75).getValue());
        //微信商户号mchId
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        //微信对应appid 小程序  公众号  app id
        data.put("appid", config.getAppID());
        //商户号
        data.put("mch_id", config.getMchID());
        //订单号
        data.put("nonce_str", generateNonceStr);
        String body = "";
        if (classify == 1) {
            //订单类型
            body = "下单支付";
        } else if (classify == 2) {
            body = "充值余额";
        } else if (classify == 4) {
            body = "购买会员";
        }
        //订单内容
        data.put("body", body);
        //生成商户订单号，不可重复
        data.put("out_trade_no", outTradeNo);
        data.put("total_fee", money);
        //自己的服务器IP地址
        data.put("spbill_create_ip", SPBILL_CREATE_IP);
        //异步通知地址（请注意必须是外网）
        data.put("notify_url", url);
        //交易类型
        data.put("trade_type", type == 1 ? TRADE_TYPE_APP : TRADE_TYPE_JSAPI);
        //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        data.put("attach", "");
        data.put("sign", WXPayUtil.generateSignature(data, config.getKey(),
                WXPayConstants.SignType.MD5));
        if (type == 3 || type == 2) {
            UserEntity userEntity = userService.queryByUserId(userId);
            if (type == 2) {
                data.put("openid", userEntity.getWxOpenId());
            } else {
                data.put("openid", userEntity.getOpenId());
            }
        }
        //使用官方API请求预付订单
        Map<String, String> response = wxpay.unifiedOrder(data);
        for (String key : response.keySet()) {
            log.info("微信支付订单微信返回参数：keys:" + key + "    value:" + response.get(key).toString());
        }
        if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数
            PayDetails payDetails = payDetailsDao.selectByOrderId(outTradeNo);
            if (payDetails == null) {
                payDetails = new PayDetails();
                payDetails.setState(0);
                payDetails.setCreateTime(sdf.format(new Date()));
                payDetails.setOrderId(outTradeNo);
                payDetails.setUserId(userId);
                payDetails.setMoney(AmountCalUtils.divide(Double.parseDouble(money), 100));
                payDetails.setClassify(classify);
                payDetails.setType(type);
                payDetailsDao.insert(payDetails);
            }
            if (type == 1) {
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("package", "Sign=WXPay");
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                        WXPayConstants.SignType.MD5));
                param.put("outtradeno", outTradeNo);
                return Result.success().put("data", param);
            } else {
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                    /*param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                            WXPayConstants.SignType.MD5));*/
                String stringSignTemp = "appId=" + config.getAppID() + "&nonceStr=" + generateNonceStr + "&package=prepay_id=" + response.get("prepay_id") + "&signType=MD5&timeStamp=" + currentTimeMillis + "" + "&key=" + config.getKey();
                String sign = MD5Util.md5Encrypt32Upper(stringSignTemp).toUpperCase();
                param.put("sign", sign);
                param.put("outtradeno", outTradeNo);
                param.put("package", "prepay_id=" + response.get("prepay_id"));//给前端返回的值
                param.put("mweb_url", response.get("mweb_url"));
                param.put("trade_type", response.get("trade_type"));
                param.put("return_msg", response.get("return_msg"));
                param.put("result_code", response.get("result_code"));
                param.put("signType", "MD5");
                return Result.success().put("data", param);
            }
        }
        return Result.error("获取订单失败");
    }

    /**
     * 商家缴纳保证金
     * @param moneys
     * @param outTradeNo
     * @param openId
     * @param shopId
     * @param type
     * @return
     * @throws Exception
     */
    private Result shopPay(Double moneys, String outTradeNo, String openId, Long shopId, Integer type) throws Exception {
        //h5服务域名配置
        CommonInfo oneu = commonInfoService.findOne(19);
        String url;
        if (type == 3) {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyJsApiShop";//小程序支付
        } else if (type == 2) {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyMpShop";//公众号支付
        } else {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyShop";//app支付
        }
        String currentTimeMillis = (System.currentTimeMillis() / 1000) + "";
        //后台服务名称
        CommonInfo one = commonInfoService.findOne(12);
        log.info("回调地址：" + url);
        Double mul = AmountCalUtils.mul(moneys, 100);
        String money = String.valueOf(mul.intValue());
        String generateNonceStr = WXPayUtil.generateNonceStr();
        WXConfig config = new WXConfig();
        /*//微信小程序APPID
        config.setAppId(commonInfoService.findOne(305).getValue());*/
        //微信小程序APPID        微信公众号APPID
        if (type == 1) {
            config.setAppId(commonInfoService.findOne(337).getValue());
        } else if (type == 2) {
            config.setAppId(commonInfoService.findOne(5).getValue());
        } else if (type == 3) {
            config.setAppId(commonInfoService.findOne(305).getValue());
        }
        //微信商户key
        config.setKey(commonInfoService.findOne(75).getValue());
        //微信商户号mchId
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        //微信对应appid 小程序  公众号  app id
        data.put("appid", config.getAppID());
        //商户号
        data.put("mch_id", config.getMchID());
        //订单号
        data.put("nonce_str", generateNonceStr);
        String body = one.getValue();
        //订单内容
        data.put("body", body);
        //生成商户订单号，不可重复
        data.put("out_trade_no", outTradeNo);
        data.put("total_fee", money);
        //自己的服务器IP地址
        data.put("spbill_create_ip", SPBILL_CREATE_IP);
        //异步通知地址（请注意必须是外网）
        data.put("notify_url", url);
        //交易类型
        data.put("trade_type", type == 1 ? TRADE_TYPE_APP : TRADE_TYPE_JSAPI);
        //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        data.put("attach", "");
        data.put("sign", WXPayUtil.generateSignature(data, config.getKey(),
                WXPayConstants.SignType.MD5));
        if (type == 3 || type == 2) {
            data.put("openid", openId);
        }
        //使用官方API请求预付订单
        Map<String, String> response = wxpay.unifiedOrder(data);
        for (String key : response.keySet()) {
            log.info("微信支付订单微信返回参数：keys:" + key + "    value:" + response.get(key).toString());
        }
        if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数
            PayDetails payDetails = payDetailsDao.selectByOrderId(outTradeNo);
            if (payDetails == null) {
                payDetails = new PayDetails();
                payDetails.setState(0);
                payDetails.setCreateTime(sdf.format(new Date()));
                payDetails.setOrderId(outTradeNo);
                payDetails.setShopId(shopId);
                payDetails.setMoney(AmountCalUtils.divide(Double.parseDouble(money), 100));
                payDetails.setClassify(3);
                payDetails.setType(type);
                payDetails.setRemark(String.valueOf(shopId));
                payDetailsDao.insert(payDetails);
            }

            if (type == 1) {
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("package", "Sign=WXPay");
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                        WXPayConstants.SignType.MD5));
                param.put("outtradeno", outTradeNo);
                return Result.success().put("data", param);
            } else {
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                    /*param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                            WXPayConstants.SignType.MD5));*/
                String stringSignTemp = "appId=" + config.getAppID() + "&nonceStr=" + generateNonceStr + "&package=prepay_id=" + response.get("prepay_id") + "&signType=MD5&timeStamp=" + currentTimeMillis + "" + "&key=" + config.getKey();
                String sign = MD5Util.md5Encrypt32Upper(stringSignTemp).toUpperCase();
                param.put("sign", sign);
                param.put("outtradeno", outTradeNo);
                param.put("package", "prepay_id=" + response.get("prepay_id"));//给前端返回的值
                param.put("mweb_url", response.get("mweb_url"));
                param.put("trade_type", response.get("trade_type"));
                param.put("return_msg", response.get("return_msg"));
                param.put("result_code", response.get("result_code"));
                param.put("signType", "MD5");
                return Result.success().put("data", param);
            }
        }
        return Result.error("获取订单失败");
    }

    @Override
    public String payBack(String resXml, Integer type) {
        WXConfig config = null;
        try {
            config = new WXConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("进入回调了！！！");
        if (type == 1) {
            config.setAppId(commonInfoService.findOne(74).getValue());
        } else if (type == 2) {
            config.setAppId(commonInfoService.findOne(5).getValue());
        } else {
            config.setAppId(commonInfoService.findOne(45).getValue());
        }
        config.setKey(commonInfoService.findOne(75).getValue());
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        try {
            notifyMap = WXPayUtil.xmlToMap(resXml);         // 调用官方SDK转换成map类型数据
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效，有效则进一步处理
                log.error("验证成功！！！");
                String return_code = notifyMap.get("return_code");//状态
                String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
                if (return_code.equals("SUCCESS")) {
                    log.error("验证成功222！！！");
                    if (out_trade_no != null) {
                        // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                        // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志
                        //业务数据持久化
                        log.error("订单号！！！" + out_trade_no);
                        PayDetails payDetails = payDetailsDao.selectByOrderId(out_trade_no);
                        //设置查询条件
                        if (payDetails.getState() == 0) {
                            payDetailsDao.updateState(payDetails.getId(), 1, sdf.format(new Date()), "");
                            //调用处理接口
                            //业务操作
                            notfiy(payDetails);

                        }
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                } else {
                }
                return xmlBack;
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
                System.err.println("手机支付回调通知签名错误");
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } catch (Exception e) {
            System.err.println("手机支付回调通知失败" + e);
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            log.error("支付回调异常！", e.getMessage(), e);
        }
        return xmlBack;
    }

    @Override
    public String payBackShop(String resXml, Integer type) {
        WXConfig config = null;
        try {
            config = new WXConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("进入回调了！！！");
        if (type == 1) {
            config.setAppId(commonInfoService.findOne(337).getValue());
        } else if (type == 2) {
            config.setAppId(commonInfoService.findOne(5).getValue());
        } else if (type == 3) {
            config.setAppId(commonInfoService.findOne(305).getValue());
        }
        config.setKey(commonInfoService.findOne(75).getValue());
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        try {
            notifyMap = WXPayUtil.xmlToMap(resXml);         // 调用官方SDK转换成map类型数据
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效，有效则进一步处理
                log.error("验证成功！！！");
                String return_code = notifyMap.get("return_code");//状态
                String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
                if (return_code.equals("SUCCESS")) {
                    log.error("验证成功222！！！");
                    if (out_trade_no != null) {
                        // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                        // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志
                        //业务数据持久化
                        log.error("订单号！！！" + out_trade_no);
                        PayDetails payDetails = payDetailsDao.selectByOrderId(out_trade_no);
                        //设置查询条件
                        if (payDetails.getState() == 0) {
                            payDetailsDao.updateState(payDetails.getId(), 1, sdf.format(new Date()), "");
                            //调用处理接口
                            //业务操作
                            notfiy(payDetails);

                        }
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                } else {
                }
                return xmlBack;
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
                System.err.println("手机支付回调通知签名错误");
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } catch (Exception e) {
            System.err.println("手机支付回调通知失败" + e);
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            log.error("支付回调异常！", e.getMessage(), e);
        }
        return xmlBack;
    }


    public String getGeneralOrder() {
        Date date = new Date();
        String newString = String.format("%0" + 4 + "d", (int) ((Math.random() * 9 + 1) * 1000));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(date);
        return format + newString;
    }

    @Override
    public void notifyRider(PayDetails payDetails) {
        if (payDetails.getClassify() == 1) {
            //充值金额
            payDetails.setClassify(1);//分类：1微信  2支付宝
            String date = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss").format(new Date());
            payDetails.setType(1);
            userDao.topUpMoney(payDetails.getClassify(), payDetails.getTradeNo(), payDetails.getMoney(), payDetails.getUserId(), payDetails.getState(), date, date, payDetails.getType());
        } else if (payDetails.getClassify() == 2) {
            //订单支付
            TbIndent indentByIndentNumber = indentService.findIndentByIndentNumber(payDetails.getOrderId());
            indentByIndentNumber.setIndentState("2");
            indentService.updateById(indentByIndentNumber);
        } else if (payDetails.getClassify() == 3) {
            //将保证金添加到骑手保证金里
            Double cashDeposit = payDetails.getMoney();
            Long userId = payDetails.getUserId();
            userDao.updateCashDeposit(userId, cashDeposit);
            //交保证金的记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setTitle("骑手缴纳保证金");
            userMoneyDetails.setContent("骑手缴纳保证金：" + cashDeposit + "元");
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(BigDecimal.valueOf(cashDeposit));
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss").format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);


            String remark = payDetails.getRemark();
            JSONObject user = JSONObject.parseObject(remark);

            String format = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss").format(new Date());
            userDao.certification(Long.parseLong(user.getString("userId")), user.getString("phone"),
                    user.getString("userName"), user.getString("identityCardNumber"), user.getString("identityCardFront"),
                    user.getString("identityCardVerso"), user.getString("selfIdentityCard"), format, payDetails.getOrderId(),
                    user.getBigDecimal("cashDeposit"));

        } else if (payDetails.getClassify() == 4) {
            Long userId = payDetails.getUserId();
            Double money = payDetails.getMoney();
            UserEntity userEntity = userDao.selectById(userId);
            BigDecimal cashDeposit = userEntity.getCashDeposit().add(BigDecimal.valueOf(money));
            UserEntity userEntity1 = new UserEntity();
            userEntity1.setUserId(userId);
            userEntity1.setCashDeposit(cashDeposit);
            userDao.updateById(userEntity1);

            //交保证金的记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setTitle("骑手缴纳保证金");
            userMoneyDetails.setContent("骑手缴纳保证金：" + payDetails.getMoney() + "元");
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss").format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        }
    }

    @Transactional
    @Override
    public void notfiy(PayDetails payDetails) {
        log.error("回调订单:"+payDetails.toString());
        if (payDetails.getClassify() == 2) {
            //充值金额
            userMoneyService.updateMoney(1, payDetails.getUserId(), payDetails.getMoney());
            //修改本充值记录状态
            PayDetails payDetails1 = new PayDetails();
            String date = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss").format(new Date());
            payDetails1.setId(payDetails.getId());
            payDetails1.setState(1);
            payDetails1.setPayTime(date);
            payDetailsDao.updateById(payDetails1);
            //添加钱包消费记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(payDetails.getUserId());
            userMoneyDetails.setTitle("钱包充值");
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
            userMoneyDetails.setContent("账户充值到账：" + payDetails.getMoney() + "元");
            userMoneyDetails.setCreateTime(sdf.format(new Date()));
            userMoneyDetailsDao.insert(userMoneyDetails);
        } else if (payDetails.getClassify() == 1) {
            //订单支付
            TbOrder tbOrder = appOrderService.selectOrderByNum(payDetails.getOrderId());
            Integer autoSendOrder = 1;
            //如果是外卖订单,则生成一个跑腿的订单
            if (tbOrder.getOrderType() == 2) {
                GoodsShop goodsShop = goodsShopDao.selectById(tbOrder.getShopId());
                //商户开启自动推单再生成订单
                if (goodsShop.getAutoSendOrder() == 0) {
                    autoSendOrder = 0;
                }
            }
            tbOrder.setAutoSendOrder(autoSendOrder);
            appOrderDao.updateById(tbOrder);
            List<TbOrder> tbOrderList = appOrderDao.selectList(new QueryWrapper<TbOrder>().eq("parent_id", tbOrder.getParentId()));
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            for (int i = 0; i < tbOrderList.size(); i++) {
                TbOrder tbOrder1 = new TbOrder();
                TbOrder tbOrder2 = orderGoodsDao.selectByPayTime(time);
                String orderCode = null;
                if (tbOrder2 == null) {
                    String a = new SimpleDateFormat("yyyyMMdd").format(new Date());
                    orderCode = a + "001";
                } else {
                    Long a = Long.parseLong(tbOrder2.getOrderCode()) + 1;
                    orderCode = a.toString();
                }
                tbOrder.setOrderCode(orderCode);
                tbOrder1.setOrderCode(orderCode);
                tbOrder1.setOrderId(tbOrderList.get(i).getOrderId());
                tbOrder1.setIsPay(1);
                tbOrder1.setStatus(7);
                tbOrder1.setPayTime(time);
                appOrderDao.updateById(tbOrder1);
            }
            tbOrder.setPayTime(time);
            tbOrder.setIsPay(1);
            tbOrder.setStatus(7);
            indentService.insertIndent(tbOrder);
            //将红包改为已使用状态
            TbCouponUser tbCouponUser = new TbCouponUser();
            tbCouponUser.setId(tbOrder.getCouponId());
            tbCouponUser.setStatus(1);
            tbCouponUserDao.updateById(tbCouponUser);
            //支付成功，增加该商品销量，减少该商品库存
            Long shopId1 = tbOrder.getShopId();
            Long orderId = tbOrder.getOrderId();
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId));
            for (int a = 0; a < orderGoodsList.size(); a++) {
                Integer goodsNum = orderGoodsList.get(a).getGoodsNum();
                Long goodsId = orderGoodsList.get(a).getGoodsId();
                GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                        .eq("shop_id", shopId1).eq("goods_id", goodsId));
                GoodsShopRelevancy goodsShopRelevancy1 = new GoodsShopRelevancy();
                goodsShopRelevancy1.setId(goodsShopRelevancy.getId());
                goodsShopRelevancy1.setSales(goodsShopRelevancy.getSales() + goodsNum);//加销量
                goodsShopRelevancy1.setInventory(goodsShopRelevancy.getInventory() - goodsNum);//减库存
                goodsShopRelevancyDao.updateById(goodsShopRelevancy1);
                goodsShopDao.updateShopSales(1, goodsNum, goodsShopRelevancy.getShopId());
            }

            //添加用户钱包消费记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(tbOrder.getUserId());
            if (payDetails.getType() == 1 || payDetails.getType() == 2 || payDetails.getType() == 3) {
                userMoneyDetails.setTitle("微信支付");
                userMoneyDetails.setContent("使用微信支付：" + tbOrder.getPayMoney() + "元");
            } else {
                userMoneyDetails.setTitle("支付宝支付");
                userMoneyDetails.setContent("使用支付宝支付：" + tbOrder.getPayMoney() + "元");
            }

            userMoneyDetails.setType(2);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(tbOrder.getPayMoney());

            userMoneyDetails.setCreateTime(sdf.format(new Date()));
            userMoneyDetailsDao.insert(userMoneyDetails);
            //用户端添加消息记录
            MessageInfo messageInfo = new MessageInfo();
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            messageInfo.setTitle("下单");
            messageInfo.setContent("恭喜您，下单成功！");
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            messageInfo.setCreateAt(format);
            messageInfo.setUserId(tbOrder.getUserId().toString());
            messageInfo.setUserName(userEntity.getUserName());
            messageInfoDao.insert(messageInfo);
            //店铺端添加消息记录
            MessageInfo messageInfo1 = new MessageInfo();
            messageInfo1.setTitle("有新订单");
            messageInfo1.setCreateAt(format);
            messageInfo1.setContent("有新订单，请及时处理！");
            messageInfo1.setShopId(tbOrder.getShopId());
            messageInfo1.setReadFlag(2);
            messageInfo1.setIsSee("2");
            messageInfoDao.insert(messageInfo1);
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(269);
            List<String> msgList = new ArrayList<>();
            Long shopId = tbOrder.getShopId();
            GoodsShop goodsShop = goodsShopDao.selectById(shopId);
            String shopName = goodsShop.getShopName();
            String orderNum = tbOrder.getOrderNumber();
            msgList.add("下单成功");
            msgList.add(orderNum);
            msgList.add(shopName);
            msgList.add(format);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
            userService.pushToSingle("下单成功", "亲爱的用户您好，您已下单成功！", userEntity.getClientid());
            BigDecimal shopRate = goodsShop.getShopRate();
            BigDecimal sumMoney = tbOrder.getPayMoney();
            if (tbOrder.getCouponId() != null) {
                tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
                sumMoney = tbOrder.getPayMoney().add(tbCouponUser.getMoney());
            }
            if (tbOrder.getAutoSendOrder() == 0) {
                //再减去商户需要支付的配送费
                sumMoney = sumMoney.subtract(goodsShop.getErrandMoney());
            }

            BigDecimal shopMoney = sumMoney.multiply(shopRate);
            shopMoney = (shopMoney.setScale(2, BigDecimal.ROUND_DOWN));
            tbOrder.setShopIncomeMoney(shopMoney);
            if (goodsShop.getAutoAcceptOrder() != null && goodsShop.getAutoAcceptOrder() == 0) {
                tbOrder.setStatus(6);
                tbOrder.setIsPay(1);
                appOrderService.updateOrder(tbOrder);
            } else {
                appOrderService.updateOrder(tbOrder);
            }

            CommonInfo shopTemplate = commonInfoService.findOne(352);
            //商家通知
            List<String> msgShopList = new ArrayList<>();
            msgShopList.add(tbOrder.getOrderNumber());
            msgShopList.add(tbOrder.getPayMoney().toString());
            msgShopList.add(tbOrder.getPayTime());
            msgShopList.add("生意来了，立即去接单>");
            UserEntity shopUser = userService.selectUserById(goodsShop.getUserId());
            if (StringUtils.isNotEmpty(shopUser.getShopOpenId())) {
                SenInfoCheckUtil.sendShopMsg(shopUser.getShopOpenId(), shopTemplate.getValue(), msgShopList, 7);
            }
            if (StringUtils.isNotEmpty(shopUser.getShopClientId())) {
                userService.pushToSingleShop("下单成功", "生意来了，立即去接单>", shopUser.getShopClientId());
            }

        } else if (payDetails.getClassify() == 3) {
            //商户交保证金
            Double money = payDetails.getMoney();
            Long shopId = payDetails.getShopId();
            goodsShopDao.updateCashDeposit(money, shopId);
            PayDetails payDetails1 = new PayDetails();
            payDetails1.setId(payDetails.getId());
            payDetails1.setState(1);
            payDetailsDao.updateById(payDetails1);
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setShopId(shopId);
            userMoneyDetails.setTitle("商户缴纳保证金");
            userMoneyDetails.setState(2);
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(2);
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setContent("商户缴纳保证金" + money + "元");
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            userMoneyDetailsDao.insert(userMoneyDetails);

        } else if (payDetails.getClassify() == 4) {
            PayDetails payDetails1 = new PayDetails();
            payDetails1.setId(payDetails.getId());
            payDetails1.setState(1);
            payDetailsDao.updateById(payDetails1);
            dataCentreService.presenterVip(payDetails.getUserId());
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(payDetails.getUserId());
            userMoneyDetails.setTitle("用户开通会员");
            userMoneyDetails.setState(2);
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
            userMoneyDetails.setContent("用户开通会员，花费" + payDetails.getMoney() + "元");
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            userMoneyDetailsDao.insert(userMoneyDetails);
        } else if (payDetails.getClassify() == 5) {
            //订单支付
            TbIndent indentByIndentNumber = indentService.findIndentByPayOrdersNo(payDetails.getOrderId());
            indentByIndentNumber.setIndentState("2");
            indentService.updateById(indentByIndentNumber);

            CommonInfo one = commonInfoService.findOne(335);
            List<String> msgList = new ArrayList<>();

            String orderNum = indentByIndentNumber.getIndentNumber();
            msgList.add(orderNum);
            msgList.add("已支付");
            msgList.add("下单成功,正在寻找跑腿师傅");
            msgList.add(DateUtils.format(new Date()));
            UserEntity userEntity = userService.getById(indentByIndentNumber.getUserId());
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 5);
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(indentByIndentNumber.getUserId());
            if (payDetails.getType() == 1 || payDetails.getType() == 2 || payDetails.getType() == 3) {
                userMoneyDetails.setTitle("微信支付");
                userMoneyDetails.setContent("使用微信支付：" + indentByIndentNumber.getIndentMoney() + "元");
            } else {
                userMoneyDetails.setTitle("支付宝支付");
                userMoneyDetails.setContent("使用支付宝支付：" + indentByIndentNumber.getIndentMoney() + "元");
            }

            userMoneyDetails.setType(2);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(indentByIndentNumber.getIndentMoney());

            userMoneyDetails.setCreateTime(sdf.format(new Date()));
            userMoneyDetailsDao.insert(userMoneyDetails);
            indentService.sendNewIndentMsg(indentByIndentNumber);
        }
    }


    /*@Override
    public boolean refund(Orders orders) {
        WXConfigUtil config = null;
        try {
            config = new WXConfigUtil();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int commInfoId = 0;
        Integer payWay = null;
        //orders.getPayWay(); //支付方式（1app微信 2微信公众号 3微信小程序 4app支付宝 5H5支付宝 6零钱）
        switch (payWay) {
            case 1:
                commInfoId = 5;
                break; //appId
            case 2:
                commInfoId = 74;
                break; //公众号id
            case 3:
                commInfoId = 45;
                break; //小程序id
        }
        config.setAppId(commonInfoService.findOne(commInfoId).getValue());
        config.setKey(commonInfoService.findOne(75).getValue());
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        try {
            data.put("sign", WXPayUtil.generateSignature(data, config.getKey(), WXPayConstants.SignType.MD5));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        data.put("out_trade_no", orders.getOrdersNo()); //订单号,支付单号一致
        data.put("out_refund_no", orders.getOrdersNo()); //退款单号，同一笔用不同的退款单号
        double total_fee = 0.00;
        data.put("total_fee", new Double(orders.getPayMoney().doubleValue() * 100).intValue() + ""); //1块等于微信支付传入100);
        data.put("refund_fee", new Double(orders.getPayMoney().doubleValue() * 100).intValue() + ""); //1块等于微信支付传入100);
        //使用官方API退款
        try {
            Map<String, String> response = wxpay.refund(data);
            if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数
                System.err.println("退款成功");
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.info("返回");
            e.printStackTrace();
            return false;
        }
    }*/

    @Override
    public boolean wxRefund(PayDetails payDetails) {
        WXConfigUtil config = null;
        String h5Url = commonInfoService.findOne(19).getValue().split("://")[1];
        String filePath = "/www/wwwroot/" + h5Url + "/service/apiclient_cert.p12";
        try {
            config = new WXConfigUtil(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int commInfoId = 0;
        Integer payWay = payDetails.getType(); //支付方式（1app微信 2微信公众号 3微信小程序 4app支付宝 5H5支付宝 6零钱）
        switch (payWay) {
            case 1:
                commInfoId = 74;
                break; //appId
            case 2:
                commInfoId = 5;
                break; //公众号id
            case 3:
                commInfoId = 45;
                break; //小程序id
        }
        config.setAppId(commonInfoService.findOne(commInfoId).getValue());
        config.setKey(commonInfoService.findOne(75).getValue());
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        try {
            data.put("sign", WXPayUtil.generateSignature(data, config.getKey(), WXPayConstants.SignType.MD5));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        data.put("out_trade_no", payDetails.getOrderId()); //订单号,支付单号一致
        data.put("out_refund_no", payDetails.getOrderId()); //退款单号，同一笔用不同的退款单号
        double total_fee = 0.00;
        data.put("total_fee", String.valueOf((new BigDecimal(payDetails.getMoney()).multiply(BigDecimal.valueOf(100))).intValue())); //1块等于微信支付传入100);
        data.put("refund_fee", String.valueOf((new BigDecimal(payDetails.getMoney()).multiply(BigDecimal.valueOf(100))).intValue())); //1块等于微信支付传入100);
        //使用官方API退款
        try {
            Map<String, String> response = wxpay.refund(data);
            if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数
                System.err.println("退款成功");
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error("返回");
            e.printStackTrace();
            log.error("微信退款失败！，订单号" + payDetails.getOrderId() + "，失败原因：" + e.getMessage(), e);
            return false;
        }
    }


}