package com.skr.mdm.util;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author nfq
 * @date 2020/8/20 15:30
 */
public class ExportPdfUtil {

    /**
     * 定义临时文件存放目录
     */
    private static final String REPORT_PDF = "report" + File.separator + "pdf";

    private static final String ABSOLUTE_PATH = FilePathUtil.getFileAbsolutePath(ExportPdfUtil.class);

    public static String pdf(List<Map<String, Object>> dataMapList, String[] titles,
                           String[] mapKeys, String fileName, String filePath, Integer companyId,
                           HttpServletResponse response) throws Exception {
        // 获取路径
        fileName = fileName.concat(".pdf") ;
        filePath = getFilePath(filePath, fileName, companyId);
        // 生成文件
        createPdf(dataMapList, titles, mapKeys, filePath, fileName);
        // 导出文件
        if (response != null) {
            exportFile(response, filePath, fileName);
        }
        return filePath;
    }


    private static void createPdf(List<Map<String, Object>> dataMapList, String[] titles,
                                  String[] mapKeys, String filePath, String fileName) throws Exception {
        File file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile() ;
        }
        Document document = new Document();
        FileOutputStream out = new FileOutputStream(file);
        // 将pdf文件输出到磁盘
        PdfWriter.getInstance(document, out);
        document.open();
        // 设置内容
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
        Font fontZH = new Font(bfChinese, 12.0F, 0);
        document.add(new Paragraph(new Chunk(fileName, fontZH).setLocalDestination(fileName)));
        document.add(new Paragraph("\n"));
        PdfPTable table = new PdfPTable(titles.length);
        table.setWidthPercentage(100.0F);
        //  列表名
        table.setHeaderRows(1);
        table.getDefaultCell().setHorizontalAlignment(1);
        for (String title : titles) {
            table.addCell(new Paragraph(title, fontZH));
        }
        // 添加内容
        for (Map<String, Object> dataMap : dataMapList){
            for (String mapKey : mapKeys){
                Object value = dataMap.get(mapKey);
                if (value instanceof Date) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    table.addCell(new Paragraph(format.format(value), fontZH));
                } else {
                    if (value != null) {
                        table.addCell(new Paragraph(String.valueOf(value), fontZH));
                    } else {
                        table.addCell(new Paragraph("", fontZH));
                    }
                }
            }
        }
        document.add(table);
        document.add(new Paragraph("\n"));
        document.close();
        out.close();
    }

    private static void exportFile(HttpServletResponse response, String filePath, String fileName) throws Exception {
        FileInputStream inputStream = null;
        File pdfFile = new File(filePath);
        try{
            //设置发送到客户端的响应内容类型
            response.reset();
            response.setContentLength((int) pdfFile.length());
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            inputStream = new FileInputStream(filePath);
            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
        } finally{
            if(inputStream != null){
                inputStream.close();
            }
            // 删除本地临时文件
            if (pdfFile.exists()) {
                File[] files = pdfFile.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile() && file.exists()) {
                            file.delete();
                        }
                    }
                }
                if (pdfFile.isDirectory() || pdfFile.isFile()) {
                    pdfFile.delete();
                }
            }
        }
    }

    private static String getFilePath(String filePath, String fileName, Integer companyId){
        if (StringUtils.isBlank(filePath)) {
            filePath = ABSOLUTE_PATH;
        }
        filePath = filePath + File.separator + REPORT_PDF + File.separator + companyId;
        File fileDir = new File(filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs() ;
        }
        return filePath + File.separator  +  fileName ;
    }

}
