package com.cyl.h5.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyl.h5.pojo.dto.*;
import com.cyl.h5.pojo.request.CancelOrderRequest;
import com.cyl.h5.pojo.request.OrderPayRequest;
import com.cyl.h5.pojo.response.OrderPayResponse;
import com.cyl.h5.pojo.response.WechatMemberCouponResponse;
import com.cyl.h5.pojo.vo.*;
import com.cyl.h5.pojo.vo.form.OrderSubmitForm;
import com.cyl.manager.marketing.domain.WechatMemberCoupon;
import com.cyl.manager.marketing.mapper.WechatMemberCouponMapper;
import com.cyl.manager.marketing.service.IWechatMemberCouponService;
import com.cyl.manager.oms.convert.AftersaleItemConvert;
import com.cyl.manager.oms.convert.OrderItemConvert;
import com.cyl.manager.oms.domain.*;
import com.cyl.manager.oms.mapper.*;
import com.cyl.manager.oms.service.OmsOrderServiceService;
import com.cyl.manager.oms.service.OrderItemService;
import com.cyl.manager.oms.service.OrderOperateHistoryService;
import com.cyl.manager.pms.domain.Product;
import com.cyl.manager.pms.domain.Sku;
import com.cyl.manager.pms.mapper.ProductMapper;
import com.cyl.manager.pms.mapper.SkuMapper;
import com.cyl.manager.staff.domain.BondTransaction;
import com.cyl.manager.staff.domain.Staff;
import com.cyl.manager.staff.service.IBondTransactionService;
import com.cyl.manager.staff.service.IStaffService;
import com.cyl.manager.ums.domain.*;
import com.cyl.manager.ums.mapper.MemberAddressMapper;
import com.cyl.manager.ums.mapper.MemberCartMapper;
import com.cyl.manager.ums.mapper.MemberWechatMapper;
import com.cyl.manager.ums.pojo.vo.PetVO;
import com.cyl.manager.ums.service.PetService;
import com.cyl.tencent.OrderMessageModel;
import com.cyl.wechat.WechatPayData;
import com.cyl.wechat.WechatPayService;
import com.cyl.wechat.WechatPayUtil;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.common.enums.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IDGenerator;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.LocalDataUtil;
//import com.ruoyi.model.domain.AppletUsersTeacher;
//import com.ruoyi.model.service.IAppletUsersTeacherService;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class H5OrderService {

    @Autowired
    private MemberAddressMapper memberAddressMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private MemberCartMapper memberCartMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OmsOrderServiceMapper omsOrderServiceMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderOperateHistoryMapper orderOperateHistoryMapper;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderOperateHistoryService orderOperateHistoryService;

    @Autowired
//    @Lazy
    private WechatPayService wechatPayService;

    @Autowired
    private MemberWechatMapper memberWechatMapper;


    @Autowired
    private IWechatMemberCouponService wechatMemberCouponService;

    @Autowired
    private WechatPaymentHistoryMapper wechatPaymentHistoryMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private AftersaleMapper aftersaleMapper;

    @Autowired
    private AftersaleItemMapper aftersaleItemMapper;

    @Autowired
    private AftersaleItemConvert aftersaleItemConvert;

    @Autowired
    private OrderItemConvert orderItemConvert;

    @Autowired
    private OmsOrderServiceService omsOrderServiceService;

    @Autowired
    @Qualifier("taskQueue")
    private BlockingQueue<OrderMessageModel> taskQueue;

    @Autowired
    private PetService petService;

    @Autowired
    private IBondTransactionService bondTransactionService;

    @Autowired
    private IStaffService staffService;

    @Autowired
    private H5CouponService h5CouponService;

    @Autowired
    private WechatMemberCouponMapper wechatMemberCouponMapper;


    @Autowired
    private  H5PetService h5PetService;

//
//    @Autowired
//    private IAppletUsersTeacherService appletUsersTeacherService;

    @Transactional
    public Order submit(OrderSubmitForm form) {
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);

        if(member == null){
            throw new RuntimeException("用户信息不存在");
        }

        //只支持快递
        Long addressId = form.getAddressId();
        if (addressId == null){
            throw new RuntimeException("地址不能为空");
        }
        MemberAddress memberAddress = memberAddressMapper.selectById(addressId);
        if (memberAddress == null){
            throw new RuntimeException("地址不能为空");
        }

        //PetOrderService 宠物服务不能为空
        List<PetOrderServiceDTO> petOrderServices = form.getPetOrderServices();

        if (CollectionUtil.isEmpty(petOrderServices)){
            throw new RuntimeException("宠物服务不能为空");
        }
        //校验宠物服务
        for (PetOrderServiceDTO petOrderService : petOrderServices) {
            verificationPetOrderService(petOrderService);
        }

//        BigDecimal orderTotalAmount = calculatePrice(petOrderServices,form,member);
        BigDecimal orderTotalAmount = new BigDecimal(form.getTotalPrice());


        BigDecimal bigDecimalValue = new BigDecimal(form.getTotalPrice()).setScale(2, RoundingMode.HALF_UP);
        log.info("订单提交总价（折扣后）：{}，member:{}",bigDecimalValue,member.getNickname());
        //判断价格是否匹配
