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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ycwl.basic.biz.CouponBiz;
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.couponRecord.resp.CouponRecordQueryResp;
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.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.PriceRepository;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @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 CouponBiz couponBiz;
    @Autowired
    private TemplateRepository templateRepository;
    @Autowired
    private TaskTaskServiceImpl taskTaskService;
    @Autowired
    private PrinterMapper printerMapper;
    @Autowired
    private ScenicService scenicService;

    @Override
    public ApiResponse<PageInfo<OrderRespVO>> pageQuery(OrderReqQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<OrderRespVO> list = orderMapper.list(query);
        list.forEach(item -> {
            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(0).equals(orderItemList.getFirst().getGoodsType())) {
                        item.setOrderType("旅行Vlog");
                        item.setGoodsName(orderItemList.getFirst().getGoodsName());
                    } 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);
        PageInfo<OrderRespVO> pageInfo = new PageInfo<>(list);
        return ApiResponse.success(pageInfo);
    }

    @Override
    public ApiResponse<List<OrderRespVO>> list(OrderReqQuery query) {
        return ApiResponse.success(orderMapper.list(query));
    }

    @Override
    public ApiResponse<OrderRespVO> detail(Long orderId) {
        OrderRespVO byId = orderMapper.getById(orderId);
        List<OrderItemVO> orderItemList = byId.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(byId.getMemberId(), 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.getUrl());
                            goods.setGoodsType(sourceEntity.getType());
                            goods.setScenicId(sourceEntity.getScenicId());
                            goods.setUrl(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(byId.getMemberId(), 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(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.setScenicId(sourceEntity.getScenicId());
                            goods.setCreateTime(sourceEntity.getCreateTime());
                            goodsList.add(goods);
                        }
                    }
                }
            } else {
                item.setCoverList(Collections.singletonList(item.getCoverUrl()));
                VideoEntity videoMapperById = videoRepository.getVideo(item.getGoodsId());
                if (videoMapperById != null) {
                    TaskEntity task = videoTaskRepository.getTaskById(videoMapperById.getTaskId());
                    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());
                    long deviceCount;
                    if (task.getTaskParams() == null) {
                        deviceCount = 1;
                    } else {
                        JSONObject paramJson = JSON.parseObject(task.getTaskParams());
                        List<String> templatePlaceholder = templateRepository.getTemplatePlaceholder(task.getTemplateId());
                        deviceCount = paramJson.keySet().stream()
                                .filter(StringUtils::isNumeric)
                                .filter(templatePlaceholder::contains)
                                .count();
                    }
                    goods.setCreateTime(videoTaskRepository.getTaskShotDate(task.getId()));
                    goods.setParts(Math.toIntExact(deviceCount));
                    goodsList.add(goods);
                    item.setShootingTime(videoTaskRepository.getTaskShotDate(videoMapperById.getTaskId()));
                    item.setVideoUrl(videoMapperById.getVideoUrl());
                }
            }
        });
        byId.setGoodsList(goodsList);
        return ApiResponse.success(byId);
    }

    /**
     * 发起支付
     *
     * @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 = "景区照片包";
            }
        }
        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(orderReqQuery.getMemberId(), item.getFaceId());
                    item.setCoverList(memberVideoEntityList.stream().map(SourceEntity::getUrl).collect(Collectors.toList()));
                    if (!memberVideoEntityList.isEmpty()) {
                        item.setShootingTime(memberVideoEntityList.getFirst().getCreateTime());
                    }
                } else if (Integer.valueOf(2).equals(item.getGoodsType())) {
                    List<SourceEntity> memberVideoEntityList = sourceMapper.listImageByFaceRelation(orderReqQuery.getMemberId(), item.getFaceId());
                    item.setCoverList(memberVideoEntityList.stream().map(SourceEntity::getUrl).collect(Collectors.toList()));
                    if (!memberVideoEntityList.isEmpty()) {
                        item.setShootingTime(memberVideoEntityList.getFirst().getCreateTime());
                    }
                } 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()));
                    }
                } 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()));
                }
            });
        });
        PageInfo<OrderAppRespVO> pageInfo = new PageInfo<>(list);
        return ApiResponse.success(pageInfo);
    }

    @Override
    public ApiResponse<OrderAppRespVO> appDetail(Long id) {
        OrderAppRespVO orderAppRespVO = orderMapper.appDetail(id);
        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.forEach(item -> {
            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(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
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<Map<String, Object>> createOrder(Long userId, CreateOrderReqVO createOrderReqVO) throws Exception {
        IsBuyRespVO isBuy = orderBiz.isBuy(userId, createOrderReqVO.getScenicId(), createOrderReqVO.getGoodsType(), createOrderReqVO.getGoodsId());
        if (isBuy.isBuy()) {
            return ApiResponse.fail("您已购买此内容，无需重复购买！");
        }
        // 看看有没有之前购买的订单
        OrderEntity order = orderMapper.getUserOrderItem(userId, createOrderReqVO.getScenicId(), 0, null, createOrderReqVO.getGoodsType(), createOrderReqVO.getGoodsId());
        boolean haveOldOrder = order != null;
        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(), createOrderReqVO.getGoodsType(), createOrderReqVO.getGoodsId());
            order.setSlashPrice(priceObj.getSlashPrice());
            order.setPrice(priceObj.getPrice());
            // 判断是否是本人数据
            FaceEntity goodsFace = faceRepository.getFace(priceObj.getFaceId());
            if (goodsFace != null && !goodsFace.getMemberId().equals(userId)) {
                return ApiResponse.fail("您无权购买此内容！");
            }
            // promo code
            order.setPayPrice(priceObj.getPrice());
            order.setPayPrice(order.getPayPrice().subtract(order.getCouponPrice()));
            if (order.getPayPrice().compareTo(BigDecimal.ZERO) < NumberConstant.ZERO) {
                // 至少需要支付0.01
                order.setPayPrice(BigDecimal.valueOf(0.01));
            }
            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());
            }
        }
        // coupon
        CouponRecordQueryResp couponRecord = null;
        switch (createOrderReqVO.getGoodsType()) {
            case 0: // vlog
                VideoEntity video = videoRepository.getVideo(createOrderReqVO.getGoodsId());
                TaskEntity taskById = videoTaskRepository.getTaskById(video.getTaskId());
                if (taskById != null) {
                    couponRecord = couponBiz.queryUserCouponRecord(order.getScenicId(), userId, order.getFaceId(), taskById.getTemplateId().toString());
                }
                break;
            case 1:
            case 2:
                couponRecord = couponBiz.queryUserCouponRecord(order.getScenicId(), userId, order.getFaceId(), String.valueOf(createOrderReqVO.getGoodsType()));
                break;
        }
        order.setCouponPrice(BigDecimal.ZERO);
        order.setCouponRecordId(null);
        order.setCouponId(null);
        if (couponRecord != null) {
            if (couponRecord.isUsable()) {
                order.setCouponId(couponRecord.getCouponId());
                order.setCouponRecordId(couponRecord.getId());
                order.setCouponPrice(couponRecord.getCoupon().calculateDiscountPrice(order.getPrice()));
            }
        }
        List<OrderItemEntity> orderItems = new ArrayList<>();
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setGoodsId(createOrderReqVO.getGoodsId());
        orderItem.setGoodsType(createOrderReqVO.getGoodsType());
        orderItem.setOrderId(order.getId());
        orderItems.add(orderItem);
        if (!haveOldOrder) {
            orderMapper.add(order);
            int addOrderItems = orderMapper.addOrderItems(orderItems);
            if (addOrderItems == NumberConstant.ZERO) {
                log.error("订单明细添加失败");
                return ApiResponse.fail("订单添加失败");
            }
        } else {
            orderMapper.updateOrderPrice(order);
        }
        if (order.getPayPrice().compareTo(BigDecimal.ZERO) <= 0) {
            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
    @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("您无权购买此内容！");
        }
        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.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);
            if (Long.valueOf(1L).equals(goods.getGoodsId())) {
                orderItem.setGoodsId(batchOrderReqVO.getFaceId());
                orderItem.setGoodsType(1);
            } else if (Long.valueOf(2L).equals(goods.getGoodsId())) {
                orderItem.setGoodsId(batchOrderReqVO.getFaceId());
                orderItem.setGoodsType(2);
            } else {
                // templateId
                orderItem.setGoodsId(goods.getGoodsId());
                orderItem.setGoodsType(-1);
            }
            return orderItem;
        }).collect(Collectors.toList());
        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;
    }

}
