package com.trade.service.filestorage.util.watermark;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.github.pagehelper.util.StringUtil;
import com.trade.service.filestorage.util.FileUtil;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;

/**
 * 预览工具类
 */
public class PreviewUtil {

    private static final Logger log = LogManager.getLogger(PreviewUtil.class);

    public static final String DEFAULT_WATER_MARK_TEXT = "长安银科";

    private static final class MakeWaterMarkHolder {
        static final MakeWaterMark makeWaterMark = SpringUtil.getBean(MakeWaterMark.class);
    }

    public static MakeWaterMark getWaterMarkInstance() {
        return MakeWaterMarkHolder.makeWaterMark;
    }

    /**
     * 以流的方式在浏览器上查看pdf文件
     */
    public static void previewPdf(HttpServletResponse response, File pdfFile, String fileName, String sourceType, String waterMarkText) {
        File tempFile = null;
        try {
            if (StringUtil.isNotEmpty(fileName)) {
                int end = fileName.lastIndexOf(".");
                String newName = fileName.substring(0, end);
                if (StringUtil.isNotEmpty(newName)) {
                    response.setHeader("Content-disposition",
                            "filename=" + new String(newName.getBytes("gbk"), "iso8859-1") + ".pdf");
                }
            }
            response.setContentType("application/pdf;charset=gb2312");
            // 加水印
            String strTargetPdf = FileUtil.getFileOnlinePreviewPath() + File.separator
                    + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT) + ".pdf";
            tempFile = new File(strTargetPdf);
            if (!tempFile.exists()) {
                tempFile.createNewFile();
            }
            getWaterMarkInstance().textMarkForPdf(pdfFile.getPath(), strTargetPdf, new TextMark(waterMarkText));
            // 通过文件路径获得File对象
            readFileWithInputStream(response, tempFile);
        } catch (Exception e) {
            log.error("预览PDF文件出错：" + e.getMessage());
        } finally {
            if (StringUtil.isEmpty(sourceType)) {
                if (pdfFile.exists()) {
                    pdfFile.delete();
                }
            }
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }

    /**
     * 用流的方式在浏览器上查看html文件
     */
    public static void previewHtmlFile(HttpServletResponse response, File fileHtml) {
        response.setContentType("text/html");
        try {
            readFileWithInputStream(response, fileHtml);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("预览文件出错：" + e.getMessage());
        } finally {
            if (fileHtml.exists()) {
                fileHtml.delete();
            }
        }
    }

    private static void readFileWithInputStream(HttpServletResponse response, File file) throws IOException {
        FileInputStream inputStream;
        inputStream = new FileInputStream(file);
        OutputStream os = response.getOutputStream();
        int read;
        while ((read = inputStream.read()) != -1) {
            os.write(read);
        }
        os.flush();
        inputStream.close();
        os.close();
    }
}
