package com.cf.imes.module.report.controller.admin.template;

import com.bstek.designer.bean.ReportDefinitionWrapper;
import com.bstek.designer.excel.ExcelParserUtils;
import com.bstek.ureport.definition.ReportDefinition;
import com.bstek.ureport.dsl.ReportParserLexer;
import com.bstek.ureport.dsl.ReportParserParser;
import com.bstek.ureport.export.html.HtmlReport;
import com.bstek.ureport.expression.ErrorInfo;
import com.bstek.ureport.expression.ScriptErrorListener;
import com.bstek.ureport.utils.StringUtils;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.operatelog.core.annotations.OperateLog;
import com.cf.imes.module.report.controller.admin.template.vo.*;
import com.cf.imes.module.report.service.template.ReportTemplateService;
import com.cf.imes.module.report.validation.template.ReportTemplateProducerTypeInEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.apache.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cf.imes.framework.common.pojo.CommonResult.success;
import static com.cf.imes.framework.operatelog.core.enums.OperateTypeEnum.*;

/**
 * 报表模板信息控制器
 *
 * @author Gqr
 * @since 2024/7/3 14:22
 */
@Tag(name = "管理后台 - 报表模板信息")
@RestController
@RequestMapping("/report")
@Validated
@Slf4j
public class ReportTemplateController {
    @Resource
    private ReportTemplateService templateService;

    @PutMapping("/template")
    @Operation(summary = "创建报表模板")
    @OperateLog(type = CREATE)
    @PreAuthorize("@ss.hasAnyPermissions('system:report:insert','base:report:insert')")
    public CommonResult<ReportTemplateRespVO> createTemplate(@Valid @RequestBody ReportTemplateSaveReqVO createReqVO) {
        return success(templateService.createReportTemplate(createReqVO));
    }

    @PutMapping("/template/copy")
    @Operation(summary = "复制报表模板")
    @PreAuthorize("@ss.hasAnyPermissions('system:report:copy','base:report:copy')")
    public CommonResult<Long> copyTemplate(@Valid @RequestBody ReportTemplateSaveReqVO createReqVO) {
        return success(templateService.copyReportTemplate(createReqVO));
    }

    @PostMapping("/template")
    @Operation(summary = "更新报表模板")
    @OperateLog(type = UPDATE)
    @PreAuthorize("@ss.hasAnyPermissions('system:report:update','base:report:update','system:report:save','base:report:save')")
    public CommonResult<ReportTemplateRespVO> updateTemplate(@Valid @RequestBody ReportTemplateSaveReqVO updateReqVO) {
        return success(templateService.updateReportTemplate(updateReqVO));
    }

    @DeleteMapping("/template/{id}")
    @Operation(summary = "删除报表模板")
    @Parameter(name = "id", description = "模板id", required = true)
    @PreAuthorize("@ss.hasAnyPermissions('system:report:delete','base:report:delete')")
    public CommonResult<Boolean> deleteReportTemplate(@PathVariable("id") Long id) {
        templateService.deleteReportTemplate(id);
        return success(true);
    }

