package com.ycwl.basic.service.pc.impl;

import cn.hutool.core.date.DateUtil;
import com.ycwl.basic.dto.MobileOrderRequest;
import com.ycwl.basic.model.pc.printer.entity.PrinterEntity;
import com.ycwl.basic.model.pc.source.entity.MemberSourceEntity;
import com.ycwl.basic.model.pc.video.entity.MemberVideoEntity;
import com.ycwl.basic.model.printer.resp.PrintTaskResp;
import com.ycwl.basic.order.dto.PaymentParamsRequest;
import com.ycwl.basic.order.dto.PaymentParamsResponse;
import com.ycwl.basic.pricing.dto.CouponUseRequest;
import com.ycwl.basic.pricing.dto.PriceCalculationResult;
import com.ycwl.basic.pricing.dto.ProductItem;
import com.ycwl.basic.pricing.service.ICouponService;
import com.ycwl.basic.pricing.service.IVoucherService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ycwl.basic.biz.OrderBiz;
import com.ycwl.basic.biz.PriceBiz;
import com.ycwl.basic.constant.BaseContextHandler;
import com.ycwl.basic.constant.NumberConstant;
import com.ycwl.basic.enums.*;
import com.ycwl.basic.exception.AppException;
import com.ycwl.basic.exception.BaseException;
import com.ycwl.basic.mapper.*;
import com.ycwl.basic.model.mobile.goods.GoodsDetailVO;
import com.ycwl.basic.model.mobile.order.IsBuyRespVO;
import com.ycwl.basic.model.mobile.order.OrderAppPageReq;
import com.ycwl.basic.model.mobile.order.PriceObj;
import com.ycwl.basic.model.mobile.order.RefundOrderReq;
import com.ycwl.basic.model.pc.face.entity.FaceEntity;
import com.ycwl.basic.model.pc.member.resp.MemberRespVO;
import com.ycwl.basic.model.pc.order.entity.OrderEntity;
import com.ycwl.basic.model.pc.order.entity.OrderItemEntity;
import com.ycwl.basic.model.pc.order.req.CreateBatchOrderReqVO;
import com.ycwl.basic.model.pc.order.req.CreateOrderReqVO;
import com.ycwl.basic.model.pc.order.req.OrderUpdateReq;
import com.ycwl.basic.model.pc.order.req.OrderReqQuery;
import com.ycwl.basic.model.pc.order.resp.OrderAppRespVO;
import com.ycwl.basic.model.pc.order.resp.OrderItemVO;
import com.ycwl.basic.model.pc.order.resp.OrderRespVO;
import com.ycwl.basic.model.pc.orderOp.entity.OrderOperationEntity;
import com.ycwl.basic.model.pc.price.entity.PriceConfigEntity;
import com.ycwl.basic.model.pc.price.resp.GoodsListRespVO;
import com.ycwl.basic.model.pc.printer.resp.MemberPrintResp;
import com.ycwl.basic.model.pc.source.entity.SourceEntity;
import com.ycwl.basic.model.pc.source.resp.SourceRespVO;
import com.ycwl.basic.model.pc.task.entity.TaskEntity;
import com.ycwl.basic.model.pc.template.resp.TemplateRespVO;
import com.ycwl.basic.model.pc.video.entity.VideoEntity;
import com.ycwl.basic.model.wx.WXPayOrderReqVO;
import com.ycwl.basic.pay.adapter.IPayAdapter;
import com.ycwl.basic.pay.entity.PayResponse;
import com.ycwl.basic.repository.FaceRepository;
import com.ycwl.basic.repository.MemberRelationRepository;
import com.ycwl.basic.repository.PriceRepository;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.repository.TemplateRepository;
import com.ycwl.basic.repository.VideoRepository;
import com.ycwl.basic.repository.VideoTaskRepository;
import com.ycwl.basic.service.mobile.WxPayService;
import com.ycwl.basic.service.pc.OrderService;
import com.ycwl.basic.service.pc.ScenicService;
import com.ycwl.basic.service.task.impl.TaskTaskServiceImpl;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author：longbinbin
 * @Date：2024/12/3 13:54
 */
