package com.starry.admin.modules.order.module.dto;

import com.starry.admin.modules.order.module.constant.OrderConstant;
import com.starry.admin.modules.order.module.constant.OrderConstant.OrderActor;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Data;
import org.springframework.lang.Nullable;

/**
 * 订单创建上下文，用于聚合下单所需的全部信息。
 */
@Data
@Builder
public class OrderCreationContext {

    @NotBlank(message = "订单ID不能为空")
    private String orderId;

    @NotBlank(message = "订单编号不能为空")
    private String orderNo;

    @NotNull(message = "订单状态不能为空")
    private OrderConstant.OrderStatus orderStatus;

    @NotNull(message = "订单类型不能为空")
    private OrderConstant.OrderType orderType;

    @NotNull(message = "下单类型不能为空")
    private OrderConstant.PlaceType placeType;

    private OrderConstant.RewardType rewardType;

    private boolean isFirstOrder;

    private OrderConstant.PaymentSource paymentSource;

    private String sourceRewardId;

    @Valid
    @NotNull(message = "商品信息不能为空")
    private CommodityInfo commodityInfo;

    @Valid
    @NotNull(message = "支付信息不能为空")
    private PaymentInfo paymentInfo;

    @NotBlank(message = "下单人不能为空")
    private String purchaserBy;

    private String acceptBy;

    private String weiChatCode;

    private String remark;

    private RandomOrderRequirements randomOrderRequirements;

    @Builder.Default
    private OrderActor creatorActor = OrderActor.SYSTEM;

    @Nullable
    private String creatorId;

    public String getFirstOrderString() {
        return isFirstOrder ? "1" : "0";
    }

    public boolean isValidForRandomOrder() {
        return placeType == OrderConstant.PlaceType.RANDOM && randomOrderRequirements != null;
    }

    public boolean isRewardOrder() {
        return placeType == OrderConstant.PlaceType.REWARD;
    }

    public boolean isSpecifiedOrder() {
        return placeType == OrderConstant.PlaceType.SPECIFIED;
    }

    public OrderConstant.PaymentSource resolvePaymentSource() {
        if (paymentSource != null) {
            return paymentSource;
        }
        return paymentInfo != null && paymentInfo.getPaymentSource() != null
                ? paymentInfo.getPaymentSource()
                : OrderConstant.PaymentSource.BALANCE;
    }
}
