package cn.ysk.cashier.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.ysk.cashier.dto.ScanPayDTO;
import cn.ysk.cashier.dto.shoptable.PayDTO;
import cn.ysk.cashier.enums.TableStateEnum;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.mybatis.entity.TbOrderPayment;
import cn.ysk.cashier.mybatis.entity.TbShopUserFlow;
import cn.ysk.cashier.mybatis.mapper.*;
import cn.ysk.cashier.mybatis.service.TbOrderPaymentService;
import cn.ysk.cashier.mybatis.vo.pay.MainScanResp;
import cn.ysk.cashier.mybatis.vo.pay.ScanPayReq;
import cn.ysk.cashier.pojo.TbShopPayType;
import cn.ysk.cashier.pojo.order.TbCashierCart;
import cn.ysk.cashier.pojo.order.TbOrderDetail;
import cn.ysk.cashier.pojo.order.TbOrderInfo;
import cn.ysk.cashier.pojo.shop.*;
import cn.ysk.cashier.repository.shop.TbMerchantThirdApplyRepository;
import cn.ysk.cashier.repository.shop.TbShopInfoRepository;
import cn.ysk.cashier.service.TbPayService;
import cn.ysk.cashier.thirdpay.resp.PublicResp;
import cn.ysk.cashier.thirdpay.service.ThirdPayService;
import cn.ysk.cashier.utils.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TbPayServiceImpl implements TbPayService {

    private final TbShopInfoRepository tbShopInfoRepository;
    private final TbMerchantAccountMapper tbMerchantAccountMapper;
    private final TbMShopUserMapper tbMShopUserMapper;
    private final TbShopPayTypeMapper tbShopPayTypeMapper;
    private final TbMemberInMapper tbMemberInMapper;
    private final TbActivateMapper tbActivateMapper;
    @Value("${gateway.url}")
    private String gateWayUrl;
    @Value("${client.backUrl}")
    private String backUrl;
    @Value("${thirdPay.payType}")
    private String thirdPayType;
    @Value("${thirdPay.url}")
    private String url;
    @Value("${thirdPay.callBack}")
    private String callBack;


    private final TbOrderInfoMapper orderInfoMapper;
    private final TbCashierCartMapper cashierCartMapper;
    private final TbMerchantThirdApplyRepository merchantThirdApplyRepository;
    private final TbOrderPaymentService orderPaymentService;
    private final TbShopPayTypeMapper shopPayTypeMapper;
    private final TbOrderDetailMapper orderDetailMapper;
    private final RabbitTemplate rabbitTemplate;
    private final RabbitMsgUtils rabbitMsgUtils;
    private final MpShopTableMapper mpShopTableMapper;
    private final RestTemplate restTemplate;
    private final MpOrderPaymentMapper mpOrderPaymentMapper;
    private final ThirdPayService thirdPayService;
    private final MpUserInfoMapper mpUserInfoMapper;



    public TbPayServiceImpl(TbOrderInfoMapper orderInfoMapper, TbCashierCartMapper cashierCartMapper, TbMerchantThirdApplyRepository merchantThirdApplyRepository, TbOrderPaymentService orderPaymentService, TbShopPayTypeMapper shopPayTypeMapper, TbOrderDetailMapper orderDetailMapper, RabbitTemplate rabbitTemplate, RabbitMsgUtils rabbitMsgUtils, MpShopTableMapper mpShopTableMapper, RestTemplate restTemplate, MpOrderPaymentMapper mpOrderPaymentMapper, ThirdPayService thirdPayService, TbMShopUserMapper shopUserMapper, TbShopUserFlowMapper shopUserFlowMapper, TbShopInfoRepository tbShopInfoRepository, TbMerchantAccountMapper tbMerchantAccountMapper, TbMShopUserMapper tbMShopUserMapper, TbShopPayTypeMapper tbShopPayTypeMapper, TbMemberInMapper tbMemberInMapper, MpUserInfoMapper mpUserInfoMapper, TbActivateMapper tbActivateMapper) {
        this.orderInfoMapper = orderInfoMapper;
        this.cashierCartMapper = cashierCartMapper;
        this.merchantThirdApplyRepository = merchantThirdApplyRepository;
        this.orderPaymentService = orderPaymentService;
        this.shopPayTypeMapper = shopPayTypeMapper;
        this.orderDetailMapper = orderDetailMapper;
        this.rabbitTemplate = rabbitTemplate;
        this.rabbitMsgUtils = rabbitMsgUtils;
        this.mpShopTableMapper = mpShopTableMapper;
        this.restTemplate = restTemplate;
        this.mpOrderPaymentMapper = mpOrderPaymentMapper;
        this.thirdPayService = thirdPayService;
        this.shopUserMapper = shopUserMapper;
        this.shopUserFlowMapper = shopUserFlowMapper;
        this.tbShopInfoRepository = tbShopInfoRepository;
        this.tbMerchantAccountMapper = tbMerchantAccountMapper;
        this.tbMShopUserMapper = tbMShopUserMapper;
        this.tbShopPayTypeMapper = tbShopPayTypeMapper;
        this.tbMemberInMapper = tbMemberInMapper;
        this.mpUserInfoMapper = mpUserInfoMapper;
        this.tbActivateMapper = tbActivateMapper;
    }

    @Override
    public TbOrderInfo scanPay(PayDTO scanPayDTO) {
        if (StrUtil.isBlank(scanPayDTO.getCode())) {
            throw new BadRequestException("无效码");
        }

        TbOrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaUpdateWrapper<TbOrderInfo>()
                .in(TbOrderInfo::getStatus, "unpaid", "paying")
                .eq(TbOrderInfo::getId, scanPayDTO.getOrderId())
                .eq(TbOrderInfo::getShopId, scanPayDTO.getShopId()));

        if (orderInfo == null) {
            throw new BadRequestException("订单不存在或已支付");
        }


        if (ObjectUtil.isNull(orderInfo.getMerchantId()) || ObjectUtil.isEmpty(orderInfo.getMerchantId())) {
            throw new BadRequestException("订单商户id为空");
        }


        List<TbCashierCart> cashierCarts = cashierCartMapper.selectList(new LambdaUpdateWrapper<TbCashierCart>()
                .eq(TbCashierCart::getShopId, scanPayDTO.getShopId())
                .eq(TbCashierCart::getOrderId, scanPayDTO.getOrderId()));
        if (cashierCarts.isEmpty()) {
            throw new BadRequestException("购物车为空");
        }

        StringBuilder body = new StringBuilder();
        for (TbCashierCart cashierCart : cashierCarts) {
            body.append(cashierCart.getName());
        }

        BigDecimal payMount = orderInfo.getOrderAmount().multiply(BigDecimal.valueOf(scanPayDTO.getDiscount())).setScale(2, RoundingMode.HALF_UP);


        TbMerchantThirdApply thirdApply = merchantThirdApplyRepository.getById(Integer.valueOf(orderInfo.getMerchantId()));
        if (ObjectUtil.isEmpty(thirdApply) || ObjectUtil.isNull(thirdApply)) {
            throw new BadRequestException("三方支付信息不存在");
        }

        String payType;
        String payName;
        String qpay;
        String payTypeCode = scanPayDTO.getCode().substring(0, 2);// 判断收款码

        if(Integer.parseInt(payTypeCode) >=25 && Integer.parseInt(payTypeCode) <= 30){
            payType = "aliPay";
            payName = "支付宝支付";
            qpay = "scanCode";
        }else if(Integer.parseInt(payTypeCode) >=10 &&Integer.parseInt(payTypeCode) <=19){
            payType = "wechatPay";
            payName = "微信支付";
            qpay = "scanCode";
        }else if("62".equals(payTypeCode)){
            throw new BadRequestException("错误码");
        }else if("01".equals(payTypeCode)){
            throw new BadRequestException("错误码");
        }else {
            throw new BadRequestException("错误码");
        }

        long count = shopPayTypeMapper.selectCount(new LambdaUpdateWrapper<TbShopPayType>()
                .eq(TbShopPayType::getShopId, scanPayDTO.getShopId())
                .eq(TbShopPayType::getIsDisplay, 1)
                .eq(TbShopPayType::getPayType, qpay));
        if (count < 1) {
            throw new BadRequestException("未到找支付方式");
        }

        TbOrderPayment payment = orderPaymentService.getById(scanPayDTO.getOrderId());
        if (ObjectUtil.isEmpty(payment) || payment == null) {
            payment = new TbOrderPayment();
            payment.setPayTypeId("ysk");
            payment.setAmount(payMount.doubleValue());
            payment.setPaidAmount(orderInfo.getPayAmount().doubleValue());
            payment.setHasRefundAmount((double) 0);
            payment.setPayName(payName);
            payment.setPayType(payType);
            payment.setReceived(payment.getAmount());
            payment.setChangeFee((double) 0);
            payment.setMemberId(orderInfo.getMemberId());
            payment.setShopId(orderInfo.getShopId());
            payment.setOrderId(orderInfo.getId().toString());
            payment.setCreatedAt(System.currentTimeMillis());
            payment.setAuthCode(scanPayDTO.getCode());
            orderPaymentService.save(payment);
        } else {
            payment.setAuthCode(scanPayDTO.getCode());
            payment.setUpdatedAt(System.currentTimeMillis());
            orderPaymentService.updateById(payment);
        }


        orderInfo.setPayAmount(payMount);
        orderInfo.setPayType(qpay);
        orderInfo.setUpdatedAt(System.currentTimeMillis());
        orderInfoMapper.update(orderInfo, new LambdaUpdateWrapper<TbOrderInfo>()
                .eq(TbOrderInfo::getId, scanPayDTO.getOrderId()));

        if ("ysk".equals(thirdPayType)) {

            ScanPayReq scanPayReq = new ScanPayReq();
            scanPayReq.setAppId(thirdApply.getAppId());
            scanPayReq.setTimestamp(System.currentTimeMillis());
            scanPayReq.setAuthCode(scanPayDTO.getCode());
            scanPayReq.setNotifyUrl(backUrl);
            scanPayReq.setConsumeFee(BigDecimal.valueOf(payment.getAmount()).setScale(2, RoundingMode.DOWN).toPlainString());

            Map<String, Object> map = BeanUtil.transBean2Map(scanPayReq);
            scanPayReq.setSign(MD5Util.encrypt(map, thirdApply.getAppToken(), true));


            ResponseEntity<String> response = restTemplate.postForEntity(gateWayUrl.concat("merchantOrder/scanPay"), scanPayReq, String.class);
            log.info("响应信息, {}", response);
            if (response.getStatusCodeValue() == 200 && ObjectUtil.isNotEmpty(response.getBody())) {
                JSONObject object = JSONObject.parseObject(response.getBody());
                if (object.get("code").equals("0")) {
                    payment.setTradeNumber(object.getJSONObject("data").get("orderNumber").toString());
                    payment.setUpdatedAt(System.currentTimeMillis());
                    orderPaymentService.saveOrUpdate(payment);

                    //处理支付成功的订单
                    orderInfo.setStatus("closed");
                    orderInfo.setPayOrderNo(object.getJSONObject("data").get("orderNumber").toString());
                    orderInfoMapper.update(orderInfo, new LambdaQueryWrapper<TbOrderInfo>()
                            .eq(TbOrderInfo::getId, scanPayDTO.getOrderId()));

                    //更新购物车状态
                    TbCashierCart cashierCart = new TbCashierCart();
                    cashierCart.setStatus("final");
                    int cartCount = cashierCartMapper.update(cashierCart, new LambdaQueryWrapper<TbCashierCart>()
                            .eq(TbCashierCart::getOrderId, scanPayDTO.getOrderId()));
                    log.info("更新购物车:{}", cartCount);

                    //更新子单状态
                    TbOrderDetail orderDetail = new TbOrderDetail();
                    orderDetail.setStatus("closed");
                    orderDetailMapper.update(orderDetail, new LambdaQueryWrapper<TbOrderDetail>()
                            .eq(TbOrderDetail::getOrderId, scanPayDTO.getOrderId()));


                    return orderInfo;

                } else {
                    String status = ObjectUtil.isNotEmpty(object.getJSONObject("data")) ? object.getJSONObject("data").getString("status") : null;
                    if (ObjectUtil.isNotNull(status) && "7".equals(status)) {

                        orderInfo.setStatus("paying");
                        orderInfo.setPayOrderNo(payment.getTradeNumber());
                        orderInfoMapper.updateById(orderInfo);

                        payment.setTradeNumber(object.getJSONObject("data").get("orderNumber").toString());
                        payment.setUpdatedAt(System.currentTimeMillis());
                        mpOrderPaymentMapper.updateById(payment);

                    }
//                orderInfo.setStatus("fail");
//                orderInfo.setPayOrderNo(payment.getTradeNumber());
//                tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo);
                    return orderInfo;
                }
            }
        } else {

            String reqbody = "";

            if (body.length() > 15) {
                reqbody = body.substring(0, 6).concat("....").concat(body.substring(body.length() - 6, body.length()));
            } else {
                reqbody = body.toString();
            }

            PublicResp<MainScanResp> publicResp = thirdPayService.mainScan(url, thirdApply.getAppId(),
                    reqbody, reqbody,
                    BigDecimal.valueOf(payment.getAmount()).setScale(2, RoundingMode.DOWN).multiply(new BigDecimal(100)).longValue(),
                    payType.equals("wechatPay") ? thirdApply.getSmallAppid() : null,
                    scanPayDTO.getCode(), DateUtils.getSsdfTimes(), thirdApply.getStoreId(), callBack, thirdApply.getAppToken());
            log.info("响应信息, {}", publicResp);
            if (ObjectUtil.isNotNull(publicResp) && ObjectUtil.isNotEmpty(publicResp)) {
                if ("000000".equals(publicResp.getCode())) {
                    MainScanResp mainScanResp = publicResp.getObjData();
                    if ("TRADE_SUCCESS".equals(mainScanResp.getState())) {
                        payment.setTradeNumber(mainScanResp.getPayOrderId());
                        payment.setUpdatedAt(System.currentTimeMillis());
                        orderPaymentService.updateById(payment);

                        //处理支付成功的订单
                        orderInfo.setStatus("closed");
                        orderInfo.setPayOrderNo(mainScanResp.getPayOrderId());
                        orderInfoMapper.updateById(orderInfo);

                        //更新购物车状态
                        int cartCount = cashierCartMapper.update(null, new LambdaUpdateWrapper<TbCashierCart>()
                                .eq(TbCashierCart::getOrderId, orderInfo.getId())
                                .set(TbCashierCart::getStatus, "final"));
                        log.info("更新购物车:{}", cartCount);

                        //更新子单状态
                        orderDetailMapper.update(null, new LambdaUpdateWrapper<TbOrderDetail>()
                                .eq(TbOrderDetail::getOrderId, orderInfo.getId())
                                .set(TbOrderDetail::getStatus, "closed"));

                        return orderInfo;
                    } else if ("TRADE_AWAIT".equals(mainScanResp.getState())) {
                        orderInfo.setStatus("paying");
                        orderInfo.setPayOrderNo(payment.getTradeNumber());
                        orderInfoMapper.updateById(orderInfo);

                        payment.setTradeNumber(mainScanResp.getPayOrderId());
                        payment.setUpdatedAt(System.currentTimeMillis());
                        orderPaymentService.updateById(payment);

                        return orderInfo;
                    }
                }

                throw new BadRequestException("支付失败:" + publicResp.getMsg());
            }

        }
        throw new BadRequestException("支付失败");

    }

    @Override
    public TbOrderInfo vipPay(@NotNull Integer shopId, @NotNull Integer orderId, Double discount, Integer vipUserId) {

        TbOrderInfo orderInfo = orderInfoMapper.selectById(orderId);

        if (ObjectUtil.isEmpty(orderInfo)) {
            throw new BadRequestException("订单不存在");
        }

        if (!"unpaid".equals(orderInfo.getStatus()) && !"pending".equals(orderInfo.getStatus())) {
            throw new BadRequestException("订单非未支付状态");
        }

        if (vipUserId != null) {
            orderInfo.setUserId(String.valueOf(vipUserId));
        }


        // 扣减会员余额
        TbShopUser shopUser = shopUserMapper.selectOne(new LambdaUpdateWrapper<TbShopUser>()
                .eq(TbShopUser::getStatus, 1)
                .eq(TbShopUser::getId, orderInfo.getUserId()));

        if (shopUser == null) {
            throw new BadRequestException("用户不存在或已被禁用");
        }

        BigDecimal finalAmount = orderInfo.getOrderAmount().multiply(BigDecimal.valueOf(discount)).setScale(2, RoundingMode.HALF_UP);
        long flag = shopUserMapper.decrBalance(Integer.valueOf(orderInfo.getUserId()), finalAmount);
        if (flag < 1) {
            throw new BadRequestException("余额不足或扣除余额失败");
        }

        TbShopUserFlow userFlow = new TbShopUserFlow();
        userFlow.setAmount(finalAmount);
        userFlow.setBalance(shopUser.getAmount().subtract(finalAmount));
        userFlow.setShopUserId(shopUser.getId());
        userFlow.setBizCode("vipCardCash");
        userFlow.setBizName("余额支付");
        userFlow.setCreateTime(new Timestamp(System.currentTimeMillis()));
        userFlow.setType("-");
        shopUserFlowMapper.insert(userFlow);

        orderInfo.setPayAmount(finalAmount);
        orderInfo.setPayType("cash");
        orderInfo.setStatus("closed");
        orderInfo.setPayOrderNo("cash".concat(SnowFlakeUtil.generateOrderNo()));
        orderInfo.setDiscountRatio(BigDecimal.valueOf(discount));
        orderInfo.setDiscountAmount(orderInfo.getAmount().subtract(finalAmount));
        orderInfoMapper.updateById(orderInfo);
        //更新购物车状态
        int cartCount = cashierCartMapper.update(null, new LambdaUpdateWrapper<TbCashierCart>()
                .eq(TbCashierCart::getOrderId, orderId)
                .set(TbCashierCart::getStatus, "final"));

        orderDetailMapper.update(null, new LambdaUpdateWrapper<TbOrderDetail>()
                .eq(TbOrderDetail::getOrderId, orderId)
                .set(TbOrderDetail::getStatus, "closed"));
        return orderInfo;
    }


    private final TbMShopUserMapper shopUserMapper;
    private final TbShopUserFlowMapper shopUserFlowMapper;


    @Override
    public TbOrderInfo cashPay(PayDTO payDTO) {
        TbOrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaUpdateWrapper<TbOrderInfo>()
                .eq(TbOrderInfo::getId, payDTO.getOrderId())
                .eq(TbOrderInfo::getShopId, payDTO.getShopId()));

        if (orderInfo == null) {
            throw new BadRequestException("订单信息不存在");
        }

        if (!"unpaid".equals(orderInfo.getStatus()) && !"pending".equals(orderInfo.getStatus())) {
            throw  new BadRequestException("此订单不处于未支付状态");
        }


        mpShopTableMapper.update(null, new LambdaUpdateWrapper<TbShopTable>()
                .eq(TbShopTable::getQrcode, orderInfo.getTableId())
                .set(TbShopTable::getStatus, TableStateEnum.PAYING.getState()));
