package com.kmall.common.utils.print.ticket;

import com.kmall.common.utils.print.ticket.doc.PrintAttributeBuilder;
import com.kmall.common.utils.print.ticket.item.Ticket;

import javax.print.*;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

/**
 * 票据打印类
 *
 * @author Scott Chen
 * @since 1.0
 * 2018-10-26
 */
public class TicketPrinter {

    /**
     * 打印票据一
     *
     * @param ticket
     */
    public static void print(Ticket ticket) {
        try {
            // 创建打印作业
            PrinterJob job = PrinterJob.getPrinterJob();
            if (job.getPrintService() == null) {
                throw new PrinterException("没有默认打印机");
            }

            // 打印票据构建
            TicketBuilder ticketBuilder = new TicketBuilder();
            if (ticket == null) {
                throw new PrinterException("无对应小票信息");
            }
            ticketBuilder.setTicket(ticket);

            //设置打印文档
            job.setPageable(ticketBuilder.getPage());

            job.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印票据二
     *
     * @param ticket
     */
    public static void print2(Ticket ticket) {

        // 获取默认的打印服务
        PrintService pringService = PrintServiceLookup.lookupDefaultPrintService();
        if (pringService == null) {
            throw new RuntimeException("没有默认打印服务");
        }

        // 创建打印作业
        DocPrintJob job = pringService.createPrintJob();
        if (job.getPrintService() == null) {
            throw new RuntimeException("没有默认打印机");
        }

        // 打印属性设置(自定义)
        PrintAttributeBuilder printAttr = new PrintAttributeBuilder();


        // 小票打印信息
        TicketBuilder ticketBuilder = new TicketBuilder();
        if (ticket == null) {
            throw new IllegalArgumentException("无对应小票信息");
        }
        ticketBuilder.setTicket(ticket);


        /**
         * 打印文档设置
         * ticketBuilder 为实现Printable接口的类实例
         */
        Doc doc = new SimpleDoc(ticketBuilder,
                printAttr.buildDocFlavor(),
                printAttr.buildDocAttributeSet());

        // 不显示打印对话框,直接进行打印工作
        try {
            // 打印操作
            job.print(doc, printAttr.buildPrintRequestAttributeSet());

        } catch (PrintException pe) {
            pe.printStackTrace();
        }

    }


}
