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

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.mortals.xhx.common.code.PrintTypeEnum;
import lombok.extern.slf4j.Slf4j;

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;

@Slf4j
public class UrlPrintComponent extends BasePrintComponent {

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

    @Override
    public void print(ComponentCons cons) {
        PrintService printService = getPrintService(cons);
        //通过网络下载附件地址
        byte[] fileBytes = HttpUtil.downloadBytes(cons.getUrl());
        //获取文件后缀
        String suffixName = FileUtil.getSuffix(cons.getUrl());
        log.info("file lens:{}", fileBytes.length);
        log.info("file suffixName:{}", suffixName);

        //打印文件
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        DocPrintJob job = printService.createPrintJob();
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        DocAttributeSet das = new HashDocAttributeSet();
        pras.add(new Copies(1));
        Doc doc = new SimpleDoc(fileBytes, flavor, das);
        try {
            job.print(doc, pras);
        } catch (PrintException e) {
            throw new RuntimeException(e);
        }
    }


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