    @GetMapping("/template/{id}")
    @Operation(summary = "获取报表模板信息")
    @Parameter(name = "id", description = "模板id", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('report:design')")
    public CommonResult<ReportDefinitionWrapper> getReportTemplate(@PathVariable("id") Long id) {
        return success(templateService.getReportTemplateDefinition(id));
    }

    @GetMapping("/templates")
    @Operation(summary = "获取报表模板信息列表")
    @PreAuthorize("@ss.hasPermission('report:design')")
    public CommonResult<List<ReportTemplateRespVO>> getTemplatePage(
            @RequestParam(value = "name", required = false) @Size(max = 64, message = "模板名称长度不能超过64个字符") String name,
            @RequestParam(value = "organId", required = false) Long organId) {
        ReportTemplateReqVO reqVO = new ReportTemplateReqVO(name, null, organId);
        return success(BeanUtils.toBean(templateService.getReportTemplateList(reqVO), ReportTemplateRespVO.class));
    }

    @PostMapping("/template/preview")
    @Operation(summary = "模板预览")
    @OperateLog(enable = false)
    @PreAuthorize("@ss.hasAnyPermissions('system:report:preview','base:report:preview')")
    public CommonResult<HtmlReport> preview(@RequestBody ReportTemplatePreviewReqVO reqVO) {
        return success(templateService.preview(reqVO));
    }

    @PostMapping("/template/preview/common/")
    @Operation(summary = "模板通用预览")
    @OperateLog(enable = false)
    public CommonResult<HtmlReport> commonPreview(@RequestBody ReportTemplateCommonPreviewReqVO reqVO) {
        return success(templateService.commonPreview(reqVO));
    }

    @PostMapping("/template/print")
    @Operation(summary = "模板预览打印")
    @PreAuthorize("@ss.hasAnyPermissions('system:report:preview','base:report:preview')")
    public void print(@RequestBody ReportTemplatePreviewReqVO reqVO, HttpServletResponse response) {
        templateService.print(reqVO, response);
    }

    @PostMapping("/template/print/common")
    @Operation(summary = "模板预览打印")
    @PreAuthorize("@ss.hasAnyPermissions('system:report:preview','base:report:preview')")
    public void commonPrint(@RequestBody ReportTemplateCommonPreviewReqVO reqVO, HttpServletResponse response) {
        templateService.commonPrint(reqVO, response);
    }

    @PostMapping("/template/download/{type}")
    @Operation(summary = "模板预览下载")
    @PreAuthorize("@ss.hasAnyPermissions('system:report:preview','base:report:preview')")
    public void print(@PathVariable @ReportTemplateProducerTypeInEnum @NotBlank(message = "模板下载类型不能为空") String type, @RequestBody ReportTemplatePreviewReqVO reqVO, HttpServletResponse response) {
        templateService.download(type, reqVO, response);
    }

    @PostMapping("/template/download/{type}/common")
    @Operation(summary = "模板预览下载")
    @PreAuthorize("@ss.hasAnyPermissions('system:report:preview','base:report:preview')")
    public void commonPrint(@PathVariable @ReportTemplateProducerTypeInEnum @NotBlank(message = "模板下载类型不能为空") String type, @RequestBody ReportTemplateCommonPreviewReqVO reqVO, HttpServletResponse response) {
        templateService.commonDownload(type, reqVO, response);
    }

    @PostMapping("/template/excel/import")
    @Operation(summary = "导入excel模板")
    @OperateLog(type = IMPORT)
    @PreAuthorize("@ss.hasPermission('report:design')")
    public ReportDefinitionWrapper importExcel(@RequestParam("file") MultipartFile file) {
        ReportDefinition report = ExcelParserUtils.parser(file);
        if (report != null) {
            report.setReportFullName("");
            return new ReportDefinitionWrapper(report);
        }
        throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "文件未识别");
    }

    @GetMapping("/scriptValidation")
    @Operation(summary = "校验表达式")
    @Parameter(name = "content", description = "表达式", required = true)
    @PreAuthorize("@ss.hasPermission('report:design')")
    public List<ErrorInfo> scriptValidation(@RequestParam("content") @NotEmpty(message = "表达式不能为空") String content) {
        content = StringUtils.decode(content);
        ANTLRInputStream antlrInputStream = new ANTLRInputStream(content);
        ReportParserLexer lexer = new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        ReportParserParser parser = new ReportParserParser(tokenStream);
        ScriptErrorListener errorListener = new ScriptErrorListener();
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        parser.expression();
        return errorListener.getInfos();
    }

    /**
     * 解析表达式中的数据集
     *
     * @param expr
     * @return
     */
    @GetMapping("/parseDataSet")
    @Operation(summary = "解析表达式中的数据集")
    @Parameter(name = "expr", description = "表达式", required = true)
    @PreAuthorize("@ss.hasPermission('report:design')")
    public Map<String, String> parseDatasetName(@RequestParam("expr") @NotEmpty(message = "表达式不能为空") String expr) {
        ANTLRInputStream antlrInputStream = new ANTLRInputStream(expr);
        ReportParserLexer lexer = new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        ReportParserParser parser = new ReportParserParser(tokenStream);
        parser.removeErrorListeners();

        Map<String, String> result = new HashMap<>();
        ReportParserParser.DatasetContext ctx = parser.dataset();
        if (ctx != null) {
            TerminalNode node = ctx.Identifier();
            if (node != null) {
                String datasetName = ctx.Identifier().getText();
                result.put("datasetName", datasetName);
            }
        }
        return result;
    }

    @GetMapping("/xml/{id}")
    @Operation(summary = "导出模版")
    @Parameter(name = "id", description = "模板id", required = true)
    @PreAuthorize("@ss.hasAnyPermissions('system:report:export','base:report:export')")
    public void exportTemplate(@PathVariable("id") Long templateId, HttpServletResponse response) {
        templateService.exportTemplate(templateId, response);
    }

    @PutMapping("/xml")
    @Operation(summary = "导入模版")
    @OperateLog(type = IMPORT)
    @PreAuthorize("@ss.hasAnyPermissions('system:report:import','base:report:import')")
    public CommonResult<Boolean> importTemplate(@RequestParam("name") @NotEmpty(message = "模版名称不能为空") String name, @RequestParam("file") MultipartFile file) {
        templateService.importTemplate(name, file);
        return success(true);
    }
}
