package com.erp.warehouse.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.Builder;

import java.time.LocalDateTime;

/**
 * 库存实体（ERP本地库存）
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@TableName("stock")
public class Stock {

    @TableId(type = IdType.AUTO)
    private Long id;

    /** SKU编码 */
    private String skuCode;

    /** SKU名称 */
    private String skuName;

    /** 仓库ID */
    private Long warehouseId;

    /** 总库存数量 */
    private Integer quantity;

    /** 锁定数量（审核中订单占用） */
    private Integer lockedQuantity;

    /** 预扣数量（冻结库存，两阶段模式） */
    private Integer reservedQuantity;

    /** 残次品数量 */
    private Integer defectiveQuantity;

    /** 预警阈值 */
    private Integer warningThreshold;

    /** 版本号（乐观锁） */
    private Integer version;

    /** 创建时间 */
    private LocalDateTime createTime;

    /** 更新时间 */
    private LocalDateTime updateTime;

    /**
     * 计算可用库存
     * 可用库存 = 总库存 - 锁定 - 预扣 - 残次
     */
    public int getAvailableQuantity() {
        int locked = lockedQuantity != null ? lockedQuantity : 0;
        int reserved = reservedQuantity != null ? reservedQuantity : 0;
        int defective = defectiveQuantity != null ? defectiveQuantity : 0;
        int qty = quantity != null ? quantity : 0;
        return qty - locked - reserved - defective;
    }

    /**
     * 是否低于预警
     */
    public boolean isLowStock() {
        return getAvailableQuantity() <= (warningThreshold != null ? warningThreshold : 0);
    }
}
