package nckd.jimin.jyyy.fi.common.util;

import kd.bos.dataentity.resource.ResManager;
import kd.bos.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.print.api.PrintContext;
import kd.bos.print.api.PrintTask;
import kd.bos.print.api.PrintWork;
import kd.bos.print.core.service.PrtAttach;
import kd.bos.print.core.service.PrtAttach.AttachDetail;
import kd.bos.print.service.BosPrintServiceHelper;
import kd.bos.servicehelper.print.NotePrintService;
import kd.bos.session.EncreptSessionUtils;
import kd.bos.url.UrlService;
import kd.bos.util.ExceptionUtils;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class PrintPdfUtil {
    private static Log logger = LogFactory.getLog(PrintPdfUtil.class);

    /**
     *  获取打印模板的pdf  支持新旧
     * @param pageId pageId
     * @param formId 单据类型
     * @param templateId 模板id
     * @param printType 1.billForm单据   2. querylist查询    3.report报表     4.dynamic 动态表单
     * @param type 1.旧模板 2.新模板
     * @param pkIds 单据id
     * @return
     */
    public static byte[] getPrintByte(String pageId, String formId, String templateId, List<Object> pkIds, String printType, int type) {
        byte[] returnBytes = null;
        try {
            if (type == 1) {
                NotePrintService printService = new NotePrintService();
                if (pkIds == null) {
                    Object object = new Object();
                    pkIds = new ArrayList<>(1);
                    pkIds.add(object);
                }
                returnBytes = printService.createSinglePdf(pageId, formId, templateId, pkIds.get(0));
            }
            if (type == 2) {
                returnBytes =  getNewPrintByte(pageId, formId, templateId, pkIds, printType);
            }
        } catch (Exception e) {
            throw e;
        }
        return returnBytes;
    }

    /**
     *  获取新打印模板的pdf
     * @param pageId pageId
     * @param formId 单据类型
     * @param templateId 模板id
     * @param printType 1.billForm单据   2. querylist查询    3.report报表     4.dynamic 动态表单
     * @param pkIds 单据id
     * @return
     * @throws IOException
     */
    public static byte[] getNewPrintByte(String pageId, String formId, String templateId, List<Object> pkIds, String printType) {
        PrintWork work = new PrintWork();
        work.setPageId(pageId);
        work.setPrintLang(PrintContext.get().getLang());
        // 导出类型 1. pdf  2.xls
        work.setExpType("1");
        PrintTask task = new PrintTask();
        task.setFormId(formId);
        task.setPageId(pageId);
        //task.setPrintType(printType);
        task.setTplId(templateId);
        task.setPkIds(pkIds);
        work.add(task);
        List<String> urls = new ArrayList<String>(2);
        PrtAttach prtAttach = BosPrintServiceHelper.execPrint(work);
        List<AttachDetail> attachDetails = prtAttach.getAttachDetail();
        for (AttachDetail attachDetail : attachDetails) {
            String xString   = attachDetail.getFilePath();
			/*String string  =  UrlService.getDomainContextUrl() + URLEncoder.encode(xString,ComonConstant.ENCODE);
			String downloadUrl = EncreptSessionUtils.encryptSession(string);*/
            urls.add(xString);
        }
        try {
            if (urls.size() > 0) {
                //InputStream inputStream = FileServiceFactory.getAttachmentFileService().getInputStream(urls.get(0));
                //execPrint方法改为获取临时文件流
                InputStream inputStream = BosPrintServiceHelper.getFileInputStream(urls.get(0));
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                try {
                    IOUtils.copy(inputStream, bos);
                } finally {
                    closeInputStreamQuietly(inputStream);
                }
                return bos.toByteArray();
            }
            return null;
        } catch (Exception e) {
            String message = String.format(ResManager.loadKDString("%1$s获取新打印模板的pdf失败：%2$s", "ArchiveOpService_9", "fi-aef-opplugin") ,formId, ExceptionUtils.getExceptionStackTraceMessage(e));
            throw new KDBizException(message);
        }
    }

    public static String getNewPrintUrl(String pageId, String formId, String templateId, List<Object> pkIds, String printType , String accessToken) {
        try{
            PrintWork work = new PrintWork();
            work.setPageId(pageId);
            work.setPrintLang(PrintContext.get().getLang());
            // 导出类型 1. pdf  2.xls
            work.setExpType("1");
            PrintTask task = new PrintTask();
            task.setFormId(formId);
            task.setPageId(pageId);
            //task.setPrintType(printType);
            task.setTplId(templateId);
            task.setPkIds(pkIds);
            work.add(task);
            PrtAttach prtAttach = BosPrintServiceHelper.execPrint(work);
            List<AttachDetail> attachDetails = prtAttach.getAttachDetail();
            if(attachDetails != null && attachDetails.size() > 0){
                String url = UrlService.getDomainContextUrl() + "/tempfile/download.do?" + attachDetails.get(0).getFilePath() + "&accessToken=" + accessToken;
                logger.info("临时地址为" + url);
                return EncreptSessionUtils.encryptSession(url);
            }
        }catch (Exception e){
            logger.error("获取单据打印url失败" , e);
            throw new KDBizException("获取单据打印url失败");
        }

        return "" ;
    }
    /**
     * 关闭 OutputStream 流
     */
    public static void closeOutputStreamQuietly(OutputStream output) {
        try {
            if (output != null)
                output.close();
        } catch (Exception e) {
        }
    }

    /**
     * 关闭 InputStream 流
     */
    public static void closeInputStreamQuietly(InputStream input) {
        try {
            if (input != null)
                input.close();
        } catch (Exception e) {
        }
    }
}