// 创建 StockTakeRecordRepository.kt
package com.ffii.fpsms.modules.stock.entity

import com.ffii.core.support.AbstractRepository
import org.springframework.stereotype.Repository
import java.io.Serializable
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import java.time.LocalDate
@Repository
interface StockTakeRecordRepository : AbstractRepository<StockTakeRecord, Long> {
    fun findAllByStockTakeIdAndDeletedIsFalse(stockTakeId: Long): List<StockTakeRecord>;
    fun findAllByStockTakeIdInAndDeletedIsFalse(stockTakeIds: Collection<Long>): List<StockTakeRecord>;
    fun findAllByStockTakeRoundIdAndDeletedIsFalse(stockTakeRoundId: Long): List<StockTakeRecord>;
    fun findAllByStockTakeRoundIdInAndDeletedIsFalse(stockTakeRoundIds: Collection<Long>): List<StockTakeRecord>;
    fun findByIdAndDeletedIsFalse(id: Serializable): StockTakeRecord?;
    fun findAllByStockTakeIdAndWarehouseIdInAndDeletedIsFalse(
        stockTakeId: Long,
        warehouseIds: Collection<Long>
    ): List<StockTakeRecord>

    @Query(
        """
        SELECT r
        FROM StockTakeRecord r
        WHERE r.deleted = false
          AND r.stockTake.id = :stockTakeId
          AND r.stockTakeSection = :stockTakeSection
          AND r.approverStockTakeQty IS NULL
          AND (r.pickerFirstStockTakeQty IS NOT NULL OR r.pickerSecondStockTakeQty IS NOT NULL)
        """
    )
    fun findPendingApproverRecordsByStockTakeAndSection(
        @Param("stockTakeId") stockTakeId: Long,
        @Param("stockTakeSection") stockTakeSection: String
    ): List<StockTakeRecord>

    @Query("""
    SELECT sl FROM StockLedger sl
    LEFT JOIN sl.stockInLine sil
    LEFT JOIN sl.stockOutLine sol
    LEFT JOIN sl.inventory inv
    LEFT JOIN inv.item i
    WHERE sl.deleted = false
      AND (:itemCode IS NULL OR sl.itemCode LIKE CONCAT('%', :itemCode, '%'))
      AND (:itemName IS NULL OR i.name LIKE CONCAT('%', :itemName, '%'))
      AND (:type IS NULL OR sl.type = :type)
      AND (:startDate IS NULL OR DATE(sl.created) >= :startDate)
      AND (:endDate IS NULL OR DATE(sl.created) <= :endDate)
    ORDER BY COALESCE(sl.date, DATE(sl.created)) ASC, sl.created ASC, sl.itemId
""")
    fun countStockTakeRecordsBySectionAndStockTakeId(): List<Array<Any>>




}

