package com.yem.wm.im.intauditbusa.op;

import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.YEM;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.exception.KDException;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.print.api.PrintTask;
import kd.bos.print.api.PrintWork;
import kd.bos.print.core.service.PrtAttach;
import kd.bos.print.service.BosPrintServiceHelper;
import kd.bos.servicehelper.AttDto;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 单据操作
 */
public class IntAuditBuSaAuditOp extends AbstractOperationServicePlugIn implements Plugin {
    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
//            writeBackSumCost(dataEntitie);
            createPdf(dataEntitie);
        }
    }

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
    }

    /**
     * @description 反写金额系列字段
     * @author xwudd
     * @param[1] dataEntitie
     * return
     * @time 2023/10/30 9:18
     */

    public void writeBackSumCost(DynamicObject dataEntitie) {
        DynamicObject billType = dataEntitie.getDynamicObject("yem_billtype");
        if (YEM.isNotEmpty(billType)) {
            String number = billType.getString("number");
            if ("yem_im_intauditbusa_ZJWX".equals(number)) {
                String sourceBillType = dataEntitie.getString("yem_sourcebilltype");
                Long sourceBillId = dataEntitie.getLong("yem_sourcebillid");
                Long sourceEntryId = dataEntitie.getLong("yem_sourceentryid");
                DynamicObject entity = BusinessDataServiceHelper.loadSingle(sourceBillId, sourceBillType);
                if (YEM.isNotEmpty(entity)) {
                    String name = entity.getDynamicObjectType().getName();
                    DynamicObjectCollection entrys = null;
                    if ("yem_es_salesorder".equals(name)) {
                        entrys = entity.getDynamicObjectCollection("yem_es_materialinfo");
                    }
                    if ("yem_im_clientdemand".equals(name)) {
                        entrys = entity.getDynamicObjectCollection("yem_im_detailedinfor");
                    }
                    BigDecimal commissionAmtTotal = BigDecimal.ZERO;
                    BigDecimal commissionAmtBaTotal = BigDecimal.ZERO;
                    BigDecimal commissionAmt = (BigDecimal) dataEntitie.get("yem_commissionamt");
                    BigDecimal commissionAmtBa = (BigDecimal) dataEntitie.get("yem_commissionamtba");
                    commissionAmtTotal = commissionAmtTotal.add(commissionAmt);
                    commissionAmtBaTotal = commissionAmtBaTotal.add(commissionAmtBa);
                    if (YEM.isNotEmpty(entrys)) {
                        BigDecimal amtPriceClause = BigDecimal.ZERO;
                        BigDecimal amtPriceClauseBase = BigDecimal.ZERO;
                        for (DynamicObject entry : entrys) {
                            long entryId = entry.getLong("id");
                            if (sourceEntryId == entryId) {
                                BigDecimal disAmt = entry.getBigDecimal("yem_disamt");
                                BigDecimal saFobPrice = entry.getBigDecimal("yem_safobprice");//销售fob单价
                                BigDecimal exrate = entity.getBigDecimal("yem_exrate");//汇率
                                BigDecimal qty = entry.getBigDecimal("yem_qty");//数量
                                BigDecimal priceFieldAccBa = entry.getBigDecimal("yem_pricefieldaccba");//资源配置单价
                                BigDecimal sumCost = (BigDecimal) dataEntitie.get("yem_sumcost");
                                BigDecimal sumCostBase = (BigDecimal) dataEntitie.get("yem_sumcostbase");
                                BigDecimal saPricePriceClause = BigDecimal.ZERO;
                                if(disAmt.compareTo(BigDecimal.ZERO) > 0){
                                    BigDecimal afterFrontDisPrice = entity.getBigDecimal("yem_afterfrontdisprice");
                                    saPricePriceClause = afterFrontDisPrice.add(priceFieldAccBa).add(sumCost);
                                }else{
                                    saPricePriceClause = saFobPrice.add(priceFieldAccBa).add(sumCost);
                                }
                                BigDecimal frontDisPrice = sumCost.add(saFobPrice);
                                BigDecimal frontDisAmt = frontDisPrice.multiply(qty);
                                BigDecimal saaAmtPriceClause = saPricePriceClause.multiply(qty);
                                BigDecimal saaAmtPriceClauseBase = saaAmtPriceClause.multiply(exrate);
                                amtPriceClause = amtPriceClause.add(saaAmtPriceClause);
                                amtPriceClauseBase = amtPriceClauseBase.add(saaAmtPriceClauseBase);

                                entry.set("yem_onecarsum", sumCost);//单车总费用
                                entry.set("yem_onecarsumbase", sumCostBase);//单车总费用(人民币)
                                entry.set("yem_sapricepriceclause", saPricePriceClause);//销售单价（价格条款）
                                entry.set("yem_sapriceclausebase", saPricePriceClause.multiply(exrate));//销售单价（价格条款人民币）
                                entry.set("yem_saamtpriceclause", saaAmtPriceClause);//销售金额（价格条款）
                                entry.set("yem_samtpriceclauseba", saaAmtPriceClauseBase);//销售金额（价格条款人民币）
                                entry.set("yem_truecarprice", saFobPrice.add(sumCost));//实际整车单价
                                entry.set("yem_truecaramt", (saFobPrice.add(sumCost)).multiply(qty));//实际整车金额
                                entry.set("yem_truecarpriceba", (saFobPrice.add(sumCost)).multiply(exrate));//实际整车单价人民币
                                entry.set("yem_truecaramtba", (saFobPrice.add(sumCost)).multiply(qty).multiply(exrate));//实际整车金额人民币
//                                    entry.set("yem_commissionamten",commissionAmt);//
//                                    entry.set("yem_commissionamtbaen",commissionAmtBa);//
                                entry.set("yem_frontdisprice", frontDisPrice);//折扣前销售单价
                                entry.set("yem_frontdisamt", frontDisAmt);//折扣前销售金额
                                entry.set("yem_totalamount", sumCost.multiply(entry.getBigDecimal("yem_qty")));//总费用
                                entry.set("yem_totalamountrmb", sumCostBase.multiply(entry.getBigDecimal("yem_qty")));//总费用（人民币）
                            } else {
                                amtPriceClause = amtPriceClause.add(entry.getBigDecimal("yem_saamtpriceclause"));
                                amtPriceClauseBase = amtPriceClauseBase.add(entry.getBigDecimal("yem_samtpriceclauseba"));
                                BigDecimal commissionAmtEn = entry.getBigDecimal("yem_commissionamten");
                                BigDecimal commissionAmtBaEn = entry.getBigDecimal("yem_commissionamtbaen");
                                commissionAmtTotal = commissionAmtTotal.add(commissionAmtEn);
                                commissionAmtBaTotal = commissionAmtBaTotal.add(commissionAmtBaEn);
                            }
                        }
                        BigDecimal oneCarSum = BigDecimal.ZERO;
                        BigDecimal oneCarBaseSum = BigDecimal.ZERO;
                        for (DynamicObject entry : entrys) {
                            BigDecimal qty = entry.getBigDecimal("yem_qty");
                            BigDecimal oneCar = entry.getBigDecimal("yem_onecarsum");
                            BigDecimal oneCarBase = entry.getBigDecimal("yem_onecarsumbase");
                            oneCarSum = oneCarSum.add(qty.multiply(oneCar));
                            oneCarBaseSum = oneCarBaseSum.add(qty.multiply(oneCarBase));
                        }
                        entity.set("yem_sumcost", oneCarSum);
                        entity.set("yem_sumcostbase", oneCarBaseSum);
                        entity.set("yem_offeramount", amtPriceClause);
                        entity.set("yem_offerstandardcoin", amtPriceClauseBase);
                        DynamicObject recCondition = entity.getDynamicObject("yem_reccondition");
                        if(YEM.isNotEmpty(recCondition)){
                            String basis = recCondition.getString("basis");
                            if("A".equals(basis)){
                                DynamicObjectCollection salesContraC_ss = null;
                                if(sourceBillType.equals("yem_im_clientdemand")){
                                    salesContraC_ss = entity.getDynamicObjectCollection("yem_salescontrac_s");
                                }else{
                                    salesContraC_ss = entity.getDynamicObjectCollection("yem_es_salescontrac_s");
                                }
                                for(DynamicObject salesContraC_s : salesContraC_ss){
                                    BigDecimal rapRate = salesContraC_s.getBigDecimal("yem_raprate");
                                    salesContraC_s.set("yem_rapamt",rapRate.divide(new BigDecimal(100)).multiply(amtPriceClause));
                                }
                            }
                        }
                    }
                    SaveServiceHelper.save(new DynamicObject[]{entity});
                }
            }
            if ("yem_im_intauditbusa_PJWX".equals(number)) {
                String sourceBillType = dataEntitie.getString("yem_sourcebilltype");
                Long sourceBillId = dataEntitie.getLong("yem_sourcebillid");
                Long sourceEntryId = dataEntitie.getLong("yem_sourceentryid");
                DynamicObject entity = BusinessDataServiceHelper.loadSingle(sourceBillId, sourceBillType);
                if (YEM.isNotEmpty(entity)) {
//                        entity.set("yem_commissionamt",dataEntitie.getBigDecimal("yem_commissionamt"));
//                        entity.set("yem_commissionamtba",dataEntitie.getBigDecimal("yem_commissionamtba"));
                    BigDecimal exrate = entity.getBigDecimal("yem_exrate");
                    BigDecimal carLoadFobPrice = dataEntitie.getBigDecimal("yem_carloadfobprice");
                    BigDecimal carLoadFobPriceBa = dataEntitie.getBigDecimal("yem_carloadfobpriceba");
                    BigDecimal contractPriceSum = dataEntitie.getBigDecimal("yem_contractpricesum");
                    BigDecimal contractPriceSumBa = dataEntitie.getBigDecimal("yem_contractpricesumba");
                    BigDecimal sumCost = dataEntitie.getBigDecimal("yem_sumcost");
                    BigDecimal sumCostBase = dataEntitie.getBigDecimal("yem_sumcostbase");
                    BigDecimal currTotalAmount = BigDecimal.ZERO;
                    BigDecimal currOneCarSum = BigDecimal.ZERO;
                    entity.set("yem_offeramount", contractPriceSum);//
                    entity.set("yem_offerstandardcoin", contractPriceSumBa);//
                    String name = entity.getDynamicObjectType().getName();
                    DynamicObjectCollection entrys = null;
                    if ("yem_es_salesorder".equals(name)) {
                        entrys = entity.getDynamicObjectCollection("yem_es_materialinfo");
                    }
                    if ("yem_im_clientdemand".equals(name)) {
                        entrys = entity.getDynamicObjectCollection("yem_im_detailedinfor");
                    }

                    int lastIdx = 0;

                    for (DynamicObject entry : entrys) {
                        int index = entrys.indexOf(entry);
                        boolean ifGift = entry.getBoolean("yem_ifgift");
                        if (!ifGift) {
                            lastIdx = index;
                        }
                    }

                    for (DynamicObject entry : entrys) {
                        int index = entrys.indexOf(entry);
                        boolean ifGift = entry.getBoolean("yem_ifgift");
                        if (!ifGift) {
                            BigDecimal disAmt = entry.getBigDecimal("yem_disamt");
                            BigDecimal qty = entry.getBigDecimal("yem_qty");
                            BigDecimal saFobAmount = entry.getBigDecimal("yem_safobamount");
                            BigDecimal saFobPrice = entry.getBigDecimal("yem_safobprice");//销售fob单价
                            BigDecimal oneCarSum = saFobAmount.divide(carLoadFobPrice, RoundingMode.HALF_UP).multiply(sumCost).divide(qty, RoundingMode.HALF_UP);
                            BigDecimal oneCarSumBase = oneCarSum.multiply(exrate);
                            BigDecimal frontDisPrice = oneCarSum.add(saFobPrice);
                            BigDecimal frontDisAmt = frontDisPrice.multiply(qty);
                            BigDecimal saPricePriceClause = BigDecimal.ZERO;
                            if(disAmt.compareTo(BigDecimal.ZERO) > 0){
                                BigDecimal afterFrontDisPrice = entry.getBigDecimal("yem_afterfrontdisprice");
                                saPricePriceClause = afterFrontDisPrice.add(oneCarSum);
                            }else{
                                saPricePriceClause = saFobPrice.add(oneCarSum);
                            }
                            BigDecimal saPriceAmtClause = saPricePriceClause.multiply(qty);

                            entry.set("yem_saamtpriceclause", saPriceAmtClause);//销售金额（价格条款）
                            entry.set("yem_sapricepriceclause", saPricePriceClause);//销售单价（价格条款）
                            entry.set("yem_samtpriceclauseba", saPriceAmtClause.multiply(exrate));//销售金额（价格条款）（人民币）
                            entry.set("yem_sapriceclausebase", saPricePriceClause.multiply(exrate));//销售单价（价格条款）（人民币）
                            entry.set("yem_frontdisprice", frontDisPrice);//折扣前销售单价
                            entry.set("yem_frontdisamt", frontDisAmt);//折扣前销售金额

                            BigDecimal calcTotalAmount = saFobAmount.divide(carLoadFobPrice, RoundingMode.HALF_UP).multiply(sumCost);
                            // 尾差处理
                            BigDecimal scale = sumCost.subtract(currTotalAmount.setScale(2, RoundingMode.HALF_UP));
                            if (index == lastIdx) {
                                entry.set("yem_totalamount", scale.setScale(2, RoundingMode.HALF_UP));//总费用
                                entry.set("yem_totalamountrmb", scale.multiply(exrate));//总费用（人民币）
                                entry.set("yem_onecarsum", scale.divide(qty, RoundingMode.HALF_UP));//总费用
                                entry.set("yem_onecarsumbase", scale.divide(qty, RoundingMode.HALF_UP).multiply(exrate));//总费用（人民币）
                            } else {
                                entry.set("yem_totalamount", calcTotalAmount.setScale(2, RoundingMode.HALF_UP));//总费用
                                entry.set("yem_totalamountrmb", calcTotalAmount.multiply(exrate));//总费用（人民币）
                                entry.set("yem_onecarsum", calcTotalAmount.divide(qty, RoundingMode.HALF_UP));//总费用
                                entry.set("yem_onecarsumbase", calcTotalAmount.divide(qty, RoundingMode.HALF_UP).multiply(exrate));//总费用（人民币）
                                currTotalAmount = currTotalAmount.add(calcTotalAmount.setScale(2, RoundingMode.HALF_UP));
                            }

                        } else {
                            entry.set("yem_onecarsum", null);//总费用
                            entry.set("yem_onecarsumbase", null);//总费用（人民币）
                            entry.set("yem_saamtpriceclause", null);//销售金额（价格条款）
                            entry.set("yem_sapricepriceclause", null);//销售单价（价格条款）
                            entry.set("yem_samtpriceclauseba", null);//销售金额（价格条款）（人民币）
                            entry.set("yem_sapriceclausebase", null);//销售单价（价格条款）（人民币）
                            entry.set("yem_frontdisprice", null);//折扣前销售单价
                            entry.set("yem_frontdisamt", null);//折扣前销售金额
                        }
                    }
                    entity.set("yem_sumcost", sumCost);//
                    entity.set("yem_sumcostbase", sumCostBase);//

                    DynamicObject recCondition = entity.getDynamicObject("yem_reccondition");
                    if(YEM.isNotEmpty(recCondition)){
                        String basis = recCondition.getString("basis");
                        if("A".equals(basis)){
                            DynamicObjectCollection salesContraC_ss = null;
                            if(sourceBillType.equals("yem_im_clientdemand")){
                                salesContraC_ss = entity.getDynamicObjectCollection("yem_salescontrac_s");
                            }else{
                                salesContraC_ss = entity.getDynamicObjectCollection("yem_es_salescontrac_s");
                            }
                            for(DynamicObject salesContraC_s : salesContraC_ss){
                                BigDecimal rapRate = salesContraC_s.getBigDecimal("yem_raprate");
                                salesContraC_s.set("yem_rapamt",rapRate.divide(new BigDecimal(100)).multiply(contractPriceSum));
                            }
                        }
                    }

                    SaveServiceHelper.save(new DynamicObject[]{entity});
                }
            }
        }
    }


