package com.ximai.web.controller.common;

import com.ximai.common.config.RuoYiConfig;
import com.ximai.common.constant.Constants;
import com.ximai.common.core.domain.AjaxResult;
import com.ximai.common.core.domain.AjaxResult2;
import com.ximai.common.core.domain.PreviewParameters;
import com.ximai.common.core.domain.model.UploadFileResult;
import com.ximai.common.utils.barcode.BarcodeUtil;
import com.ximai.common.utils.data.StringUtils;
import com.ximai.common.utils.file.FileUploadUtils;
import com.ximai.common.utils.file.FileUtils;
import com.ximai.common.utils.uuid.UUID;
import com.ximai.framework.config.ServerConfig;
import com.bstek.ureport.export.ExportConfigureImpl;
import com.bstek.ureport.export.ExportManager;
import com.bstek.ureport.export.html.HtmlReport;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 通用请求处理
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ExportManager exportManager;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public AjaxResult<UploadFileResult> uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = ServerConfig.getUrl() + fileName;
            UploadFileResult rst = new UploadFileResult();
            rst.setUrl(url);
            rst.setFilePath(fileName);
            rst.setOriginalFilename(file.getOriginalFilename());
            rst.setSize(file.getSize());
            return AjaxResult.success(rst);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult<List<UploadFileResult>> uploadFiles(@RequestParam("file") List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<UploadFileResult> rst = new ArrayList<>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = ServerConfig.getUrl() + fileName;
                UploadFileResult temp = new UploadFileResult();
                temp.setUrl(url);
                temp.setFilePath(fileName);
                temp.setOriginalFilename(file.getOriginalFilename());
                temp.setSize(file.getSize());
                rst.add(temp);
            }
            return AjaxResult.success(rst);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    @PostMapping("/uploadMinio")
    public AjaxResult2 uploadFileMinio(MultipartFile file) throws Exception {
        try {
            String fileName = FileUploadUtils.uploadMinio(file);
            AjaxResult2 rt = AjaxResult2.success();
            rt.put("url", fileName);
            rt.put("fileName", fileName);
            rt.put("newFileName", FileUtils.getName(fileName));
            rt.put("originalFileName", file.getOriginalFilename());
            return rt;
        } catch (Exception e) {
            return AjaxResult2.error(e.getMessage());
        }
    }

    @GetMapping("/buildCode")
    public void img(@RequestParam String code, @RequestParam Integer type, HttpServletResponse response) throws IOException {
        String tempPath = System.getProperty("java.io.tmpdir");
        tempPath += UUID.fastUUID() + ".png";
        File file = null;
        if (type == 1) {
            file = BarcodeUtil.generateBarCode(code, "QR_CODE", tempPath);
        } else {
            file = BarcodeUtil.generateBarCode(code, "EAN_CODE", tempPath);
        }
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        FileInputStream fio = new FileInputStream(file);
        IOUtils.copy(fio, os);
        os.close();

    }

    @ApiOperation("模版生成PDF")
    @PostMapping("/print")
    public void buildPrint(HttpServletRequest request, @RequestBody PreviewParameters reportParameters, HttpServletResponse response) throws IOException {
        ExportConfigureImpl configure = new ExportConfigureImpl(reportParameters.getReportName(),
                reportParameters.getValues(), response.getOutputStream());
        exportManager.exportPdf(configure);
    }

    @ApiOperation("模版批量生成PDF")
    @PostMapping("/printBatch")
    public void printBatch(HttpServletRequest request, @RequestBody PreviewParameters reportParameters, HttpServletResponse response) throws IOException {
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        for (Map<String, Object> values : reportParameters.getValueList()) {
            String tempPath = System.getProperty("java.io.tmpdir");
            String fileName = UUID.fastUUID() + ".pdf";
            tempPath += fileName;
            FileOutputStream fo = new FileOutputStream(tempPath);
            ExportConfigureImpl configure = new ExportConfigureImpl(reportParameters.getReportName(),
                    values, fo);
            mergePdf.setDestinationStream(response.getOutputStream());
            exportManager.exportPdf(configure);
            mergePdf.addSource(new FileInputStream(tempPath));
        }
        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
    }

    @ApiOperation("模版生成PDF下载")
    @PostMapping("/printDown")
    public AjaxResult2 printDown(HttpServletRequest request, @RequestBody PreviewParameters reportParameters, HttpServletResponse response) throws IOException {
        String tempPath = System.getProperty("java.io.tmpdir");
        String fileName = UUID.fastUUID() + ".pdf";
        tempPath += fileName;
        FileOutputStream fo = new FileOutputStream(tempPath);
        ExportConfigureImpl configure = new ExportConfigureImpl(reportParameters.getReportName(),
                reportParameters.getValues(), fo);
        exportManager.exportPdf(configure);
        AjaxResult2 r = AjaxResult2.success();
        String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
        r.put("fileUrl", baseUrl + "common/downTempPDF?fileName=" + fileName);
        return r;
    }

    @ApiOperation("模版生成PNG图片")
    @PostMapping("/report2Png")
    public void report2Png(HttpServletRequest request, @RequestBody PreviewParameters reportParameters, HttpServletResponse response) throws IOException {
        String tempPath = System.getProperty("java.io.tmpdir");
        String fileName = UUID.fastUUID() + ".pdf";
        tempPath += fileName;
        FileOutputStream fo = new FileOutputStream(tempPath);
        ExportConfigureImpl configure = new ExportConfigureImpl(reportParameters.getReportName(),
                reportParameters.getValues(), fo);
        exportManager.exportPdf(configure);
        response.setContentType("image/png");
        PDDocument document = PDDocument.load(new File(tempPath));
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        for (int page = 0; page < document.getNumberOfPages(); ++page) {
            BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 150, ImageType.RGB);
            // 输出格式为PNG的图片文件
            ImageIO.write(bim, "PNG", response.getOutputStream());
        }
        document.close();
        response.getOutputStream().close();
    }

    @ApiOperation("模版生成HTML生成")
    @PostMapping("/printHtml")
    public void printHtml(HttpServletRequest request, @RequestBody PreviewParameters reportParameters, HttpServletResponse response) throws IOException {
        HtmlReport htmlReport = exportManager.exportHtml(reportParameters.getReportName(),reportParameters.getReportName(),reportParameters.getValues());
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(htmlReport.getContent());
        response.getWriter().close();
    }


    @ApiOperation("下载临时文件")
    @GetMapping("/downTempPDF")
    public void downTempFile(HttpServletRequest request, @RequestParam(name = "fileName") String fileName, HttpServletResponse response) throws IOException {
        String tempPath = System.getProperty("java.io.tmpdir");
        File file = new File(tempPath + fileName);
        FileInputStream fileio = new FileInputStream(file);
        response.setContentType("application/pdf");
        IOUtils.copy(fileio, response.getOutputStream());
        response.getOutputStream().close();
    }

}
