package com.yiqi.order.service.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import cn.binarywang.wx.miniapp.bean.express.result.WxMaExpressOrderInfoResult;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiqi.app.domain.AppGoodsMarket;
import com.yiqi.app.domain.vo.AppUserInfoVO;
import com.yiqi.app.service.IAppGoodsMarketService;
import com.yiqi.app.service.IAppUserBillMstrService;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.common.core.domain.AuthHolder;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.core.domain.entity.SysUser;
import com.yiqi.common.enums.*;
import com.yiqi.common.exception.GlobalException;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.common.utils.*;
import com.yiqi.common.utils.pay.PayCodeUtils;
import com.yiqi.core.domain.GoodsInfo;
import com.yiqi.core.domain.GoodsSkuStore;
import com.yiqi.core.domain.dto.GoodsSkuStockRecordDTO;
import com.yiqi.core.domain.dto.GoodsUpdateSalesDTO;
import com.yiqi.core.service.IGoodsInfoService;
import com.yiqi.core.service.IGoodsSkuService;
import com.yiqi.core.service.IGoodsSkuStockRecordService;
import com.yiqi.core.service.IGoodsSkuStoreService;
import com.yiqi.delay.DelayMessage;
import com.yiqi.delay.DelayQueueCache;
import com.yiqi.order.domain.*;
import com.yiqi.order.domain.dto.*;
import com.yiqi.order.domain.dto.weapp.AppGoodsOrderInfoQueryDTO;
import com.yiqi.order.domain.dto.weapp.AppOrderGoodsCancelDTO;
import com.yiqi.order.domain.dto.weapp.AppOrderGoodsRefundDTO;
import com.yiqi.order.domain.vo.*;
import com.yiqi.order.domain.vo.weapp.AppGoodsOrderInfoQueryVO;
import com.yiqi.order.service.*;
import com.yiqi.recharge.domain.dto.BillMstrOrderDTO;
import com.yiqi.recharge.domain.dto.ConsumeOrderDTO;
import com.yiqi.recharge.service.IRechargePasswordCardService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yiqi.order.mapper.OrderGoodsMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 零售商品订单Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-06
 */
@Service
public class OrderGoodsServiceImpl extends ServiceImpl<OrderGoodsMapper, OrderGoods> implements IOrderGoodsService {

    @Autowired
    private OrderNoUtils orderNoUtils;

    @Autowired
    private IGoodsInfoService goodsInfoService;

    @Autowired
    private IOrderGoodsItemService orderGoodsItemService;

    @Autowired
    private IOrderGoodsSkuService orderGoodsSkuService;

    @Autowired
    private IGoodsSkuStoreService goodsSkuStoreService;

    @Autowired
    private IGoodsSkuService goodsSkuService;

    @Autowired
    private IRechargePasswordCardService rechargePasswordCardService;

    @Autowired
    private IAppGoodsMarketService appGoodsMarketService;

    @Autowired
    private IGoodsSkuStockRecordService goodsSkuStockRecordService;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IAppUserBillMstrService appUserBillMstrService;

    @Autowired
    private IPayService payService;

    @Autowired
    private IThirdDeliveryService thirdDeliveryService;

    @Autowired
    private IOrderPayInfoService orderPayInfoService;
    @Autowired
    private DelayQueueCache delayQueueCache;
    @Autowired
    private IOrderGoodsRefundService orderGoodsRefundService;

    //<editor-folder desc="基础韩素">