//        if(orderTotalAmount.compareTo(bigDecimalValue) != 0){
//            throw new RuntimeException("价格不匹配");
//        }

        LocalDateTime optTime = LocalDateTime.now();


        //生成一个统一的订单号
        Long orderId = IDGenerator.generateId();
        //生产一个payId
        Long payId = IDGenerator.generateId();
        //创建订单
        Order order = new Order();
        order.setPayId(payId);
        order.setId(orderId);
        order.setOrderSn(this.getOrderIdPrefix() + orderId);
        order.setMemberId(member.getId());
        order.setMemberUsername(member.getNickname());
        order.setPayType(Constants.PayType.WECHAT);
        order.setTotalAmount(new BigDecimal(form.getOldPrice()).add(new BigDecimal(form.getMemberDiscount())));
        order.setPurchasePrice(orderTotalAmount);
        order.setFreightAmount(BigDecimal.ZERO);
        order.setPayAmount(orderTotalAmount);
        order.setStatus(Constants.OrderStatus.NOTPAID);
        order.setAftersaleStatus(1);
        order.setReceiverName(memberAddress.getName());
        order.setReceiverPhone(memberAddress.getPhoneHidden());
        order.setReceiverPostCode(memberAddress.getPostCode());
        order.setReceiverProvince(memberAddress.getProvince());
        order.setReceiverCity(memberAddress.getCity());
        order.setReceiverDistrict(memberAddress.getDistrict());
        order.setReceiverProvinceId(memberAddress.getProvinceId());
        order.setReceiverCityId(memberAddress.getCityId());
        order.setReceiverDistrictId(memberAddress.getDistrictId());
        order.setReceiverDetailAddress(memberAddress.getDetailAddress());



        order.setAddressId(addressId);
        order.setLongitude(memberAddress.getLongitude());
        order.setLatitude(memberAddress.getLatitude());
        //设置伴宠师ID和下单方式
        if(form.getServicerId() != null){
            order.setServicerId(form.getServicerId());
        }
        if(!StringUtils.isEmpty(form.getOrderMethod())){
            order.setOrderMethod(form.getOrderMethod());
        }

        if(form.getOrderId() != null && form.getOrderId() != 0){
            order.setOldOrderId(form.getOrderId());
        }

        /*
        //优惠券优惠
        couponDiscount: this.discount,
        //会员折扣
        memberDiscount: this.memberDiscount,
        //费用总计
        oldPrice : this.originalTotalPrice,
        //提前熟悉的费用
        preFamiliarizePrice: this.price_config.preFamiliarize.price,
        * */
        order.setCouponDiscount(new BigDecimal(form.getCouponDiscount()));
        order.setMemberDiscount(new BigDecimal(form.getMemberDiscount()));
        order.setOldPrice(new BigDecimal(form.getOldPrice()));
        order.setPreFamiliarizePrice(new BigDecimal(form.getPreFamiliarizePrice()));

        order.setCompanionLevelPrice(new BigDecimal(form.getCompanionLevelPrice()));
        order.setCompanionLevelTitle(form.getCompanionLevelTitle());


        //设置伴宠师ID和下单方式
        if(form.getTeacherId() != null){
            order.setTeacherId(form.getTeacherId());
        }
        if(form.getCompanionLevel()!=null){
            order.setCompanionLevel(form.getCompanionLevel());
        }
 
        order.setNote(form.getNote());
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
//        order.setPaymentTime(optTime);
        //是否提前熟悉
        order.setNeedPreFamiliarize(form.getNeedPreFamiliarize());
        //优惠券
        order.setWechatMemberCouponId(form.getCouponId());
        order.setCreateTime(optTime);
        order.setCreateBy(member.getId());
        int rows = orderMapper.insert(order);
        if (rows < 1){
            throw new RuntimeException("订单新增失败");
        }

        //保存 orderService 记录、orderItem 记录、orderOperateHistory 记录
        submitOrderService(order.getId(), form);

        //如果存在优惠券，需要执行优惠券核销
        Integer couponId =  form.getCouponId();
        if(couponId != null){
            wechatMemberCouponService.use(couponId,order.getId());
        }

        // 保存订单操作记录
        OrderOperateHistory orderOperateHistory = new OrderOperateHistory();
        orderOperateHistory.setOrderId(orderId);
        orderOperateHistory.setOrderSn(order.getOrderSn());
        orderOperateHistory.setOperateMan(member.getId() + "");
        orderOperateHistory.setOrderStatus(Constants.OrderStatus.NOTPAID);
        orderOperateHistory.setCreateTime(optTime);
        orderOperateHistory.setCreateBy(member.getId());
        rows = orderOperateHistoryMapper.insert(orderOperateHistory);
        if (rows < 1){
            throw new RuntimeException("保存订单操作记录失败");
        }

        //当前订单id，接入支付后可返回payId
        return order;
    }

    private BigDecimal calculatePrice(List<PetOrderServiceDTO> petOrderServices,OrderSubmitForm form,Member member){
        /**
         * 1. 专业喂养价格 - 75元，锚定不变，不随宠物数量、天数变化
         * 专业喂养项目根据OrderProductListDTO的isMainProduct取 skuId
         */
        //1.获取专业喂养项目价格
        OrderProductListDTO orderProductListDTO =  takeMainProducts(petOrderServices);
        BigDecimal majorFeedPrice = BigDecimal.valueOf(75);
        if(!ObjectUtil.isNull(orderProductListDTO)){
            Sku sku = skuMapper.selectById(orderProductListDTO.getSkuId());
            majorFeedPrice = sku==null? BigDecimal.valueOf(75):sku.getPrice();
        }
        log.info("专业喂养单价：{}",majorFeedPrice);

        //2、先计算专业喂养价格
        BigDecimal majorFeedTotalAmount = BigDecimal.ZERO;
        Map<LocalDate, List<PetOrderServiceDTO>> petOrderServiceMap = petOrderServices.stream().collect(Collectors.groupingBy(PetOrderServiceDTO::getServiceDate));
        Map<LocalDate,Integer> maxFeedCountMap = new HashMap();
        for (Map.Entry<LocalDate, List<PetOrderServiceDTO>> entry : petOrderServiceMap.entrySet()) {
            LocalDate serviceDate = entry.getKey();
            List<PetOrderServiceDTO> petOrderServiceDTOs = entry.getValue();
            // 找到喂养次数的最大值
            int maxFeedCount = petOrderServiceDTOs.stream()
                    .mapToInt(PetOrderServiceDTO::getFeedCount)
                    .max()
                    .orElse(0); // 如果没有元素，返回 0

            // 将最大喂养次数放入 maxFeedCountMap 中
            if(maxFeedCount > 0){
                maxFeedCountMap.put(serviceDate, maxFeedCount);
            }
        }
        //存在专业喂养的清空
        if(!CollectionUtils.isEmpty(maxFeedCountMap)){
            BigDecimal majorFeedCount = BigDecimal.valueOf(maxFeedCountMap.size());
            majorFeedTotalAmount = majorFeedTotalAmount.add(majorFeedCount.multiply(majorFeedPrice));
        }
        log.info("专业喂养总价：{}，member:{}",majorFeedTotalAmount,member.getNickname());

        /**
         * 2. 当日多次服务总价，取当日不同宠物中，最大的服务次数作为价格计算基准（如1天内，狗狗1天2次，猫咪1天3次，此日服务次数选择3次）
         *  - 1天1次：+0 元
         *  - 1天2次：+ 45元
         *  - 1天3次：+130 元
         */
        //2、当日多次服务额外费用
        BigDecimal serviceExtraTotalAmount = BigDecimal.ZERO;
        if(!CollectionUtils.isEmpty(maxFeedCountMap)){
            for (Map.Entry<LocalDate,  Integer> entry : maxFeedCountMap.entrySet()) {
                LocalDate date = entry.getKey();
                Integer count = entry.getValue();
                if(count == 2){
                    serviceExtraTotalAmount = serviceExtraTotalAmount.add(BigDecimal.valueOf(45));
                }else if(count > 2){
                    serviceExtraTotalAmount = serviceExtraTotalAmount.add(BigDecimal.valueOf(130));
                }
            }
        }

        log.info("当日多次服务额外费用总价：{}，member:{}",serviceExtraTotalAmount,member.getNickname());
        /**
         *  额外宠物费用：单日所勾选的宠物超过3只猫或2只小型犬或1只中型犬，超过其中任意一个，会收取标准外的额外费用：
         *  - 猫：1只/次：10元
         *  - 小型犬：1只/天：15元
         *  - 中型犬：1只/天：30元
         *  - 大型犬：1只/天：40元 (大型犬不参与价格计算，单独计算价格）
         */
        //3、额外宠物费用
        BigDecimal extraPetTotalAmount = BigDecimal.ZERO;
        BigDecimal bigBodyPetTotalAmount = BigDecimal.ZERO;
        Map<LocalDate, Map<String,Integer>> petCountMap = new HashMap<>();
        for (PetOrderServiceDTO petOrderService : petOrderServices) {
            LocalDate serviceDate = petOrderService.getServiceDate();
            // CAT、SMALL_DOG、MEDIUM_DOG、BIG_DOG
            String petType = getPetType(petOrderService.getPetId());
            if(petType.equals("BIG_DOG")){
                bigBodyPetTotalAmount = bigBodyPetTotalAmount.add(BigDecimal.valueOf(40));
                continue;
            }
            // 统计每天每种类型宠物的数量
            petCountMap.putIfAbsent(serviceDate, new HashMap<>());
            Map<String, Integer> petCount = petCountMap.get(serviceDate);
            petCount.put(petType, petCount.getOrDefault(petType, 0) + 1);
            petCountMap.put(serviceDate,petCount);
        }

        for (Map.Entry<LocalDate, Map<String, Integer>> entry : petCountMap.entrySet()) {
            Map<String, Integer> valueMap =  entry.getValue();
            BigDecimal extraPetAmount = BigDecimal.ZERO;
            for (Map.Entry<String, Integer> valueEntry : valueMap.entrySet()) {
                String petType =  valueEntry.getKey();
                BigDecimal price = BigDecimal.ZERO;
                //CAT、SMALL_DOG、MEDIUM_DOG、BIG_DOG
                if(ObjectUtil.equals(petType,"CAT")){
                    price = BigDecimal.valueOf(10);
                }else if(ObjectUtil.equals(petType,"SMALL_DOG")){
                    price = BigDecimal.valueOf(15);
                }else if(ObjectUtil.equals(petType,"MEDIUM_DOG")){
                    price = BigDecimal.valueOf(30);
                }else if(ObjectUtil.equals(petType,"BIG_DOG")){
                    price = BigDecimal.valueOf(40);
                }
                extraPetAmount = extraPetAmount.add(price.multiply(BigDecimal.valueOf(valueEntry.getValue())));
            }
            if(extraPetAmount.compareTo(BigDecimal.valueOf(30))>0){
                extraPetTotalAmount =  extraPetTotalAmount.add(extraPetAmount.subtract(BigDecimal.valueOf(30)));
            }
        }
        log.info("额外宠物费用总价：{}，member:{}",extraPetTotalAmount,member.getNickname());
        log.info("大型犬费用总价：{}，member:{}",bigBodyPetTotalAmount,member.getNickname());

        //4,定制服务费用总价
        BigDecimal customizedTotalAmount = BigDecimal.ZERO;
        for (PetOrderServiceDTO petOrderService : petOrderServices) {
            List<OrderProductListDTO> skuList = petOrderService.getSkuList();
            // 计算定制服务费用时过滤掉主商品
            List<OrderProductListDTO> nonMainProducts = skuList.stream()
                    .filter(orderProduct -> Boolean.FALSE.equals(orderProduct.getIsMainProduct()))
                    .collect(Collectors.toList());
            for (OrderProductListDTO orderProductListDto : nonMainProducts) {
                Sku sku = skuMapper.selectById(orderProductListDto.getSkuId());
                customizedTotalAmount = customizedTotalAmount.add(sku.getPrice().multiply(BigDecimal.valueOf(orderProductListDto.getQuantity())));
            }
        }
        log.info("定制服务费用总价：{}，member:{}",customizedTotalAmount,member.getNickname());
        //5、是否需要提前熟悉
        BigDecimal preFamiliarizeAmount = BigDecimal.ZERO;
        if(form.getNeedPreFamiliarize() ){
            preFamiliarizeAmount = BigDecimal.valueOf(40);
        }
        log.info("是否需要提前熟悉总价：{}，member:{}",preFamiliarizeAmount,member.getNickname());

        //订单总价格
        BigDecimal totalAmount = majorFeedTotalAmount.add(serviceExtraTotalAmount).add(extraPetTotalAmount).add(customizedTotalAmount).add(preFamiliarizeAmount).add(bigBodyPetTotalAmount);

        // 6、是否包含优惠券
        Integer couponId =  form.getCouponId();
        if(couponId != null){
            WechatMemberCoupon wechatMemberCoupon =  wechatMemberCouponMapper.selectById(couponId);
            //校验券的有效性
            verificationCoupon(wechatMemberCoupon,member);

            List<WechatMemberCouponResponse>  list =   wechatMemberCouponMapper.selectMemberCouponById(couponId);
            if(CollectionUtils.isEmpty(list)){
                throw new RuntimeException("优惠券不存在");
            }
            WechatMemberCouponResponse wechatMemberCouponResponse =  list.get(0);
            if(wechatMemberCouponResponse.getStockType().equals(StockTypeEnum.PNORMAL.getLabel())){
                //折扣前是否满足满减
                if(totalAmount.compareTo(new BigDecimal(wechatMemberCouponResponse.getTransactionMinimum()))>0){
                    log.info("满减优惠券 优惠后价格：{}，member:{}",wechatMemberCouponResponse.getDiscountAmount(),member.getNickname());
                    totalAmount = totalAmount.subtract(new BigDecimal(wechatMemberCouponResponse.getDiscountAmount()));
                    log.info("满减优惠券 满减优惠后总价：{}，member:{}",totalAmount,member.getNickname());
                }else{
                    log.info("折扣优惠券 不满足满减条件，订单总价:{},消费门槛金额:{}",totalAmount,wechatMemberCouponResponse.getTransactionMinimum());
                    throw new RuntimeException("优惠券不满足满减条件");
                }
            }else if (wechatMemberCouponResponse.getStockType().equals(StockTypeEnum.PDISCOUNT.getLabel())){
                //折扣前是否满足折扣
                if(totalAmount.compareTo(new BigDecimal(wechatMemberCouponResponse.getTransactionMinimum()))>0){
                    BigDecimal discountFactor = BigDecimal.valueOf((wechatMemberCouponResponse.getDiscountPercent()) / 100.0);
                    log.info("折扣优惠券 折扣优惠后折扣比例：{}，member:{}",discountFactor,member.getNickname());
                    totalAmount = totalAmount.multiply(discountFactor).setScale(2, RoundingMode.HALF_UP);
                    log.info("折扣优惠券 折扣优惠后总价：{}，member:{}",totalAmount,member.getNickname());
                }else{
                    log.info("折扣优惠券 不满足满减条件，订单总价:{},消费门槛金额:{}",totalAmount,wechatMemberCouponResponse.getTransactionMinimum());
                    throw new RuntimeException("优惠券不满足满减条件");
                }
            }
        }
        double discount = MemberDiscountEnum.getDisCount(member.getLevel());
        BigDecimal orderTotalAmount = totalAmount.multiply(BigDecimal.valueOf(discount)).setScale(2, RoundingMode.HALF_UP);

        log.info("费用总价（折扣后）：{}，member:{}",orderTotalAmount,member.getNickname());
        return  orderTotalAmount;

    }

    private OrderProductListDTO takeMainProducts(List<PetOrderServiceDTO> petOrderServices) {
        for (PetOrderServiceDTO petOrderService : petOrderServices) {
            List<OrderProductListDTO> skuList = petOrderService.getSkuList();
            List<OrderProductListDTO> orderProductListDTOs =  skuList.stream().filter(orderProduct -> Boolean.TRUE.equals(orderProduct.getIsMainProduct())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(orderProductListDTOs))  {
                return orderProductListDTOs.get(0);
            }
        }
        return null;
    }

    private void verificationCoupon(WechatMemberCoupon wechatMemberCoupon, Member member) {
        if(!ObjectUtil.equals(wechatMemberCoupon.getMemberId(),member.getId())){
                throw new RuntimeException("优惠券校验失败");
        }
        if(!wechatMemberCoupon.getCouponState().equals("SENDED")){
             throw new RuntimeException("优惠券不可用");
        }

    }

    private List<OrderProductListDTO> convertSkuList(List<PetOrderServiceDTO> petOrderServices) {
        Map<Long, Integer> skuQuantityMap = new HashMap<>();
        for (PetOrderServiceDTO petOrderService : petOrderServices) {
            List<OrderProductListDTO> skuList = petOrderService.getSkuList();
            if (skuList != null) {
                // 遍历 skuList，累加 SKU 数量
                for (OrderProductListDTO orderProduct : skuList) {
                    Long skuId = orderProduct.getSkuId();
                    Integer quantity = orderProduct.getQuantity();
                    // 在 map 中累积数量
                    skuQuantityMap.put(skuId, skuQuantityMap.getOrDefault(skuId, 0) + quantity);
                }
            }
        }

        Map<Long, OrderProductListDTO> skuInfoMap = new HashMap<>();
        // 遍历每个 PetOrderServiceDTO
        for (PetOrderServiceDTO service : petOrderServices) {
            List<OrderProductListDTO> skuList = service.getSkuList();
            if (skuList != null) {
                // 遍历 skuList，累加 SKU 的数量、消费金额和运费
                for (OrderProductListDTO orderProduct : skuList) {
                    Long skuId = orderProduct.getSkuId();
                    Sku sku = orderProduct.getSku();
                    Product product = orderProduct.getProduct();
                    BigDecimal consumption = orderProduct.getConsumption() != null ? orderProduct.getConsumption() : BigDecimal.ZERO;
                    BigDecimal freightAmount = orderProduct.getFreightAmount() != null ? orderProduct.getFreightAmount() : BigDecimal.ZERO;

                    // 查找或创建新的 MergedProductInfo
                    OrderProductListDTO mergedInfo = skuInfoMap.getOrDefault(skuId, new OrderProductListDTO());

                    // 更新数量、消费金额和运费金额
                    mergedInfo.setConsumption(consumption);
                    mergedInfo.setSku(sku);
                    mergedInfo.setSkuId(skuId);
                    mergedInfo.setProduct(product);
                    mergedInfo.setFreightAmount(freightAmount);
                    // 将更新后的信息放回 map
                    skuInfoMap.put(skuId, mergedInfo);
                }
            }
        }

        List<OrderProductListDTO> skuList = new ArrayList<>();
        for (OrderProductListDTO value : skuInfoMap.values()) {
            Integer quantity = skuQuantityMap.get(value.getSkuId());
            value.setQuantity(quantity);
            skuList.add(value);
        }
        return skuList;
    }


    private String getPetType(Integer petId) {
        // 从宠物服务中获取宠物信息
        PetVO petVo = petService.selectPetById(petId);

        // 根据PetVO的petType返回对应的类型
        String petType = petVo.getPetType();
        String bodyType = petVo.getBodyType().substring(0,2);

        // 判断宠物类型并返回相应的字符串
        if ("CAT".equalsIgnoreCase(petType)) {
            return "CAT"; // 返回猫
        } else if ("DOG".equalsIgnoreCase(petType)) {
            // 判断体型以返回小型犬、中型犬或大型犬
            if ("小型".equalsIgnoreCase(bodyType)) {
                return "SMALL_DOG";
            } else if ("中型".equalsIgnoreCase(bodyType)) {
                return "MEDIUM_DOG";
            } else if ("大型".equalsIgnoreCase(bodyType)) {
                return "BIG_DOG";
            }
        }
        return "未知类型"; // 返回一个默认的未知类型
    }


    private void verificationPetOrderService(PetOrderServiceDTO petOrderService) {
        if(ObjectUtil.isNull(petOrderService.getPetId())){
            throw new RuntimeException("宠物不能为空");
        }

        if(ObjectUtil.isNull(petOrderService.getServiceDate())){
            throw new RuntimeException("服务日期不能为空");
        }

        if(petOrderService.getFeedCount()!= null && petOrderService.getFeedCount() <= 0){
            throw new RuntimeException("当天喂养次数不能小于0");
        }

//        if(StringUtils.isEmpty(petOrderService.getSelectedTimeSlots())){
//            throw new RuntimeException("上门时间段不能为空");
//        }

        if(CollectionUtils.isEmpty(petOrderService.getSkuList())){
            throw new RuntimeException("专属服务不能为空");
        }
    }

    public int submitServiceInfo(Long orderId, ServiceInfoDTO serviceInfoDTO) {
        if (orderId == null || serviceInfoDTO == null) {
            return 0;
        }
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        OmsOrderService omsOrderService = new OmsOrderService();
        omsOrderService.setOrderId(orderId);
        omsOrderService.setId(IDGenerator.generateId());
        omsOrderService.setServiceFrequency(serviceInfoDTO.getServiceFrequency());
        if (serviceInfoDTO.getPet() != null) {
            Gson gson = new Gson();
            omsOrderService.setPet(gson.toJson(serviceInfoDTO.getPet()));
        }
        if (serviceInfoDTO.getServiceDate() != null) {
            Gson gson = new Gson();
            omsOrderService.setServiceDate(gson.toJson(serviceInfoDTO.getServiceDate()));
        }

        omsOrderService.setCreateTime(LocalDateTime.now());
        omsOrderService.setCreateBy(member.getId());
        omsOrderService.setServiceTimeFirst(serviceInfoDTO.getServiceTimeFirst());
        omsOrderService.setServiceTimeSecond(serviceInfoDTO.getServiceTimeSecond());

        return omsOrderServiceService.insertOmsOrderService(omsOrderService);
    }

    public OrderCalcVO addOrderCheck(OrderCreateDTO orderCreateDTO) {
        OrderCalcVO res = new OrderCalcVO();
        List<SkuViewDTO> skuList = new ArrayList<>();
        List<OrderProductListDTO> list = orderCreateDTO.getSkuList();
        if (CollectionUtil.isEmpty(list)){
            throw new RuntimeException("商品SKU信息不能为空");
        }
        //将购买的sku信息转化为key：skuId value：数量
        Map<Long, Integer> quantityMap = list.stream().
                collect(Collectors.toMap(OrderProductListDTO::getSkuId, OrderProductListDTO::getQuantity, (v1, v2) -> v2));
        //查询所有sku信息
        Set<Long> collect = list.stream().map(OrderProductListDTO::getSkuId).collect(Collectors.toSet());
        Map<Long, Sku> querySkuMap = skuMapper.selectBatchIds(collect).stream().collect(Collectors.toMap(Sku::getId, it -> it));
        //计算商品总金额、订单总金额
        BigDecimal productTotalAmount = BigDecimal.ZERO;
        BigDecimal orderTotalAmount = BigDecimal.ZERO;
        for (OrderProductListDTO dto : list){
            if (!querySkuMap.containsKey(dto.getSkuId())){
                throw new RuntimeException("商品SKU不存在");
            }
            Sku sku = querySkuMap.get(dto.getSkuId());
            //查product
            Product product = productMapper.selectById(sku.getProductId());
            if (product == null){
                throw new RuntimeException("商品不存在");
            }
            if (Constants.PublishStatus.UNDERCARRIAGE.equals(product.getPublishStatus())){
                throw new RuntimeException("商品" + product.getName() + "已下架");
            }
            if (sku.getStock() < quantityMap.get(sku.getId())) {
                throw new RuntimeException("库存不足");
            }
            BigDecimal addAmount = sku.getPrice().multiply(BigDecimal.valueOf(dto.getQuantity()));
            //由于目前没有运费等数据，暂时订单总金额=商品总金额了
            productTotalAmount = productTotalAmount.add(addAmount);
            orderTotalAmount = orderTotalAmount.add(addAmount);
            //封装sku信息
            SkuViewDTO skuViewDTO = new SkuViewDTO();
            skuViewDTO.setPic(product.getPic());
            skuViewDTO.setPrice(sku.getPrice());
            skuViewDTO.setProductId(product.getId());
            skuViewDTO.setProductName(product.getName());
            skuViewDTO.setQuantity(quantityMap.get(sku.getId()));
            skuViewDTO.setSkuId(sku.getId());
            skuViewDTO.setSpData(sku.getSpData());
            skuList.add(skuViewDTO);
        }
        res.setSkuList(skuList);
        res.setOrderTotalAmount(orderTotalAmount);
        res.setProductTotalAmount(productTotalAmount);
        return res;
    }


    private String getOrderIdPrefix(){
        LocalDateTime time = LocalDateTime.now();
        return time.format(DateTimeFormatter.ofPattern("yyMMdd")) + "-";
    }

    /**
     * h5订单分页查询
     * @param status 订单状态 -1->全部；0->待付款；1->待发货；2->待收货；-2->售后单
     * @param memberId 会员id
     * @param pageable 分页
     * @return 结果
     */
    public PageImpl<H5OrderVO> orderPage(Integer status, Long memberId, Pageable pageable) {
        // 如果全部且页数为1，看看有无待付款单
        List<H5OrderVO> unpaidOrderList = new ArrayList<>();
        if (Constants.H5OrderStatus.ALL.equals(status) && pageable.getPageNumber() == 0){
            unpaidOrderList = orderMapper.orderPage(Constants.H5OrderStatus.UN_PAY, memberId);
        }
        if (pageable != null){
            PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        }
        List<H5OrderVO> orderList = orderMapper.orderPage(status, memberId);
        long total = ((com.github.pagehelper.Page) orderList).getTotal();
        // 两个list都没数据那肯定返回空了
        if (CollectionUtil.isEmpty(unpaidOrderList) && CollectionUtil.isEmpty(orderList)){
            return new PageImpl<>(Collections.EMPTY_LIST, pageable, total);
        }
        // 开始组装item了
        // 拿出所有orderId，查item，然后分组 by orderId
        List<Long> idList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(unpaidOrderList)){
            idList.addAll(unpaidOrderList.stream().map(H5OrderVO::getOrderId).collect(Collectors.toList()));
        }
        if (CollectionUtil.isNotEmpty(orderList)){
            idList.addAll(orderList.stream().map(H5OrderVO::getOrderId).collect(Collectors.toList()));
        }
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.in("order_id", idList);
        Map<Long, List<OrderItem>> orderItemMap =
                orderItemMapper.selectList(orderItemQw).stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
        orderList.addAll(0, unpaidOrderList);
        orderList.forEach(item -> {
            item.setOrderItemList(orderItemMap.get(item.getOrderId()));
        });
        return new PageImpl<>(orderList, pageable, total);
    }

    /**
     * h5订单分页查询(参数为openid)
     * @param status 订单状态 -1->全部；0->待付款；1->待发货；2->待收货；-2->售后单
     * @param openId 会员Openid
     * @return 结果
     */
    public PageImpl<H5OrderVO> orderPageByOpenid(List<Integer> status, String openId, Pageable pageable) {
        QueryWrapper<MemberWechat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("routine_openid", openId);
        MemberWechat memberWechat = memberWechatMapper.selectOne(queryWrapper);

        if (memberWechat == null) {
            return new PageImpl<>(Collections.EMPTY_LIST, pageable, 0);
        }

        if (pageable != null){
            PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        }

        List<H5OrderVO> orderList = orderMapper.orderPage2(status, memberWechat.getMemberId());
        long total = ((com.github.pagehelper.Page) orderList).getTotal();
        // 两个list都没数据那肯定返回空了
        if (CollectionUtil.isEmpty(orderList)){
            return new PageImpl<>(Collections.EMPTY_LIST, pageable, 0);
        }
        // 开始组装item了
        // 拿出所有orderId，查item，然后分组 by orderId
        List<Long> idList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(orderList)){
            idList.addAll(orderList.stream().map(H5OrderVO::getOrderId).collect(Collectors.toList()));
        }
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.in("order_id", idList);
        Map<Long, List<OrderItem>> orderItemMap =
                orderItemMapper.selectList(orderItemQw).stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
        orderList.forEach(item -> {
            item.setOrderItemList(orderItemMap.get(item.getOrderId()));

            OmsOrderService orderServiceInfo = omsOrderServiceService.selectByOrderId(item.getOrderId());
            PetVO petVO = h5PetService.selectPetById(orderServiceInfo.getPetId());
            orderServiceInfo.setPetVo(petVO);
            item.setService(orderServiceInfo);



            OmsOrderService omsOrderService = new OmsOrderService();
            omsOrderService.setOrderId(item.getOrderId());
            List<OmsOrderService> orderServiceList = omsOrderServiceMapper.selectListBySql(omsOrderService);



            // 使用一个 Set 来跟踪已经添加的 PetVO 的 id
            Set<Integer> addedPetIds = new HashSet<>();
            List<PetVO> petVOList = new ArrayList<>();

            for (OmsOrderService service1 : orderServiceList) {
                // 宠物标识不为空的时候查询数据
                if (service1.getPetId() != null) {
                    PetVO petVO1 = h5PetService.selectPetById(service1.getPetId());

                    // 检查 petVO 的 id 是否已经添加过
                    if (petVO1 != null && !addedPetIds.contains(petVO1.getId())) {
                        service1.setPetVo(petVO1);
                        petVOList.add(petVO1);
                        addedPetIds.add(petVO1.getId()); // 标记该 id 已添加
                    }
                }
            }
            item.setOrderServiceList(orderServiceList);
            item.setPetVOList(petVOList);

//            item.setUsersTeacher(appletUsersTeacherService.selectAppletUsersTeacherById(item.getTeacherId()));


        });






        return new PageImpl<>(orderList, pageable, total);
    }

    public H5OrderVO orderDetail(Long orderId) {
        H5OrderVO order = orderMapper.selectOrderDetail(orderId);
        if (order == null){
            throw new RuntimeException("未查询到该订单");
        }
        // 组装item
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.eq("order_id", orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemQw);
        order.setOrderItemList(orderItemList);

        //组装order_service
        OmsOrderService omsOrderService = new OmsOrderService();
        omsOrderService.setOrderId(orderId);
        List<OmsOrderService> orderServiceList = omsOrderServiceMapper.selectListBySql(omsOrderService);
        order.setOrderServiceList(orderServiceList);

        // 如果未付款，计算倒计时
        if (Constants.OrderStatus.NOTPAID.equals(order.getStatus())){
            // 订单超时时间900s，后面可以配置到字典等
            Integer time = 900;
            Date addDate = Date.from(order.getCreateTime().plusSeconds(time).atZone(ZoneId.systemDefault()).toInstant());
            if (addDate.after(new Date())) {
                order.setTimeToPay(addDate.getTime());
            }
        }
        return order;
    }

    @Transactional
    public String orderComplete(Long orderId) {
        LocalDateTime optDate = LocalDateTime.now();
        Order order = orderMapper.selectById(orderId);
        OrderItem queryOrderItem = new OrderItem();
        queryOrderItem.setOrderId(orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectByEntity(queryOrderItem);
        if(order == null || CollectionUtil.isEmpty(orderItemList)){
            throw new RuntimeException("未查询到订单信息");
        }
        // 只有【待收货】状态才能确认
        if(!order.getStatus().equals(Constants.H5OrderStatus.DELIVERED)){
            throw new RuntimeException("订单状态已改变，请刷新");
        }
        //更新订单
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", order.getId());
        updateWrapper.set("status", Constants.H5OrderStatus.COMPLETED);
        updateWrapper.set("confirm_status", 1);
        updateWrapper.set("receive_time", optDate);
        int rows = orderMapper.update(null, updateWrapper);
        if (rows < 1){
            throw new RuntimeException("更新订单状态失败");
        }
        //创建订单操作记录
        OrderOperateHistory optHistory = new OrderOperateHistory();
        optHistory.setOrderId(order.getId());
        optHistory.setOrderSn(order.getOrderSn());
        optHistory.setOperateMan("" + order.getMemberId());
        optHistory.setOrderStatus(Constants.H5OrderStatus.COMPLETED);
        optHistory.setCreateTime(optDate);
        optHistory.setCreateBy(order.getMemberId());
        optHistory.setUpdateBy(order.getMemberId());
        optHistory.setUpdateTime(optDate);
        rows = orderOperateHistoryMapper.insert(optHistory);
        if (rows < 1){
            throw new RuntimeException("创建订单操作记录失败");
        }
        return order.getOrderSn();
    }

    /**
     * 统计待付款、待发货、待收货和售后订单数量
     * @param memberId
     * @return
     */
    public CountOrderVO orderNumCount(Long memberId) {
        return  orderMapper.countByStatusAndMemberId(memberId);
    }

    @Transactional
    public String orderBatchCancel(CancelOrderRequest request, Long userId) {
        LocalDateTime optDate = LocalDateTime.now();
        if (CollectionUtil.isEmpty(request.getIdList())){
            throw new RuntimeException("未指定需要取消的订单号");
        }
        QueryWrapper<Order> orderQw = new QueryWrapper<>();
        orderQw.in("id", request.getIdList());
        List<Order> orderList = orderMapper.selectList(orderQw);
        if (orderList.size() < request.getIdList().size()){
            throw new RuntimeException("未查询到订单信息");
        }
        //查orderItem
        QueryWrapper<OrderItem> qw = new QueryWrapper<>();
        qw.in("order_id", request.getIdList());
        List<OrderItem> orderItem = orderItemMapper.selectList(qw);
        if (CollectionUtil.isEmpty(orderItem)) {
            throw new RuntimeException("未查询到订单信息");
        }
        long count = orderList.stream().filter(it -> !Constants.H5OrderStatus.UN_PAY.equals(it.getStatus())).count();
        if (count > 0){
            throw new RuntimeException("订单状态已更新，请刷新页面");
        }
        List<OrderOperateHistory> addHistoryList = new ArrayList<>();
        orderList.forEach(item -> {
            item.setStatus(Constants.H5OrderStatus.CLOSED);
            item.setUpdateTime(optDate);
            item.setUpdateBy(userId);
            OrderOperateHistory history = new OrderOperateHistory();
            history.setOrderId(item.getId());
            history.setOrderSn(item.getOrderSn());
            history.setOperateMan(userId == null ? "后台管理员" : "" + item.getMemberId());
            history.setOrderStatus(Constants.H5OrderStatus.CLOSED);
            history.setCreateTime(optDate);
            history.setCreateBy(userId);
            history.setUpdateBy(userId);
            history.setUpdateTime(optDate);
            addHistoryList.add(history);

        });
        //取消订单
        int rows = orderMapper.cancelBatch(orderList);
        if (rows < 1){
            throw new RuntimeException("更改订单状态失败");
        }
        orderItem.stream().collect(Collectors.groupingBy(it->it.getSkuId())).forEach((k,v)->{
            AtomicReference<Integer> totalCount = new AtomicReference<>(0);
            v.forEach(it-> totalCount.updateAndGet(v1 -> v1 + it.getQuantity()));
            skuMapper.updateStockById(k, optDate, -1 * totalCount.get());
        });

        //创建订单操作记录
        boolean flag = orderOperateHistoryService.saveBatch(addHistoryList);
        if (!flag){
            throw new RuntimeException("创建订单操作记录失败");
        }
        return "取消订单成功";
    }

    /**
     * 订单支付
     * @param req 支付请求
     * @return
     */
    public OrderPayResponse orderPay(OrderPayRequest req) {
        QueryWrapper<Order> qw = new QueryWrapper<>();
        qw.eq("pay_id", req.getPayId());
        qw.eq("status", 0);
        List<Order> orderList = orderMapper.selectList(qw);
        if (CollectionUtil.isEmpty(orderList)){
            throw new RuntimeException("没有待支付的订单");
        }
        QueryWrapper<MemberWechat> memberWechatQw = new QueryWrapper<>();
        memberWechatQw.eq("member_id", req.getMemberId());
        MemberWechat memberWechat = memberWechatMapper.selectOne(memberWechatQw);
        if (memberWechat == null || StrUtil.isBlank(memberWechat.getOpenid())){
            throw new RuntimeException("获取用户openId失败");
        }
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.eq("order_id", orderList.get(0).getId());
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemQw);
        String orderDesc = orderItemList.get(0).getProductName().substring(0, Math.min(40, orderItemList.get(0).getProductName().length()));
        //保存微信支付历史
        LocalDateTime optDate = LocalDateTime.now();
        QueryWrapper<WechatPaymentHistory> wxPaymentQw = new QueryWrapper<>();
        wxPaymentQw.eq("order_id", orderList.get(0).getPayId());
        wxPaymentQw.eq("op_type", Constants.PaymentOpType.PAY);
        WechatPaymentHistory wechatPaymentHistory = wechatPaymentHistoryMapper.selectOne(wxPaymentQw);
        if (wechatPaymentHistory == null){
            wechatPaymentHistory = new WechatPaymentHistory();
            wechatPaymentHistory.setOrderId(orderList.get(0).getPayId());
            wechatPaymentHistory.setMemberId(req.getMemberId());
            wechatPaymentHistory.setOpenid(memberWechat.getOpenid());
            wechatPaymentHistory.setTitle(orderItemList.get(0).getProductName());
            wechatPaymentHistory.setMoney(orderList.get(0).getPayAmount());
            wechatPaymentHistory.setOpType(Constants.PaymentOpType.PAY);
            wechatPaymentHistory.setPaymentStatus(0);
            wechatPaymentHistory.setCreateBy(req.getMemberId());
            wechatPaymentHistory.setCreateTime(optDate);
            wechatPaymentHistory.setUpdateBy(req.getMemberId());
            wechatPaymentHistory.setUpdateTime(optDate);
            wechatPaymentHistoryMapper.insert(wechatPaymentHistory);
        }else {
            wechatPaymentHistory.setMoney(orderList.get(0).getPayAmount());
            wechatPaymentHistoryMapper.updateById(wechatPaymentHistory);
        }
        //请开启微信支付 wechat.enabled=true
        //调用wx的jsapi拿prepayId，返回签名等信息
        String openId = memberWechat.getOpenid();
        String appId = WechatPayData.appId;
        if (2 == req.getWechatType()) {
            openId = memberWechat.getRoutineOpenid();
            appId = WechatPayData.miniProgramAppId;
        }
        String prepayId = wechatPayService.jsapiPay(
                String.valueOf(req.getPayId()),
                orderDesc,
                Integer.valueOf(orderList.stream().map(Order::getPayAmount).
                        reduce(BigDecimal.ZERO, BigDecimal::add).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString()),
                openId,
                req.getMemberId(),
                appId
        );
        OrderPayResponse response = new OrderPayResponse();
        response.setPayType(2);
        String nonceStr = WechatPayUtil.generateNonceStr();
        long timeStamp = WechatPayUtil.getCurrentTimestamp();
        prepayId = "prepay_id=" + prepayId;
        String signType = "RSA";
        String paySign = null;
        String signatureStr = Stream.of(appId, String.valueOf(timeStamp), nonceStr, prepayId)
                .collect(Collectors.joining("\n", "", "\n"));
        try {
            paySign = WechatPayUtil.getSign(signatureStr, WechatPayData.privateKeyPath);
        } catch (Exception e) {
            throw new RuntimeException("支付失败");
        }
        response.setAppId(appId);
        response.setTimeStamp(String.valueOf(timeStamp));
        response.setNonceStr(nonceStr);
        response.setSignType(signType);
        response.setPackage_(prepayId);
        response.setPaySign(paySign);
        response.setOrderId(orderList.get(0).getId());
        return response;
    }


    public OrderPayResponse orderCreateAndPay(Order order, Member member, String openId) {
        log.info("【支付】开始组装支付参数");
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.eq("order_id", order.getId());
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemQw);
        String orderDesc = orderItemList.get(0).getProductName().substring(0, Math.min(40, orderItemList.get(0).getProductName().length()));
        //保存微信支付历史
        LocalDateTime optDate = LocalDateTime.now();
        QueryWrapper<WechatPaymentHistory> wxPaymentQw = new QueryWrapper<>();
        wxPaymentQw.eq("order_id", order.getPayId());
        wxPaymentQw.eq("op_type", Constants.PaymentOpType.PAY);
        WechatPaymentHistory wechatPaymentHistory = wechatPaymentHistoryMapper.selectOne(wxPaymentQw);
        if (wechatPaymentHistory == null){
            wechatPaymentHistory = new WechatPaymentHistory();
            wechatPaymentHistory.setOrderId(order.getPayId());
            wechatPaymentHistory.setMemberId(member.getId());
            wechatPaymentHistory.setOpenid(openId);
            wechatPaymentHistory.setTitle(orderItemList.get(0).getProductName());
            wechatPaymentHistory.setMoney(order.getPayAmount());
            wechatPaymentHistory.setOpType(Constants.PaymentOpType.PAY);
            wechatPaymentHistory.setPaymentStatus(0);
            wechatPaymentHistory.setCreateBy(member.getId());
            wechatPaymentHistory.setCreateTime(optDate);
            wechatPaymentHistory.setUpdateBy(member.getId());
            wechatPaymentHistory.setUpdateTime(optDate);
            wechatPaymentHistoryMapper.insert(wechatPaymentHistory);
        }else {
            wechatPaymentHistory.setMoney(order.getPayAmount());
            wechatPaymentHistoryMapper.updateById(wechatPaymentHistory);
        }
        //请开启微信支付 wechat.enabled=true
        //调用wx的jsapi拿prepayId，返回签名等信息
        log.info("【支付】开始调用jsapiPay支付：" + orderDesc);
        String appId = WechatPayData.miniProgramAppId;

        //TODO
        String payAmount = order.getPayAmount().multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();

        payAmount = "1";//支付一分钱
        String prepayId = wechatPayService.jsapiPay(
                String.valueOf(order.getPayId()),
                orderDesc,
                Integer.valueOf(payAmount),
                openId,
                member.getId(),
                appId
        );
