package com.fs.erp.dto.sdk.wangdian.enums;

public enum TradeStatus {

    UNCONFIRMED(10, "未确认"),
    WAITING_FOR_FINAL_PAYMENT(20, "待尾款"),
    PAID_WAITING_FOR_SHIPMENT(30, "已付款待发货"),
    PARTIALLY_SHIPPED(40, "部分发货"),
    SHIPPED(50, "已发货"),
    COMPLETED(70, "已完成"),
    REFUNDED(80, "已退款"),
    CLOSED(90, "已关闭");

    private final int value;
    private final String description;

    TradeStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }

    public int getValue() {
        return value;
    }

    public String getDescription() {
        return description;
    }

    /**
     * 检查状态是否可以更新到新的状态
     * @param newStatus 新的状态
     * @return 是否可以更新
     */
    public boolean canUpdateTo(TradeStatus newStatus) {
        // 状态值仅限从小向大更新，不支持逆向更新
        if (this.value >= newStatus.value) {
            return false;
        }

        // 特殊规则：30 只能变更为 70 或 80
        if (this == PAID_WAITING_FOR_SHIPMENT &&
            newStatus != COMPLETED && newStatus != REFUNDED) {
            return false;
        }

        //已发货状态，在自建商城可以直接到完成状态70
        if(this == SHIPPED && newStatus == COMPLETED){
            return  true;
        }

        return true;
    }

     /**
     * 根据状态值获取枚举实例
     *
     * @param value 状态值
     * @return 对应的枚举实例，如果找不到则返回 null
     */
    public static TradeStatus fromValue(int value) {
        for (TradeStatus status : TradeStatus.values()) {
            if (status.value == value) {
                return status;
            }
        }
        return null;
    }
}
