package com.zt.plat.module.base.controller.admin.doctemplate;

import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.module.base.controller.admin.doctemplate.vo.DocTemplateInstancePageReqVO;
import com.zt.plat.module.base.controller.admin.doctemplate.vo.DocTemplateInstanceRespVO;
import com.zt.plat.module.base.controller.admin.doctemplate.vo.DocTemplateInstanceSaveReqVO;
import com.zt.plat.module.base.service.doctemplate.DocTemplateInstanceService;
import com.zt.plat.module.base.service.doctemplate.DocTemplateRenderService;
import com.zt.plat.module.base.service.doctemplate.DocumentRenderApiService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import static com.zt.plat.framework.common.pojo.CommonResult.success;

/**
 * 模板实例 Controller
 *
 * @author 系统生成
 */
@Tag(name = "管理后台 - 模板实例")
@RestController
@RequestMapping("/base/doc-template-instance")
@Validated
public class DocTemplateInstanceController {

    @Resource
    private DocTemplateInstanceService templateInstanceService;

    @Resource
    private DocTemplateRenderService renderService;

    @Resource
    private DocumentRenderApiService documentRenderApiService;

    @PostMapping("/create")
    @Operation(summary = "创建模板实例")
    @PreAuthorize("@ss.hasPermission('base:template-instance:create')")
    public CommonResult<Long> createTemplateInstance(@Valid @RequestBody DocTemplateInstanceSaveReqVO createReqVO) {
        return success(templateInstanceService.createTemplateInstance(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新模板实例")
    @PreAuthorize("@ss.hasPermission('base:template-instance:update')")
    public CommonResult<Boolean> updateTemplateInstance(@Valid @RequestBody DocTemplateInstanceSaveReqVO updateReqVO) {
        templateInstanceService.updateTemplateInstance(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除模板实例")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('base:template-instance:delete')")
    public CommonResult<Boolean> deleteTemplateInstance(@RequestParam("id") Long id) {
        templateInstanceService.deleteTemplateInstance(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得模板实例")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public CommonResult<DocTemplateInstanceRespVO> getTemplateInstance(@RequestParam("id") Long id) {
        return success(templateInstanceService.getTemplateInstance(id));
    }

    @GetMapping("/page")
    @Operation(summary = "获得模板实例分页")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public CommonResult<PageResult<DocTemplateInstanceRespVO>> getTemplateInstancePage(@Valid DocTemplateInstancePageReqVO pageReqVO) {
        return success(templateInstanceService.getTemplateInstancePage(pageReqVO));
    }

    @GetMapping("/list")
    @Operation(summary = "获得模板实例列表")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public CommonResult<List<DocTemplateInstanceRespVO>> getTemplateInstanceList() {
        return success(templateInstanceService.getTemplateInstanceList());
    }

    @PostMapping("/render")
    @Operation(summary = "渲染模板实例")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public CommonResult<String> renderTemplateInstance(
            @Parameter(name = "instanceId", description = "实例ID", required = true) @RequestParam("instanceId") Long instanceId,
            @Parameter(name = "dataMap", description = "数据Map") @RequestBody(required = false) Map<String, Object> dataMap) {
        String renderedContent = renderService.render(null, instanceId, null, dataMap);
        return success(renderedContent);
    }

    @PostMapping("/render-and-save")
    @Operation(summary = "渲染并保存模板实例")
    @PreAuthorize("@ss.hasPermission('base:template-instance:update')")
    public CommonResult<Boolean> renderAndSaveTemplateInstance(
            @Parameter(name = "instanceId", description = "实例ID", required = true) @RequestParam("instanceId") Long instanceId,
            @Parameter(name = "dataMap", description = "数据Map", required = true) @RequestBody Map<String, Object> dataMap) {
        renderService.renderAndSave(instanceId, dataMap);
        return success(true);
    }

    @PostMapping("/render-and-export-word")
    @Operation(summary = "渲染实例并导出为Word")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public ResponseEntity<byte[]> renderAndExportToWord(
            @Parameter(name = "instanceId", description = "实例ID", required = true) @RequestParam("instanceId") Long instanceId,
            @Parameter(name = "fileName", description = "文件名") @RequestParam(value = "fileName", required = false) String fileName,
            @Parameter(name = "dataMap", description = "数据Map") @RequestBody(required = false) Map<String, Object> dataMap) {
        byte[] fileContent = documentRenderApiService.renderAndExportToWord(instanceId, dataMap, fileName);
        String actualFileName = (fileName != null ? fileName : "document") + ".docx";
        String encodedFileName = URLEncoder.encode(actualFileName, StandardCharsets.UTF_8).replace("+", "%20");
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=\"document.docx\"; filename*=UTF-8''" + encodedFileName)
                .header("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                .body(fileContent);
    }

    @PostMapping("/export-html-to-word")
    @Operation(summary = "导出HTML为Word文档")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public ResponseEntity<byte[]> exportHtmlToWord(
            @Parameter(name = "html", description = "HTML内容", required = true) @RequestBody String html,
            @Parameter(name = "fileName", description = "文件名") @RequestParam(value = "fileName", required = false) String fileName) {
        byte[] fileContent = documentRenderApiService.exportToWord(html, fileName);
        String actualFileName = (fileName != null ? fileName : "document") + ".docx";
        String encodedFileName = URLEncoder.encode(actualFileName, StandardCharsets.UTF_8).replace("+", "%20");
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=\"document.docx\"; filename*=UTF-8''" + encodedFileName)
                .header("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                .body(fileContent);
    }

}
