package com.ffii.fpsms.modules.master.web

import com.ffii.core.response.RecordsRes
import com.ffii.core.utils.CriteriaArgsBuilder
import com.ffii.core.utils.PagingUtils
import com.ffii.fpsms.modules.master.entity.Equipment
import com.ffii.fpsms.modules.master.service.EquipmentService
import com.ffii.fpsms.modules.master.service.EquipmentQrCodeService
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import jakarta.validation.Valid
import org.springframework.web.bind.annotation.*
import java.util.Collections.emptyList
import com.ffii.fpsms.modules.master.web.models.NewEquipmentRequest
import net.sf.jasperreports.engine.JasperExportManager
import net.sf.jasperreports.engine.JasperPrint
import java.io.OutputStream

@RestController
@RequestMapping("/Equipment")
class EquipmentController(
    private val equipmentService: EquipmentService,
    private val equipmentQrCodeService: EquipmentQrCodeService
) {
    @GetMapping
    fun allEquipment(): List<Equipment> {
        return equipmentService.allEquipments()
    }

//    @GetMapping("/getRecordByPage")
//    fun getAllItemsByPage(@RequestBody filterRequest: HttpServletRequest): RecordsRes<Map<String, Any>> {
//        val pageSize = filterRequest.getParameter("pageSize").toString().toInt(); // Default to 10 if not provided
//        val pageNumber = filterRequest.getParameter("pageNum").toString().toInt(); // Default to 0 if not provided
//        val criteriaArgs = CriteriaArgsBuilder.withRequest(filterRequest)
//            .addStringLike("name")
//            .build();
//
//        val fullList = itemsService.getItemsByPage(criteriaArgs)?.subList(pageSize*pageNumber+1, pageSize*pageNumber+pageSize)
//        val outputList = fullList?.subList(pageSize*pageNumber+1, pageSize*pageNumber+pageSize)
//
//        return RecordsRes(outputList as List<Map<String, Any>>?, fullList?.size)
//    }

@GetMapping("/getRecordByPage")
fun getAllEquipmentByPage(
    request: HttpServletRequest
): RecordsRes<Map<String, Any>> {
    val criteriaArgs = CriteriaArgsBuilder.withRequest(request)
        .addStringLike("name")
        .addStringLike("code")
        .addStringLike("description")
        .addStringLike("id")
        .build()

    val pageSize = request.getParameter("pageSize")?.toIntOrNull() ?: 10
    val pageNum = request.getParameter("pageNum")?.toIntOrNull() ?: 1

    // 方法名和变量名都要和 Service 保持一致
    val fullList = equipmentService.getEquipmentsByPage(criteriaArgs) ?: emptyList()
    val paginatedList = PagingUtils.getPaginatedList(fullList, pageSize, pageNum)

    return RecordsRes(paginatedList as List<Map<String, Any>>, fullList.size)
}

    // 详情
    @GetMapping("/details/{id}")
    fun getEquipment(@PathVariable id: Long): Equipment? {
        return equipmentService.findById(id)
    }

    // 新增/编辑
    @PostMapping("/save")
    fun saveEquipment(@Valid @RequestBody equipment: NewEquipmentRequest): Equipment {
        return equipmentService.saveEquipment(equipment)
    }

    // 逻辑删除
    @DeleteMapping("/delete/{id}")
    fun deleteEquipment(@PathVariable id: Long) {
        equipmentService.deleteEquipment(id)
    }

    @PostMapping("/export-qrcode")
    fun exportQrCode(@Valid @RequestBody request: ExportEquipmentQrCodeRequest, response: HttpServletResponse) {
        response.characterEncoding = "utf-8"
        response.contentType = "application/pdf"
        val out: OutputStream = response.outputStream
        val pdf = equipmentQrCodeService.exportEquipmentQrCode(request)
        val jasperPrint = pdf["report"] as JasperPrint
        val fileName = pdf["fileName"] as String
        response.addHeader("Content-Disposition", "attachment; filename=\"${fileName}_qrcode.pdf\"")
        out.write(JasperExportManager.exportReportToPdf(jasperPrint))
        out.flush()
    }

    @PostMapping("/print-qrcode")
    fun printQrCode(@Valid @RequestBody request: PrintEquipmentQrCodeRequest) {
        equipmentQrCodeService.printEquipmentQrCode(request)
    }

}