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

import com.ffii.core.utils.PdfUtils
import com.ffii.core.utils.QrCodeUtil
import com.ffii.fpsms.modules.user.entity.UserRepository
import com.ffii.fpsms.modules.user.web.ExportUserQrCodeRequest
import net.sf.jasperreports.engine.JasperCompileManager
import net.sf.jasperreports.engine.JasperPrint
import net.sf.jasperreports.engine.export.JRPdfExporter
import net.sf.jasperreports.export.SimpleExporterInput
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput
import org.springframework.core.io.ClassPathResource
import org.springframework.stereotype.Service
import java.io.FileNotFoundException
import java.awt.GraphicsEnvironment
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString

@Service
class UserQrCodeService(
    private val userRepository: UserRepository
) {

    fun exportUserQrCode(request: ExportUserQrCodeRequest): Map<String, Any> {
        val QRCODE_HANDLE_PDF = "qrCodeHandle/qrCodeHandle.jrxml"
        val resource = ClassPathResource(QRCODE_HANDLE_PDF)
        if (!resource.exists()) {
            throw FileNotFoundException("Report file not found: $QRCODE_HANDLE_PDF")
        }
        
        val inputStream = resource.inputStream
        val qrCodeHandleReport = JasperCompileManager.compileReport(inputStream)
        
        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 username = user.username ?: "N/A"
            
            val qrContentMap = mapOf("staffNo" to staffNo)
            val qrCodeContent = Json.encodeToString(qrContentMap)
            
            val qrCodeImage = QrCodeUtil.generateQRCodeImage(qrCodeContent)
            
            field["username"] = username
            field["staffNo"] = staffNo.ifEmpty { "N/A" }
            field["qrCode"] = qrCodeImage
            
            fields.add(field)
        }
        
        val params: MutableMap<String, Any> = mutableMapOf()
        
        // Configure for Chinese character support
        // Try to find a Chinese-supporting font
        val availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().availableFontFamilyNames
        val chineseFont = availableFonts.find { 
            it.contains("SimSun", ignoreCase = true) || 
            it.contains("Microsoft YaHei", ignoreCase = true) ||
            it.contains("STSong", ignoreCase = true) ||
            it.contains("SimHei", ignoreCase = true)
        } ?: "Arial Unicode MS" // Fallback
        
        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"] = chineseFont
        
        return mapOf(
            "report" to PdfUtils.fillReport(qrCodeHandleReport, fields, params),
            "fileName" to (users.firstOrNull()?.username ?: "user_qrcode")
        )
    }
}