package com.erp.warehouse.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.warehouse.entity.StockLog;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

/**
 * 库存流水日志Mapper
 */
@Mapper
public interface StockLogMapper extends BaseMapper<StockLog> {

    /**
     * 分页查询库存流水
     */
    @Select("SELECT sl.*, w.name as warehouse_name " +
            "FROM stock_log sl " +
            "LEFT JOIN warehouse w ON sl.warehouse_id = w.id " +
            "WHERE (#{skuCode} IS NULL OR sl.sku_code = #{skuCode}) " +
            "AND (#{warehouseId} IS NULL OR sl.warehouse_id = #{warehouseId}) " +
            "AND (#{changeType} IS NULL OR sl.change_type = #{changeType}) " +
            "AND (#{orderId} IS NULL OR sl.order_id = #{orderId}) " +
            "AND sl.create_time >= #{startDate} " +
            "AND sl.create_time <= #{endDate} " +
            "ORDER BY sl.create_time DESC")
    IPage<StockLog> selectLogsPage(Page<StockLog> page,
                                    @Param("skuCode") String skuCode,
                                    @Param("warehouseId") Long warehouseId,
                                    @Param("changeType") String changeType,
                                    @Param("orderId") Long orderId,
                                    @Param("startDate") String startDate,
                                    @Param("endDate") String endDate);

    /**
     * 查询预扣凭证对应的记录
     */
    @Select("SELECT * FROM stock_log WHERE remark LIKE CONCAT('%', #{reserveToken}, '%') " +
            "AND change_type = 'reserve' AND order_id = #{orderId} ORDER BY id DESC LIMIT 1")
    StockLog findByReserveToken(@Param("reserveToken") String reserveToken, @Param("orderId") Long orderId);
}
