package com.erp.inventory.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;

import java.time.LocalDateTime;

/**
 * 库存实体
 * 对应PHP Stock模型
 * 
 * @author ERP Migration
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@EqualsAndHashCode(callSuper = false)
@TableName("stocks")
public class Stock {

    /**
     * 主键ID
     */
    @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;

    /**
     * 创建时间
     */
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createdAt;

    /**
     * 更新时间
     */
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updatedAt;

    // ==================== 计算字段（Java中通过方法实现） ====================

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

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

    /**
     * 计算缺货量（预警阈值 - 可用库存）
     */
    public Integer getDeficit() {
        int available = getAvailableQuantity();
        int threshold = warningThreshold != null ? warningThreshold : 0;
        return Math.max(0, threshold - available);
    }
}
