package com.ffii.fpsms.modules.deliveryOrder.service

import com.ffii.core.support.JdbcDao
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrderRepository
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrderLineRepository
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrderRecordRepository
import com.ffii.fpsms.modules.deliveryOrder.enums.DoPickOrderStatus
import com.ffii.fpsms.modules.deliveryOrder.web.models.AssignByLaneRequest
import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.pickOrder.entity.PickOrderRepository
import com.ffii.fpsms.modules.pickOrder.enums.PickOrderStatus
import com.ffii.fpsms.modules.user.entity.UserRepository
import org.springframework.stereotype.Service
import java.time.LocalDateTime
import java.time.LocalDate
import java.time.LocalTime
@Service
class DoPickOrderAssignmentService(
    private val doPickOrderRepository: DoPickOrderRepository,
    private val doPickOrderLineRepository: DoPickOrderLineRepository,
    private val doPickOrderRecordRepository: DoPickOrderRecordRepository,
    private val pickOrderRepository: PickOrderRepository,
    private val userRepository: UserRepository,
    private val jdbcDao: JdbcDao  //  添加 JdbcDao
) {
    
    fun assignByLane(request: AssignByLaneRequest): MessageResponse {
        val user = userRepository.findById(request.userId).orElse(null)
            ?: return MessageResponse(
                id = null, code = "USER_NOT_FOUND", name = null, type = null,
                message = "User not found", errorPosition = null, entity = null
            )
        
        //  转换 storeId 格式
        val actualStoreId = when (request.storeId) {
            "2/F" -> "2/F"
            "4/F" -> "4/F"
            else -> request.storeId
        }
        println("    DEBUG: assignByLane - Converting storeId from '${request.storeId}' to '$actualStoreId'")
        
        //  获取日期（如果提供）
        val requiredDate = request.requiredDate
        println("    DEBUG: assignByLane - Requested date: $requiredDate")
        val requestedDepartureTime: LocalTime? = request.truckDepartureTime
            ?.takeIf { it.isNotBlank() }
            ?.let {
                try {
                    LocalTime.parse(it)
                } catch (e: Exception) {
                    null
                }
            }
        
        //  根据是否有日期参数选择不同的查询方法
        val allCandidates = if (requiredDate != null) {
            println("    DEBUG: Filtering by date: $requiredDate")
            doPickOrderRepository.findByStoreIdAndRequiredDeliveryDateAndTicketStatusIn(
                actualStoreId,
                requiredDate,
                listOf(DoPickOrderStatus.pending)
            )
        } else {
            println("    DEBUG: No date filter applied")
            doPickOrderRepository.findByStoreIdAndTicketStatusOrderByTruckDepartureTimeAsc(
                actualStoreId,
                DoPickOrderStatus.pending
            )
        }
            .filter { it.truckLanceCode == request.truckLanceCode }
            .let { candidates ->
                requestedDepartureTime?.let { dep ->
                    candidates.filter { it.truckDepartureTime == dep }
                } ?: candidates
            }
            .let { candidates ->
                request.loadingSequence?.let { seq ->
                    candidates.filter { it.loadingSequence == seq }
                } ?: candidates
            }
            .sortedBy { it.truckDepartureTime }
        
        println("    DEBUG: Found ${allCandidates.size} candidate do_pick_orders for lane ${request.truckLanceCode}")
        
        //  过滤掉所有 pick orders 都是 issue 的记录
        val filteredCandidates = allCandidates.filter { doPickOrder ->
            val hasNonIssueLines = checkDoPickOrderHasNonIssueLines(doPickOrder.id!!)
            if (!hasNonIssueLines) {
                println("    DEBUG: Filtering out DoPickOrder ${doPickOrder.id} - all lines are issues")
            }
            hasNonIssueLines
        }
        
        println("    DEBUG: After filtering, ${filteredCandidates.size} do_pick_orders remain")
        
        if (filteredCandidates.isEmpty()) {
            return MessageResponse(
                id = null, code = "NO_ORDERS", name = null, type = null,
                message = "No available pick order(s) for this lane (all have stock issues).", 
                errorPosition = null, entity = null
            )
        }
        
        val firstOrder = filteredCandidates.first()
        
        //  更新 do_pick_order
        firstOrder.handledBy = request.userId
        firstOrder.handlerName = user.name
        firstOrder.ticketStatus = DoPickOrderStatus.released
        firstOrder.ticketReleaseTime = LocalDateTime.now()
        doPickOrderRepository.save(firstOrder)
        
        //  获取这个 do_pick_order 下的所有 pick orders 并分配给用户
        val doPickOrderLines = doPickOrderLineRepository.findByDoPickOrderIdAndDeletedFalse(firstOrder.id!!)
        println("    DEBUG: Found ${doPickOrderLines.size} pick orders in do_pick_order ${firstOrder.id}")
        
        doPickOrderLines.forEach { line ->
            if (line.pickOrderId != null) {
                val pickOrder = pickOrderRepository.findById(line.pickOrderId!!).orElse(null)
                if (pickOrder != null) {
                    pickOrder.assignTo = user
                    pickOrder.status = PickOrderStatus.RELEASED
                    pickOrderRepository.save(pickOrder)
                    println("    DEBUG: Assigned pick order ${line.pickOrderId} to user ${request.userId}")
                } else {
                    println("⚠️ WARNING: Pick order ${line.pickOrderId} not found")
                }
            }
        }
        
        //  同步更新 do_pick_order_record（如果有的话）
        doPickOrderLines.forEach { line ->
            if (line.pickOrderId != null) {
                val records = doPickOrderRecordRepository.findByPickOrderId(line.pickOrderId!!)
                records.forEach { record ->
                    record.handledBy = request.userId
                    record.handlerName = user.name
                    record.ticketStatus = DoPickOrderStatus.released
                    record.ticketReleaseTime = LocalDateTime.now()
                }
                if (records.isNotEmpty()) {
                    doPickOrderRecordRepository.saveAll(records)
                    println("    DEBUG: Updated ${records.size} do_pick_order_record for pick order ${line.pickOrderId}")
                }
            }
        }
        
        return MessageResponse(
            id = firstOrder.id,
            code = "SUCCESS",
            name = null,
            type = null,
            message = "Assigned ${doPickOrderLines.size} pick order(s) from lane ${request.truckLanceCode}",
            errorPosition = null,
            entity = mapOf(
                "doPickOrderId" to firstOrder.id,
                "ticketNo" to firstOrder.ticketNo,
                "numberOfPickOrders" to doPickOrderLines.size,
                "pickOrderIds" to doPickOrderLines.mapNotNull { it.pickOrderId }
            )
        )
    }
    
    //  添加过滤方法（和 DoPickOrderQueryService 中相同的逻辑）
    private fun checkDoPickOrderHasNonIssueLines(doPickOrderId: Long): Boolean {
        return try {
            val totalLinesSql = """
                SELECT COUNT(*) as total_lines
                FROM fpsmsdb.do_pick_order_line dpol
                WHERE dpol.do_pick_order_id = :doPickOrderId 
                AND dpol.deleted = 0
            """.trimIndent()
            
            val totalLinesResult = jdbcDao.queryForList(totalLinesSql, mapOf("doPickOrderId" to doPickOrderId))
            val totalLines = (totalLinesResult.firstOrNull()?.get("total_lines") as? Number)?.toInt() ?: 0
            
            if (totalLines == 0) {
                return true  // 没有 lines，不算过滤
            }
            
            val nonIssueLinesSql = """
                SELECT COUNT(*) as non_issue_lines
                FROM fpsmsdb.do_pick_order_line dpol
                WHERE dpol.do_pick_order_id = :doPickOrderId 
                AND dpol.deleted = 0
                AND (dpol.status IS NULL OR dpol.status != 'issue')
            """.trimIndent()
            
            val nonIssueLinesResult = jdbcDao.queryForList(nonIssueLinesSql, mapOf("doPickOrderId" to doPickOrderId))
            val nonIssueLines = (nonIssueLinesResult.firstOrNull()?.get("non_issue_lines") as? Number)?.toInt() ?: 0
            
            val hasNonIssueLines = nonIssueLines > 0
            
            println("    DEBUG: DoPickOrder $doPickOrderId - Total lines: $totalLines, Non-issue lines: $nonIssueLines, Has non-issue lines: $hasNonIssueLines")
            
            hasNonIssueLines
            
        } catch (e: Exception) {
            println("❌ Error checking non-issue lines for do_pick_order $doPickOrderId: ${e.message}")
            true  // 出错时不过滤
        }
    }
}