package com.ffii.fpsms.modules.deliveryOrder.web

import com.ffii.core.response.RecordsRes
import com.ffii.core.utils.CriteriaArgsBuilder
import com.ffii.core.utils.PagingUtils
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrder
import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.pickOrder.entity.PickOrderRepository
import com.ffii.fpsms.modules.pickOrder.entity.projection.PickOrderInfo
import com.ffii.fpsms.modules.pickOrder.service.PickOrderService
import com.ffii.fpsms.modules.pickOrder.web.models.*
import com.ffii.fpsms.modules.pickOrder.web.models.ConsoPickOrderRequest
import com.ffii.fpsms.modules.pickOrder.web.models.ConsoPickOrderResponse
import com.ffii.fpsms.modules.pickOrder.web.models.ReleaseConsoPickOrderRequest
import com.ffii.fpsms.modules.pickOrder.web.models.SearchPickOrderRequest
import com.ffii.fpsms.modules.deliveryOrder.web.models.DoDetailResponse
import com.ffii.fpsms.modules.pickOrder.web.models.SavePickOrderGroupRequest
import jakarta.servlet.http.HttpServletRequest
import jakarta.validation.Valid
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.time.DateTimeException
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.LocalDate
import com.ffii.fpsms.modules.deliveryOrder.service.DoPickOrderService
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrderRepository
import com.ffii.fpsms.modules.deliveryOrder.web.models.AssignByStoreRequest
import com.ffii.fpsms.modules.deliveryOrder.web.models.*
import org.springframework.format.annotation.DateTimeFormat
import com.ffii.fpsms.modules.deliveryOrder.service.DoReleaseCoordinatorService
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrderLineRepository
import com.ffii.fpsms.modules.deliveryOrder.service.DoPickOrderQueryService
import com.ffii.fpsms.modules.deliveryOrder.service.DoPickOrderAssignmentService
@RestController
@RequestMapping("/doPickOrder")
class DoPickOrderController(
    private val doPickOrderService: DoPickOrderService,
    private val doPickOrderRepository: DoPickOrderRepository,
    private val doReleaseCoordinatorService: DoReleaseCoordinatorService,
    private val doPickOrderLineRepository: DoPickOrderLineRepository,
    private val doPickOrderQueryService: DoPickOrderQueryService,
    private val doPickOrderAssignmentService: DoPickOrderAssignmentService,
    private val pickOrderService: PickOrderService,
) {
    @PostMapping("/assign-by-store")
    fun assignPickOrderByStore(@RequestBody request: AssignByStoreRequest): MessageResponse {
        return doPickOrderService.assignByStore(request)
    }
    
    @PostMapping("/release-assigned-by-store")  
    fun releaseAssignedPickOrderByStore(@RequestBody request: AssignByStoreRequest): MessageResponse {
        return doPickOrderService.releaseAssignedByStore(request)
    }
/*
    @GetMapping("/released")
    fun getReleasedDoPickOrders(): List<DoPickOrder> {
        return doPickOrderService.findReleasedDoPickOrders()
    }
        */

        @GetMapping("/released")
        fun getReleasedDoPickOrders(
            @RequestParam(required = false) shopName: String?,
            @RequestParam(required = false) storeId: String?,
            @RequestParam(required = false) truck: String?
        ): List<ReleasedDoPickOrderListItem> {
            return doPickOrderService.findReleasedDoPickOrdersForSelection(shopName, storeId, truck)
        }
        @GetMapping("/released-today")
        fun getReleasedDoPickOrdersToday(
            @RequestParam(required = false) shopName: String?,
            @RequestParam(required = false) storeId: String?,
            @RequestParam(required = false) truck: String?
        ): List<ReleasedDoPickOrderListItem> {
            return doPickOrderService.findReleasedDoPickOrdersForSelectionToday(shopName, storeId, truck)
        }
        
        @PostMapping("/assign-by-id")
        fun assignByDoPickOrderId(@RequestBody request: AssignByDoPickOrderIdRequest): MessageResponse {
            return doReleaseCoordinatorService.assignByDoPickOrderId(request)  // 改用 doReleaseCoordinatorService
        }
    @GetMapping("/summary-by-store")
    fun getSummaryByStore(
        @RequestParam storeId: String,
        @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) requiredDate: LocalDate?,
        @RequestParam releaseType: String?
    ): StoreLaneSummary {
        return doPickOrderQueryService.getSummaryByStore(storeId, requiredDate, releaseType?: "ALL")
    }
    @PostMapping("/assign-by-lane")
    fun assignByLane(@RequestBody request: AssignByLaneRequest): MessageResponse {
        return doPickOrderAssignmentService.assignByLane(request)  //  使用新的 Service
    }
    
    @PostMapping("/batch-release/async")
    fun startBatchReleaseAsync(
        @RequestBody ids: List<Long>,
        @RequestParam(defaultValue = "1") userId: Long
    ): MessageResponse {
        return doReleaseCoordinatorService.startBatchReleaseAsync(ids, userId)
    }
    @PostMapping("/batch-release/async-single")
    fun startBatchReleaseAsyncSingle(    @RequestBody doId: Long,  @RequestParam(defaultValue = "1") userId: Long
    ): MessageResponse {
        return doReleaseCoordinatorService.startBatchReleaseAsyncSingle(doId, userId)
    }
    @GetMapping("/batch-release/progress/{jobId}")
    fun getBatchReleaseProgress(@PathVariable jobId: String): MessageResponse {
        return doReleaseCoordinatorService.getBatchReleaseProgress(jobId)
    }

    @GetMapping("/ticket-release-table/{startDate}&{endDate}")
    fun getTicketReleaseTable(
        @PathVariable startDate: LocalDate,
        @PathVariable endDate: LocalDate
    ): List<TicketReleaseTableResponse> {
        return doPickOrderService.getTicketReleaseTable(startDate, endDate)
    }

    @GetMapping("/truck-schedule-dashboard")
    fun getTruckScheduleDashboard(
        @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) date: LocalDate?
    ): List<TruckScheduleDashboardResponse> {
        return doPickOrderService.getTruckScheduleDashboard(date ?: LocalDate.now())
    }

    /** 強制完成仍處於進行中的 do_pick_order（僅改狀態，不調整已揀數量） */
    @PostMapping("/force-complete/{doPickOrderId}")
    fun forceCompleteDoPickOrder(@PathVariable doPickOrderId: Long): MessageResponse {
        return pickOrderService.forceCompleteDoPickOrder(doPickOrderId)
    }

    /** 撤銷使用者領取，使單據可再次分配 */
    @PostMapping("/revert-assignment/{doPickOrderId}")
    fun revertDoPickOrderAssignment(@PathVariable doPickOrderId: Long): MessageResponse {
        return doPickOrderService.revertUserAssignment(doPickOrderId)
    }

}