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

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.xhx.common.code.Base64TypeEnum;
import com.mortals.xhx.common.code.PrintTypeEnum;

import org.apache.commons.codec.binary.Base64;

import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.Copies;
import java.io.File;
import java.util.Date;
import java.util.List;


public class Base64PrintComponent extends BasePrintComponent {

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

    @Override
    public Rest<Void> print(ComponentCons cons) {
        PrintService printService = getPrintService(cons);
        //base64 转换成图片 等其它 data:image/jpg;base64,/9j/4AAQSkZJRgA
        String base64 = cons.getBase64();
        String filePath = SpringUtil.getProperty("upload.path");
        List<String> split = StrUtil.split(base64, ",");
        if(split.size()<2){
            throw new AppException("base64格式不正确！");
        }
        String head = split.get(0);
        String base64Content = split.get(1);
        if(Base64TypeEnum.BASE64_FILETYPE_JPG.getDesc().equalsIgnoreCase(head)){
            return Rest.fail("暂不支持该格式");
        }else if(Base64TypeEnum.BASE64_FILETYPE_TXT.getDesc().equalsIgnoreCase(head)){
            String destFile = filePath + File.separator + new Date().getTime() + "." + Base64TypeEnum.BASE64_FILETYPE_TXT.getValue();
            //Base64Util.decodeBase64(destFile,base64Content);
            byte[] bytes = Base64.decodeBase64(base64Content);

            //打印文件
            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(bytes, flavor, das);
            try {
                job.print(doc, pras);
                return Rest.ok();
            } catch (PrintException e) {
//                throw new RuntimeException(e);
                return Rest.fail("打印错误");
            }

            //Base64Util.decodeBase64String()
        }


        //String type = StrUtil.subBetween(head, "data:", ";");

        //判断base64文件类型 生成不同类型文件

        return Rest.ok();




    }


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