package com.erp.print.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.erp.print.dto.request.PrintTemplateRequest;
import com.erp.common.core.model.ApiResponse;
import com.erp.common.core.model.PageResponse;
import com.erp.print.entity.PrintTemplate;
import com.erp.print.service.PrintTemplateService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

@Tag(name = "打印模板管理")
@RestController
@RequestMapping("/api/print/templates")
@RequiredArgsConstructor
public class PrintTemplateController {

    private final PrintTemplateService templateService;

    @Operation(summary = "分页查询模板")
    @GetMapping
    public ApiResponse<PageResponse<PrintTemplate>> listTemplates(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer limit,
            @RequestParam(required = false) String templateType,
            @RequestParam(required = false) String keyword) {
        return ApiResponse.success(templateService.listTemplates(page, limit, templateType, keyword));
    }

    @Operation(summary = "获取模板详情")
    @GetMapping("/{id}")
    public ApiResponse<PrintTemplate> getTemplate(@PathVariable Long id) {
        return ApiResponse.success(templateService.getTemplateById(id));
    }

    @Operation(summary = "根据编码获取模板")
    @GetMapping("/code/{templateCode}")
    public ApiResponse<PrintTemplate> getTemplateByCode(@PathVariable String templateCode) {
        return ApiResponse.success(templateService.getTemplateByCode(templateCode));
    }

    @Operation(summary = "创建模板")
    @PostMapping
    public ApiResponse<PrintTemplate> createTemplate(@Valid @RequestBody PrintTemplateRequest request) {
        return ApiResponse.success("创建成功", templateService.createTemplate(request));
    }

    @Operation(summary = "更新模板")
    @PutMapping("/{id}")
    public ApiResponse<PrintTemplate> updateTemplate(@PathVariable Long id, @Valid @RequestBody PrintTemplateRequest request) {
        request.setId(id);
        return ApiResponse.success("更新成功", templateService.updateTemplate(request));
    }

    @Operation(summary = "删除模板")
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteTemplate(@PathVariable Long id) {
        templateService.deleteTemplate(id);
        return ApiResponse.success("删除成功", null);
    }

    @Operation(summary = "设置默认模板")
    @PostMapping("/{id}/default")
    public ApiResponse<Void> setDefaultTemplate(@PathVariable Long id) {
        templateService.setDefaultTemplate(id);
        return ApiResponse.success("设置成功", null);
    }
}