//    public void createPdf(DynamicObject dataEntitie) {
//        String billKey = dataEntitie.getDataEntityType().getName();
//        DynamicObject billType = dataEntitie.getDynamicObject("yem_billtype");
//        String billTypeNumber = YEM.isNotEmpty(billType) ? billType.getString("number") : "";
//        String selectFields = DynamicObjectUtil.getSelectfields("bos_manageprinttpl", false);
//        List<DynamicObject> managePrintTpls = new ArrayList();
//        if ("yem_im_intauditbusa_PJWX".equals(billTypeNumber)) {
//            DynamicObject[] managePrintTpl = BusinessDataServiceHelper.load("bos_manageprinttpl", selectFields, new QFilter[]{new QFilter("billformid.number", QCP.equals, billKey), new QFilter("printtplid.number", QCP.like, "%PJ%"), new QFilter("enable", QCP.equals, "1")});
//            if (managePrintTpl.length > 0) {
//                managePrintTpls.add(managePrintTpl[0]);
//            }
//        }
//        if ("yem_im_intauditbusa_ZJWX".equals(billTypeNumber)) {
//            DynamicObject[] managePrintTpl = BusinessDataServiceHelper.load("bos_manageprinttpl", selectFields, new QFilter[]{new QFilter("billformid.number", QCP.equals, billKey), new QFilter("printtplid.number", QCP.like, "%HSZJ%"), new QFilter("enable", QCP.equals, "1")});
//            if (managePrintTpl.length > 0) {
//                managePrintTpls.add(managePrintTpl[0]);
//            }
//            managePrintTpl = BusinessDataServiceHelper.load("bos_manageprinttpl", selectFields, new QFilter[]{new QFilter("billformid.number", QCP.equals, billKey), new QFilter("printtplid.number", QCP.like, "%NSZJ%"), new QFilter("enable", QCP.equals, "1")});
//            if (managePrintTpl.length > 0) {
//                managePrintTpls.add(managePrintTpl[0]);
//            }
//        }
//        long id = dataEntitie.getLong("id");
//        //租户ID
//        String tenantId = RequestContext.get().getTenantId();
//        //账套ID
//        String accountId = RequestContext.get().getAccountId();
//        for (DynamicObject managePrintTpl : managePrintTpls) {
//            if (YEM.isNotEmpty(managePrintTpl)) {
//                String tplIdByNum = managePrintTpl.getDynamicObject("printtplid").getString("number");
//                String tplId = BosPrintServiceHelper.getTplIdByNum(tplIdByNum);
//                String attName = FunctionalCommon.setAttName(tplIdByNum, dataEntitie);
//                PrintWork work = new PrintWork();
//                //设置打印语言
//                work.setPrintLang("zh_CN");
//                //设置类型：1代表pdf
//                work.setExpType("1");
//                List<PrintTask> printTasks = new ArrayList<>();
//                PrintTask printTask = new PrintTask();
//                //设置模板ID
//                printTask.setTplId(tplId);
//                //设置当前单据id
//                printTask.setPkIds(new ArrayList<Object>(Arrays.asList(id)));
//                printTasks.add(printTask);
//                work.setTaskList(printTasks);
//                //调用打印服务接口
//                PrtAttach prtAttach = BosPrintServiceHelper.doPrint(work);
//                //获取生成的pdf在文件服务器中的路径
//                String path = prtAttach.getAttachDetail().get(0).getFilePath();
//                //因为打印生成的临时文件，后续会自动清理，故而需要业务上传的文件服务器转存。
//                FileService fileService = FileServiceFactory.getAttachmentFileService();
//                InputStream inputStream = FileServiceFactory.getAttachmentFileService().getInputStream(path);
//                try {
//                    ByteArrayOutputStream dest = new ByteArrayOutputStream();
//                    IOUtils.copy(inputStream, dest);
//                    InputStream stream1 = new ByteArrayInputStream(dest.toByteArray());
//                    InputStream stream2 = new ByteArrayInputStream(dest.toByteArray());
//                    long fileSize = getFileSize(stream1);
//                    SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
//                    String date = yyyyMMdd.format(new Date());
//                    String biilNo = dataEntitie.getString("billno");
//                    path = fileService.upload(new FileItem(attName + ".pdf", "/" + tenantId + "/" + accountId + "/" + date + "/yem_im_intauditbus_prtpl/" + attName + ".pdf", stream2));
////                path = fileService.upload(new FileItem(attName + ".pdf", "/yxzg-topview-dev/1797950314112879616/" + date + "/yem_im_intauditbus_prtpl/" + attName + ".pdf", inputStream));
//
//                    List<Map<String, Object>> attachments = new ArrayList<>();
//                    Map<String, Object> attaMap = new HashMap<>(16);
//                    attaMap.put("size", fileSize);
//                    attaMap.put("url", path);
//                    attaMap.put("name", attName + ".pdf");
//                    attaMap.put("type", ".pdf");
//                    attaMap.put("uid", "rc-upload-" + System.nanoTime() + "-" + (int) (Math.random() * 100));
//                    attaMap.put("status", "success");
//                    attaMap.put("entityNum", dataEntitie.getString("yem_sourcebilltype"));
//                    attaMap.put("client", "web");
//                    // 当前时间戳
//                    long time = System.currentTimeMillis();
//                    attaMap.put("createdate", time);
//                    attaMap.put("lastModified", time);
//                    attachments.add(attaMap);
//                    AttachmentServiceHelper.upload(dataEntitie.getString("yem_sourcebilltype"), String.valueOf(dataEntitie.getLong("yem_sourcebillid")), "attachmentpanel", attachments);
////                    List<AttDto> attDtoList = new ArrayList<>();
////                    AttDto attDto = new AttDto();
////                    //绑定文件服务器中的路径
////                    attDto.setPath(path);
////                    //单据附件标识
////                    attDto.setAttKey("attachmentpanel");
////                    //文件大小(字节数)
////                    attDto.setSize(Long.valueOf(AttachmentServiceHelper.getFileSizeByPath(path)));
////                    attDtoList.add(attDto);
////                    //第一个参数为目标单据标识;第二个参数为目标单据pkId,第三个参数为附件列表
////                    Map<String, Object> bindingParam = AttachmentServiceHelper.genBindingParam(dataEntitie.getString("yem_sourcebilltype"), String.valueOf(dataEntitie.getLong("yem_sourcebillid")), attDtoList);
////                    //绑定接口返回结果
////                    Map<String, Object> resultMap = AttachmentServiceHelper.bindingAttachment(bindingParam);
//                } catch (Exception e) {
//                    String message = e.getMessage();
//                    e.printStackTrace();
//                }
//
//            }
//        }
//    }

    public void createPdf(DynamicObject dataEntitie) {
        String billKey = dataEntitie.getDataEntityType().getName();
        DynamicObject billType = dataEntitie.getDynamicObject("yem_billtype");
        String billTypeNumber = YEM.isNotEmpty(billType) ? billType.getString("number") : "";
        String selectFields = DynamicObjectUtil.getSelectfields("bos_manageprinttpl", false);
        List<DynamicObject> managePrintTpls = new ArrayList();
        if ("yem_im_intauditbusa_PJWX".equals(billTypeNumber)) {
            DynamicObject[] managePrintTpl = BusinessDataServiceHelper.load("bos_manageprinttpl", selectFields,
                    new QFilter[]{new QFilter("billformid.number", QCP.equals, billKey),
                            new QFilter("printtplid.number", QCP.like, "%PJ%"),
                            new QFilter("enable", QCP.equals, "1")});
            if (managePrintTpl.length > 0) {
                managePrintTpls.add(managePrintTpl[0]);
            }
        }
        if ("yem_im_intauditbusa_ZJWX".equals(billTypeNumber)) {
            DynamicObject[] managePrintTpl = BusinessDataServiceHelper.load("bos_manageprinttpl", selectFields,
                    new QFilter[]{new QFilter("billformid.number", QCP.equals, billKey),
                            new QFilter("printtplid.number", QCP.like, "%HSZJ%"),
                            new QFilter("enable", QCP.equals, "1")});
            if (managePrintTpl.length > 0) {
                managePrintTpls.add(managePrintTpl[0]);
            }
            managePrintTpl = BusinessDataServiceHelper.load("bos_manageprinttpl", selectFields,
                    new QFilter[]{new QFilter("billformid.number", QCP.equals, billKey),
                            new QFilter("printtplid.number", QCP.like, "%NSZJ%"),
                            new QFilter("enable", QCP.equals, "1")});
            if (managePrintTpl.length > 0) {
                managePrintTpls.add(managePrintTpl[0]);
            }
        }
        long id = dataEntitie.getLong("id");
        //租户ID
        String tenantId = RequestContext.get().getTenantId();
        //账套ID
        String accountId = RequestContext.get().getAccountId();
        for (DynamicObject managePrintTpl : managePrintTpls) {
            if (YEM.isNotEmpty(managePrintTpl)) {
                String tplIdByNum = managePrintTpl.getDynamicObject("printtplid").getString("number");
                String tplId = BosPrintServiceHelper.getTplIdByNum(tplIdByNum);
                String attName = FunctionalCommon.setAttName(tplIdByNum, dataEntitie);
                PrintWork work = new PrintWork();
                //设置打印语言
                work.setPrintLang("zh_CN");
                //设置类型：1代表pdf
                work.setExpType("1");
                List<PrintTask> printTasks = new ArrayList<>();
                PrintTask printTask = new PrintTask();
                //设置模板ID
                printTask.setTplId(tplId);
                //设置当前单据id
                printTask.setPkIds(new ArrayList<Object>(Arrays.asList(id)));
                printTasks.add(printTask);
                work.setTaskList(printTasks);
                //调用打印服务接口
                PrtAttach prtAttach = BosPrintServiceHelper.doPrint(work);
                //获取生成的pdf在文件服务器中的路径
                String path = prtAttach.getAttachDetail().get(0).getFilePath();
                //因为打印生成的临时文件，后续会自动清理，故而需要业务上传的文件服务器转存。
                FileService fileService = FileServiceFactory.getAttachmentFileService();
                InputStream inputStream = FileServiceFactory.getAttachmentFileService().getInputStream(path);
                SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
                String date = yyyyMMdd.format(new Date());
                String biilNo = dataEntitie.getString("billno");
                path = fileService.upload(new FileItem(attName + ".pdf", "/" + tenantId + "/" + accountId + "/" + date + "/yem_im_intauditbus_prtpl/" + attName + ".pdf", inputStream));
                path = "/" + tenantId + "/" + accountId + "/" + date + "/yem_im_intauditbus_prtpl/" + attName + ".pdf";
                try {
                    List<AttDto> attDtoList = new ArrayList<>();
                    AttDto attDto = new AttDto();
                    //绑定文件服务器中的路径
                    attDto.setPath(path);
                    //单据附件标识
                    attDto.setAttKey("attachmentpanel");
                    //文件大小(字节数)
                    attDto.setSize(Long.valueOf(AttachmentServiceHelper.getFileSizeByPath(attDto.getPath())));
                    attDtoList.add(attDto);
                    //第一个参数为目标单据标识;第二个参数为目标单据pkId,第三个参数为附件列表
                    Map<String, Object> bindingParam = AttachmentServiceHelper.genBindingParam(dataEntitie.getString("yem_sourcebilltype"),
                            String.valueOf(dataEntitie.getLong("yem_sourcebillid")), attDtoList);
                    //绑定接口返回结果
                    Map<String, Object> resultMap = AttachmentServiceHelper.bindingAttachment(bindingParam);
                } catch (Exception e) {
                    String message = e.getMessage();
                    e.printStackTrace();
                    throw new KDException(e.getMessage());
                }

            }
        }
    }

    public static long getFileSize(InputStream instream) throws IOException {
        long fileSize = 0;
        byte[] buffer = new byte[1024];
        int len;
        while ((len = instream.read(buffer)) != -1) {
            fileSize += len;
        }
        instream.close();
        return fileSize;
    }

    private static ByteArrayOutputStream cloneInputStream(InputStream input) {

        try {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];

            int len;

            while ((len = input.read(buffer)) > -1) {

                baos.write(buffer, 0, len);

            }

            baos.flush();

            return baos;

        } catch (IOException e) {

            e.printStackTrace();

            return null;

        }

    }

}
