package com.starry.admin.modules.weichat.service;

import com.starry.admin.common.conf.ThreadLocalRequestDetail;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.custom.service.IPlayCustomGiftInfoService;
import com.starry.admin.modules.custom.service.IPlayCustomUserInfoService;
import com.starry.admin.modules.order.module.constant.OrderConstant;
import com.starry.admin.modules.order.module.constant.OrderConstant.OrderActor;
import com.starry.admin.modules.order.module.constant.OrderConstant.RewardType;
import com.starry.admin.modules.order.module.dto.CommodityInfo;
import com.starry.admin.modules.order.module.dto.OrderCreationContext;
import com.starry.admin.modules.order.module.dto.OrderPlacementCommand;
import com.starry.admin.modules.order.module.dto.OrderPlacementResult;
import com.starry.admin.modules.order.module.dto.PaymentInfo;
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
import com.starry.admin.modules.order.service.IOrderLifecycleService;
import com.starry.admin.modules.order.service.IPlayOrderInfoService;
import com.starry.admin.modules.shop.module.entity.PlayGiftInfoEntity;
import com.starry.admin.modules.shop.service.IPlayClerkGiftInfoService;
import com.starry.admin.modules.shop.service.IPlayGiftInfoService;
import com.starry.admin.modules.weichat.entity.PlayOrderInfoGiftAdd;
import com.starry.common.utils.IdUtils;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Objects;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 微信礼物订单服务，负责处理顾客赠送礼物的事务逻辑。
 */
@Service
public class WxGiftOrderService {

    @Resource
    private IPlayGiftInfoService giftInfoService;

    @Resource
    private IPlayOrderInfoService playOrderInfoService;

    @Resource
    private IOrderLifecycleService orderLifecycleService;

    @Resource
    private IPlayCustomUserInfoService customUserInfoService;

    @Resource
    private IPlayCustomGiftInfoService playCustomGiftInfoService;

    @Resource
    private IPlayClerkGiftInfoService playClerkGiftInfoService;

    /**
     * 创建礼物订单并处理余额与礼物计数。
     *
     * @param request 礼物下单请求
     * @return 生成的订单ID
     */
    @Transactional(rollbackFor = Exception.class)
    public String createGiftOrder(PlayOrderInfoGiftAdd request) {
        PlayCustomUserInfoEntity sessionUser = ThreadLocalRequestDetail.getCustomUserInfo();
        if (sessionUser == null || sessionUser.getId() == null) {
            throw new CustomException("用户未登录");
        }
        PlayCustomUserInfoEntity customUserInfo = customUserInfoService.selectById(sessionUser.getId());
        if (customUserInfo == null) {
            throw new CustomException("用户不存在");
        }

        PlayGiftInfoEntity giftInfo = giftInfoService.selectPlayGiftInfoById(request.getGiftId());
        BigDecimal unitPrice = Objects.requireNonNull(giftInfo.getPrice(), "礼物价格未配置");
        int giftQuantity = request.getGiftQuantity();
        if (giftQuantity <= 0) {
            throw new CustomException("礼物数量必须大于0");
        }

        BigDecimal totalAmount = unitPrice.multiply(BigDecimal.valueOf(giftQuantity));
        if (totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new CustomException("礼物金额必须大于0");
        }

        String orderId = IdUtils.getUuid();
        OrderCreationContext orderRequest = buildOrderCreationContext(orderId, request, sessionUser.getId(),
                giftInfo, totalAmount);
        OrderPlacementResult result = orderLifecycleService.placeOrder(OrderPlacementCommand.builder()
                .orderContext(orderRequest)
                .balanceOperationAction("赠送礼物")
                .build());
        PlayOrderInfoEntity order = result.getOrder();

        String tenantId = customUserInfo.getTenantId();
        long delta = giftQuantity;
        playCustomGiftInfoService.incrementGiftCount(customUserInfo.getId(), request.getGiftId(), tenantId, delta);
        playClerkGiftInfoService.incrementGiftCount(request.getClerkId(), request.getGiftId(), tenantId, delta);

        return order.getId();
    }

    private OrderCreationContext buildOrderCreationContext(String orderId, PlayOrderInfoGiftAdd request,
                                                           String purchaserId, PlayGiftInfoEntity giftInfo,
                                                           BigDecimal totalAmount) {
        return OrderCreationContext.builder()
                .orderId(orderId)
                .orderNo(playOrderInfoService.getOrderNo())
                .orderStatus(OrderConstant.OrderStatus.COMPLETED)
                .orderType(OrderConstant.OrderType.NORMAL)
                .placeType(OrderConstant.PlaceType.REWARD)
                .rewardType(RewardType.GIFT)
                .isFirstOrder(true)
                .creatorActor(OrderActor.CUSTOMER)
                .creatorId(purchaserId)
                .commodityInfo(CommodityInfo.builder()
                        .commodityId(giftInfo.getId())
                        .commodityType(OrderConstant.CommodityType.GIFT)
                        .commodityPrice(giftInfo.getPrice())
                        .serviceDuration("")
                        .commodityName(giftInfo.getName())
                        .commodityNumber(String.valueOf(request.getGiftQuantity()))
                        .build())
                .paymentInfo(PaymentInfo.builder()
                        .orderMoney(totalAmount)
                        .finalAmount(totalAmount)
                        .discountAmount(BigDecimal.ZERO)
                        .couponIds(Collections.emptyList())
                        .build())
                .purchaserBy(purchaserId)
                .acceptBy(request.getClerkId())
                .weiChatCode(request.getWeiChatCode())
                .remark(request.getRemark())
                .build();
    }
}
