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


import com.mortals.framework.exception.AppException;
import com.mortals.xhx.common.code.PrintTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.print.PrinterJob;

@Slf4j
public abstract class BasePrintComponent {

    private String type;

    public BasePrintComponent(String type) {
        this.type = type;
    }


    public abstract void print(ComponentCons cons);

    protected PrintService getPrintService(ComponentCons cons) {
        PrintService printService = null;
        if (ObjectUtils.isEmpty(cons.getPrintername())) {
            printService = PrintServiceLookup.lookupDefaultPrintService();
            if(printService==null){
                PrintService[] printServices = PrinterJob.lookupPrintServices();
                if(printServices.length>0){
                    printService=printServices[0];
                }
            }
        } else {
            // 匹配指定打印机
            // 获得本台电脑连接的所有打印机
            PrintService[] printServices = PrinterJob.lookupPrintServices();
            if (printServices == null || printServices.length == 0) {
                log.info("打印失败，未找到可用打印机，请检查!");
                throw new AppException("打印失败，未找到可用打印机，请检查!");
            }
            for (int i = 0; i < printServices.length; i++) {
                log.info(printServices[i].getName());
                if (printServices[i].getName().contains(cons.getPrintername())) {
                    printService = printServices[i];
                    break;
                }
            }
            if(printService==null){
                printService = PrintServiceLookup.lookupDefaultPrintService();
            }
        }
        return printService;
    }

    public static BasePrintComponent createType(String type) {
        if (type.equals(PrintTypeEnum.PRINT_URL.getValue())) {
            return new UrlPrintComponent(type);
        } else if (type.equals(PrintTypeEnum.PRINT_BASE64.getValue())) {
            return new Base64PrintComponent(type);
        } else if (type.equals(PrintTypeEnum.PRINT_NORMAL.getValue())) {
            return new NormalPrintComponent(type);
        } else {
            throw new AppException(String.format("不支持当前组件类型,Type:%s", type));
        }
    }

    public abstract String getType();

}