//        int count = shopInfoRepository.countSelectByShopIdAndPayType(orderInfo.getShopId(), "cash");
//        if (count < 1) {
//            return Result.fail(CodeEnum.PAYTYPENOEXIST);
//        }

        BigDecimal payMount = orderInfo.getOrderAmount().multiply(BigDecimal.valueOf(payDTO.getDiscount())).setScale(2, RoundingMode.HALF_UP);
        orderInfo.setPayAmount(payMount);
        orderInfo.setPayType("cash");
        orderInfo.setStatus("closed");
        orderInfo.setPayOrderNo("cash".concat(SnowFlakeUtil.generateOrderNo()));
        orderInfo.setDiscountRatio(BigDecimal.valueOf(payDTO.getDiscount()));
        orderInfo.setDiscountAmount(orderInfo.getAmount().subtract(payMount));
        orderInfoMapper.updateById(orderInfo);

        //更新购物车状态
        TbCashierCart cashierCart = new TbCashierCart();
        cashierCart.setStatus("final");
        int cartCount = cashierCartMapper.update(cashierCart, new LambdaUpdateWrapper<TbCashierCart>()
                .eq(TbCashierCart::getOrderId, payDTO.getOrderId()));

        TbOrderDetail orderDetail = new TbOrderDetail();
        orderDetail.setStatus("closed");
        orderDetailMapper.update(orderDetail, new LambdaUpdateWrapper<TbOrderDetail>()
                .eq(TbOrderDetail::getOrderId, payDTO.getOrderId()));

        return orderInfo;
    }

    public TbOrderInfo memberAccountPay(String memberId, String shopId, String accountCode, Integer orderId, Double discount)  {
        if (StrUtil.isBlank(accountCode)) {
            throw new BadRequestException("无效码");
        }

        TbOrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaUpdateWrapper<TbOrderInfo>()
                .eq(TbOrderInfo::getId, orderId)
                .eq(TbOrderInfo::getShopId, shopId));

        if (orderInfo == null) {
            throw new BadRequestException("订单不存在或已支付");
        }

        if (!"unpaid".equals(orderInfo.getStatus()) && !"pending".equals(orderInfo.getStatus())) {
            throw  new BadRequestException("此订单不处于未支付状态");
        }

        BigDecimal payMount = orderInfo.getOrderAmount().multiply(BigDecimal.valueOf(discount)).setScale(2, RoundingMode.HALF_UP);

        long count = tbShopPayTypeMapper.selectCount(new LambdaQueryWrapper<TbShopPayType>()
                .eq(TbShopPayType::getShopId, shopId)
                .eq(TbShopPayType::getIsDisplay, 1)
                .eq(TbShopPayType::getPayType, "deposit"));
        if (count < 1) {
            throw new BadRequestException("未知支付方式");
        }


        TbShopUser user = null;

        if (ObjectUtil.isNotEmpty(memberId)) {
            user = shopUserMapper.selectById(Integer.valueOf(memberId));
        }


        if (ObjectUtil.isNotEmpty(accountCode)) {

            if (!accountCode.startsWith("46")) {
                throw new BadRequestException("无效二维码");
            }

            user = shopUserMapper.selectOne(new LambdaQueryWrapper<TbShopUser>()
                    .eq(TbShopUser::getShopId, shopId)
                    .eq(TbShopUser::getDynamicCode, accountCode));

        }


        if (ObjectUtil.isEmpty(user) || !"1".equals(user.getIsVip().toString())) {
            throw new BadRequestException("用户不存在");
        }

        shopUserMapper.update(null, new LambdaUpdateWrapper<TbShopUser>()
                .eq(TbShopUser::getId, user.getId())
                .apply(StrUtil.format("amount-{}>=0", payMount.doubleValue()))
                .setSql(StrUtil.format("amount=amount-{}", payMount.doubleValue()))
                .setSql(StrUtil.format("consume_amount=consume_amount+{}", payMount.doubleValue()))
                .setSql(StrUtil.format("consume_number=consume_number+1"))
                .set(TbShopUser::getUpdatedAt, DateUtil.current() / 1000)
        );


        TbShopUserFlow flow = new TbShopUserFlow();
        flow.setShopUserId(user.getId());
        flow.setBizCode("accountPay");
        flow.setBizName("余额支付");
        flow.setType("-");
        flow.setAmount(payMount);
        flow.setBalance(user.getAmount().subtract(payMount));
        flow.setCreateTime(DateUtil.date().toTimestamp());
        flow.setIsReturn("0");
        shopUserFlowMapper.insert(flow);


        orderInfo.setPayAmount(payMount);
        orderInfo.setUserId(user.getUserId());
        orderInfo.setMemberId(user.getId().toString());
        orderInfo.setPayType("deposit");
        orderInfo.setStatus("closed");
        orderInfo.setPayOrderNo("deposit".concat(SnowFlakeUtil.generateOrderNo()));
        orderInfoMapper.updateById(orderInfo);
        //更新购物车状态
        int cartCount = cashierCartMapper.update(null, new LambdaUpdateWrapper<TbCashierCart>()
                .eq(TbCashierCart::getId, orderId)
                .set(TbCashierCart::getStatus, "final"));


        orderDetailMapper.update(null, new LambdaUpdateWrapper<TbOrderDetail>()
                .eq(TbOrderDetail::getOrderId, orderId)
                .set(TbOrderDetail::getStatus, "closed"));

        log.info("更新购物车:{}", cartCount);


        return orderInfo;
    }
}
