package com.ffii.fpsms.modules.purchaseOrder.web

import com.ffii.core.response.RecordsRes
import com.ffii.core.support.JdbcDao
import com.ffii.core.utils.CriteriaArgsBuilder
import com.ffii.core.utils.ZebraPrinterUtil
import com.ffii.fpsms.modules.master.entity.Items
import com.ffii.fpsms.modules.master.service.ItemsService
import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.purchaseOrder.entity.PurchaseOrder
import com.ffii.fpsms.modules.purchaseOrder.entity.projections.PurchaseOrderDataClass
import com.ffii.fpsms.modules.purchaseOrder.entity.projections.PurchaseOrderInfo
import com.ffii.fpsms.modules.purchaseOrder.service.PurchaseOrderService
import com.ffii.fpsms.modules.purchaseOrder.web.model.PagingRequest
import com.ffii.fpsms.modules.stock.service.StockInLineService
import com.ffii.fpsms.modules.stock.web.model.ExportQrCodeRequest
import com.ffii.fpsms.modules.stock.web.model.SaveStockInLineRequest
import jakarta.servlet.http.HttpServletRequest
import net.sf.jasperreports.engine.JasperExportManager
import net.sf.jasperreports.engine.JasperPrint
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.web.bind.annotation.*
import java.io.File
import com.ffii.fpsms.modules.purchaseOrder.web.model.PurchaseOrderSummary
@RestController
@RequestMapping("/po")
class PurchaseOrderController(
    private val purchaseOrderService: PurchaseOrderService,
    private val stockInLineService: StockInLineService
) {
    @GetMapping("/list")
    fun getPoList(
        request: HttpServletRequest
//            @RequestParam(required = false) pageNum: Int,
//            @RequestParam(required = false) pageSize: Int
    ): RecordsRes<PurchaseOrderDataClass> {
//        println("request")
//        println(request)
        val criteriaArgs = CriteriaArgsBuilder.withRequest(request)
            .addStringLike("supplier")
            .addStringLike("code")
            .addString("status")
            .addBoolean("escalated")
            .addDate("orderDate")
            .addDate("orderDateTo")
            .addDate("estimatedArrivalDate")
            .addDate("estimatedArrivalDateTo")
            .build()
//        println(criteriaArgs)
        val pageSize = request.getParameter("pageSize")?.toIntOrNull()?.coerceAtLeast(1) ?: 10
        val pageNum = request.getParameter("pageNum")?.toIntOrNull()?.coerceAtLeast(1) ?: 1

        val total = purchaseOrderService.getPoListTotalCount(criteriaArgs)
        if (total == 0) {
            return RecordsRes(emptyList<PurchaseOrderDataClass>(), 0)
        }
        val pageRows = purchaseOrderService.getPoListPage(criteriaArgs, pageSize, pageNum)
        return RecordsRes(pageRows, total)
    }
    /** Class mapping is `/po`; path must be `/summary` → full path `/api/po/summary` (not `/po/po/summary`). */
    @GetMapping("/summary")
    fun getPoSummaries(
        @RequestParam ids: List<Long>
    ): List<PurchaseOrderSummary> {
        return purchaseOrderService.getPoSummariesByIds(ids)
    }

    @GetMapping("/testing")
    fun testing(request: HttpServletRequest) {
        val criteriaArgs = CriteriaArgsBuilder.withRequest(request)
            .addStringLike("code")
            .addStringLike("name")
            .addBoolean("escalated")
            .build()
            println("criteriaArgs")
            println(criteriaArgs)
    }

    @GetMapping("/detail/{id}") // purchaseOrderId
    fun getDetailedPo(@PathVariable id: Long): Map<String, Any> {

        /*
        // tested the sample printing function by a pdf file
        // just get a pdf file for demo , it can be any files? didn't try pdf with pages or multi pdf files
        val request = ExportQrCodeRequest(
            stockInLineIds = listOf(2L)
        )
        val pdf = stockInLineService.exportStockInLineQrcode(request)
        val jasperPrint = pdf["report"] as JasperPrint

        // 1. Create a temporary file to save the PDF.
        val tempPdfFile = File.createTempFile("print_job_", ".pdf")

        try {

            // 2. Export the JasperPrint to the temporary PDF file.
            JasperExportManager.exportReportToPdfFile(jasperPrint, tempPdfFile.absolutePath)

            // 3. Call the utility function with the temporary file.
            ZebraPrinterUtil.printPdfToZebra(tempPdfFile, "192.168.245.16", 9100)

        } finally {
            // 4. Ensure the temporary file is deleted after the print job is sent.
            tempPdfFile.delete()
        }
        
         */

        return purchaseOrderService.getDetailedPo(id)
    }

    @PostMapping("/start/{id}") // purchaseOrderId
    fun startPo(@PathVariable id: Long): MessageResponse {
        return purchaseOrderService.startPo(id)
    }
    @PostMapping("/check/{id}") // purchaseOrderId
    fun checkPolAndCompletePo(@PathVariable id: Long): MessageResponse {
        return purchaseOrderService.checkPolAndCompletePo(id)
    }

}