package com.ffii.fpsms.modules.report.web

import com.ffii.fpsms.modules.report.service.ReportService
import com.ffii.fpsms.modules.report.service.StockTakeVarianceReportService
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.time.LocalDate
import java.time.LocalTime
import java.time.format.DateTimeFormatter

@RestController
@RequestMapping("/report")
class StockTakeVarianceReportController(
    private val reportService: ReportService,
    private val stockTakeVarianceReportService: StockTakeVarianceReportService,
) {

    /**
     * 產生 Stock Take Variance 報表 PDF
     *
     * 查詢條件與 Stock Ledger 報表保持一致：
     * - stockCategory
     * - itemCode
     * - storeLocation
     * - stockTakeDateStart / stockTakeDateEnd
     */
    @GetMapping("/print-stock-take-variance")
    fun generateStockTakeVarianceReport(
        @RequestParam(required = false) stockCategory: String?,
        @RequestParam(required = false) itemCode: String?,
        @RequestParam(required = false) storeLocation: String?,
        @RequestParam(required = false) stockTakeDateStart: String?,
        @RequestParam(required = false) stockTakeDateEnd: String?,
    ): ResponseEntity<ByteArray> {
        val parameters = mutableMapOf<String, Any>()

        parameters["stockCategory"] = stockCategory ?: "All"
        parameters["stockSubCategory"] = stockCategory ?: "All"
        parameters["itemNo"] = itemCode ?: "All"
        parameters["year"] = LocalDate.now().year.toString()
        parameters["reportDate"] = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
        parameters["reportTime"] = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"))

        parameters["storeLocation"] = storeLocation ?: ""
        parameters["balanceFilterStart"] = ""
        parameters["balanceFilterEnd"] = ""

        parameters["stockTakeDateStart"] = stockTakeDateStart ?: ""
        parameters["stockTakeDateEnd"] = stockTakeDateEnd ?: ""
        parameters["lastInDateEnd"] = ""
        parameters["lastOutDateEnd"] = ""



        val dbData = stockTakeVarianceReportService.searchStockTakeVarianceReport(
            stockCategory = stockCategory,
            itemCode = itemCode,
            storeLocation = storeLocation,
            stockTakeDateStart = stockTakeDateStart,
            stockTakeDateEnd = stockTakeDateEnd,
        )
        val stockTakeDateDisplay = dbData
            .mapNotNull { it["stockTakeDate"] as? String }
            .filter { it.isNotBlank() }
            .maxOrNull()
            ?: ""

        parameters["stockTakeDate"] = stockTakeDateDisplay

        parameters["stockTakeFilterCaption"] = ""

        val pdfBytes = reportService.createPdfResponse(
            "/jasper/StockTakeVarianceReport.jrxml",
            parameters,
            dbData
        )

        val headers = HttpHeaders().apply {
            contentType = MediaType.APPLICATION_PDF
            setContentDispositionFormData("attachment", "StockTakeVarianceReport.pdf")
            set("filename", "StockTakeVarianceReport.pdf")
        }
        return ResponseEntity(pdfBytes, headers, HttpStatus.OK)
    }

    /**
     * Stock Take Variance 報表 V2：依盤點輪次 + 可選物料編號；僅含已有已完成盤點紀錄之列；審核時間為 approver 之日期時間。
     */
    @GetMapping("/print-stock-take-variance-v2")
    fun generateStockTakeVarianceReportV2(
        @RequestParam stockTakeRoundId: Long,
        @RequestParam(required = false) itemCode: String?,
    ): ResponseEntity<ByteArray> {
        val parameters = mutableMapOf<String, Any>()

        parameters["stockCategory"] = "All"
        parameters["stockSubCategory"] = "All"
        parameters["itemNo"] = itemCode ?: "All"
        parameters["year"] = LocalDate.now().year.toString()
        parameters["reportDate"] = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
        parameters["reportTime"] = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"))

        parameters["storeLocation"] = ""
        parameters["balanceFilterStart"] = ""
        parameters["balanceFilterEnd"] = ""

        parameters["stockTakeDateStart"] = ""
        parameters["stockTakeDateEnd"] = ""
        parameters["lastInDateEnd"] = ""
        parameters["lastOutDateEnd"] = ""

        parameters["stockTakeFilterCaption"] =
            stockTakeVarianceReportService.getStockTakeRoundCaption(stockTakeRoundId)
        parameters["stockTakeConditionLabel"] = "盤點輪次："

        val dbData = stockTakeVarianceReportService.searchStockTakeVarianceReportV2(
            stockTakeRoundId = stockTakeRoundId,
            itemCode = itemCode,
        )
        val stockTakeDateDisplay = dbData
            .mapNotNull { it["stockTakeDate"] as? String }
            .filter { it.isNotBlank() }
            .maxOrNull()
            ?: ""

        parameters["stockTakeDate"] = stockTakeDateDisplay

        val pdfBytes = reportService.createPdfResponse(
            "/jasper/StockTakeVarianceReport.jrxml",
            parameters,
            dbData
        )

        val headers = HttpHeaders().apply {
            contentType = MediaType.APPLICATION_PDF
            setContentDispositionFormData("attachment", "StockTakeVarianceReport.pdf")
            set("filename", "StockTakeVarianceReport.pdf")
        }
        return ResponseEntity(pdfBytes, headers, HttpStatus.OK)
    }
}

