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

import net.sf.jasperreports.engine.*
import org.springframework.http.*
import org.springframework.web.bind.annotation.*
import java.time.LocalDate
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import com.ffii.fpsms.modules.report.service.ItemQcFailReportService
import com.ffii.fpsms.modules.report.service.ReportService

@RestController
@RequestMapping("/report")
class ItemQcFailReportController(

    private val reportService: ReportService,
    private val itemQcFailReportService: ItemQcFailReportService,
) {

    @GetMapping("/print-item-qc-fail")
    fun generateItemQcFailReport(
        @RequestParam(required = false) stockCategory: String?,
        @RequestParam(required = false) itemCode: String?,
        @RequestParam(required = false) lastInDateStart: String?,
        @RequestParam(required = false) lastInDateEnd: String?,
    ): ResponseEntity<ByteArray> {
        val parameters = mutableMapOf<String, Any>()

        parameters["stockCategory"] = stockCategory ?: "All"
        parameters["stockSubCategory"] = stockCategory ?: "All" // 你定义 stock sub category = items.type
        parameters["itemNo"] = itemCode ?: "All"
        parameters["year"] = java.time.LocalDate.now().year.toString()
        parameters["reportDate"] = java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"))
        parameters["reportTime"] = java.time.LocalTime.now().format(java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss"))

        // jrxml 里有这些参数，先给空
        parameters["storeLocation"] = ""
        parameters["balanceFilterStart"] = ""
        parameters["balanceFilterEnd"] = ""
        parameters["lastInDateStart"] = lastInDateStart ?: ""
        parameters["lastInDateEnd"] = lastInDateEnd ?: ""
        parameters["lastOutDateStart"] = ""
        parameters["lastOutDateEnd"] = ""

        val dbData = itemQcFailReportService.searchItemQcFailReport(
            stockCategory = stockCategory,
            itemCode = itemCode,
            lastInDateStart = lastInDateStart,
            lastInDateEnd = lastInDateEnd,
        )

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

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