//        String prepayId = "TODO";

        log.info("【支付】jsapiPay支付成功，预付单ID：" + prepayId);
        OrderPayResponse response = new OrderPayResponse();
        response.setPayType(2);
        String nonceStr = WechatPayUtil.generateNonceStr();
        long timeStamp = WechatPayUtil.getCurrentTimestamp();
        prepayId = "prepay_id=" + prepayId;
        String signType = "RSA";
        String paySign = null;
        String signatureStr = Stream.of(appId, String.valueOf(timeStamp), nonceStr, prepayId)
                .collect(Collectors.joining("\n", "", "\n"));
        //TODO
//        paySign = "TODO";
        try {
            paySign = WechatPayUtil.getSign(signatureStr, WechatPayData.privateKeyPath);
        } catch (Exception e) {
            log.error("获取签名失败，");
            throw new RuntimeException("支付失败");
        }
        response.setAppId(appId);
        response.setTimeStamp(String.valueOf(timeStamp));
        response.setNonceStr(nonceStr);
        response.setSignType(signType);
        response.setPackage_(prepayId);
        response.setPaySign(paySign);
        response.setOrderId(order.getId());
        return response;
    }


    /**
     * 支付回调方法
     * @param messageDTO
     * @return
     */
    @Transactional
    public ResponseEntity<String> payCallBack(PayNotifyMessageDTO messageDTO){
        log.info("【订单支付回调】" + JSONObject.toJSON(messageDTO));
        String redisKey = "h5_oms_order_pay_notify_" + messageDTO.getOutTradeNo();
        String redisValue = messageDTO.getOutTradeNo() + "_" + System.currentTimeMillis();
        LocalDateTime optDate = LocalDateTime.now();
        try{
            redisService.lock(redisKey, redisValue, 60);
            //先判断回信回调的是否未success
            if (!Transaction.TradeStateEnum.SUCCESS.equals(messageDTO.getTradeStatus())){
                log.error("【订单支付回调】订单状态不是支付成功状态" + messageDTO.getTradeStatus());
                throw new RuntimeException();
            }
            QueryWrapper<WechatPaymentHistory> paymentWrapper = new QueryWrapper<>();
            paymentWrapper.eq("order_id", messageDTO.getOutTradeNo());
            paymentWrapper.eq("op_type", Constants.PaymentOpType.PAY);
            WechatPaymentHistory paymentHistory = wechatPaymentHistoryMapper.selectOne(paymentWrapper);

            if(paymentHistory == null){
                LambdaQueryWrapper<WechatPaymentHistory> qw = new LambdaQueryWrapper<>();
                paymentHistory = wechatPaymentHistoryMapper.selectOne(qw
                        .eq(WechatPaymentHistory::getPayId, messageDTO.getOutTradeNo())
                        .eq(WechatPaymentHistory::getOpType, Constants.PaymentOpType.PAY));
            }

            if (paymentHistory.getPaymentStatus() != Constants.PaymentStatus.INCOMPLETE) {
                log.info("【订单支付回调】支付订单不是未支付状态，不再处理" + "orderId" + paymentHistory.getOrderId() + "status" + paymentHistory.getPaymentStatus());
                throw new RuntimeException();
            }
            QueryWrapper<Order> orderQw = new QueryWrapper<>();
            orderQw.eq("pay_id", messageDTO.getOutTradeNo());
            orderQw.eq("status", OrderStatus.UN_PAY.getType());
            List<Order> orderList = orderMapper.selectList(orderQw);
            orderList.forEach(order -> {
                order.setPaymentTime(messageDTO.getPayTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                order.setStatus(OrderStatus.NOT_DELIVERED.getType());
                orderMapper.updateById(order);

                OrderOperateHistory optHistory = new OrderOperateHistory();
                optHistory.setOrderId(order.getId());
                optHistory.setOrderSn(order.getOrderSn());
                optHistory.setOperateMan("" + order.getMemberId());
                optHistory.setOrderStatus(OrderStatus.NOT_DELIVERED.getType());
                optHistory.setCreateTime(optDate);
                optHistory.setCreateBy(order.getMemberId());
                optHistory.setUpdateBy(order.getMemberId());
                optHistory.setUpdateTime(optDate);
                orderOperateHistoryMapper.insert(optHistory);

                //TODO 往腾讯轻联推送消息
                OrderMessageModel rderMessageModel = new OrderMessageModel();
                rderMessageModel.setOrder(order);
                taskQueue.add(rderMessageModel);
            });
            UpdateWrapper<WechatPaymentHistory> paymentHistoryUpdateWrapper = new UpdateWrapper<>();
            paymentHistoryUpdateWrapper.eq("order_id", messageDTO.getOutTradeNo()).set("payment_id", messageDTO.getTradeNo())
                    .set("payment_status", Constants.PaymentStatus.COMPLETE).set("update_time", optDate);
            wechatPaymentHistoryMapper.update(null, paymentHistoryUpdateWrapper);

            LambdaUpdateWrapper<WechatPaymentHistory> qw = new LambdaUpdateWrapper<>();
                wechatPaymentHistoryMapper.update(null, qw
                        .eq(WechatPaymentHistory::getPayId, messageDTO.getOutTradeNo())
                        .set(WechatPaymentHistory::getPaymentStatus, Constants.PaymentStatus.COMPLETE)
                        .set(WechatPaymentHistory::getUpdateTime, optDate));

        }catch (Exception e){
            log.error("订单支付回调异常",e);
            throw new RuntimeException("订单支付回调异常");
        }finally {
            try{
                redisService.unLock(redisKey, redisValue);
            }catch (Exception e){
                log.error("", e);
            }
        }
        return ResponseEntity.ok("订单支付回调成功");
    }

    /**
     * 申请售后
     * @param applyRefundDTO
     * @return
     */
    @Transactional
    public String applyRefund(ApplyRefundDTO applyRefundDTO) {
        Order order = orderMapper.selectById(applyRefundDTO.getOrderId());
        //是否符合售后条件
        this.checkIfCanApplyRefund(order);
        LocalDateTime optDate = LocalDateTime.now();
        Long memberId = order.getMemberId();
        //创建售后单aftersale
        Aftersale addAftersale = new Aftersale();
        addAftersale.setId(IDGenerator.generateId());
        addAftersale.setMemberId(order.getMemberId());
        addAftersale.setOrderId(order.getId());
        addAftersale.setReturnAmount(order.getPayAmount());
        addAftersale.setType(applyRefundDTO.getApplyRefundType());
        addAftersale.setStatus(AftersaleStatus.APPLY.getType());
        addAftersale.setReason(applyRefundDTO.getReason());
        addAftersale.setQuantity(applyRefundDTO.getQuantity());
        addAftersale.setReason(applyRefundDTO.getReason());
        addAftersale.setDescription(applyRefundDTO.getDescription());
        addAftersale.setProofPics(applyRefundDTO.getProofPics());
        addAftersale.setCreateTime(optDate);
        addAftersale.setCreateBy(memberId);
        addAftersale.setUpdateTime(optDate);
        addAftersale.setUpdateBy(memberId);
        int rows = aftersaleMapper.insert(addAftersale);
        if (rows != 1) {
            throw new RuntimeException("插入订单售后失败");
        }
        //创建aftersale item
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.eq("order_id", order.getId());
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemQw);
        List<AftersaleItem> addAftersaleItemList = new ArrayList<>();
        orderItemList.forEach(orderItem -> {
            AftersaleItem aftersaleItem = new AftersaleItem();
            aftersaleItem.setMemberId(memberId);
            aftersaleItem.setAftersaleId(addAftersale.getId());
            aftersaleItem.setOrderId(orderItem.getOrderId());
            aftersaleItem.setOrderItemId(orderItem.getId());
            aftersaleItem.setReturnAmount(orderItem.getSalePrice().multiply(BigDecimal.valueOf(orderItem.getQuantity())));
            aftersaleItem.setQuantity(orderItem.getQuantity());
            aftersaleItem.setCreateTime(optDate);
            aftersaleItem.setCreateBy(memberId);
            aftersaleItem.setUpdateTime(optDate);
            aftersaleItem.setUpdateBy(memberId);
            addAftersaleItemList.add(aftersaleItem);
        });
        rows = aftersaleItemMapper.insertBatch(addAftersaleItemList);
        if (rows < 1){
            throw new RuntimeException("创建售后订单item失败");
        }
        //更新订单
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", order.getId()).set("aftersale_status", OrderRefundStatus.APPLY.getType())
                .set("update_time", optDate)
                .set("update_by", memberId);
        rows = orderMapper.update(null, updateWrapper);
        if (rows < 1){
            throw new RuntimeException("修改订单状态失败");
        }
        //创建订单操作记录
        OrderOperateHistory optHistory = new OrderOperateHistory();
        optHistory.setOrderId(order.getId());
        optHistory.setOrderSn(order.getOrderSn());
        optHistory.setOperateMan("" + memberId);
        optHistory.setOrderStatus(11);
        optHistory.setCreateTime(optDate);
        optHistory.setCreateBy(memberId);
        optHistory.setUpdateBy(memberId);
        optHistory.setUpdateTime(optDate);
        rows = orderOperateHistoryMapper.insert(optHistory);
        if (rows < 1){
            throw new RuntimeException("创建订单操作记录失败");
        }
        return "售后申请成功";
    }

    /**
     * check是否能售后 可售后的状态为：待发货、待收货、已完成
     * @param order 订单
     */
    private void checkIfCanApplyRefund(Order order){
        if (order == null){
            throw new RuntimeException("为查询到订单信息");
        }
        Integer status = order.getStatus();
        boolean flag = OrderStatus.NOT_DELIVERED.getType().equals(status) || OrderStatus.DELIVERED.getType().equals(status)
                || OrderStatus.COMPLETE.getType().equals(status);
        if (!flag){
            throw new RuntimeException("该订单无法申请售后");
        }
        if (OrderStatus.COMPLETE.getType().equals(order.getStatus()) &&
                DateUtils.betweenDay(LocalDateTime.now(), order.getReceiveTime()) > 7){
            throw new RuntimeException("订单确认收货时间已超过7天，无法申请售后");
        }
        if(OrderRefundStatus.APPLY.getType().equals(order.getAftersaleStatus())
                || OrderRefundStatus.WAIT.getType().equals(order.getAftersaleStatus())){
            throw new RuntimeException("售后正在处理中");
        }
    }

    /**
     * 取消售后
     * @param orderId 订单id
     * @return
     */
    @Transactional
    public String cancelRefund(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null){
            throw new RuntimeException("未查询到该订单");
        }
        //查询是否有（待处理和退货中）售后单
        QueryWrapper<Aftersale> aftersaleQw = new QueryWrapper<>();
        aftersaleQw.eq("order_id", orderId);
        aftersaleQw.in("status", Arrays.asList(AftersaleStatus.APPLY.getType(), AftersaleStatus.WAIT.getType()));
        Aftersale aftersale = aftersaleMapper.selectOne(aftersaleQw);
        if (aftersale == null){
            throw new RuntimeException("无售后单");
        }
        if (OrderRefundStatus.SUCCESS.getType().equals(order.getAftersaleStatus())){
            throw new RuntimeException("已退款成功");
        }
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        LocalDateTime optDate = LocalDateTime.now();
        //更新售后单状态
        UpdateWrapper<Aftersale> aftersaleUpdateWrapper = new UpdateWrapper<>();
        aftersaleUpdateWrapper.eq("id", aftersale.getId());
        aftersaleUpdateWrapper.set("status", AftersaleStatus.CANCEL.getType());
        aftersaleUpdateWrapper.set("update_time", optDate);
        aftersaleUpdateWrapper.set("update_by", member.getId());
        int rows = aftersaleMapper.update(null, aftersaleUpdateWrapper);
        if (rows < 1){
            throw new RuntimeException("更新售后单失败");
        }
        //更新订单售后状态
        // 更新订单
        UpdateWrapper<Order> updateOrderWrapper = new UpdateWrapper<>();
        updateOrderWrapper.eq("id", orderId)
                .set("aftersale_status", OrderRefundStatus.NO_REFUND.getType()).set("update_time", optDate)
                .set("update_by", member.getId());
        rows = orderMapper.update(null, updateOrderWrapper);
        if (rows != 1) {
            throw new RuntimeException("更新订单状态失败");
        }
        return "售后取消成功";
    }

    /**
     * 售后订单详情
     * @param orderId 订单id
     * @return
     */
    public AftersaleRefundInfoVO refundOrderDetail(Long orderId) {
        QueryWrapper<Aftersale> aftersaleQw = new QueryWrapper<>();
        aftersaleQw.eq("order_id", orderId);
        aftersaleQw.orderByDesc("create_time");
        aftersaleQw.last("limit 1");
        Aftersale aftersale = aftersaleMapper.selectOne(aftersaleQw);
        if (aftersale == null){
            throw new RuntimeException("未查询到售后订单");
        }
        //查一下售后订单item
        QueryWrapper<AftersaleItem> aftersaleItemQw = new QueryWrapper<>();
        aftersaleItemQw.eq("aftersale_id", aftersale.getId());
        List<AftersaleItem> aftersaleItemList = aftersaleItemMapper.selectList(aftersaleItemQw);
        List<Long> orderItemIdList = aftersaleItemList.stream().map(AftersaleItem::getOrderItemId).collect(Collectors.toList());
        //再去查orderItem
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.in("id", orderItemIdList);
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemQw);
        AftersaleRefundInfoVO vo = new AftersaleRefundInfoVO();
        BeanUtils.copyProperties(aftersale, vo);
        vo.setAftersaleItemList(aftersaleItemConvert.dos2vos(aftersaleItemList));
        vo.setOrderItemList(orderItemConvert.dos2vos(orderItemList));
        return vo;
    }

    /**
     * 根据memberId查询所有有效订单
     * @param memberId
     * @return
     */
    public List<Order> getAllOrderByMemberId(Long memberId) {
        QueryWrapper<Order> orderQw = new QueryWrapper<>();
        orderQw.eq("member_id", memberId);
        List<Integer> statusList = new ArrayList<>();
        statusList.add(OrderStatus.NOT_DELIVERED.getType());
        statusList.add(OrderStatus.DELIVERED.getType());
        statusList.add(OrderStatus.COMPLETE.getType());
        statusList.add(OrderStatus.UNDERWAY.getType());
        orderQw.in("status", statusList);
        orderQw.in("delete_status", 0);
        orderQw.orderByAsc("create_time");
        return orderMapper.selectList(orderQw);
    }

    //todo 兼容老数据的方式需要跟德哥再讨论下
    public void submitOrderService(Long orderId, OrderSubmitForm form) {
        List<PetOrderServiceDTO>  petOrderServices = form.getPetOrderServices();
        if (orderId == null || CollectionUtils.isEmpty(petOrderServices)) {
            return;
        }

        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);

        for (PetOrderServiceDTO petOrderService : petOrderServices) {
            OmsOrderService omsOrderService = new OmsOrderService();
            omsOrderService.setOrderId(orderId);
            omsOrderService.setId(IDGenerator.generateId());
            omsOrderService.setPetId(petOrderService.getPetId());
            //服务日期
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            omsOrderService.setServiceDate(petOrderService.getServiceDate().format(formatter));
            //期望上门时间
            omsOrderService.setExpectServiceTime(petOrderService.getSelectedTimeSlots());
            omsOrderService.setCreateTime(LocalDateTime.now());
            assert member != null;
            omsOrderService.setCreateBy(member.getId());

            List<OrderProductListDTO> skuList = petOrderService.getSkuList();


            //设置服务频次，一天服务几次，有可能没有，因为不是主商品
            for (OrderProductListDTO sku : skuList) {
                if (sku.getIsMainProduct()){
                    omsOrderService.setServiceFrequency(sku.getQuantity() + "");
                }
            }

            //feedCountPrice 当日多次服务加价
            omsOrderService.setFeedCountPrice(new BigDecimal(petOrderService.getFeedCountPrice()));

            omsOrderServiceService.insertOmsOrderService(omsOrderService);

            if (CollectionUtils.isEmpty(skuList)) {
                continue;
            }
            //保存 orderItem 新增 orderServiceId 字段
            orderItemService.saveOrderItem(member,omsOrderService, omsOrderService.getCreateTime(), orderId, skuList);
            skuList.forEach(item -> {
                //减少sku的库存
                skuMapper.updateStockById(item.getSkuId(),LocalDateTime.now(),item.getQuantity());
            });

            //若来源为购物车，删除购物车
            if (Constants.OrderFrom.CART.equals(form.getFrom())){
                List<Long> skuIdList = skuList.stream().map(OrderProductListDTO::getSkuId).collect(Collectors.toList());
                LambdaUpdateWrapper<MemberCart> wrapper = Wrappers.lambdaUpdate();
                wrapper.eq(MemberCart::getMemberId, member.getId());
                wrapper.in(MemberCart::getSkuId, skuIdList);
                int rows = memberCartMapper.delete(wrapper);
                if (rows < 1){
                    throw new RuntimeException("删除购物车失败");
                }
            }

        }
    }

    /**
     * 伴宠师小程序 支付保证金接口
     *
     * @param staff
     * @param openId
     * @return
     */
    public OrderPayResponse bondPay(Staff staff, String openId, BigDecimal amount) {
        log.info("【支付】开始组装支付参数");
        //1、增加保证金缴纳明细
        Long payId = IDGenerator.generateId();
        BondTransaction bondTransaction = new BondTransaction();
        bondTransaction.setAmount(amount);
        bondTransaction.setPayId(payId);
        bondTransaction.setType(BondTransactionType.PAY.getType());
        bondTransaction.setStaffId(staff.getId());
        bondTransaction.setStatus(BondOrderStatus.UN_PAY.getType());
        bondTransaction.setPayType(Constants.PayType.WECHAT);//默认微信支付
        bondTransactionService.save(bondTransaction);

        //2、保存微信支付历史
        LocalDateTime optDate = LocalDateTime.now();
        WechatPaymentHistory wechatPaymentHistory = new WechatPaymentHistory();
        wechatPaymentHistory.setId(payId);
        wechatPaymentHistory.setOrderId(bondTransaction.getId());
        wechatPaymentHistory.setMemberId(staff.getId());
        wechatPaymentHistory.setOpenid(openId);
        wechatPaymentHistory.setTitle("保证金缴纳");
        wechatPaymentHistory.setMoney(amount);
        wechatPaymentHistory.setOpType(Constants.PaymentOpType.PAY);
        wechatPaymentHistory.setPaymentStatus(0);
        wechatPaymentHistory.setCreateBy(staff.getId());
        wechatPaymentHistory.setCreateTime(optDate);
        wechatPaymentHistory.setUpdateBy(staff.getId());
        wechatPaymentHistory.setUpdateTime(optDate);
        wechatPaymentHistoryMapper.insert(wechatPaymentHistory);

        //请开启微信支付 wechat.enabled=true
        //调用wx的jsapi拿prepayId，返回签名等信息
        log.info("【支付】开始调用jsapiPay支付：保证金缴纳");
        //注意：此处为伴宠师小程序ID
        String appId = WechatPayData.staffAppId;


        //TODO
        String payAmount = amount.multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
        payAmount = "1";//支付一分钱
        String prepayId = wechatPayService.jsapiPayForBCHSHI(
                String.valueOf(payId),
                "保证金缴纳",
                Integer.valueOf(payAmount),
                openId,
                staff.getId(),
                appId
        );
//        String prepayId = "TODO";

        log.info("【支付】jsapiPay支付成功，预付单ID：" + prepayId);
        OrderPayResponse response = new OrderPayResponse();
        response.setPayType(2);
        String nonceStr = WechatPayUtil.generateNonceStr();
        long timeStamp = WechatPayUtil.getCurrentTimestamp();
        prepayId = "prepay_id=" + prepayId;
        String signType = "RSA";
        String paySign = null;
        String signatureStr = Stream.of(appId, String.valueOf(timeStamp), nonceStr, prepayId)
                .collect(Collectors.joining("\n", "", "\n"));
        //TODO
//        paySign = "TODO";
        try {
            paySign = WechatPayUtil.getSign(signatureStr, WechatPayData.privateKeyPath);
        } catch (Exception e) {
            log.error("获取签名失败，");
            throw new RuntimeException("支付失败");
        }
        response.setAppId(appId);
        response.setTimeStamp(String.valueOf(timeStamp));
        response.setNonceStr(nonceStr);
        response.setSignType(signType);
        response.setPackage_(prepayId);
        response.setPaySign(paySign);
        response.setOrderId(payId);
        return response;
    }

    /**
     * 伴宠师保证金缴纳成功 支付回调方法
     *
     * @param messageDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<String> payCallBackForBCHSHI(PayNotifyMessageDTO messageDTO) {
        log.info("【伴宠师保证金缴纳成功支付回调】" + JSONObject.toJSON(messageDTO));
        String redisKey = "h5_oms_bond_order_pay_notify_" + messageDTO.getOutTradeNo();
        String redisValue = messageDTO.getOutTradeNo() + "_" + System.currentTimeMillis();
        LocalDateTime optDate = LocalDateTime.now();
        try {
            redisService.lock(redisKey, redisValue, 60);
            //先判断回信回调的是否未success
            if (!Transaction.TradeStateEnum.SUCCESS.equals(messageDTO.getTradeStatus())) {
                log.error("【订单支付回调】订单状态不是支付成功状态" + messageDTO.getTradeStatus());
                throw new RuntimeException();
            }
            QueryWrapper<WechatPaymentHistory> paymentWrapper = new QueryWrapper<>();
            paymentWrapper.eq("order_id", messageDTO.getOutTradeNo());
            paymentWrapper.eq("op_type", Constants.PaymentOpType.PAY);
            WechatPaymentHistory paymentHistory = wechatPaymentHistoryMapper.selectOne(paymentWrapper);
            if (paymentHistory.getPaymentStatus() != Constants.PaymentStatus.INCOMPLETE) {
                log.info("【订单支付回调】支付订单不是未支付状态，不再处理" + "orderId" + paymentHistory.getOrderId() + "status" + paymentHistory.getPaymentStatus());
                throw new RuntimeException();
            }

            //更新保证金缴纳明细表状态
            bondTransactionService.updateBondStatusByPayId(messageDTO.getOutTradeNo(), BondOrderStatus.SUCCESS.getType());
            //更新staff表金额 以及 保证金缴纳状态
            staffService.updateStaffBondMoney(paymentHistory.getMemberId(), paymentHistory.getMoney(),1);

            UpdateWrapper<WechatPaymentHistory> paymentHistoryUpdateWrapper = new UpdateWrapper<>();
            paymentHistoryUpdateWrapper.eq("order_id", messageDTO.getOutTradeNo()).set("payment_id", messageDTO.getTradeNo())
                    .set("payment_status", Constants.PaymentStatus.COMPLETE).set("update_time", optDate);
            wechatPaymentHistoryMapper.update(null, paymentHistoryUpdateWrapper);


        } catch (Exception e) {
            log.error("订单支付回调异常", e);
            throw new RuntimeException("订单支付回调异常");
        } finally {
            try {
                redisService.unLock(redisKey, redisValue);
            } catch (Exception e) {
                log.error("", e);
            }
        }
        return ResponseEntity.ok("订单支付回调成功");
    }
}
