package com.ffii.fpsms.modules.master.service

import com.ffii.core.utils.PdfUtils
import com.ffii.core.utils.QrCodeUtil
import com.ffii.fpsms.modules.master.entity.WarehouseRepository
import com.ffii.fpsms.modules.master.web.ExportWarehouseQrCodeRequest
import net.sf.jasperreports.engine.JasperCompileManager
import net.sf.jasperreports.engine.JasperPrint
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 WarehouseQrCodeService(
    private val warehouseRepository: WarehouseRepository
) {

    fun exportWarehouseQrCode(request: ExportWarehouseQrCodeRequest): Map<String, Any> {
        val QRCODE_HANDLE_PDF = "qrCodeHandle/warehouse_QrHandle.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 warehouses = warehouseRepository.findAllById(request.warehouseIds)
        if (warehouses.isEmpty()) {
            throw IllegalArgumentException("No warehouses found for the provided warehouse IDs: ${request.warehouseIds}")
        }
        
        val fields = mutableListOf<MutableMap<String, Any>>()
        
        for (warehouse in warehouses) {
            val field = mutableMapOf<String, Any>()
            
            val code = warehouse.code ?: ""
            
            if (code.isBlank()) {
                continue
            }
            
            val warehouseId = warehouse.id
            if (warehouseId == null) {
            continue  
            }
    
            val qrContentMap = mapOf("warehouseId" to warehouseId) 
            val qrCodeContent = Json.encodeToString(qrContentMap).replace(Regex("""(?<!:)(:)(?!\s)"""), ": ")
            
            val qrCodeImage = QrCodeUtil.generateQRCodeImage(qrCodeContent)
            
            field["username"] = ""
            field["staffNo"] = ""
            field["code"] = code
            field["equipmentCode"] = ""
            field["qrCode"] = qrCodeImage
            
            fields.add(field)
        }
        
        if (fields.isEmpty()) {
            throw IllegalArgumentException("No valid warehouses found for the provided warehouse IDs: ${request.warehouseIds}")
        }
        
        val params: MutableMap<String, Any> = mutableMapOf()
        
        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"
        
        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
        
        val firstWarehouse = warehouses.firstOrNull()
        
        return mapOf(
            "report" to PdfUtils.fillReport(qrCodeHandleReport, fields, params),
            "fileName" to (firstWarehouse?.code ?: "warehouse_qrcode")
        )
    }
}
