package com.mortals.xhx.module.print.service.PrintComponent;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.common.code.PrintTypeEnum;
import com.mortals.xhx.common.utils.FileDownloader;
import com.mortals.xhx.common.utils.PdfUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;

import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.Sides;
import java.awt.print.*;
import java.io.File;
import java.io.IOException;

@Slf4j
public class UrlPrintComponent extends BasePrintComponent {

    public UrlPrintComponent(String type) {
        super(type);
    }

    public static String word[] = {"doc", "dot", "wps", "wpt", "docx", "dotx", "docm", "dotm"};

    public static String imgs[] = {"jpg", "png", "jpeg", "gif"};
    public static String pdf[] = {"pdf"};
    int downStaus = 0;  // 下载文件的状态  0正在下载  1成功  -1失败

    // 获取当前系统名称
    static String osName = System.getProperty("os.name").toLowerCase();
    @Override
    public Rest<Void> print(ComponentCons cons) {

        //获取文件后缀
        String suffixName = FileUtil.getSuffix(cons.getUrl());

        String samplePath = "/tmp/sourceFile."+suffixName;  //源文件下载地址
        //通过网络下载附件地址
//        File file = HttpUtil.downloadFileFromUrl(cons.getUrl(),"/tmp/sourceFile."+suffixName);
        FileDownloader.downloadFileFromUrl(cons.getUrl(), "/tmp/sourceFile." + suffixName, new FileDownloader.Callback() {
            @Override
            public void onSuccess() {
                downStaus = 1;
            }

            @Override
            public void onError(Exception e) {
                downStaus = -1;
            }
        });

        while (downStaus == 0){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        if(downStaus == 1){

            File file = new File("/tmp/sourceFile." + suffixName);
            log.info("file name:{}",file.getAbsolutePath());
            log.info("file suffixName:{}", suffixName);
            String pdfPath = "/tmp/target.pdf";


            //判断文件类型是否为doc pdf jpg png 等
            if (this.isExsitArry(suffixName, word)) {
                // 根据系统选择执行方法
                if (osName.contains("win")) {
                    PdfUtil.winWordToPdf(samplePath,pdfPath);
                } else if (osName.contains("nux") || osName.contains("nix")) {
                    pdfPath = "/tmp/sourceFile.pdf";  //linux下不会指定新文件名称  会以原文件名+.pdf生成一个新文件
                    PdfUtil.linuxWordToPdf(samplePath,"/tmp/");
                }
            } else if (this.isExsitArry(suffixName, pdf)) {
                pdfPath = samplePath;
            }else if(this.isExsitArry(suffixName, imgs)){
                PdfUtil.imgToPdf(samplePath,pdfPath);
            }

            PDDocument document = null;
            try {
                // 加载PDF文档
                File pdfFile = new File(pdfPath);
                document = PDDocument.load(pdfFile);

                // 创建一个打印任务
                PrinterJob job = PrinterJob.getPrinterJob();


                // 查找并设置打印机
                PrintService defaultPrintService = getPrintService(cons);
                if (defaultPrintService != null) {
                    job.setPrintService(defaultPrintService);
                }else {
                    downStaus = 0;
                    return Rest.fail("未找到打印机");
                }

                job.setJobName(pdfFile.getName());
                //设置纸张
                PDFPrintable pdfPrintable = new PDFPrintable(document);
                //设置多页打印
                Book book = new Book();
                PageFormat pageFormat = new PageFormat();
                Paper paper = getPaper();
                pageFormat.setPaper(paper);
                book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
                job.setPageable(new PDFPageable(document));
                job.setPageable(book);
                job.setCopies(1);//设置打印份数

                HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
                pars.add(Sides.ONE_SIDED); // 设置单双页
                pars.add(MediaSizeName.ISO_A4);//默认A4纸打印
                // 执行打印
                job.print(pars);

                log.info("打印成功！");
                downStaus = 0;
                return Rest.ok();
            }catch (PrinterException e){
                log.error("打印异常", e);
                downStaus = 0;
                return Rest.fail("打印异常");
            }catch (IOException e){
                log.error("文件处理异常", e);
                downStaus = 0;
                return Rest.fail("文件处理异常");
            }finally {
                if (document != null) {
                    try {
                        // 关闭PDF文档
                        document.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }else {
            downStaus = 0;
            return Rest.fail("文件下载失败");
        }


    }

    private Paper getPaper() {
        Paper paper = new Paper();
        // 默认为A4纸张，对应像素宽和高分别为 595, 842
        int width = 595;
        int height = 842;
        // 设置边距，单位是像素，10mm边距，对应 28px
        int marginLeft = 12;
        int marginRight = 12;
        int marginTop = 12;
        int marginBottom = 12;
        paper.setSize(width, height);
        // 下面一行代码，解决了打印内容为空的问题
        paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
        return paper;
    }


    public boolean isExsitArry(String chex, String arry[]) {
        for (String ex : arry) {
            if (chex.equalsIgnoreCase(ex)) {
                return true;
            }
        }
        return false;
    }




    @Override
    public String getType() {
        return PrintTypeEnum.PRINT_URL.getValue();
    }

    public static void main(String[] args) throws PrinterException, IOException {
        ComponentCons cons = new ComponentCons();
        cons.setUrl("http://192.168.0.98:11091/file/fileupload/1730257895855.docx");
        cons.setPapertype("A4");

        new UrlPrintComponent("url").print(cons);


//        // 加载PDF文档
//        File pdfFile = new File("H:\\test.pdf");
//        PDDocument document = PDDocument.load(pdfFile);
//
//        // 创建一个打印任务
//        PrinterJob job = PrinterJob.getPrinterJob();
//        job.setPageable(new PDFPageable(document));
//
//        // 查找并设置打印机
//        PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
//        if (defaultPrintService != null) {
//            job.setPrintService(defaultPrintService);
//        }
//
//        // 执行打印
//        job.print();
//
//        // 关闭PDF文档
//        document.close();

    }
}
