package com.ffii.fpsms.modules.user.service

import com.ffii.core.utils.PdfUtils
import com.ffii.core.utils.QrCodeUtil
import com.ffii.fpsms.modules.master.print.A4PrintDriverRegistry
import com.ffii.fpsms.modules.master.service.PrinterService
import com.ffii.fpsms.modules.user.entity.UserRepository
import com.ffii.fpsms.modules.user.web.ExportUserQrCodeRequest
import com.ffii.fpsms.modules.user.web.PrintUserQrCodeRequest
import net.sf.jasperreports.engine.JasperCompileManager
import net.sf.jasperreports.engine.JasperExportManager
import net.sf.jasperreports.engine.JasperReport
import net.sf.jasperreports.engine.JasperPrint
import org.springframework.core.io.ClassPathResource
import org.springframework.stereotype.Service
import java.io.File
import java.io.FileNotFoundException
import java.awt.GraphicsEnvironment
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString

@Service
class UserQrCodeService(
    private val userRepository: UserRepository,
    private val printerService: PrinterService,
) {
    private val qrCodeHandleJrxmlPath = "qrCodeHandle/qrCodeHandle.jrxml"

    /**
     * Compile the Jasper template once; compiling per request is expensive.
     */
    private val qrCodeHandleReport: JasperReport by lazy {
        val resource = ClassPathResource(qrCodeHandleJrxmlPath)
        if (!resource.exists()) {
            throw FileNotFoundException("Report file not found: $qrCodeHandleJrxmlPath")
        }
        resource.inputStream.use { JasperCompileManager.compileReport(it) }
    }

    /** Cache the chosen Chinese font family name (font scanning is expensive). */
    private val chineseFontFamily: String by lazy {
        val availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().availableFontFamilyNames
        availableFonts.find { family ->
            family.contains("SimSun", ignoreCase = true) ||
                family.contains("Microsoft YaHei", ignoreCase = true) ||
                family.contains("STSong", ignoreCase = true) ||
                family.contains("SimHei", ignoreCase = true)
        } ?: "Arial Unicode MS"
    }

    fun exportUserQrCode(request: ExportUserQrCodeRequest): Map<String, Any> {
        val users = userRepository.findAllById(request.userIds)
        val fields = mutableListOf<MutableMap<String, Any>>()
        
        for (user in users) {
            val field = mutableMapOf<String, Any>()
            
            val staffNo = user.staffNo ?: ""
            val name = user.name ?: "N/A"
            
            val qrContentMap = mapOf("staffNo" to staffNo)
            val qrCodeContent = Json.encodeToString(qrContentMap)
            
            val qrCodeImage = QrCodeUtil.generateQRCodeImage(qrCodeContent)
            
            field["name"] = name
            field["staffNo"] = staffNo.ifEmpty { "N/A" }
            field["qrCode"] = qrCodeImage
            
            fields.add(field)
        }
        
        val params: MutableMap<String, Any> = mutableMapOf()

        params["net.sf.jasperreports.default.pdf.encoding"] = "Identity-H"
        params["net.sf.jasperreports.default.pdf.embedded"] = true
        params["net.sf.jasperreports.default.pdf.font.name"] = chineseFontFamily
        
        return mapOf(
            "report" to PdfUtils.fillReport(qrCodeHandleReport, fields, params),
            "fileName" to (users.firstOrNull()?.username ?: "user_qrcode")
        )
    }

    fun printUserQrCode(request: PrintUserQrCodeRequest) {
        val printer = printerService.findById(request.printerId) ?: throw NoSuchElementException("No such printer")
        val pdf = exportUserQrCode(ExportUserQrCodeRequest(request.userIds))
        val jasperPrint = pdf["report"] as JasperPrint
        val tempPdfFile = File.createTempFile("print_job_", ".pdf")

        try {
            JasperExportManager.exportReportToPdfFile(jasperPrint, tempPdfFile.absolutePath)
            val printQty = if (request.printQty == null || request.printQty <= 0) 1 else request.printQty
            printer.ip?.let { ip ->
                val port = printer.port ?: 9100
                val driver = A4PrintDriverRegistry.getDriver(printer.brand)
                driver.print(tempPdfFile, ip, port, printQty)
            }
        } finally {
            tempPdfFile.delete()
        }
    }
}