package com.emr.service.ipml;


import com.emr.dto.DownloadPdfBloodDto;
import com.emr.service.DownloadPdfBloodService;
import com.emr.service.ExportZdAssortService;

import com.emr.vo.ExportPdfVo;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;




import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class DownloadPdfBloodServiceImpl implements DownloadPdfBloodService {
    @Autowired
    ExportZdAssortService exportZdAssortService;

    @Value("${export_pdf_hospital_info}")
    private String flieName;


    @Override
    public void downloadPdfBlood(HttpServletResponse response, DownloadPdfBloodDto dto) throws Exception {
        String fileName;
        try {
            //组织导出文件名
            fileName = exportFlieName(dto);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        //查询当前患者需要打印的pdf
        List<ExportPdfVo> pdfPathList = exportZdAssortService.getPdfPath(dto.getMasterId());
        downPdfResponse(fileName,response);
        exportPdf(response, pdfPathList);
    }

    private static void exportPdf(HttpServletResponse response, List<ExportPdfVo> pdfPathList) {
        //上一个目录名称
        String lastOutline = null;
        //是否增加标签
        boolean outFlag = true;
        //标签顺序
        Integer outNum = 1;
        Integer pageNum=1;
        Document document = new Document();
        PdfCopy writer = null;
        try {
            writer = new PdfCopy(document, response.getOutputStream());
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12);
            cb.beginText();
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "目录", 300, 780, 0);
            cb.endText();
            // 创建目录
            PdfOutline root = cb.getRootOutline();
            for (int i = 0; i < pdfPathList.size(); i++) {
                try {
                    String assortName = pdfPathList.get(i).getAssortName();
                    if (StringUtils.isNotBlank(lastOutline) && lastOutline.equals(assortName)) {
                        outFlag = false;
                    }
                    if (StringUtils.isBlank(lastOutline)) {
                        lastOutline = assortName;
                        outFlag=true;
                    }
                    if (!lastOutline.equals(assortName)){
                        lastOutline = assortName;
                        outFlag=true;
                    }
                    PdfReader reader = new PdfReader(pdfPathList.get(i).getPdfPath());
                    int n = reader.getNumberOfPages();
                    for (int s = 1; s <= n; s++) {
                        PdfImportedPage page = writer.getImportedPage(reader, s);
                        writer.addPage(page);
                    }
                    if (outFlag) {
                        //目录跳转页面内容设置。
                        PdfAction action = PdfAction.gotoLocalPage(pageNum, new PdfDestination(PdfDestination.FIT), writer);
                        //标题目录
                        String title = outNum+"."+pdfPathList.get(i).getAssortName();
                        new PdfOutline(root, action, title, false);
                        outNum++;
                    }
                    pageNum =pageNum+getPageNum(pdfPathList.get(i));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }


    private void downPdfResponse(String pdfName, HttpServletResponse response) {
        try {
            pdfName = java.net.URLEncoder.encode(pdfName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.reset();
        response.setContentType("application/pdf");
        response.setHeader("content-disposition", "attachment; filename=" + pdfName + ".pdf");
    }



//    private static void mulFile2One(HttpServletResponse response, DownloadPdfBloodDto dto, List<ExportPdfVo> pdfPathList, String fileName) {
//        //获取需要导出pdf
//        List<String> filePaths = pdfPathList.stream().map(ExportPdfVo::getPdfPath).collect(Collectors.toList());
//        if (!filePaths.isEmpty()) {
//            //标签顺序
//            Integer outNum = 1;
//            // pdf合并工具类
//            Document document = null;
//            PdfCopy copy = null;
//            PdfWriter writer;
//            try {
//                writer = PdfWriter.getInstance(document, response.getOutputStream());//创建编写器（PDF类型）
//                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
//                response.reset();
//                response.setCharacterEncoding("utf-8");
//                response.setContentType("application/pdf");
//                response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
//                document = new Document(new PdfReader(filePaths.get(0)).getPageSize(1));
//                copy = new PdfCopy(document, response.getOutputStream());
//                document.open();
//                for (int i = 0; i < pdfPathList.size(); i++) {
//                    PdfReader reader = new PdfReader(pdfPathList.get(i).getPdfPath());
//                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
//                    PdfReader pdfReader = null;
//                    int n = reader.getNumberOfPages();
//                    for (int j = 1; j <= n; j++) {
//                        document.newPage();
//                        PdfImportedPage page = copy.getImportedPage(reader, j);
//                        copy.addPage(page);
//                    }
//                    if (null != pdfReader) {
//                        pdfReader.close();
//                    }
//                    reader.close();
//                    try {
//                        bos.flush();
//                        bos.close();
//                    } catch (Exception e) {
//                        //e.printStackTrace();
//                    }
//                }
//            } catch (Exception e) {
//                //e.printStackTrace();
//            } finally {
//                if (null != document) {
//                    document.close();
//                }
//            }
//
//        }
//    }

    private String exportFlieName(DownloadPdfBloodDto dto) throws ParseException {
        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = originalFormat.parse(dto.getDischargeDateTime());
        String formattedDate = targetFormat.format(date);
        return flieName + "_" + dto.getInpNo() + "_" + formattedDate;
    }
  private static int getPageNum(ExportPdfVo obj) {
      FileInputStream is;
      com.itextpdf.kernel.pdf.PdfReader pdfReader = null;
      int pages = 0;
      //创建File类
      File file = new File(obj.getPdfPath());
      //判断文件是否存在
      if (file.exists()) {
          try {
              is = new FileInputStream(file);
              pdfReader = new com.itextpdf.kernel.pdf.PdfReader(is);
              com.itextpdf.kernel.pdf.PdfDocument redDocument = new com.itextpdf.kernel.pdf.PdfDocument(pdfReader);
              pages = redDocument.getNumberOfPages();
          } catch (IOException e) {
              throw new RuntimeException(e);
          }
      }
      return pages;
  }


}