@Slf4j
@Service("OrderServiceOldImpl")
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    @Qualifier(value = "OrderServiceOldImpl")
    private OrderServiceImpl self;
    @Autowired
    private SourceMapper sourceMapper;
    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderOperationMapper orderOperationMapper;
    @Autowired
    private OrderBiz orderBiz;
    @Autowired
    private VideoRepository videoRepository;
    @Autowired
    private VideoTaskRepository videoTaskRepository;
    @Autowired
    private PriceRepository priceRepository;
    @Autowired
    private PriceBiz priceBiz;
    @Autowired
    private FaceRepository faceRepository;
    @Autowired
    private TemplateRepository templateRepository;
    @Autowired
    private PrinterMapper printerMapper;
    @Autowired
    private ScenicService scenicService;
    @Autowired
    private ScenicRepository scenicRepository;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private IVoucherService iVoucherService;
    @Autowired
    private ICouponService iCouponService;
    @Autowired
    private MemberRelationRepository memberRelationRepository;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ApiResponse<PageInfo<OrderRespVO>> pageQuery(OrderReqQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<OrderRespVO> list = orderMapper.list(query);
        
        // 批量获取景区名称
        List<Long> scenicIds = list.stream()
                .map(OrderRespVO::getScenicId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, String> scenicNames = scenicRepository.batchGetScenicNames(scenicIds);
        
        list.forEach(item -> {
            // 设置景区名称
            if (item.getScenicId() != null) {
                item.setScenicName(scenicNames.get(item.getScenicId()));
            }
            
            if (Integer.valueOf(-1).equals(item.getType())) {
                item.setGoodsName("一口价");
                item.setOrderType("一口价");
            } else if (Integer.valueOf(0).equals(item.getType())) {
                // 单品，查询
                OrderAppRespVO orderAppRespVO = orderMapper.appDetail(item.getId());
                List<OrderItemVO> orderItemList = orderAppRespVO.getOrderItemList();
                if (!orderItemList.isEmpty()) {
                    if (Integer.valueOf(1).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("录像集");
                        item.setOrderType("录像集");
                    } else if (Integer.valueOf(2).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("照片集");
                        item.setOrderType("照片集");
                    } else if (Integer.valueOf(13).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("AI微单");
                        item.setOrderType("AI微单");
                    } else if (Integer.valueOf(0).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setOrderType("旅行Vlog");
                        item.setGoodsName(orderItemList.getFirst().getGoodsName());
                    } else if (Integer.valueOf(4).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("一体机打印");
                        item.setOrderType("一体机打印");
                    } else if (Integer.valueOf(5).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("plog图");
                        item.setOrderType("plog图");
                    } else {
                        item.setGoodsName("未知商品");
                        item.setOrderType("未知商品");
                    }
                }
            } else if (Integer.valueOf(1).equals(item.getType())) {
                item.setGoodsName("多项商品");
                item.setOrderType("打包购买");
            } else if (Integer.valueOf(3).equals(item.getType())) {
                item.setGoodsName("打印照片");
                item.setOrderType("照片打印");
            }
        });
        PageInfo<OrderRespVO> pageInfo = new PageInfo<>(list);
        return ApiResponse.success(pageInfo);
    }

    @Override
    public ApiResponse<PageInfo<OrderRespVO>> pageQueryDetail(OrderReqQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<OrderRespVO> list = orderMapper.listDetail(query);
        
        // 批量获取景区名称
        List<Long> scenicIds = list.stream()
                .map(OrderRespVO::getScenicId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, String> scenicNames = scenicRepository.batchGetScenicNames(scenicIds);
        
        for (OrderRespVO item : list) {
            item.setPrice(item.getPayPrice());
            // 设置景区名称
            if (item.getScenicId() != null) {
                item.setScenicName(scenicNames.get(item.getScenicId()));
            }
            
            if (Integer.valueOf(-1).equals(item.getType())) {
                item.setGoodsName("一口价");
                item.setOrderType("一口价");
            } else if (Integer.valueOf(0).equals(item.getType())) {
                // 单品，查询
                OrderAppRespVO orderAppRespVO = orderMapper.appDetail(item.getId());
                List<OrderItemVO> orderItemList = orderAppRespVO.getOrderItemList();
                if (!orderItemList.isEmpty()) {
                    if (Integer.valueOf(1).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("录像集");
                        item.setOrderType("录像集");
                    } else if (Integer.valueOf(2).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("照片集");
                        item.setOrderType("照片集");
                    } else if (Integer.valueOf(13).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("AI微单");
                        item.setOrderType("AI微单");
                    } else if (Integer.valueOf(0).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setOrderType("旅行Vlog");
                        item.setGoodsName(orderItemList.getFirst().getGoodsName());
                    } else if (Integer.valueOf(4).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("一体机打印");
                        item.setOrderType("一体机打印");
                    } else {
                        item.setGoodsName("未知商品");
                        item.setOrderType("未知商品");
                    }
                }
            } else if (Integer.valueOf(1).equals(item.getType())) {
                item.setGoodsName("多项商品");
                item.setOrderType("打包购买");
            } else if (Integer.valueOf(3).equals(item.getType())) {
                item.setGoodsName("打印照片");
                item.setOrderType("照片打印");
            }
        }
        PageInfo<OrderRespVO> pageInfo = new PageInfo<>(list);
        return ApiResponse.success(pageInfo);
    }

    @Override
    public ApiResponse<List<OrderRespVO>> list(OrderReqQuery query) {
        List<OrderRespVO> list = orderMapper.list(query);
        
        // 批量获取景区名称
        List<Long> scenicIds = list.stream()
                .map(OrderRespVO::getScenicId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, String> scenicNames = scenicRepository.batchGetScenicNames(scenicIds);
        
        for (OrderRespVO item : list) {
            item.setPrice(item.getPayPrice());
            // 设置景区名称
            if (item.getScenicId() != null) {
                item.setScenicName(scenicNames.get(item.getScenicId()));
            }
            if (Integer.valueOf(3).equals(item.getType())) {
                item.setGoodsName("打印照片");
                if (item.getOrderItemList() != null && !item.getOrderItemList().isEmpty()) {
                    item.getOrderItemList().getFirst().setGoodsName(item.getGoodsName());
                }
            }
            if (Integer.valueOf(4).equals(item.getType())) {
                item.setGoodsName("一体机打印");
                if (item.getOrderItemList() != null && !item.getOrderItemList().isEmpty()) {
                    item.getOrderItemList().getFirst().setGoodsName(item.getGoodsName());
                }
            }
        }
        return ApiResponse.success(list);
    }

    @Override
    public ApiResponse<OrderRespVO> detail(Long orderId) {
        OrderRespVO order = orderMapper.getById(orderId);
        List<OrderItemVO> orderItemList = order.getOrderItemList();
        List<GoodsDetailVO> goodsList = new ArrayList<>();
        List<Integer> _f = new ArrayList<>();
        orderItemList.forEach(item -> {
            if (Integer.valueOf(1).equals(item.getGoodsType())) { // 原片 goodsId就是人脸ID
                List<SourceEntity> memberVideoEntityList = sourceMapper.listVideoByFaceRelation(item.getGoodsId());
                item.setCoverList(memberVideoEntityList.stream().map(SourceEntity::getUrl).collect(Collectors.toList()));
                if (!_f.contains(1)) {
                    _f.add(1);
                    if (!memberVideoEntityList.isEmpty()) {
                        for (SourceEntity sourceEntity : memberVideoEntityList) {
                            GoodsDetailVO goods = new GoodsDetailVO();
                            goods.setGoodsId(sourceEntity.getId());
                            goods.setGoodsName("录像集录像");
                            goods.setUrl(sourceEntity.getVideoUrl());
                            goods.setGoodsType(sourceEntity.getType());
                            goods.setScenicId(sourceEntity.getScenicId());
                            goods.setVideoUrl(sourceEntity.getVideoUrl());
                            goods.setTemplateCoverUrl(sourceEntity.getUrl());
                            goods.setCreateTime(sourceEntity.getCreateTime());
                            goodsList.add(goods);
                        }
                        item.setShootingTime(memberVideoEntityList.getFirst().getCreateTime());
                    }
                }
            } else if (Integer.valueOf(2).equals(item.getGoodsType())) { // 照片 goodsId就是人脸ID
                List<SourceEntity> memberVideoEntityList = sourceMapper.listImageByFaceRelation(item.getGoodsId());
                item.setCoverList(memberVideoEntityList.stream().map(SourceEntity::getUrl).collect(Collectors.toList()));
                if (!_f.contains(2)) {
                    _f.add(2);
                    if (!memberVideoEntityList.isEmpty()) {
                        for (SourceEntity sourceEntity : memberVideoEntityList) {
                            GoodsDetailVO goods = new GoodsDetailVO();
                            goods.setGoodsId(sourceEntity.getId());
                            goods.setGoodsName("照片集照片");
                            goods.setUrl(sourceEntity.getUrl());
                            goods.setGoodsType(sourceEntity.getType());
                            goods.setScenicId(sourceEntity.getScenicId());
                            goods.setUrl(sourceEntity.getUrl());
                            goods.setTemplateCoverUrl(sourceEntity.getUrl());
                            goods.setScenicId(sourceEntity.getScenicId());
                            goods.setCreateTime(sourceEntity.getCreateTime());
                            goodsList.add(goods);
                        }
                        item.setShootingTime(memberVideoEntityList.getFirst().getCreateTime());
                    }
                }
            } else if (Integer.valueOf(13).equals(item.getGoodsType())) { // AI相机照片 goodsId就是人脸ID
                List<SourceEntity> aiCamImageList = sourceMapper.listAiCamImageByFaceRelation(item.getGoodsId());
                item.setCoverList(aiCamImageList.stream().map(SourceEntity::getUrl).collect(Collectors.toList()));
                if (!_f.contains(13)) {
                    _f.add(13);
                    if (!aiCamImageList.isEmpty()) {
                        for (SourceEntity sourceEntity : aiCamImageList) {
                            GoodsDetailVO goods = new GoodsDetailVO();
                            goods.setGoodsId(sourceEntity.getId());
                            goods.setGoodsName("AI相机照片");
                            goods.setUrl(sourceEntity.getUrl());
                            goods.setGoodsType(sourceEntity.getType());
                            goods.setScenicId(sourceEntity.getScenicId());
                            goods.setTemplateCoverUrl(sourceEntity.getUrl());
                            goods.setCreateTime(sourceEntity.getCreateTime());
                            goodsList.add(goods);
                        }
                        item.setShootingTime(aiCamImageList.getFirst().getCreateTime());
                    }
                }
            } else if (Integer.valueOf(3).equals(item.getGoodsType())) { // 打印照片 goodsId就是memberPrintId
                List<MemberPrintResp> list = printerMapper.getUserPhotoByIds(orderItemList.stream().map(OrderItemVO::getGoodsId).collect(Collectors.toList()));
                item.setCoverList(orderItemList.stream().map(OrderItemVO::getCoverUrl).collect(Collectors.toList()));
                if (!_f.contains(3)) {
                    _f.add(3);
                    if (!list.isEmpty()) {
                        for (MemberPrintResp sourceEntity : list) {
                            GoodsDetailVO goods = new GoodsDetailVO();
                            goods.setGoodsId(Long.valueOf(sourceEntity.getId()));
                            goods.setGoodsName("打印照片("+sourceEntity.getQuantity()+"张)");
                            goods.setUrl(sourceEntity.getCropUrl());
                            goods.setGoodsType(3);
                            goods.setScenicId(sourceEntity.getScenicId());
                            goods.setTemplateCoverUrl(sourceEntity.getCropUrl());
                            goods.setCreateTime(sourceEntity.getCreateTime());
                            PrintTaskResp printTaskResp = printerMapper.queryTaskByMpId(sourceEntity.getId());
                            if (printTaskResp != null) {
                                goods.setPrinterName(printTaskResp.getPrinterName());
                                goods.setPrinterPaper(printTaskResp.getPaper());
                            } else {
                                PrinterEntity printerEntity = printerMapper.getById(sourceEntity.getPrinterId());
                                if (printerEntity != null) {
                                    goods.setPrinterName(printerEntity.getName());
                                    goods.setPrinterPaper(printerEntity.getPreferPaper());
                                }
                            }
                            goodsList.add(goods);
                        }
                    }
                }
            } else if (Integer.valueOf(-1).equals(item.getGoodsType())) { // 模板一套
                TemplateRespVO template = templateRepository.getTemplate(item.getGoodsId());
                item.setCoverUrl(template.getCoverUrl());
                List<MemberVideoEntity> videoEntities = videoMapper.listRelationByFaceAndTemplate(order.getFaceId(), item.getGoodsId());
                if (!videoEntities.isEmpty()) {
                    for (MemberVideoEntity memberVideoEntity : videoEntities) {
                        GoodsDetailVO goods = new GoodsDetailVO();
                        goods.setGoodsId(memberVideoEntity.getVideoId());
                        goods.setGoodsName(template.getName());
                        goods.setGoodsType(0);
                        goods.setScenicId(memberVideoEntity.getScenicId());
                        goods.setTemplateCoverUrl(template.getCoverUrl());
                        VideoEntity video = videoRepository.getVideo(memberVideoEntity.getVideoId());
                        if (video != null) {
                            goods.setCreateTime(videoTaskRepository.getTaskShotDate(video.getTaskId()));
                            goods.setUrl(video.getVideoUrl());
                        }
                        goodsList.add(goods);
                    }
                }
            } else if (Integer.valueOf(5).equals(item.getGoodsType())) { // pLog
                GoodsDetailVO goods = new GoodsDetailVO();
                goods.setGoodsId(item.getGoodsId());
                goods.setGoodsName("pLog");
                goods.setGoodsType(5);
                goods.setUrl(item.getCoverUrl());
                goods.setTemplateCoverUrl(item.getCoverUrl());
                goods.setScenicId(order.getScenicId());
                goodsList.add(goods);
            } else if (Integer.valueOf(14).equals(item.getGoodsType())) { // 单张照片 goodsId就是sourceId
                SourceRespVO source = sourceMapper.getById(item.getGoodsId());
                if (source != null) {
                    item.setCoverList(Collections.singletonList(source.getUrl()));
                    GoodsDetailVO goods = new GoodsDetailVO();
                    goods.setGoodsId(source.getId());
                    goods.setGoodsName("单张照片");
                    goods.setUrl(source.getUrl());
                    goods.setGoodsType(14);
                    goods.setScenicId(source.getScenicId());
                    goods.setTemplateCoverUrl(source.getUrl());
                    goods.setCreateTime(source.getCreateTime());
                    goodsList.add(goods);
                    item.setShootingTime(source.getCreateTime());
                }
            } else {
                item.setCoverList(Collections.singletonList(item.getCoverUrl()));
                VideoEntity videoMapperById = videoRepository.getVideo(item.getGoodsId());
                if (videoMapperById != null) {
                    TemplateRespVO template = templateRepository.getTemplate(videoMapperById.getTemplateId());
                    GoodsDetailVO goods = new GoodsDetailVO();
                    goods.setGoodsId(videoMapperById.getId());
                    goods.setGoodsName(template.getName());
                    goods.setUrl(videoMapperById.getVideoUrl());
                    goods.setGoodsType(0);
                    goods.setTemplateCoverUrl(template.getCoverUrl());
                    goods.setCreateTime(videoTaskRepository.getTaskShotDate(videoMapperById.getTaskId()));
                    goods.setParts(videoTaskRepository.getTaskLensNum(videoMapperById.getTaskId()));
                    goodsList.add(goods);
                    item.setShootingTime(videoTaskRepository.getTaskShotDate(videoMapperById.getTaskId()));
                    item.setVideoUrl(videoMapperById.getVideoUrl());
                }
            }
        });
        order.setGoodsList(goodsList);
        
        // 设置景区名称
        if (order.getScenicId() != null) {
            try {
                String scenicName = scenicRepository.batchGetScenicNames(List.of(order.getScenicId()))
                        .get(order.getScenicId());
                order.setScenicName(scenicName);
            } catch (Exception e) {
                log.warn("获取景区名称失败: {}", order.getScenicId(), e);
            }
        }
        
        return ApiResponse.success(order);
    }

    /**
     * 发起支付
     *
     * @param order      订单
     * @param orderItems 商品详情
     * @return 支付请求结果
     */
    private Map<String, Object> initiatePayment(OrderEntity order, List<OrderItemEntity> orderItems) throws Exception {
        WXPayOrderReqVO wxPayOrderReqVO = new WXPayOrderReqVO();
        String goodsName = null;
        if (orderItems.size() > 1) {
            goodsName = "多项景区Vlog商品";
        } else {
            int type = orderItems.getFirst().getGoodsType();
            if (type == 0) {
                goodsName = "景区Vlog视频";
            } else if (type == 1) {
                goodsName = "景区录像包";
            } else if (type == 2) {
                goodsName = "景区照片包";
            } else {
                goodsName = "景区售卖物品";
            }
        }
        wxPayOrderReqVO.setOpenId(order.getOpenId())
                .setMemberId(order.getMemberId())
                .setOrderSn(order.getId())
                .setTotalPrice(order.getPayPrice().setScale(2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).intValueExact())
                .setGoodsName(goodsName)
                .setDescription(goodsName);

        return wxPayService.createOrder(order.getScenicId(), wxPayOrderReqVO);
    }

    @Override
    public ApiResponse<Integer> update(OrderUpdateReq query) {
        int update = orderMapper.update(query);
        if (update == NumberConstant.ZERO) {
            return ApiResponse.fail("订单更新失败");
        }
        return ApiResponse.success(update);
    }

    /**
     * 更新订单支付状态
     *
     * @param orderSn 订单编号也就是订单的ID
     */
    @Override
    public void updateOrderState(Long orderSn, OrderStateEnum orderStateEnum, String reason) {
        OrderUpdateReq orderUpdateReq = new OrderUpdateReq();
        orderUpdateReq.setId(orderSn);
        if (orderStateEnum.getType() == NumberConstant.ONE) {//退款状态 0未提出，1已通过，2待审核
            orderUpdateReq.setRefundStatus(orderStateEnum.getState());
            orderUpdateReq.setRefundAt(new Date());
            if (orderStateEnum.getState() == OrderStateEnum.PASSED.getState()) {
                orderUpdateReq.setRemark(reason);
            } else if (Objects.nonNull(reason)) {
                orderUpdateReq.setRefundReason(reason);
            }
        } else if (orderStateEnum.getType() == NumberConstant.TWO) {//订单状态 0未支付，1已支付，2已退款，9已取消
            int state = orderStateEnum.getState();
            orderUpdateReq.setPayAt(new Date());
            orderUpdateReq.setStatus(orderStateEnum.getState());
            if (state == OrderStateEnum.CANCELED.getState()) {//取消支付
                orderUpdateReq.setCancelAt(new Date());

            } else if (state== OrderStateEnum.PAID.getState()) {//支付成功
                orderUpdateReq.setPayAt(new Date());

            }else if (state == OrderStateEnum.REFUNDED.getState()) {//退款成功
                orderUpdateReq.setRefundAt(new Date());

            }
        }
        orderMapper.update(orderUpdateReq);
    }

    @Override
    public ApiResponse<Integer> getOrderCountByUserId(Long userId) {
        return ApiResponse.success(orderMapper.countByUserId(userId));
    }

    @Override
    public ApiResponse<PageInfo<OrderAppRespVO>> appPageQuery(OrderAppPageReq orderReqQuery) {
        PageHelper.startPage(orderReqQuery.getPageNum(), orderReqQuery.getPageSize());
        List<OrderAppRespVO> list = orderMapper.appList(orderReqQuery);
        list.forEach(order -> {
            List<OrderItemVO> orderItemList = order.getOrderItemList();
            if (orderItemList == null) {
                return;
            }
            orderItemList.forEach(item -> {
                if (Integer.valueOf(1).equals(item.getGoodsType())) { // 原片
                    List<SourceEntity> memberVideoEntityList = sourceMapper.listVideoByFaceRelation(item.getFaceId());
                    item.setCoverList(memberVideoEntityList.stream().map(SourceEntity::getUrl).collect(Collectors.toList()));
                    if (!memberVideoEntityList.isEmpty()) {
                        item.setShootingTime(memberVideoEntityList.getFirst().getCreateTime());
                        item.setCount(1);
                    }
                } else if (Integer.valueOf(2).equals(item.getGoodsType())) {
                    List<SourceEntity> memberVideoEntityList = sourceMapper.listImageByFaceRelation(item.getFaceId());
                    item.setCoverList(memberVideoEntityList.stream().map(SourceEntity::getUrl).collect(Collectors.toList()));
                    if (!memberVideoEntityList.isEmpty()) {
                        item.setShootingTime(memberVideoEntityList.getFirst().getCreateTime());
                        item.setCount(1);
                    }
                } else if (Integer.valueOf(13).equals(item.getGoodsType())) {
                    List<SourceEntity> aiCamImageList = sourceMapper.listAiCamImageByFaceRelation(item.getFaceId());
                    item.setCoverList(aiCamImageList.stream().map(SourceEntity::getUrl).collect(Collectors.toList()));
                    if (!aiCamImageList.isEmpty()) {
                        item.setShootingTime(aiCamImageList.getFirst().getCreateTime());
                        item.setCount(1);
                    }
                } else if (Integer.valueOf(0).equals(item.getGoodsType())) {
                    item.setCoverList(Collections.singletonList(item.getCoverUrl()));
                    VideoEntity video = videoRepository.getVideo(item.getGoodsId());
                    if (video != null) {
                        item.setShootingTime(videoTaskRepository.getTaskShotDate(video.getTaskId()));
                        item.setCount(1);
                    }
                } else if (Integer.valueOf(3).equals(item.getGoodsType())) {
                    // 打印订单
                    List<MemberPrintResp> photo = printerMapper.getUserPhotoByIds(orderItemList.stream().map(OrderItemVO::getGoodsId).collect(Collectors.toList()));
                    item.setCoverList(photo.stream().map(MemberPrintResp::getCropUrl).collect(Collectors.toList()));
                    photo.stream().filter(p -> p.getId().equals(item.getGoodsId().intValue())).findAny().ifPresent(p -> {
                        item.setCount(p.getQuantity());
                    });
                }
            });
        });
        
        // 批量获取景区名称
        List<Long> scenicIds = list.stream()
                .map(OrderAppRespVO::getScenicId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, String> scenicNames = scenicRepository.batchGetScenicNames(scenicIds);
        
        // 设置景区名称
        list.forEach(order -> {
            if (order.getScenicId() != null) {
                order.setScenicName(scenicNames.get(order.getScenicId()));
            }
        });
        
        PageInfo<OrderAppRespVO> pageInfo = new PageInfo<>(list);
        return ApiResponse.success(pageInfo);
    }

    @Override
    public ApiResponse<OrderAppRespVO> appDetail(Long id) {
        OrderAppRespVO orderAppRespVO = orderMapper.appDetail(id);
        
        // 设置景区名称
        if (orderAppRespVO != null && orderAppRespVO.getScenicId() != null) {
            try {
                String scenicName = scenicRepository.batchGetScenicNames(List.of(orderAppRespVO.getScenicId()))
                        .get(orderAppRespVO.getScenicId());
                orderAppRespVO.setScenicName(scenicName);
            } catch (Exception e) {
                log.warn("获取景区名称失败: {}", orderAppRespVO.getScenicId(), e);
            }
        }
        if (orderAppRespVO != null && orderAppRespVO.getOrderItemList() != null && !orderAppRespVO.getOrderItemList().isEmpty()) {
            orderAppRespVO.getOrderItemList().forEach(orderItem -> {
                if (orderItem.getGoodsType() == 3) {
                    String size = redisTemplate.opsForValue().get("printer_size:" + id);
                    if (size != null) {
                        orderItem.setPrinterPaper(size);
                    } else {
                        PrintTaskResp printTaskResp = printerMapper.queryTaskByMpId(Math.toIntExact(orderItem.getGoodsId()));
                        if (printTaskResp != null) {
                            orderItem.setPrinterPaper(printTaskResp.getPaper());
                        }
                    }
                }
            });
        }
        
        return ApiResponse.success(orderAppRespVO);
    }

    @Override
    public ApiResponse<?> refundOrder(RefundOrderReq refundOrderReq) {
        this.updateOrderState(refundOrderReq.getOrderId(), OrderStateEnum.TO_BE_REVIEWED, refundOrderReq.getRefundReason());
        return ApiResponse.buildResult(BizCodeEnum.REQUEST_OK);
    }

    @Override
    public ApiResponse<?> auditRefundOrder(RefundOrderReq refundOrderReq) {
        this.updateOrderState(refundOrderReq.getOrderId(), OrderStateEnum.PASSED, refundOrderReq.getRefundReason());
        // 调用微信发起退款
        try {
            wxPayService.refundOrder(refundOrderReq.getOrderId().toString());
        } catch (Exception e) {
            throw new AppException(BizCodeEnum.ADVANCE_PAYMENT_REFUND_FAILED,e.getMessage());
        }
        return ApiResponse.buildResult(BizCodeEnum.REQUEST_OK);
    }

    @Override
    public void remarkOrder(Long orderId, OrderEntity query) {
        OrderUpdateReq updateOrder = new OrderUpdateReq();
        updateOrder.setId(orderId);
        updateOrder.setRemark(query.getRemark());
        orderMapper.update(updateOrder);
        OrderOperationEntity orderOperationEntity = new OrderOperationEntity();
        orderOperationEntity.setOrderId(orderId);
        orderOperationEntity.setType("修改备注");
        orderOperationEntity.setRemark("备注修改为："+query.getRemark());
        orderOperationEntity.setUser(BaseContextHandler.getAccount());
        orderOperationEntity.setUserId(BaseContextHandler.getUserId());
        orderOperationMapper.add(orderOperationEntity);
    }

    @Override
    public ApiResponse<PageInfo<OrderRespVO>> refundPageQuery(OrderReqQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<OrderRespVO> list = orderMapper.refundList(query);
        
        // 批量获取景区名称
        List<Long> scenicIds = list.stream()
                .map(OrderRespVO::getScenicId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, String> scenicNames = scenicRepository.batchGetScenicNames(scenicIds);
        
        list.forEach(item -> {
            // 设置景区名称
            if (item.getScenicId() != null) {
                item.setScenicName(scenicNames.get(item.getScenicId()));
            }
            
            if (Integer.valueOf(-1).equals(item.getType())) {
                item.setGoodsName("一口价");
                item.setOrderType("一口价");
            } else if (Integer.valueOf(0).equals(item.getType())) {
                // 单品，查询
                OrderAppRespVO orderAppRespVO = orderMapper.appDetail(item.getId());
                List<OrderItemVO> orderItemList = orderAppRespVO.getOrderItemList();
                if (!orderItemList.isEmpty()) {
                    if (Integer.valueOf(1).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("录像集");
                        item.setOrderType("录像集");
                    } else if (Integer.valueOf(2).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("照片集");
                        item.setOrderType("照片集");
                    } else if (Integer.valueOf(13).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setGoodsName("打卡点拍照");
                        item.setOrderType("打卡点拍照");
                    } else if (Integer.valueOf(0).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setOrderType("旅行Vlog");
                        item.setGoodsName(orderItemList.getFirst().getGoodsName());
                    } else {
                        item.setGoodsName("未知商品");
                        item.setOrderType("未知商品");
                    }
                }
            }
        });
        PageInfo<OrderRespVO> pageInfo = new PageInfo<>(list);
        return ApiResponse.success(pageInfo);
    }

    @Override
    public ApiResponse<Map<String, Object>> createOrder(Long userId, CreateOrderReqVO createOrderReqVO) throws Exception {
        // 防重复提交检查：基于用户ID、景区ID、商品类型、商品ID生成唯一键
        String orderKey = String.format("createOrder:%d:%d:%d:%d",
                userId, createOrderReqVO.getScenicId(),
                createOrderReqVO.getGoodsType(), createOrderReqVO.getGoodsId());

        // 使用synchronized确保同一用户对同一商品的订单创建操作串行化
        synchronized (orderKey.intern()) {
            // 看看有没有之前购买的订单
            OrderEntity order = orderMapper.getUserOrderItem(userId, createOrderReqVO.getScenicId(), 0, null, createOrderReqVO.getGoodsType(), createOrderReqVO.getGoodsId());
            boolean haveOldOrder = false;
            if (order != null) {
                // 如果订单已支付，直接返回错误，不允许重复购买
                if (order.getStatus() == OrderStateEnum.PAID.getState()) {
                    return ApiResponse.fail("您已购买此内容，无需重复购买！");
                }
                // 只有未支付的订单才允许复用
                if (order.getStatus() == OrderStateEnum.UNPAID.getState()
                        && DateUtil.isSameDay(order.getCreateAt(), new Date())) {
                    haveOldOrder = true;
                }
            }
            if (!haveOldOrder) {
                order = new OrderEntity();
                order.setId(SnowFlakeUtil.getLongId());
                order.setMemberId(userId);
                MemberRespVO member = memberMapper.getById(userId);
                order.setOpenId(member.getOpenId());
                order.setScenicId(createOrderReqVO.getScenicId());

                PriceObj priceObj = orderBiz.queryPrice(order.getScenicId(), member.getId(), createOrderReqVO.getGoodsType(), createOrderReqVO.getGoodsId());
                order.setSlashPrice(priceObj.getSlashPrice());
                order.setPrice(priceObj.getPrice());
                // 判断是否是本人数据
                FaceEntity goodsFace = faceRepository.getFace(priceObj.getFaceId());
                if (goodsFace != null) {
                    if (!goodsFace.getMemberId().equals(userId)) {
                        return ApiResponse.fail("您无权购买此内容！");
                    }
                    IsBuyRespVO isBuy = orderBiz.isBuy(createOrderReqVO.getScenicId(), userId, goodsFace.getId(), createOrderReqVO.getGoodsType(), createOrderReqVO.getGoodsId());
                    if (isBuy.isBuy()) {
                        return ApiResponse.fail("您已购买此内容，无需重复购买！");
                    }
                }
                // promo code
                order.setPayPrice(priceObj.getPrice());
                order.setFaceId(priceObj.getFaceId());
                if (order.getPayPrice().equals(BigDecimal.ZERO)) {
                    order.setStatus(OrderStateEnum.PAID.getState());
                    order.setPayAt(new Date());
                } else {
                    order.setStatus(OrderStateEnum.UNPAID.getState());
                }
            }
            List<OrderItemEntity> orderItems = new ArrayList<>();
            OrderItemEntity orderItem = new OrderItemEntity();
            orderItem.setGoodsId(createOrderReqVO.getGoodsId());
            orderItem.setGoodsType(createOrderReqVO.getGoodsType());
            orderItem.setOrderId(order.getId());
            orderItems.add(orderItem);
            // 在事务中保存订单数据
            try {
                self.saveOrderInTransaction(order, orderItems, haveOldOrder);
            } catch (Exception e) {
                log.error("保存订单失败", e);
                return ApiResponse.fail("订单创建失败");
            }

            // 判断是否需要支付（事务外处理）
            if (order.getPayPrice().compareTo(BigDecimal.ZERO) <= 0) {
                // 只有新创建的订单才需要执行支付完成逻辑
                if (!haveOldOrder) {
                    try {
                        orderBiz.paidOrder(order.getId());
                    } catch (Exception e) {
                        log.error("处理免费订单失败", e);
                        return ApiResponse.fail("订单处理失败");
                    }
                }
                HashMap<String, Object> data = new HashMap<>();
                data.put("needPay", false);
                return ApiResponse.success(data);
            } else {
                // 发起支付（事务外调用外部服务）
                try {
                    Map<String, Object> wxPayRespVO = initiatePayment(order, orderItems);
                    return ApiResponse.success(wxPayRespVO);
                } catch (Exception e) {
                    log.error("发起支付失败", e);
                    return ApiResponse.fail("支付发起失败，请重试");
                }
            }
        } // synchronized 块结束
    }

    /**
     * 在事务中保存订单数据
     */
    @Transactional(rollbackFor = Exception.class)
    protected void saveOrderInTransaction(OrderEntity order, List<OrderItemEntity> orderItems, boolean haveOldOrder) {
        if (!haveOldOrder) {
            orderMapper.add(order);
            int addOrderItems = orderMapper.addOrderItems(orderItems);
            if (addOrderItems == NumberConstant.ZERO) {
                throw new RuntimeException("订单明细添加失败");
            }
        } else {
            // 对于旧订单，只更新价格相关字段，不重复处理业务逻辑
            orderMapper.updateOrderPrice(order);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<Map<String, Object>> createBatchOrder(Long userId, CreateBatchOrderReqVO batchOrderReqVO) throws Exception {
        PriceConfigEntity priceConfig = priceRepository.getPriceConfigByScenicTypeGoods(batchOrderReqVO.getScenicId(), batchOrderReqVO.getType(), batchOrderReqVO.getGoodsId());
        if (priceConfig == null) {
            return ApiResponse.fail("该套餐暂未开放购买");
        }
        FaceEntity face = faceRepository.getFace(batchOrderReqVO.getFaceId());
        if (face != null && !face.getMemberId().equals(userId)) {
            return ApiResponse.fail("您无权购买此内容！");
        }
        // 找下有没有照片
        List<MemberSourceEntity> photoList = memberRelationRepository.listSourceByFaceRelation(batchOrderReqVO.getFaceId(), 2);
        if (photoList.isEmpty()) {
            log.info("请先游玩后再来购买商品！");
            return ApiResponse.fail("请先游玩后再来购买商品！");
        }
        log.info("创建批量订单，价格配置：{}，请求：{}", priceConfig, batchOrderReqVO);
        OrderEntity order = new OrderEntity();
        Long orderId = SnowFlakeUtil.getLongId();
        order.setId(orderId);
        order.setMemberId(userId);
        MemberRespVO member = memberMapper.getById(userId);
        order.setOpenId(member.getOpenId());
        order.setPriceConfigId(priceConfig.getId());
        order.setScenicId(priceConfig.getScenicId());
        order.setType(priceConfig.getType());
        List<GoodsListRespVO> goodsList = priceBiz.queryGoodsList(priceConfig.getId());
        List<OrderItemEntity> orderItems = goodsList.stream().map(goods -> {
            OrderItemEntity orderItem = new OrderItemEntity();
            orderItem.setOrderId(orderId);
            orderItem.setGoodsId(goods.getGoodsId());
            orderItem.setGoodsType(goods.getGoodsType());
            if (Integer.valueOf(1).equals(goods.getGoodsType())) {
                orderItem.setGoodsId(batchOrderReqVO.getFaceId());
            } else if (Integer.valueOf(2).equals(goods.getGoodsType())) {
                orderItem.setGoodsId(batchOrderReqVO.getFaceId());
            } else if (Integer.valueOf(0).equals(goods.getGoodsType())) {
                orderItem.setGoodsType(-1);
            }
            return orderItem;
        }).collect(Collectors.toList());
        OrderItemEntity puzzleAll = new OrderItemEntity();
        puzzleAll.setOrderId(orderId);
        puzzleAll.setGoodsId(batchOrderReqVO.getScenicId());
        puzzleAll.setGoodsType(5);
        orderItems.add(puzzleAll);
        order.setSlashPrice(priceConfig.getSlashPrice());
        order.setPrice(priceConfig.getPrice());
        order.setPayPrice(priceConfig.getPrice());
        order.setFaceId(batchOrderReqVO.getFaceId());
        if (order.getPayPrice().equals(BigDecimal.ZERO)) {
            order.setStatus(OrderStateEnum.PAID.getState());
            order.setPayAt(new Date());
        } else {
            order.setStatus(OrderStateEnum.UNPAID.getState());
        }
        orderMapper.add(order);
        int addOrderItems = orderMapper.addOrderItems(orderItems);
        if (addOrderItems == NumberConstant.ZERO) {
            log.error("订单明细添加失败");
            return ApiResponse.fail("订单添加失败");
        }
        if (order.getPayPrice().equals(BigDecimal.ZERO)) {
            orderBiz.paidOrder(order.getId());
            HashMap<String, Object> data = new HashMap<>();
            data.put("needPay", false);
            return ApiResponse.success(data);
        } else {
            Map<String, Object> wxPayRespVO = initiatePayment(order, orderItems);
            return ApiResponse.success(wxPayRespVO);
        }
    }

    @Override
    public PayResponse queryOrder(Long orderId) {
        OrderRespVO order = orderMapper.getById(orderId);
        if (order == null) {
            throw new BaseException("订单不存在");
        }
        IPayAdapter scenicPayAdapter = scenicService.getScenicPayAdapter(order.getScenicId());
        PayResponse payResponse = scenicPayAdapter.queryOrder(orderId.toString());
        return payResponse;
    }

    @Override
    public Long createOrderCompact(Long userId, MobileOrderRequest request, PriceCalculationResult cachedResult) {
        FaceEntity face = faceRepository.getFace(request.getFaceId());
        ProductItem productItem = request.getProducts().getFirst();
        Integer type = switch (productItem.getProductType()) {
            case PHOTO_LOG -> 5;
            case PHOTO_SET -> 2;
            case PHOTO -> 14;
            case VLOG_VIDEO -> 0;
            case RECORDING_SET -> 1;
            case AI_CAM_PHOTO_SET -> 13;
            default -> 0;
        };
        Long goodsId = switch (productItem.getProductType()) {
            case PHOTO_LOG -> Long.valueOf(productItem.getProductId());
            case PHOTO -> Long.valueOf(productItem.getProductId());
            case PHOTO_SET, RECORDING_SET -> face.getId();
            case AI_CAM_PHOTO_SET -> face.getId();
            case VLOG_VIDEO -> {
                List<MemberVideoEntity> videos = memberRelationRepository.listRelationByFaceAndTemplate(face.getId(), Long.valueOf(productItem.getProductId()));
                yield videos.getFirst().getVideoId();
            }
            default -> 0L;
        };
        IsBuyRespVO isBuy = orderBiz.isBuy(face.getScenicId(), userId, face.getId(), type, goodsId);
        if (isBuy.isBuy()) {
            throw new BaseException("您已购买此内容，无需重复购买！");
        }
        // 看看有没有之前购买的订单
        OrderEntity order = orderMapper.getUserOrderItem(userId, face.getScenicId(), 0, null, type, goodsId);
        boolean haveOldOrder = false;
        if (order != null) {
            // 如果订单已支付，直接返回错误，不允许重复购买
            if (order.getStatus() == OrderStateEnum.PAID.getState()) {
                throw new BaseException("您已购买此内容，无需重复购买！");
            }
            // 只有未支付的订单才允许复用
            if (order.getStatus() == OrderStateEnum.UNPAID.getState()
                    && DateUtil.isSameDay(order.getCreateAt(), new Date())) {
                haveOldOrder = true;
            }
        }
        if (!haveOldOrder) {
            order = new OrderEntity();
            order.setId(SnowFlakeUtil.getLongId());
            order.setFaceId(face.getId());
            order.setMemberId(userId);
            MemberRespVO member = memberMapper.getById(userId);
            order.setOpenId(member.getOpenId());
            order.setScenicId(face.getScenicId());
        }
        order.setSlashPrice(cachedResult.getOriginalAmount());
        order.setPrice(cachedResult.getFinalAmount());
        // promo code
        order.setPayPrice(cachedResult.getFinalAmount());
        if (order.getPayPrice().compareTo(BigDecimal.ZERO) <= 0) {
            order.setStatus(OrderStateEnum.PAID.getState());
            order.setPayAt(new Date());
        } else {
            order.setStatus(OrderStateEnum.UNPAID.getState());
        }

        // coupon
        order.setCouponPrice(BigDecimal.ZERO);
        order.setCouponRecordId(null);
        order.setCouponId(null);
        if (cachedResult.getUsedCoupon() != null) {
            order.setCouponPrice(cachedResult.getUsedCoupon().getActualDiscountAmount());
            order.setCouponId(Math.toIntExact(cachedResult.getUsedCoupon().getCouponId()));

            CouponUseRequest couponUseRequest = new CouponUseRequest();
            couponUseRequest.setCouponId(cachedResult.getUsedCoupon().getCouponId());
            couponUseRequest.setUserId(userId);
            couponUseRequest.setOrderId(order.getId().toString());
            couponUseRequest.setOriginalAmount(cachedResult.getOriginalAmount());
            couponUseRequest.setDiscountAmount(cachedResult.getUsedCoupon().getActualDiscountAmount());
            couponUseRequest.setScenicId(order.getScenicId() != null ? order.getScenicId().toString() : null);
            iCouponService.useCoupon(couponUseRequest);
        }
        if (cachedResult.getUsedVoucher() != null) {
            order.setBrokerId(cachedResult.getUsedVoucher().getBrokerId());
            order.setPromoCode(cachedResult.getUsedVoucher().getVoucherCode());
            iVoucherService.markVoucherAsUsed(cachedResult.getUsedVoucher().getVoucherCode(), "用户下单", order.getId().toString(), cachedResult.getUsedVoucher().getDiscountValue(), face.getId());
        }
        List<OrderItemEntity> orderItems = new ArrayList<>();
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setGoodsId(goodsId);
        orderItem.setGoodsType(type);
        orderItem.setOrderId(order.getId());
        orderItems.add(orderItem);
        // ======== 兼容旧逻辑 ==========
        if (order.getType() == 3) {
            redisTemplate.opsForValue().set("order_content_not_downloadable_" + order.getId(), "1");
        }
        if (type == 13) {
            redisTemplate.opsForValue().set("order_content_not_downloadable_" + order.getId(), "1");
        }
        // 在事务中保存订单数据
        try {
            self.saveOrderInTransaction(order, orderItems, haveOldOrder);
            return order.getId();
        } catch (Exception e) {
            log.error("保存订单失败", e);
            throw new BaseException("订单创建失败");
        }
    }

    @Override
    public ApiResponse<PaymentParamsResponse> getPaymentParams(Long orderId, Long userId, PaymentParamsRequest request) {
        OrderEntity order = orderMapper.get(orderId);
        
        // 检查订单金额是否为0
        if (order.getPayPrice() == null || order.getPayPrice().compareTo(BigDecimal.ZERO) <= 0) {
            // 零金额订单：设置needPay为false，直接标记为已支付
            order.setStatus(1); // 1表示已支付
            order.setPayAt(new Date());
            orderMapper.updateOrder(order);
            
            // 返回免费订单响应
            return ApiResponse.success(PaymentParamsResponse.free(orderId, orderId.toString()));
        }
        
        // 非零金额订单：按原流程处理
        PaymentParamsResponse response = new PaymentParamsResponse();
        response.setOrderId(orderId);
        response.setOrderNo(orderId.toString());
        response.setNeedPay(true);
        List<OrderItemEntity> orderItems = orderMapper.getOrderItems(orderId);
        try {
            Map<String, Object> wxPayRespVO = initiatePayment(order, orderItems);
            response.setPaymentParams(wxPayRespVO);
            return ApiResponse.success(response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