    @Override
    public OrderGoods getByOrderNo(String orderNo) {
        LambdaQueryWrapper<OrderGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderGoods::getOrderNo, orderNo);
        return this.getOne(queryWrapper);
    }

    /**
     * 查询零售商品订单
     *
     * @param id 零售商品订单主键
     * @return 零售商品订单
     */
    @Override
    public List<OrderRetailGoodsSkuVO> selectOrderGoodsById(Long id) {
        return baseMapper.selectOrderGoodsById(id);
    }

    @Override
    public List<OrderRetailGoodsSkuVO> selectOrderGoodsByOrderNos(List<String> orderNoList) {
        return baseMapper.selectOrderGoodsByOrderNos(orderNoList);
    }


    /**
     * APP分页获取订单商品列表
     *
     * @param appGoodsOrderInfoQueryDTO
     * @return
     */
    @Override
    public List<AppGoodsOrderInfoQueryVO> getGoodsOrderListByApp(AppGoodsOrderInfoQueryDTO appGoodsOrderInfoQueryDTO) {
        // 分页获取用户的商品订单
        List<AppGoodsOrderInfoQueryVO> goodsOrderList = baseMapper.getGoodsOrderListByApp(appGoodsOrderInfoQueryDTO);
        if (CollUtil.isEmpty(goodsOrderList)) {
            return goodsOrderList;
        }
        // 通过商品订单编号，获取物料集合商品数量
        Map<String, List<OrderGoodsSku>> listMap = orderGoodsSkuService.list(new QueryWrapper<OrderGoodsSku>().lambda()
                        .in(OrderGoodsSku::getOrderNo, goodsOrderList.stream().map(AppGoodsOrderInfoQueryVO::getOrderNo).collect(Collectors.toList())))
                .stream().collect(Collectors.groupingBy(OrderGoodsSku::getOrderNo));
        // 获取订单商品信息
        List<OrderRetailGoodsSkuVO> goodsSkuVOS = this.selectOrderGoodsByOrderNos(goodsOrderList.stream().map(AppGoodsOrderInfoQueryVO::getOrderNo).collect(Collectors.toList()));
        Map<String, List<OrderRetailGoodsSkuVO>> map = goodsSkuVOS.stream().collect(Collectors.groupingBy(OrderRetailGoodsSkuVO::getOrderNo));


        // 通过物料集合计算总件数
        goodsOrderList.forEach(goodsOrder -> {
            if (listMap.containsKey(goodsOrder.getOrderNo())) {
                goodsOrder.setGoodsNumber(listMap.get(goodsOrder.getOrderNo()).stream().mapToInt(OrderGoodsSku::getBuyNum).sum());
            }
            if (map.containsKey(goodsOrder.getOrderNo())) {
                goodsOrder.setOrderGoodsSkuList(map.get(goodsOrder.getOrderNo()));
            }
        });
        return goodsOrderList;
    }

    /**
     * 查询零售商品订单列表
     *
     * @param goodsOrderQueryDTO 零售商品订单
     * @return 零售商品订单
     */
    @Override
    public List<GoodsOrderQueryVO> selectOrderGoodsList(GoodsOrderQueryDTO goodsOrderQueryDTO) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        goodsOrderQueryDTO.setSourceType(user.getUserType());
        if (SourceType.STORE.getCode().equals(user.getUserType())) {
            goodsOrderQueryDTO.setOrgId(user.getStoreId());
        }
        return baseMapper.selectOrderGoodsList(goodsOrderQueryDTO);
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public OrderGoods cereateRetailOrderGoods(OrderGoodsDTO orderGoodsDTO, List<OrderGoodsSkuInfoVO> orderGoodsSkuInfoVOS) {
        // 保存零售商品订单
        OrderGoods orderGoods = this.buildRetailOrderGoodsInfo(orderGoodsDTO, orderGoodsSkuInfoVOS);
        return orderGoods;
    }

    /**
     * 保存零售订单
     *
     * @param orderGoodsDTO
     * @return
     */
    private OrderGoods buildRetailOrderGoodsInfo(OrderGoodsDTO orderGoodsDTO, List<OrderGoodsSkuInfoVO> orderGoodsSkuInfoVOS) {
        // 保存订单
        OrderGoods orderGoods = new OrderGoods();
        BeanUtils.copyProperties(orderGoodsDTO, orderGoods);
        orderGoods.buildCreateData();
        orderGoods.setPayType(orderGoodsDTO.getPayType());
        orderGoods.setGoodsType(orderGoodsDTO.getGoodsType());
        orderGoods.setCouponDeductAmount(orderGoodsDTO.getCouponDeductAmount() == null ? BigDecimal.ZERO : orderGoodsDTO.getCouponDeductAmount());
        orderGoods.setCashDeductAmount(orderGoodsDTO.getDeductAmount());
        orderGoods.setPayAmount(orderGoodsDTO.getTotalPrice().subtract(orderGoods.getCashDeductAmount()).subtract(orderGoods.getCouponDeductAmount()));
        orderGoods.setOrderStatus(OrderGoodsStatusType.NO_PAY.getCode());
        orderGoods.setRefundAmount(BigDecimal.ZERO);
        orderGoods.setDeliveryWay(this.getDeliveryWayByOrderSource(orderGoodsDTO.getOrderSource()));
        orderGoods.setDelFlag(UserStatus.OK.getCode());
        // 生成订单编号
        orderGoods.setOrderNo(orderNoUtils.getGoodsOrderNo());
        orderGoods.setMemberPayAmount(BigDecimal.ZERO);
        orderGoods.setCashPayAmount(BigDecimal.ZERO);
        orderGoods.setWxPayAmount(BigDecimal.ZERO);
        orderGoods.setAliPayAmount(BigDecimal.ZERO);
        orderGoods.setGoodsCount(
                orderGoodsSkuInfoVOS.stream().mapToInt(OrderGoodsSkuInfoVO::getBuyNum).sum()
        );
        if (orderGoods.getSourceType().equals(SourceType.MANAGER.getCode())) {
            orderGoods.setOrgId(0L);
        }
        this.save(orderGoods);

        // 计算商品原价总额
        BigDecimal totalOriginalAmount = BigDecimal.ZERO;
        for (OrderGoodsSkuInfoVO skuInfo : orderGoodsSkuInfoVOS) {
            totalOriginalAmount = totalOriginalAmount.add(skuInfo.getSalePrice().multiply(new BigDecimal(skuInfo.getBuyNum())));
        }
        
        // 无法批量插入
        BigDecimal allocatedAmount = BigDecimal.ZERO;
        for (int i = 0; i < orderGoodsSkuInfoVOS.size(); i++) {
            OrderGoodsSkuInfoVO retailGoodsDTO = orderGoodsSkuInfoVOS.get(i);
            OrderGoodsSku orderGoodsSku = new OrderGoodsSku();
            orderGoodsSku.setOrderId(orderGoods.getId());
            orderGoodsSku.setOrderNo(orderGoods.getOrderNo());
            orderGoodsSku.setGoodsName(retailGoodsDTO.getGoodsName());
            orderGoodsSku.setGoodsImg(retailGoodsDTO.getGoodsImg());
            orderGoodsSku.setBuyNum(retailGoodsDTO.getBuyNum());
            orderGoodsSku.setSalePrice(retailGoodsDTO.getSalePrice());
            orderGoodsSku.setRefundAmount(BigDecimal.ZERO);
            orderGoodsSku.setSkuName(retailGoodsDTO.getSkuName());
            orderGoodsSku.setSkuId(retailGoodsDTO.getSkuId());
            orderGoodsSku.setGoodsId(retailGoodsDTO.getGoodsId());
            orderGoodsSku.setCreateBy(orderGoods.getCreateBy());
            orderGoodsSku.setCreateTime(DateUtils.getNowDate());
            orderGoodsSku.setCreateById(orderGoods.getCreateById());
            
            // 计算该商品应分摊的支付金额
            BigDecimal goodsOriginalAmount = retailGoodsDTO.getSalePrice().multiply(new BigDecimal(retailGoodsDTO.getBuyNum()));
            BigDecimal goodsPayAmount;
            
            // 最后一个商品，使用剩余金额
            if (i == orderGoodsSkuInfoVOS.size() - 1) {
                goodsPayAmount = orderGoods.getPayAmount().subtract(allocatedAmount);
            } else {
                // 按照原价比例分配
                goodsPayAmount = orderGoods.getPayAmount()
                    .multiply(goodsOriginalAmount)
                    .divide(totalOriginalAmount, 2, BigDecimal.ROUND_DOWN);
                allocatedAmount = allocatedAmount.add(goodsPayAmount);
            }
            
            orderGoodsSku.setTotalAmount(goodsPayAmount);
            orderGoodsSkuService.save(orderGoodsSku);
        }
        return orderGoods;
    }

    /**
     * 通过物料id，查询整个商品物料信息
     *
     * @param skuIdList
     * @param orderSource
     * @return
     */
    @Override
    public List<OrderGoodsSkuInfoVO> getSkuInfoList(List<Long> skuIdList, String orderSource) {
        if (OrderSourceType.APP.getCode().equals(orderSource)) {
            return goodsInfoService.getSkuInfoList(skuIdList, SourceType.MANAGER.getCode());
        }
        if (OrderSourceType.OFFLINE.getCode().equals(orderSource)) {
            return goodsInfoService.getSkuInfoList(skuIdList, SourceType.STORE.getCode());
        }
        return null;
    }


    /**
     * 处理支付
     *
     * @param orderGoods
     * @param orderGoodsDTO
     * @return
     */
    private OrderPayResultVO handlePay(OrderGoods orderGoods, OrderGoodsDTO orderGoodsDTO) {
        OrderPayResultVO orderPayResultVO = new OrderPayResultVO();
        if (orderGoods == null) {
            throw new ServiceException("未查询到订单");
        }
        if (!orderGoods.getOrderStatus().equals(OrderGoodsStatusType.NO_PAY.getCode())) {
            throw new ServiceException("订单状态不正确支付");
        }

        if (orderGoods.getPayType().equals(PayType.CASH.getCode()) && OrderSourceType.OFFLINE.getCode().equals(orderGoods.getOrderSource())) {
            orderGoods.setPayType(PayType.CASH.getCode());
            this.handlePaySuccessUpdateOrderStatus(orderGoods.getOrderNo(), null);
            orderPayResultVO = OrderPayResultVO.paySuccess(orderGoods.getOrderNo());
            orderPayResultVO.setOrderId(orderGoods.getId());
            return orderPayResultVO;
        }
        if (orderGoods.getPayType().equals(PayType.WECHAT.getCode()) && OrderSourceType.OFFLINE.getCode().equals(orderGoods.getOrderSource())) {
            String payType = null;
            try {
                payType = PayCodeUtils.getPayTypeByCode(orderGoodsDTO.getAuthCode());
            } catch (ServiceException e) {
                return OrderPayResultVO.payError(e.getMessage());
            }
            orderGoods.setPayType(payType);
            this.updateById(orderGoods);
            try {
                //创建支付订单，防止出现错误
                return payService.faceToFacePay(PayOrderFaceToFaceDTO.createRechargeOrderPayData(orderGoods.getOrderNo(), orderGoods.getPayAmount(), orderGoods.getPayType(), orderGoodsDTO.getAuthCode()));

            } catch (Exception e) {
                e.printStackTrace();
                return OrderPayResultVO.payError("扫收款码支付失败");
            }
        }
        //会员余额支付
        if (orderGoods.getPayType().equals(PayType.BALANCE.getCode())) {
            RechargeCardPayDTO rechargeCardPayDTO = new RechargeCardPayDTO(orderGoods.getAppUserId(), orderGoods.getId(), orderGoods.getSourceType(), orderGoods.getOrgId(), orderGoods.getOrderNo(), orderGoods.getPayAmount(), orderGoods.getGoodsType().equals(GoodsType.NORMAL.getCode()) ? BuyGoodsType.COMMON_GOODS.getCode() : orderGoods.getGoodsType());
            rechargePasswordCardService.orderPayByBalance(rechargeCardPayDTO);
            this.handlePaySuccessUpdateOrderStatus(orderGoods.getOrderNo(), null);
            orderPayResultVO = OrderPayResultVO.paySuccess(orderGoods.getOrderNo());
            orderPayResultVO.setOrderId(orderGoods.getId());
            return orderPayResultVO;
        }
        //微信或者支付宝小程序支付
        if (orderGoods.getPayType().equals(PayType.WECHAT.getCode()) || orderGoods.getPayType().equals(PayType.ALIPAY.getCode())) {
            orderPayResultVO.setAppPayRespVO(payService.appPay(PayOrderAppDTO.buildGoodsOrderPayData(orderGoods, orderGoodsDTO.getPlatform())));
            orderPayResultVO.setPayResult(100);
            return orderPayResultVO;
        }
        return OrderPayResultVO.payError("请重新支付");
    }

    /**
     * 支付成功后，处理订单
     *
     * @param orderNo
     * @return
     */
    @Override
    public R handlePaySuccessUpdateOrderStatus(String orderNo, String outTradeNo) {
        OrderGoods orderGoods = this.getOne(new QueryWrapper<OrderGoods>().lambda().eq(OrderGoods::getOrderNo, orderNo));
        if (orderGoods == null) {
            throw new ServiceException("商品订单不存在," + orderNo);
        }
        if (PayStatus.HAS_PAY.getCode().equals(orderGoods.getPayStatus())) {
            return R.fail("订单已付款成功");
        }
        switch (Objects.requireNonNull(EnumUtils.getEnumByType(orderGoods.getGoodsType(), GoodsType.class))) {
            case NORMAL: {
                if (OrderSourceType.APP.getCode().equals(orderGoods.getOrderSource()) || OrderSourceType.WXAPP.getCode().equals(orderGoods.getOrderSource())) {
                    orderGoods.setOrderStatus(OrderGoodsStatusType.NO_SEND.getCode());
                } else {
                    // 门店
                    orderGoods.setOrderStatus(OrderGoodsStatusType.CONFIRM_RECEIVE.getCode());
                }
                break;
            }
            case LIFE_SERVICE:
            case CAR: {
                orderGoods.setOrderStatus(OrderGoodsStatusType.WAIT_RECEIVE.getCode());
                break;
            }
        }
        if (orderGoods.getPayType().equals(PayType.CASH.getCode())) {
            orderGoods.setCashPayAmount(orderGoods.getPayAmount());
        } else if (orderGoods.getPayType().equals(PayType.BALANCE.getCode())) {
            orderGoods.setMemberPayAmount(orderGoods.getPayAmount());
        } else if (orderGoods.getPayType().equals(PayType.WECHAT.getCode())) {
            orderGoods.setWxPayAmount(orderGoods.getPayAmount());
        } else if (orderGoods.getPayType().equals(PayType.ALIPAY.getCode())) {
            orderGoods.setAliPayAmount(orderGoods.getPayAmount());
        }
        orderGoods.setPayStatus(PayStatus.HAS_PAY.getCode());
        orderGoods.setPayTime(DateUtils.getNowDate());
        orderGoods.buildUpdateData();
        this.updateById(orderGoods);
        //如果是组合支付，则扣除会员余额
        if (orderGoods.getPayType().equals(PayType.COMBINE.getCode())) {
            if (orderGoods.getMemberPayAmount().compareTo(BigDecimal.ZERO) > 0) {
                //如果支付金额大于0，则扣除会员余额
                /**
                 *     goods("1", "商品订单"),
                 *     life("2", "生活服务"),
                 *     car("3", "汽车美容"),*
                 */
                RechargeCardPayDTO rechargeCardPayDTO = new RechargeCardPayDTO(orderGoods.getAppUserId(), orderGoods.getId(), orderGoods.getSourceType(), orderGoods.getOrgId(), orderGoods.getOrderNo(), orderGoods.getMemberPayAmount(), orderGoods.getGoodsType().equals(GoodsType.NORMAL.getCode()) ? BuyGoodsType.COMMON_GOODS.getCode() : orderGoods.getGoodsType());
                rechargePasswordCardService.orderPayByBalance(rechargeCardPayDTO);
            }
        }
        // 减库存
        List<OrderGoodsSku> orderGoodsSkus = this.handleMinusStock(orderGoods);
        //  出库记录
        this.buildStockRecord(orderGoods, orderGoodsSkus, Boolean.FALSE, Boolean.FALSE);
        //处理销售数量 - 新增销量
        this.buildUpdateGoodsSales(orderGoodsSkus, Boolean.TRUE);
        return R.ok();
    }

    /**
     * 快递签收成功后，处理订单
     *
     * @param orderNo
     */
    @Override
    public void handleDeliverySuccessUpdateOrderStatus(String orderNo) {
        OrderGoods orderGoods = this.getOne(new QueryWrapper<OrderGoods>().lambda().eq(OrderGoods::getOrderNo, orderNo));
        if (orderGoods == null) {
            throw new ServiceException("商品订单不存在," + orderNo);
        }
        if (OrderGoodsStatusType.CONFIRM_RECEIVE.getCode().equals(orderGoods.getOrderStatus())) {
            log.debug("该订单已完成，无需处理， 订单编号：" + orderNo);
            return;
        }
        switch (Objects.requireNonNull(EnumUtils.getEnumByType(orderGoods.getGoodsType(), GoodsType.class))) {
            case NORMAL: {
                orderGoods.setOrderStatus(OrderGoodsStatusType.CONFIRM_RECEIVE.getCode());
                break;
            }
            case LIFE_SERVICE:
            case CAR: {
                log.debug("该订单是服务类型订单，无需处理， 订单编号：" + orderNo);
                break;
            }
        }
        orderGoods.setFinishTime(DateUtils.getNowDate());
        orderGoods.buildUpdateData();
        this.updateById(orderGoods);
    }

    /**
     * 零售商品订单-取消订单
     *
     * @param appOrderGoodsCancelDTO
     * @return 结果
     */
    @Override
    public int cancelOrder(AppOrderGoodsCancelDTO appOrderGoodsCancelDTO) {
        OrderGoods orderGoods = baseMapper.selectById(appOrderGoodsCancelDTO.getOrderId());
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (OrderGoodsStatusType.CANCEL_ORDER.getCode().equals(orderGoods.getOrderStatus())) {
            log.debug("订单已取消，不需要处理，订单id：" + appOrderGoodsCancelDTO.getOrderId());
            return 1;
        }
        if (!OrderGoodsStatusType.NO_PAY.getCode().equals(orderGoods.getOrderStatus())) {
            throw new GlobalException("订单状态已支付，无法取消");
        }
        // 加库存 返回库存
        List<OrderGoodsSku> orderGoodsSkus = this.handleAddStock(orderGoods);
        // 入库记录
        this.buildStockRecord(orderGoods, orderGoodsSkus, Boolean.TRUE, Boolean.FALSE);

        // 更新订单状态
        orderGoods.setOrderStatus(OrderGoodsStatusType.CANCEL_ORDER.getCode());
        orderGoods.setRemark(appOrderGoodsCancelDTO.getRemark());
        orderGoods.setSendTime(null);
        orderGoods.buildUpdateData();
        return baseMapper.updateById(orderGoods);

    }

    /**
     * 零售商品订单-支付失败取消订单
     *
     * @param orderNo
     * @return 结果
     */
    @Override
    public String handlePayFailCancelOrder(String orderNo) {
        OrderGoods orderGoods = this.getOne(new QueryWrapper<OrderGoods>().lambda()
                .eq(OrderGoods::getOrderNo, orderNo));
        if (orderGoods == null) {
            return "订单不存在";
        }
        if (OrderGoodsStatusType.CANCEL_ORDER.getCode().equals(orderGoods.getOrderStatus())) {
            log.debug("订单已取消，不需要处理，订单编号：" + orderNo);
            return "订单已取消，不需要处理";
        }
        if (!OrderGoodsStatusType.NO_PAY.getCode().equals(orderGoods.getOrderStatus())) {
            throw new GlobalException("订单状态已支付，无法取消");
        }
        // 加库存 返回库存
        List<OrderGoodsSku> orderGoodsSkus = this.handleAddStock(orderGoods);
        // 入库记录
        this.buildStockRecord(orderGoods, orderGoodsSkus, Boolean.TRUE, Boolean.FALSE);

        // 更新订单状态
        orderGoods.setOrderStatus(OrderGoodsStatusType.CANCEL_ORDER.getCode());
        orderGoods.setRemark("支付失败取消订单");
        orderGoods.setSendTime(null);
        orderGoods.buildUpdateData();
        baseMapper.updateById(orderGoods);
        return "取消订单成功";

    }

    @Override
    public OrderPayResultVO rePayOrder(OrderGoodsDTO orderGoodsDTO) {
        OrderGoods orderGoods = baseMapper.selectById(orderGoodsDTO.getId());
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        // 处理支付流程
        return this.handlePay(orderGoods, orderGoodsDTO);
    }

    @Override
    public OrderPayResultVO orderGoodsPay(OrderGoodsPayDTO orderGoodsPayDTO) {
        OrderGoods orderGoods = getByOrderNo(orderGoodsPayDTO.getOrderNo());
        if (orderGoods == null) {
            throw new ServiceException("未查询到订单");
        }
        if (!orderGoods.getOrderStatus().equals(OrderGoodsStatusType.NO_PAY.getCode())) {
            throw new ServiceException("订单状态不正确支付");
        }
        orderGoods.setMemberPayAmount(BigDecimal.ZERO);
        orderGoods.setCashPayAmount(BigDecimal.ZERO);
        orderGoods.setWxPayAmount(BigDecimal.ZERO);
        orderGoods.setAliPayAmount(BigDecimal.ZERO);
        orderGoods.setPayType(orderGoodsPayDTO.getPayType());
        OrderPayResultVO orderPayResultVO = new OrderPayResultVO();
        if (orderGoods.getPayType().equals(PayType.CASH.getCode()) && OrderSourceType.OFFLINE.getCode().equals(orderGoods.getOrderSource())) {
            orderGoods.setPayType(PayType.CASH.getCode());
            this.updateById(orderGoods);
            this.handlePaySuccessUpdateOrderStatus(orderGoods.getOrderNo(), null);
            orderPayResultVO = OrderPayResultVO.paySuccess(orderGoods.getOrderNo());
            orderPayResultVO.setOrderId(orderGoods.getId());
            return orderPayResultVO;
        }
        if (orderGoods.getPayType().equals(PayType.WECHAT.getCode()) && OrderSourceType.OFFLINE.getCode().equals(orderGoods.getOrderSource())) {
            String payType = null;
            try {
                payType = PayCodeUtils.getPayTypeByCode(orderGoodsPayDTO.getAuthCode());
            } catch (ServiceException e) {
                return OrderPayResultVO.payError(e.getMessage());
            }
            orderGoods.setPayType(payType);
            this.updateById(orderGoods);
            try {
                //创建支付订单，防止出现错误
                return payService.faceToFacePay(PayOrderFaceToFaceDTO.createRechargeOrderPayData(orderGoods.getOrderNo(), orderGoods.getPayAmount(), orderGoods.getPayType(), orderGoodsPayDTO.getAuthCode()));

            } catch (Exception e) {
                e.printStackTrace();
                return OrderPayResultVO.payError("扫收款码支付失败");
            }
        }
        //会员余额支付
        if (orderGoods.getPayType().equals(PayType.BALANCE.getCode())) {
            orderGoods.setPayType(PayType.BALANCE.getCode());
            this.updateById(orderGoods);
            RechargeCardPayDTO rechargeCardPayDTO = new RechargeCardPayDTO(orderGoods.getAppUserId(), orderGoods.getId(), orderGoods.getSourceType(), orderGoods.getOrgId(), orderGoods.getOrderNo(), orderGoods.getPayAmount(), orderGoods.getGoodsType().equals(GoodsType.NORMAL.getCode()) ? BuyGoodsType.COMMON_GOODS.getCode() : orderGoods.getGoodsType());
            rechargePasswordCardService.orderPayByBalance(rechargeCardPayDTO);
            this.handlePaySuccessUpdateOrderStatus(orderGoods.getOrderNo(), null);
            orderPayResultVO = OrderPayResultVO.paySuccess(orderGoods.getOrderNo());
            orderPayResultVO.setOrderId(orderGoods.getId());
            return orderPayResultVO;
        }
        //微信或者支付宝小程序支付
        if (orderGoods.getPayType().equals(PayType.WECHAT.getCode()) || orderGoods.getPayType().equals(PayType.ALIPAY.getCode())) {
            orderGoods.setPayType(orderGoods.getPayType());
            this.updateById(orderGoods);
            orderPayResultVO.setAppPayRespVO(payService.appPay(PayOrderAppDTO.buildGoodsOrderPayData(orderGoods, orderGoodsPayDTO.getOrderSource())));
            orderPayResultVO.setPayResult(100);
            return orderPayResultVO;
        }
        //组合支付
        if (orderGoods.getPayType().equals(PayType.COMBINE.getCode())) {
            orderGoods.setPayType(PayType.COMBINE.getCode());
            orderGoods.setMemberPayAmount(orderGoodsPayDTO.getMemberPayAmount());
            String otherPayType = orderGoodsPayDTO.getOtherPayType();
            if (otherPayType == null) {
                return OrderPayResultVO.payError("请先设置组合支付其他支付方式");
            }
            if (CurrencyUtil.sub(orderGoodsPayDTO.getPayAmount(), orderGoodsPayDTO.getMemberPayAmount()).compareTo(BigDecimal.ZERO) <= 0) {
                return OrderPayResultVO.payError("组合支付金额有误");
            }
            if (otherPayType.equals(PayType.CASH.getCode())) {
                orderGoods.setCashPayAmount(CurrencyUtil.sub(orderGoodsPayDTO.getPayAmount(), orderGoodsPayDTO.getMemberPayAmount()));
                this.updateById(orderGoods);
                this.handlePaySuccessUpdateOrderStatus(orderGoods.getOrderNo(), null);
                orderPayResultVO = OrderPayResultVO.paySuccess(orderGoods.getOrderNo());
                orderPayResultVO.setOrderId(orderGoods.getId());
                return orderPayResultVO;
            } else if (otherPayType.equals(PayType.WECHAT.getCode())) {
                if (OrderSourceType.OFFLINE.getCode().equals(orderGoods.getOrderSource())) {
                    String payType = null;
                    try {
                        payType = PayCodeUtils.getPayTypeByCode(orderGoodsPayDTO.getAuthCode());
                    } catch (ServiceException e) {
                        return OrderPayResultVO.payError(e.getMessage());
                    }
                    if (payType.equals(PayType.WECHAT.getCode())) {
                        orderGoods.setWxPayAmount(CurrencyUtil.sub(orderGoodsPayDTO.getPayAmount(), orderGoodsPayDTO.getMemberPayAmount()));
                    }
                    if (payType.equals(PayType.ALIPAY.getCode())) {
                        orderGoods.setAliPayAmount(CurrencyUtil.sub(orderGoodsPayDTO.getPayAmount(), orderGoodsPayDTO.getMemberPayAmount()));
                    }
                    this.updateById(orderGoods);
                    try {
                        return payService.faceToFacePay(PayOrderFaceToFaceDTO.createRechargeOrderPayData(orderGoodsPayDTO.getOrderNo(), CurrencyUtil.sub(orderGoodsPayDTO.getPayAmount(), orderGoodsPayDTO.getMemberPayAmount()), payType, orderGoodsPayDTO.getAuthCode()));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return OrderPayResultVO.payError("扫收款码支付失败");
                    }
                } else {
                    //app支付
                    orderGoods.setWxPayAmount(CurrencyUtil.sub(orderGoodsPayDTO.getPayAmount(), orderGoodsPayDTO.getMemberPayAmount()));
                    this.updateById(orderGoods);
                    orderPayResultVO.setAppPayRespVO(payService.appPay(PayOrderAppDTO.buildGoodsOrderPayDataByCombine(orderGoods, orderGoods.getWxPayAmount(), PayType.WECHAT.getCode(), orderGoodsPayDTO.getOrderSource())));
                    orderPayResultVO.setPayResult(100);
                    return orderPayResultVO;
                }
            } else if (otherPayType.equals(PayType.ALIPAY.getCode())) {
                orderGoods.setAliPayAmount(CurrencyUtil.sub(orderGoodsPayDTO.getPayAmount(), orderGoodsPayDTO.getMemberPayAmount()));
                this.updateById(orderGoods);
                orderPayResultVO.setAppPayRespVO(payService.appPay(PayOrderAppDTO.buildGoodsOrderPayDataByCombine(orderGoods, orderGoods.getAliPayAmount(), PayType.ALIPAY.getCode(), orderGoodsPayDTO.getOrderSource())));
                orderPayResultVO.setPayResult(100);
                return orderPayResultVO;
            } else {
                return OrderPayResultVO.payError("请先设置组合支付其他支付方式");
            }
        }
        return OrderPayResultVO.payError("请重新支付");
    }

    /**
     * 零售商品-总部出货
     *
     * @param orderGoodsOutGoodsDTO 商品订单
     * @return 结果
     */
    @Override
    public int outOrderGoods(OrderGoodsOutGoodsDTO orderGoodsOutGoodsDTO) throws Exception {
        OrderGoods orderGoods = baseMapper.selectById(orderGoodsOutGoodsDTO.getOrderId());
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (!OrderGoodsStatusType.NO_SEND.getCode().equals(orderGoods.getOrderStatus())) {
            throw new GlobalException("订单状态不符合，无法出货");
        }
        orderGoods.setOrderStatus(OrderGoodsStatusType.SENDING.getCode());
        orderGoods.setDeliveryCompany(orderGoodsOutGoodsDTO.getDeliveryCompany());
        orderGoods.setDeliveryId(orderGoodsOutGoodsDTO.getDeliveryId());
        orderGoods.setDeliveryNo(orderGoodsOutGoodsDTO.getDeliveryNo());
        orderGoods.setSendTime(DateUtils.getNowDate());
        orderGoods.buildUpdateData();
//        AppUserInfoVO appUserInfo = appUserService.getAppUserInfoById(orderGoods.getAppUserId());
//        List<OrderGoodsItem> goodsItems = orderGoodsItemService.list(new QueryWrapper<OrderGoodsItem>().lambda()
//                .eq(OrderGoodsItem::getOrderNo, orderGoods.getOrderNo()));
//        List<Long> goodIdList = new ArrayList<>(goodsItems.stream().collect(Collectors.groupingBy(OrderGoodsItem::getGoodsId)).keySet());
//        List<GoodsInfo> goodsInfoList = goodsInfoService.list(new QueryWrapper<GoodsInfo>().lambda().in(GoodsInfo::getId, goodIdList));
//        // 生成快递订单
//        WxMaExpressOrderInfoResult result = thirdDeliveryService.addDeliveryOrder(OrderThirdDeliveryAddDTO.buildDeliveryOrderByGoodsOrder(orderGoods, orderGoodsOutGoodsDTO, goodsInfoList, appUserInfo));
//        if (result != null) {
//            orderGoods.setDeliveryNo(result.getWaybillId());
//        }
        baseMapper.updateById(orderGoods);
        return 1;
    }

    /**
     * 生活服务/汽车美容订单-总部接单
     *
     * @param orderId
     * @return
     */
    @Override
    public int receiveOrder(Long orderId) {
        OrderGoods orderGoods = baseMapper.selectById(orderId);
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (!OrderGoodsStatusType.CONFIRM_PAY.getCode().equals(orderGoods.getOrderStatus())) {
            throw new GlobalException("订单状态不对，无法接单");
        }
        // 更新订单状态
        orderGoods.setOrderStatus(OrderGoodsStatusType.NO_SEND.getCode());
        orderGoods.buildUpdateData();
        return baseMapper.updateById(orderGoods);
    }

    /**
     * 生活服务/汽车美容订单-确认完成
     *
     * @param orderId
     * @return
     */
    @Override
    public int confirmFinish(Long orderId) {
        OrderGoods orderGoods = baseMapper.selectById(orderId);
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (!(OrderGoodsStatusType.WAIT_RECEIVE.getCode().equals(orderGoods.getOrderStatus()) || OrderGoodsStatusType.SENDING.getCode().equals(orderGoods.getOrderStatus()))) {
            throw new GlobalException("订单状态不对，无法确认完成");
        }
        // 更新订单状态
        orderGoods.setOrderStatus(OrderGoodsStatusType.CONFIRM_RECEIVE.getCode());
        orderGoods.setFinishTime(DateUtils.getNowDate());
        orderGoods.buildUpdateData();
        return baseMapper.updateById(orderGoods);
    }

    /**
     * 商品订单-操作退款申请
     *
     * @param orderGoodsRefundDTO
     * @return
     */
    @Override
    public int refundOrderGoodsApply(OrderGoodsRefundDTO orderGoodsRefundDTO, String sourceType) {
        OrderGoods orderGoods = baseMapper.selectById(orderGoodsRefundDTO.getOrderId());
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        // app客户操作
        if (SourceType.CUSTOM.getCode().equals(sourceType)) {
            // 操作人校验
            if (!AuthHolder.userId().equals(orderGoods.getAppUserId())) {
                throw new ServiceException("当前登录人没有权限操作");
            }
            // 总部操作
        } else if (SourceType.MANAGER.getCode().equals(sourceType)) {
            // 操作人校验
            if (!SecurityUtils.getLoginUser().getSourceType().equals(SourceType.MANAGER.getCode())) {
                throw new ServiceException("当前登录人没有权限操作");
            }
        }

        if (OrderRefundStatus.REFUND_SUCCESS.getCode().equals(orderGoods.getRefundStatus())) {
            throw new GlobalException("订单已退款，无法继续申请退款操作");
        }
        if (OrderRefundStatus.REFUND_APPLYING.getCode().equals(orderGoods.getRefundStatus())) {
            throw new GlobalException("退款申请中，无法操作退款申请");
        }
        // 超过3个月不能退单
        if ((DateUtils.getNowDate().compareTo(DateUtils.addMonths(orderGoods.getCreateTime(), 3))) > 0) {
            throw new GlobalException("订单已经超过3个月时间，不能操作退单");
        }
        if (OrderGoodsStatusType.NO_PAY.getCode().equals(orderGoods.getOrderStatus())) {
            throw new GlobalException("订单未支付，不能操作退单");
        }
        // 更新订单状态
        orderGoods.setRefundStatus(OrderRefundStatus.REFUNDING.getCode());
        orderGoods.setRefundReason(orderGoodsRefundDTO.getRefundReason());
        orderGoods.setRefundTime(DateUtils.getNowDate());
        orderGoods.setRefundAmount(orderGoods.getPayAmount());
        orderGoods.buildUpdateData();
        baseMapper.updateById(orderGoods);

        OrderGoodsRefund orderGoodsRefund = new OrderGoodsRefund();
        BeanUtils.copyProperties(orderGoods, orderGoodsRefund);
        orderGoodsRefund.setId(null);
        orderGoodsRefund.setOrderAmount(orderGoods.getTotalPrice());
        orderGoodsRefund.setRefundNo(orderNoUtils.getGoodsOrderNo());
        orderGoodsRefund.setGoodsType(orderGoods.getGoodsType());
        orderGoodsRefund.setRefundAmount(orderGoods.getRefundAmount());
        orderGoodsRefund.setAliRefundAmount(orderGoods.getAliPayAmount());
        orderGoodsRefund.setCashRefundAmount(orderGoods.getCashPayAmount());
        orderGoodsRefund.setWxRefundAmount(orderGoods.getWxPayAmount());
        orderGoodsRefund.setMemberRefundAmount(orderGoods.getMemberPayAmount());
        orderGoodsRefund.setRefundApplyTime(DateUtils.getNowDate());
        orderGoodsRefund.setRefundReason(orderGoodsRefundDTO.getRefundReason());
        orderGoodsRefund.setRefundStatus(OrderRefundStatus.REFUND_APPLYING.getCode());
        orderGoodsRefund.buildCreateData();
        orderGoodsRefundService.save(orderGoodsRefund);

        // 退款
        if (orderGoods.getPayType().equals(PayType.CASH.getCode())) {
            refundSuccess(orderGoodsRefund.getRefundNo(), orderGoods.getOrderNo());
        }
        if (orderGoods.getPayType().equals(PayType.BALANCE.getCode())) {
            //充值卡支付退单
            Boolean res = rechargePasswordCardService.orderRefundByBalance(orderGoods.getOrderNo(), orderGoods.getRefundAmount());
            if (res) {
                refundSuccess(orderGoodsRefund.getRefundNo(), orderGoods.getOrderNo());
            }
        }
        if (orderGoods.getPayType().equals(PayType.WECHAT.getCode()) || orderGoods.getPayType().equals(PayType.ALIPAY.getCode())) {
            PayRefundDTO payRefundDTO = new PayRefundDTO(orderGoods.getPayType(), orderGoods.getOrderNo(), orderGoods.getPayAmount(), orderGoodsRefund.getRefundNo(), orderGoods.getOutTradeOrderNo(), orderGoodsRefundDTO.getRefundReason());
            //执行微信退款逻辑
            payRefundDTO.setTotalAmount(orderGoods.getPayAmount());
            payRefundDTO.setStoreId(orderGoods.getOrgId());
            RefundResponseDTO refundResponse = payService.refundApply(payRefundDTO);

            if (refundResponse.getRefundResult().equals(PayResult.success.getCode())) {
                refundSuccess(orderGoodsRefund.getRefundNo(), orderGoods.getOrderNo());
            } else if (refundResponse.getRefundResult().equals(PayResult.fail.getCode())) {
                refundError(orderGoodsRefund.getRefundNo(), orderGoods.getOrderNo());
            } else {
                //增加到延迟支付查询队列
                DelayMessage delayMessage = new DelayMessage(payRefundDTO.getOutRequestNo(), DelayTagsEnum.ORDER_REUND_DELAY_QUEUE_TASK.getCode(), JSONUtil.toJsonStr(payRefundDTO));
                //暂不执行
                delayQueueCache.addDelayJob(delayMessage, RefundQueryTimesEnum.getDelayTime(delayMessage.getPollingNum()));
            }
        }
        //组合退款
        if (orderGoods.getPayType().equals(PayType.COMBINE.getCode())) {
            if (orderGoodsRefund.getCashRefundAmount().compareTo(BigDecimal.ZERO) > 0) {
                //退款成功
                refundSuccess(orderGoodsRefund.getRefundNo(), orderGoodsRefund.getOrderNo());
            }
            if (orderGoodsRefund.getWxRefundAmount().compareTo(BigDecimal.ZERO) > 0 || orderGoodsRefund.getAliRefundAmount().compareTo(BigDecimal.ZERO) > 0) {
                //执行微信退款逻辑
                BigDecimal refundAmount = orderGoodsRefund.getWxRefundAmount().add(orderGoodsRefund.getAliRefundAmount());
                String payType = orderGoodsRefund.getWxRefundAmount().compareTo(BigDecimal.ZERO) > 0 ? PayType.WECHAT.getCode() : PayType.ALIPAY.getCode();
                PayRefundDTO payRefundDTO = new PayRefundDTO(payType, orderGoods.getOrderNo(), refundAmount, orderGoodsRefund.getRefundNo(), orderGoods.getOutTradeOrderNo(), orderGoodsRefundDTO.getRefundReason());
                payRefundDTO.setTotalAmount(refundAmount);
                payRefundDTO.setStoreId(orderGoods.getOrgId());
                RefundResponseDTO refundResponse = payService.refundApply(payRefundDTO);
                if (refundResponse.getRefundResult().equals(PayResult.fail.getCode())) {
                    orderGoodsRefund.setRefundStatus(OrderRefundStatus.ERROR.getCode());
                    orderGoodsRefund.setRemark(refundResponse.getPayMsg());
                    orderGoodsRefundService.updateById(orderGoodsRefund);
                    orderGoods.setRefundStatus(OrderRefundStatus.ERROR.getCode());
                    baseMapper.updateById(orderGoods);
                }
            }
        }
        return 1;
    }

    @Override
    public R refundSuccess(String refundNo, String orderNo) {
        OrderGoodsRefund orderGoodsRefund = orderGoodsRefundService.getOrderClothRefundByRefundNo(refundNo);
        orderGoodsRefund.setRefundStatus(OrderRefundStatus.REFUND_SUCCESS.getCode());
        orderGoodsRefund.setRefundTime(DateUtils.getNowDate());

        if (orderGoodsRefund.getPayType().equals(PayType.CASH.getCode())) {
            orderGoodsRefund.setCashRefundAmount(orderGoodsRefund.getRefundAmount());
        } else if (orderGoodsRefund.getPayType().equals(PayType.BALANCE.getCode())) {
            orderGoodsRefund.setMemberRefundAmount(orderGoodsRefund.getRefundAmount());
        } else if (orderGoodsRefund.getPayType().equals(PayType.WECHAT.getCode())) {
            orderGoodsRefund.setWxRefundAmount(orderGoodsRefund.getRefundAmount());
        } else if (orderGoodsRefund.getPayType().equals(PayType.ALIPAY.getCode())) {
            orderGoodsRefund.setAliRefundAmount(orderGoodsRefund.getRefundAmount());
        }

        orderGoodsRefundService.updateById(orderGoodsRefund);
        if (orderNo == null) {
            orderNo = orderGoodsRefund.getOrderNo();
        }

        OrderGoods orderGoods = this.getOne(new QueryWrapper<OrderGoods>().lambda().eq(OrderGoods::getOrderNo, orderNo));
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (orderGoods.getRefundStatus().equals(OrderRefundStatus.REFUND_SUCCESS.getCode())) {//退款状态不正确，直接跳过
            return R.ok();
        }

        // 处理返回商品库存
        List<OrderGoodsSku> orderGoodsSkus = this.handleAddStock(orderGoods);
        // 入库记录
        this.buildStockRecord(orderGoods, orderGoodsSkus, Boolean.TRUE, Boolean.TRUE);

        // 更新订单状态
        orderGoods.setOrderStatus(OrderGoodsStatusType.REFUND.getCode());
        orderGoods.setRefundStatus(OrderRefundStatus.REFUND_SUCCESS.getCode());
        baseMapper.updateById(orderGoods);

        //如果是组合支付，退会员余额
        if (orderGoods.getPayType().equals(PayType.COMBINE.getCode())) {
            if (orderGoodsRefund.getMemberRefundAmount().compareTo(BigDecimal.ZERO) > 0) {
                //如果支付金额大于0，则扣除会员余额
                Boolean res = rechargePasswordCardService.orderRefundByBalance(orderGoodsRefund.getOrderNo(), orderGoodsRefund.getMemberRefundAmount());
                if (res) {
                    throw new ServiceException("会员余额退款失败");
                }
            }
        }

        // 处理销量 - 扣商品销量
        List<OrderGoodsSku> list = orderGoodsSkuService.list(new QueryWrapper<OrderGoodsSku>().lambda().eq(OrderGoodsSku::getOrderId, orderGoods.getId()));
        if (CollUtil.isNotEmpty(list)) {
            //更新商品退款金额
            for (OrderGoodsSku orderGoodsSku : list) {
                orderGoodsSku.setRefundAmount(orderGoodsSku.getTotalAmount());
                orderGoodsSku.setRefundId(orderGoodsRefund.getId());
                orderGoodsSkuService.updateById(orderGoodsSku);
            }
            this.buildUpdateGoodsSales(list, Boolean.FALSE);
        }
        return null;
    }

    @Override
    public R refundClosed(String refundNo, String orderNo) {
        if (StrUtil.isNotBlank(refundNo)) {
            OrderGoodsRefund orderGoodsRefund = orderGoodsRefundService.getOrderClothRefundByRefundNo(refundNo);
            orderGoodsRefund.setRefundStatus(OrderRefundStatus.REFUND_SUCCESS.getCode());
            orderGoodsRefund.setRefundTime(DateUtils.getNowDate());
            orderGoodsRefundService.updateById(orderGoodsRefund);
            if (orderNo == null) {
                orderNo = orderGoodsRefund.getOrderNo();
            }
        }

        OrderGoods orderGoods = this.getOne(new QueryWrapper<OrderGoods>().lambda().eq(OrderGoods::getOrderNo, orderNo));
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        orderGoods.setRefundStatus(OrderRefundStatus.REFUND_CANCEL.getCode());
        updateById(orderGoods);
        return R.ok();
    }

    @Override
    public R refundError(String refundNo, String orderNo) {
        if (StrUtil.isNotBlank(refundNo)) {
            OrderGoodsRefund orderGoodsRefund = orderGoodsRefundService.getOrderClothRefundByRefundNo(refundNo);
            orderGoodsRefund.setRefundStatus(OrderRefundStatus.REFUND_SUCCESS.getCode());
            orderGoodsRefund.setRefundTime(DateUtils.getNowDate());
            orderGoodsRefundService.updateById(orderGoodsRefund);
            if (orderNo == null) {
                orderNo = orderGoodsRefund.getOrderNo();
            }
        }

        OrderGoods orderGoods = this.getOne(new QueryWrapper<OrderGoods>().lambda().eq(OrderGoods::getOrderNo, orderNo));
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        orderGoods.setRefundStatus(OrderRefundStatus.ERROR.getCode());
        updateById(orderGoods);
        return R.ok();
    }


    /**
     * 商品订单退款审核，审批同意
     */
    @Override
    public int refundApprovalPass(Long orderId) {
        OrderGoods orderGoods = baseMapper.selectById(orderId);
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (!OrderRefundStatus.REFUND_APPLYING.getCode().equals(orderGoods.getRefundStatus())) {
            throw new GlobalException("订单非退款中状态，无法退单");
        }
        if (OrderGoodsStatusType.NO_PAY.getCode().equals(orderGoods.getOrderStatus())) {
            throw new GlobalException("订单未支付，不能操作退单");
        }

//        // 处理返回商品库存
//        List<OrderGoodsSku> orderGoodsSkus = this.handleAddStock(orderGoods);
//        // 入库记录
//        this.buildStockRecord(orderGoods, orderGoodsSkus, Boolean.TRUE, Boolean.TRUE);

        // 更新订单状态
        orderGoods.setRefundStatus(OrderRefundStatus.REFUNDING.getCode());
        orderGoods.setRefundTime(DateUtils.getNowDate());
        orderGoods.setRefundAmount(orderGoods.getPayAmount());
        orderGoods.buildUpdateData();
        baseMapper.updateById(orderGoods);

        OrderGoodsRefund orderGoodsRefund = new OrderGoodsRefund();
        BeanUtils.copyProperties(orderGoods, orderGoodsRefund);
        orderGoodsRefund.setId(null);
        orderGoodsRefund.setRefundNo(orderNoUtils.getGoodsOrderNo());
        orderGoodsRefund.setRefundAmount(orderGoods.getRefundAmount());
        orderGoodsRefund.setRefundApplyTime(DateUtils.getNowDate());
        orderGoodsRefund.setRefundReason(null);
        orderGoodsRefund.setRefundStatus(OrderRefundStatus.REFUND_APPLYING.getCode());
        orderGoodsRefundService.save(orderGoodsRefund);

        // 退款
        if (orderGoods.getPayType().equals(PayType.CASH.getCode())) {
            refundSuccess(orderGoodsRefund.getRefundNo(), orderGoods.getOrderNo());
        }
        if (orderGoods.getPayType().equals(PayType.BALANCE.getCode())) {
            //充值卡支付退单
            Boolean res = rechargePasswordCardService.orderRefundByBalance(orderGoods.getOrderNo(), orderGoods.getRefundAmount());
            if (res) {
                refundSuccess(orderGoodsRefund.getRefundNo(), orderGoods.getOrderNo());
            }
        }
        if (orderGoods.getPayType().equals(PayType.WECHAT.getCode()) || orderGoods.getPayType().equals(PayType.ALIPAY.getCode())) {
            PayRefundDTO payRefundDTO = new PayRefundDTO(orderGoods.getPayType(), orderGoods.getOrderNo(), orderGoods.getPayAmount(), orderGoodsRefund.getRefundNo(), orderGoods.getOutTradeOrderNo(), null);
            //执行微信退款逻辑
            payRefundDTO.setTotalAmount(orderGoods.getPayAmount());
            payRefundDTO.setStoreId(orderGoods.getOrgId());
            RefundResponseDTO refundResponse = payService.refundApply(payRefundDTO);

            if (refundResponse.getRefundResult().equals(PayResult.success.getCode())) {
                refundSuccess(orderGoodsRefund.getRefundNo(), orderGoods.getOrderNo());
            } else if (refundResponse.getRefundResult().equals(PayResult.fail.getCode())) {
                refundError(orderGoodsRefund.getRefundNo(), orderGoods.getOrderNo());
            } else {
                //增加到延迟支付查询队列
                DelayMessage delayMessage = new DelayMessage(payRefundDTO.getOutRequestNo(), DelayTagsEnum.ORDER_REUND_DELAY_QUEUE_TASK.getCode(), JSONUtil.toJsonStr(payRefundDTO));
                //暂不执行
                delayQueueCache.addDelayJob(delayMessage, RefundQueryTimesEnum.getDelayTime(delayMessage.getPollingNum()));
            }

        }

//        // 退款流程
//        appUserBillMstrService.refundRecord(ConsumeOrderDTO.buildOrderGoodsRefundData(orderGoods), new RefundBaseDTO(orderNoUtils.getGoodsOrderNo()));
        return 1;
    }

    /**
     * 商品订单退款审核，审批驳回
     */
    @Override
    public int refundApprovalReject(Long orderId) {
        OrderGoods orderGoods = baseMapper.selectById(orderId);
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (!OrderRefundStatus.REFUND_APPLYING.getCode().equals(orderGoods.getRefundStatus())) {
            throw new GlobalException("订单非退款中状态，无法拒单");
        }
        // 更新订单状态
        orderGoods.setRefundStatus(OrderRefundStatus.REFUND_REFUSE.getCode());
        orderGoods.setRefundTime(DateUtils.getNowDate());
        orderGoods.buildUpdateData();
        return baseMapper.updateById(orderGoods);
    }

    /**
     * 商品订单退款-APP取消退款
     *
     * @param orderId
     * @return
     */
    @Override
    public int cancelRefund(Long orderId) {
        OrderGoods orderGoods = baseMapper.selectById(orderId);
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (!OrderRefundStatus.REFUND_APPLYING.getCode().equals(orderGoods.getRefundStatus())) {
            throw new GlobalException("订单非退款中状态，无法取消");
        }
        // 操作人校验
        if (!AuthHolder.userId().equals(orderGoods.getAppUserId())) {
            throw new ServiceException("当前登录人没有权限操作");
        }
        // 更新订单状态，不在退款
        orderGoods.setRefundStatus(OrderRefundStatus.OK.getCode());
        orderGoods.buildUpdateData();
        return baseMapper.updateById(orderGoods);
    }

    /**
     * 商品订单退款-APP申请退款
     *
     * @param appOrderGoodsRefundDTO
     * @return
     */
    @Override
    public int applyRefundOrderGoods(AppOrderGoodsRefundDTO appOrderGoodsRefundDTO) {
        OrderGoods orderGoods = baseMapper.selectById(appOrderGoodsRefundDTO.getOrderId());
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        // 操作人校验
        if (!AuthHolder.userId().equals(orderGoods.getAppUserId())) {
            throw new ServiceException("当前登录人没有权限操作");
        }
        if (OrderRefundStatus.REFUND_APPLYING.getCode().equals(orderGoods.getRefundStatus())) {
            throw new GlobalException("商品订单退款申请中，请勿重复操作");
        }
        if (OrderRefundStatus.REFUND_SUCCESS.getCode().equals(orderGoods.getRefundStatus())) {
            throw new GlobalException("商品订单已退款，请勿重复操作");
        }
        orderGoods.setRefundReason(appOrderGoodsRefundDTO.getRefundReason());
        orderGoods.setRefundStatus(OrderRefundStatus.REFUND_APPLYING.getCode());
        orderGoods.buildUpdateData();
        return baseMapper.updateById(orderGoods);
    }

    /**
     * 零售出货 - 组装库存记录list
     *
     * @param orderGoods
     * @param orderGoodsSkus
     * @param isAdd
     * @param isRefund
     */
    private void buildStockRecord(OrderGoods orderGoods, List<OrderGoodsSku> orderGoodsSkus, Boolean isAdd, Boolean isRefund) {
        goodsSkuStockRecordService.saveBatch(GoodsSkuStockRecordDTO.buildStockRecordByOrderRetailGoods(orderGoods, orderGoodsSkus, isAdd, isRefund));
    }

    /**
     * 通过订单物料明细， 更新商品销售数量
     *
     * @param orderGoodsSkus
     * @param isAdd          是否新增销量
     */
    private void buildUpdateGoodsSales(List<OrderGoodsSku> orderGoodsSkus, boolean isAdd) {
        Map<Long, Integer> goodsSaleNumberMap = orderGoodsSkus.stream().collect(Collectors.groupingBy(OrderGoodsSku::getGoodsId))
                .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
                        entry -> entry.getValue().stream().mapToInt(OrderGoodsSku::getBuyNum).sum()));
        List<GoodsUpdateSalesDTO> goodsUpdateSales = new ArrayList<>();
        for (Map.Entry<Long, Integer> entry : goodsSaleNumberMap.entrySet()) {
            GoodsUpdateSalesDTO goodsUpdate = new GoodsUpdateSalesDTO();
            goodsUpdate.setId(entry.getKey());
            goodsUpdate.setSellNum(entry.getValue());
            goodsUpdate.setVirtualSellNum(entry.getValue());
            goodsUpdateSales.add(goodsUpdate);
        }
        goodsInfoService.handleGoodsSellNum(goodsUpdateSales, isAdd);
    }

    public String getDeliveryWayByOrderSource(String orderSource) {
        if (OrderSourceType.APP.getCode().equals(orderSource)) {
            return DeliveryWayType.DELIVERY.getCode();
        }
        if (OrderSourceType.WXAPP.getCode().equals(orderSource)) {
            return DeliveryWayType.DELIVERY.getCode();
        }
        if (OrderSourceType.OFFLINE.getCode().equals(orderSource)) {
            return DeliveryWayType.SELF_SEND.getCode();
        }
        return null;
    }

    /**
     * 通过购买车选中的物料id，查询物料信息，并加入购买数量返回
     *
     * @return 用于计算总价，和创建订单时用到的一些商品信息
     */
    @Override
    public List<OrderGoodsSkuInfoVO> getOrderSkuInfoByGoodsMarket() {
        List<AppGoodsMarket> appGoodsMarketList = appGoodsMarketService.list(new QueryWrapper<AppGoodsMarket>().lambda()
                .eq(AppGoodsMarket::getAppUserId, AuthHolder.userId())
                .eq(AppGoodsMarket::getIsSelect, SysBoolType.YES.getCode()));
        if (appGoodsMarketList == null || appGoodsMarketList.size() == 0) {
            throw new ServiceException("请选择商品");
        }
        if (appGoodsMarketList.stream().anyMatch(item -> item.getBuyNum() == null || item.getBuyNum() == 0)) {
            throw new ServiceException("商品数量不能为0");
        }

        List<OrderGoodsSkuInfoVO> skuInfoList = this.getSkuInfoList(
                appGoodsMarketList.stream()
                        .map(AppGoodsMarket::getGoodsSkuId).collect(Collectors.toList()), OrderSourceType.APP.getCode());
        if (CollUtil.isEmpty(skuInfoList)) {
            throw new GlobalException("商品物料信息为空，无法下单");
        }
        Map<Long, AppGoodsMarket> orderGoodsSkuInfoVOMap = appGoodsMarketList.stream()
                .collect(Collectors.toMap(AppGoodsMarket::getGoodsSkuId, AppGoodsMarket -> AppGoodsMarket));

        for (OrderGoodsSkuInfoVO orderGoodsSkuInfoVO : skuInfoList) {
            if (!orderGoodsSkuInfoVOMap.containsKey(orderGoodsSkuInfoVO.getSkuId())) {
                continue;
            }
            orderGoodsSkuInfoVO.setBuyNum(orderGoodsSkuInfoVOMap.get(orderGoodsSkuInfoVO.getSkuId()).getBuyNum());
        }
        return skuInfoList;
    }


    /**
     * 通过购买选择的物料id，查询物料信息，并加入购买数量返回
     *
     * @param orderGoodsDTO
     * @return 用于计算总价，和创建订单时用到的一些商品信息
     */
    @Override
    public List<OrderGoodsSkuInfoVO> getOrderSkuInfoByOrderSkuId(OrderGoodsDTO orderGoodsDTO) {
        List<OrderRetailGoodsSkusDTO> retailGoodsVOList = orderGoodsDTO.getRetailGoodsVOList();
        if (CollUtil.isEmpty(retailGoodsVOList)) {
            throw new GlobalException("操作失败,商品信息为空");
        }
        if (retailGoodsVOList.stream().anyMatch(item -> item.getBuyNum() == null || item.getBuyNum() == 0)) {
            throw new ServiceException("商品数量不能为0");
        }

        List<OrderGoodsSkuInfoVO> skuInfoList = this.getSkuInfoList(
                retailGoodsVOList.stream()
                        .map(OrderRetailGoodsSkusDTO::getSkuId).collect(Collectors.toList()), orderGoodsDTO.getOrderSource());
        if (CollUtil.isEmpty(skuInfoList)) {
            throw new GlobalException("商品物料信息为空，无法下单");
        }
        Map<Long, OrderRetailGoodsSkusDTO> orderGoodsSkuInfoVOMap = retailGoodsVOList.stream()
                .collect(Collectors.toMap(OrderRetailGoodsSkusDTO::getSkuId, OrderRetailGoodsSkusDTO -> OrderRetailGoodsSkusDTO));

        for (OrderGoodsSkuInfoVO orderGoodsSkuInfoVO : skuInfoList) {
            if (!orderGoodsSkuInfoVOMap.containsKey(orderGoodsSkuInfoVO.getSkuId())) {
                continue;
            }
            orderGoodsSkuInfoVO.setBuyNum(orderGoodsSkuInfoVOMap.get(orderGoodsSkuInfoVO.getSkuId()).getBuyNum());
        }
        return skuInfoList;
    }

    /**
     * 处理减库存
     *
     * @param orderGoods
     * @return
     */
    public List<OrderGoodsSku> handleMinusStock(OrderGoods orderGoods) {
        // 处理商品库存 查询本次订单内容
        List<OrderGoodsSku> orderGoodsSkus = orderGoodsSkuService.list(new QueryWrapper<OrderGoodsSku>().lambda()
                .eq(OrderGoodsSku::getOrderId, orderGoods.getId()));
        // 减库存
        if (OrderSourceType.OFFLINE.getCode().equals(orderGoods.getOrderSource())) {
            //线下订单，扣门店库存
            goodsSkuStoreService.addOrMinusGoodsSkuStockByGoods(0, orderGoods, orderGoodsSkus);
        } else {
            //线上订单，扣平台商品库存
            goodsSkuService.addOrMinusGoodsSkuStockByGoods(0, orderGoodsSkus);
        }

        return orderGoodsSkus;
    }

    /**
     * 处理加库存
     *
     * @param orderGoods
     * @return
     */
    public List<OrderGoodsSku> handleAddStock(OrderGoods orderGoods) {
        // 处理商品库存 查询本次订单内容
        List<OrderGoodsSku> orderGoodsSkus = orderGoodsSkuService.list(new QueryWrapper<OrderGoodsSku>().lambda()
                .eq(OrderGoodsSku::getOrderId, orderGoods.getId()));
        // 加库存
        if (OrderSourceType.OFFLINE.getCode().equals(orderGoods.getOrderSource())) {
            //线下订单，扣门店库存
            goodsSkuStoreService.addOrMinusGoodsSkuStockByGoods(1, orderGoods, orderGoodsSkus);
        } else {
            //线上订单，扣平台商品库存
            goodsSkuService.addOrMinusGoodsSkuStockByGoods(1, orderGoodsSkus);
        }
        return orderGoodsSkus;
    }

    @Override
    public BigDecimal getDeductAmountByUserPoint() {
        return new BigDecimal(BigInteger.ZERO);
    }

    @Override
    public List<GoodsOrderRefundQueryVO> getRefundOrderGoodsList(GoodsOrderRefundQueryDTO goodsOrderRefundQueryDTO) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        goodsOrderRefundQueryDTO.setSourceType(user.getUserType());
        if (SourceType.STORE.getCode().equals(user.getUserType())) {
            goodsOrderRefundQueryDTO.setOrgId(user.getStoreId());
        }
        return baseMapper.getRefundOrderGoodsList(goodsOrderRefundQueryDTO);
    }

    @Override
    public OrderDeliveryPathVO getDeliveryPath(Long orderId) throws Exception {
        OrderGoods orderGoods = baseMapper.selectById(orderId);
        if (orderGoods == null) {
            throw new GlobalException("订单不存在");
        }
        AppUserInfoVO appUserInfo = appUserService.getAppUserInfoById(orderGoods.getAppUserId());
        return thirdDeliveryService.getDeliveryPath(OrderThirdDeliveryPathDTO.buildDeliveryPathByGoodsOrder(orderGoods, appUserInfo.getWxOpenId()));
    }

    @Override
    public List<GoodsStatisticsVO> getGoodsStatisticsList(GoodsStatisticsQueryDTO queryDTO) {
        return baseMapper.getGoodsStatisticsList(queryDTO);
    }

}
