
package nckd.jxccl.hr.gzbb;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.TempFileCache;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.db.tx.TX;
import kd.bos.db.tx.TXHandle;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.fileservice.BatchDownloadRequest;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.fileservice.extension.FileServiceExtFactory;
import kd.bos.id.ID;
import kd.bos.logging.BizLog;
import kd.bos.org.utils.DynamicObjectUtils;
import kd.bos.orm.query.QFilter;
import kd.bos.orm.util.CollectionUtils;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.MetadataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.util.FileNameUtils;


public class AttachFileUtils {
    private static String BIDDOCUMENT_EDIT = "_biddocument_edit";
    private static String COM_ATTACHMENTPANEL = "com_attachmentpanel";
    private static String TECH_ATTACHMENTPANELAP = "tech_attachmentpanelap";
    private static String ATTACHMENTPANEL = "attachmentpanel";

    public AttachFileUtils() {
    }

    public static void copyBidDocumentFileToBill(String appId, Object sourceBillId, String sourceAttachKey, String destinationBillType, Object destinationBillId) {
        if (StringUtils.equals("all", sourceAttachKey)) {
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, ATTACHMENTPANEL, destinationBillType, destinationBillId, ATTACHMENTPANEL);
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, TECH_ATTACHMENTPANELAP, destinationBillType, destinationBillId, ATTACHMENTPANEL);
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, COM_ATTACHMENTPANEL, destinationBillType, destinationBillId, ATTACHMENTPANEL);
        } else if (StringUtils.equals(ATTACHMENTPANEL, sourceAttachKey)) {
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, ATTACHMENTPANEL, destinationBillType, destinationBillId, ATTACHMENTPANEL);
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, TECH_ATTACHMENTPANELAP, destinationBillType, destinationBillId, ATTACHMENTPANEL);
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, COM_ATTACHMENTPANEL, destinationBillType, destinationBillId, ATTACHMENTPANEL);
        }

    }

    public static void copyBidDocumentFileToBillExpComAndTech(String appId, Object sourceBillId, String sourceAttachKey, String destinationBillType, Object destinationBillId) {
        if (StringUtils.equals("all", sourceAttachKey)) {
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, ATTACHMENTPANEL, destinationBillType, destinationBillId, ATTACHMENTPANEL);
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, TECH_ATTACHMENTPANELAP, destinationBillType, destinationBillId, TECH_ATTACHMENTPANELAP);
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, COM_ATTACHMENTPANEL, destinationBillType, destinationBillId, COM_ATTACHMENTPANEL);
        } else if (StringUtils.equals(ATTACHMENTPANEL, sourceAttachKey)) {
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, ATTACHMENTPANEL, destinationBillType, destinationBillId, ATTACHMENTPANEL);
        } else if (StringUtils.equals(TECH_ATTACHMENTPANELAP, sourceAttachKey)) {
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, TECH_ATTACHMENTPANELAP, destinationBillType, destinationBillId, TECH_ATTACHMENTPANELAP);
        } else if (StringUtils.equals(COM_ATTACHMENTPANEL, sourceAttachKey)) {
            copyFileFromAToB(appId + BIDDOCUMENT_EDIT, sourceBillId, COM_ATTACHMENTPANEL, destinationBillType, destinationBillId, COM_ATTACHMENTPANEL);
        }

    }

    public static void synFileFromAToB(String sourceBillType, Object sourceBillId, String sourceAttachKey, String destinationBillType, Object destinationBillId, String destinationAttachKey) {
        List<Map<String, Object>> sourceFileList = AttachmentServiceHelper.getAttachments(sourceBillType, sourceBillId, sourceAttachKey);
        List<Object> sourceFileIdList = new ArrayList(50);
        Iterator var8 = sourceFileList.iterator();

        while(var8.hasNext()) {
            Map<String, Object> sourceAttach = (Map)var8.next();
            sourceFileIdList.add(sourceAttach.get("uid"));
        }

        List<Map<String, Object>> destinationFileList = AttachmentServiceHelper.getAttachments(destinationBillType, destinationBillId, destinationAttachKey);
        Iterator var12 = destinationFileList.iterator();

        while(var12.hasNext()) {
            Map<String, Object> destinationAttach = (Map)var12.next();
            if (!sourceFileIdList.contains(destinationAttach.get("uid"))) {
                AttachmentServiceHelper.remove(destinationBillType, destinationBillId, destinationAttach.get("uid"));
            }
        }

        copyFileFromAToB(sourceBillType, sourceBillId, sourceAttachKey, destinationBillType, destinationBillId, destinationAttachKey);
    }

    public static void copyFileFromAToB(String sourceBillType, Object sourceBillId, String sourceAttachKey, String destinationBillType, Object destinationBillId, String destinationAttachKey) {
        List<Map<String, Object>> sourceFileList = AttachmentServiceHelper.getAttachments(sourceBillType, sourceBillId, sourceAttachKey);
        copyFileToBillByPk(destinationBillType, destinationBillId, destinationAttachKey, sourceFileList);
    }

    public static void removeAllFile(String billType, Object billId, String attachKey) {
        List<Map<String, Object>> fileList = AttachmentServiceHelper.getAttachments(billType, billId, attachKey);
        Iterator var4 = fileList.iterator();

        while(var4.hasNext()) {
            Map<String, Object> sourceAttach = (Map)var4.next();
            AttachmentServiceHelper.remove(billType, billId, sourceAttach.get("uid"));
        }

    }

    public static void copyFileToBillByPk(String formId, Object pkId, String attachKey, List<Map<String, Object>> attachments) {
        if (pkId != null) {
            pkId = "" + pkId;
        }

        List<DynamicObject> attachmentFileList = new ArrayList();
        MainEntityType mainType = EntityMetadataCache.getDataEntityType("bos_attachment");
        FileService fileService = FileServiceFactory.getAttachmentFileService();
        Date date = new Date();
        int i = 1;

        for(Iterator var9 = attachments.iterator(); var9.hasNext(); ++i) {
            Map<String, Object> attach = (Map)var9.next();
            Long attPkId = (Long)((Long)attach.get("attPkId"));
            String uid = String.valueOf(attach.get("uid"));
            String fileName = String.valueOf(attach.get("name"));
            Long fileSize = (Long)attach.get("size");
            String fExtName = (String)attach.get("name");
            String newUid = String.format("%s-%s-%s", "rc-upload", date.getTime(), i);
            DynamicObject oldAttachment = BusinessDataServiceHelper.loadSingle(attPkId, "bos_attachment");
            String fileRelativePath = oldAttachment.getString("FFileId");
            InputStream in = fileService.getInputStream(fileRelativePath);
            RequestContext requestContext = RequestContext.get();
            String appId = "bid";
            if (formId.startsWith("rebm")) {
                appId = "rebm";
            }

            String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(), requestContext.getAccountId(), appId, formId, uid, fileName);
            FileItem fileItem = new FileItem(fileName, pathParam, in);
            String filePath = fileService.upload(fileItem);
            if (!StringUtils.isEmpty(filePath)) {
                DynamicObject newAttachment = new DynamicObject(mainType);
                newAttachment.set("id", ID.genLongId());
                newAttachment.set("FNUMBER", newUid);
                newAttachment.set("FBillType", formId);
                newAttachment.set("FInterID", pkId);
                Timestamp lastModified = (Timestamp)attach.get("lastModified");
                if (lastModified != null) {
                    newAttachment.set("FModifyTime", new Date(lastModified.getTime()));
                } else {
                    newAttachment.set("FModifyTime", new Date());
                }

                DynamicObject creator = oldAttachment.getDynamicObject("FCREATEMEN");
                if (creator != null) {
                    newAttachment.set("FCREATEMEN", creator.getLong("id"));
                }

                newAttachment.set("fcreatetime", new Date((Long)attach.get("createdate")));
                newAttachment.set("FaliasFileName", fileName);
                newAttachment.set("FAttachmentName", fileName);
                newAttachment.set("FExtName", fExtName != null ? fExtName.substring(fExtName.lastIndexOf(46) + 1) : "");
                newAttachment.set("FATTACHMENTSIZE", fileSize);
                newAttachment.set("fattachmentpanel", attachKey);
                newAttachment.set("fdescription", attach.get("description"));
                newAttachment.set("FFileId", filePath);
                attachmentFileList.add(newAttachment);
            }
        }

        if (!CollectionUtils.isEmpty(attachmentFileList)) {
            DynamicObject[] attachmentFileArray = new DynamicObject[attachmentFileList.size()];
            attachmentFileList.toArray(attachmentFileArray);
            SaveServiceHelper.save(attachmentFileArray);
        }

    }

    public static Map<String, List<String>> copyFileFromAToBReturnMap(String sourceBillType, Object sourceBillId, String sourceAttachKey, String destinationBillType, Object destinationBillId, String destinationAttachKey) {
        List<Map<String, Object>> sourceFileList = AttachmentServiceHelper.getAttachments(sourceBillType, sourceBillId, sourceAttachKey);
        return copyFileToBillByPkReturnMap(destinationBillType, destinationBillId, destinationAttachKey, sourceFileList);
    }

    public static Map<String, List<String>> copyFileToBillByPkReturnMap(String formId, Object pkId, String attachKey, List<Map<String, Object>> attachments) {
        if (pkId != null) {
            pkId = "" + pkId;
        }

        Map<String, List<String>> resultMap = new HashMap();
        List<String> updateUidList = new ArrayList(attachments.size());
        List<String> addUidList = new ArrayList(attachments.size());
        List<DynamicObject> attachmentFileList = new ArrayList();
        FileService fileService = FileServiceFactory.getAttachmentFileService();
        MainEntityType mainType = EntityMetadataCache.getDataEntityType("bos_attachment");
        Date date = new Date();
        int i = 1;

        for(Iterator var12 = attachments.iterator(); var12.hasNext(); ++i) {
            Map<String, Object> attach = (Map)var12.next();
            String uid = String.valueOf(attach.get("uid"));
            String newUid = String.format("%s-%s-%s", "rc-upload", date.getTime(), i);
            String fileName = String.valueOf(attach.get("name"));
            Long attPkId = (Long)((Long)attach.get("attPkId"));
            Long fileSize = (Long)attach.get("size");
            String fExtName = (String)attach.get("name");
            DynamicObject oldAttachment = BusinessDataServiceHelper.loadSingle(attPkId, "bos_attachment");
            String fileRelativePath = oldAttachment.getString("FFileId");
            InputStream in = fileService.getInputStream(fileRelativePath);
            RequestContext requestContext = RequestContext.get();
            String appId = "bid";
            if (formId.startsWith("rebm")) {
                appId = "rebm";
            }

            String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(), requestContext.getAccountId(), appId, formId, uid, fileName);
            FileItem fileItem = new FileItem(fileName, pathParam, in);
            String filePath = fileService.upload(fileItem);
            if (!StringUtils.isEmpty(filePath)) {
                DynamicObject newAttachment = new DynamicObject(mainType);
                newAttachment.set("id", ID.genLongId());
                newAttachment.set("FNUMBER", newUid);
                newAttachment.set("FBillType", formId);
                newAttachment.set("FInterID", pkId);
                Timestamp lastModified = (Timestamp)attach.get("lastModified");
                if (lastModified != null) {
                    newAttachment.set("FModifyTime", new Date(lastModified.getTime()));
                } else {
                    newAttachment.set("FModifyTime", new Date());
                }

                DynamicObject creator = oldAttachment.getDynamicObject("FCREATEMEN");
                if (creator != null) {
                    newAttachment.set("fcreatemen", creator.getLong("id"));
                }

                newAttachment.set("fcreatetime", new Date((Long)attach.get("createdate")));
                newAttachment.set("FaliasFileName", fileName);
                newAttachment.set("FAttachmentName", fileName);
                newAttachment.set("FExtName", fExtName != null ? fExtName.substring(fExtName.lastIndexOf(46) + 1) : "");
                newAttachment.set("FATTACHMENTSIZE", fileSize);
                newAttachment.set("fattachmentpanel", attachKey);
                newAttachment.set("fdescription", attach.get("description"));
                newAttachment.set("FFileId", filePath);
                attachmentFileList.add(newAttachment);
            }

            attach.put("createdate", attach.get("createdate"));
            attach.put("creator", attach.get("creator"));
        }

        if (!CollectionUtils.isEmpty(attachmentFileList)) {
            DynamicObject[] attachmentFileArray = new DynamicObject[attachmentFileList.size()];
            attachmentFileList.toArray(attachmentFileArray);
            SaveServiceHelper.save(attachmentFileArray);
        }

        resultMap.put("updateUidList", updateUidList);
        resultMap.put("addUidList", addUidList);
        return resultMap;
    }

    public static void removeSpecificFile(String formId, Object pkId, List<String> uidList) {
        Iterator var3 = uidList.iterator();

        while(var3.hasNext()) {
            String uid = (String)var3.next();
            AttachmentServiceHelper.remove(formId, pkId, uid);
        }

    }

    public static List<DynamicObject> copyToEntryAttachment(List<Map<String, Object>> attachments) {
        List<DynamicObject> attachmentFileList = new ArrayList();
        if (CollectionUtils.isEmpty(attachments)) {
            return attachmentFileList;
        } else {
            try {
                FileService fileService = FileServiceFactory.getAttachmentFileService();
                Date now = new Date();
                Iterator var4 = attachments.iterator();

                while(var4.hasNext()) {
                    Map<String, Object> attachment = (Map)var4.next();
                    String fileName = String.valueOf(attachment.get("name"));
                    String type = fileName != null ? fileName.substring(fileName.lastIndexOf(46) + 1) : "";
                    DynamicObject oldAttachment = BusinessDataServiceHelper.loadSingle(attachment.get("attPkId"), "bos_attachment");
                    String fileRelativePath = oldAttachment.getString("FFileId");
                    InputStream in = fileService.getInputStream(fileRelativePath);
                    RequestContext requestContext = RequestContext.get();
                    String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(), requestContext.getAccountId(), ID.genLongId(), fileName);
                    FileItem fileItem = new FileItem(fileName, pathParam, in);
                    String filePath = fileService.upload(fileItem);
                    if (!StringUtils.isEmpty(filePath)) {
                        DynamicObject newAttachment = new DynamicObject(MetadataServiceHelper.getDataEntityType("bd_attachment"));
                        Long id = ID.genLongId();
                        newAttachment.set("name", fileName);
                        newAttachment.set("size", attachment.get("size"));
                        newAttachment.set("url", filePath);
                        newAttachment.set("type", type);
                        newAttachment.set("description", "");
                        newAttachment.set("tempfile", "1");
                        newAttachment.set("pageid", "");
                        newAttachment.set("number", id.toString());
                        newAttachment.set("status", "B");
                        newAttachment.set("createtime", now.getTime());
                        newAttachment.set("modifytime", now.getTime());
                        newAttachment.set("creator", BusinessDataServiceHelper.loadSingle(Long.parseLong(RequestContext.get().getUserId()), "bos_user"));
                        newAttachment.set("uid", id.toString());
                        newAttachment.set("id", id);
                        attachmentFileList.add(newAttachment);
                    }
                }

                TXHandle h = TX.requiresNew();
                Throwable var31 = null;

                try {
                    try {
                        SaveServiceHelper.save((DynamicObject[])attachmentFileList.toArray(new DynamicObject[0]));
                    } catch (Exception var26) {
                        h.markRollback();
                        BizLog.log(var26.getMessage());
                    }
                } catch (Throwable var27) {
                    var31 = var27;
                    throw var27;
                } finally {
                    if (h != null) {
                        if (var31 != null) {
                            try {
                                h.close();
                            } catch (Throwable var25) {
                                var31.addSuppressed(var25);
                            }
                        } else {
                            h.close();
                        }
                    }

                }

                return attachmentFileList;
            } catch (Exception var29) {
                BizLog.log(var29.getMessage());
                return null;
            }
        }
    }

    public static DynamicObject copyBdAttachment(DynamicObject attachment) {
        if (attachment == null) {
            return null;
        } else {
            try {
                MainEntityType mainType = EntityMetadataCache.getDataEntityType("bd_attachment");
                FileService fileService = FileServiceFactory.getAttachmentFileService();
                String fileName = attachment.getString("name");
                String fileRelativePath = attachment.getString("url");
                InputStream in = fileService.getInputStream(fileRelativePath);
                RequestContext requestContext = RequestContext.get();
                String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(), requestContext.getAccountId(), ID.genLongId(), fileName);
                FileItem fileItem = new FileItem(fileName, pathParam, in);
                String filePath = fileService.upload(fileItem);
                if (!StringUtils.isEmpty(filePath)) {
                    Long id = ID.genLongId();
                    DynamicObject newAttachment = new DynamicObject(mainType);
                    DynamicObjectUtils.copy(attachment, newAttachment);
                    newAttachment.set("id", id);
                    newAttachment.set("number", id.toString());
                    newAttachment.set("uid", id.toString());
                    newAttachment.set("url", filePath);
                    SaveServiceHelper.save(new DynamicObject[]{newAttachment});
                    return newAttachment;
                } else {
                    return null;
                }
            } catch (Exception var12) {
                BizLog.log(var12.getMessage());
                return null;
            }
        }
    }

    public static void entryToPanelAttachment(List<DynamicObject> attachments, String formId, Object pkId, String attachKey) {
        MainEntityType mainType = EntityMetadataCache.getDataEntityType("bos_attachment");
        FileService fileService = FileServiceFactory.getAttachmentFileService();
        Date date = new Date();
        int i = 1;
        List<DynamicObject> attachmentFileList = new ArrayList();

        for(Iterator var9 = attachments.iterator(); var9.hasNext(); ++i) {
            DynamicObject attach = (DynamicObject)var9.next();
            String fileName = String.valueOf(attach.get("name"));
            String newUid = String.format("%s-%s-%s", "rc-upload", date.getTime(), i);
            String fileRelativePath = attach.getString("url");
            InputStream in = fileService.getInputStream(fileRelativePath);
            RequestContext requestContext = RequestContext.get();
            String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(), requestContext.getAccountId(), formId, formId.split("_")[0], newUid, fileName);
            FileItem fileItem = new FileItem(fileName, pathParam, in);
            String filePath = fileService.upload(fileItem);
            if (!StringUtils.isEmpty(filePath)) {
                DynamicObject newAttachment = new DynamicObject(mainType);
                newAttachment.set("id", ID.genLongId());
                newAttachment.set("FNUMBER", newUid);
                newAttachment.set("FBillType", formId);
                newAttachment.set("FInterID", pkId);
                newAttachment.set("FModifyTime", attach.get("modifytime"));
                DynamicObject creator = attach.getDynamicObject("creator");
                if (creator != null) {
                    newAttachment.set("FCREATEMEN", creator.getLong("id"));
                }

                newAttachment.set("fcreatetime", attach.get("createtime"));
                newAttachment.set("FaliasFileName", fileName);
                newAttachment.set("FAttachmentName", fileName);
                newAttachment.set("FExtName", fileName != null ? fileName.substring(fileName.lastIndexOf(46) + 1) : "");
                newAttachment.set("FATTACHMENTSIZE", attach.get("size"));
                newAttachment.set("fattachmentpanel", attachKey);
                newAttachment.set("fdescription", attach.get("description"));
                newAttachment.set("FFileId", filePath);
                attachmentFileList.add(newAttachment);
            }
        }

        if (!CollectionUtils.isEmpty(attachmentFileList)) {
            DynamicObject[] attachmentFileArray = new DynamicObject[attachmentFileList.size()];
            attachmentFileList.toArray(attachmentFileArray);
            SaveServiceHelper.save(attachmentFileArray);
        }

    }

    public static String downloadByAttachmentIds(String fileName, ArrayList<Long> attachmentIds) {
        QFilter qFilter = new QFilter("id", "in", attachmentIds);
        DynamicObject[] attachments = BusinessDataServiceHelper.load("bd_attachment", "id,url", new QFilter[]{qFilter});
        String[] filePaths = (String[])Arrays.stream(attachments).map((attachment) -> {
            return FileServiceExtFactory.getAttachFileServiceExt().getRealPath(attachment.getString("url"));
        }).toArray((x$0) -> {
            return new String[x$0];
        });
        return downloadByAttachmentUrls(fileName, filePaths);
    }

    public static String downloadByAttachmentUrls(String fileName, String... attachmentUrls) {
        if (attachmentUrls != null && attachmentUrls.length != 0) {
            if (attachmentUrls.length > 0) {
                fileName = fileName == null ? "attachments.zip" : (!fileName.toLowerCase(Locale.ENGLISH).endsWith(".zip") ? fileName + ".zip" : fileName);
            } else if (fileName == null) {
                String attachmentUrl = attachmentUrls[0];
                if (attachmentUrl.lastIndexOf(47) != -1) {
                    int i = attachmentUrl.lastIndexOf(47);
                    fileName = attachmentUrl.substring(i + 1);
                }
            }

            FileService fs = FileServiceFactory.getAttachmentFileService();
            String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36";

            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                Throwable var5 = null;

                String attachmentUrl;
                try {
                    if (attachmentUrls.length > 0) {
                        BatchDownloadRequest bdr = getBatchDownloadRequest(attachmentUrls);
                        fs.batchDownload(bdr, out, userAgent);
                    } else {
                        attachmentUrl = attachmentUrls[0];
                        fs.download(attachmentUrl, out, userAgent);
                    }

                    out.flush();
                    attachmentUrl = download(fileName, out.toByteArray());
                } catch (Throwable var16) {
                    var5 = var16;
                    throw var16;
                } finally {
                    if (out != null) {
                        if (var5 != null) {
                            try {
                                out.close();
                            } catch (Throwable var15) {
                                var5.addSuppressed(var15);
                            }
                        } else {
                            out.close();
                        }
                    }

                }

                return attachmentUrl;
            } catch (Exception var18) {
                return var18.getMessage();
            }
        } else {
            return null;
        }
    }

    private static BatchDownloadRequest getBatchDownloadRequest(String[] attachmentUrls) {
        BatchDownloadRequest.Dir srcDir = new BatchDownloadRequest.Dir("attachments");
        List<BatchDownloadRequest.File> srcFiles = new ArrayList(attachmentUrls.length);
        String[] var3 = attachmentUrls;
        int var4 = attachmentUrls.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            String attachmentUrl = var3[var5];
            if (attachmentUrl.lastIndexOf(47) != -1) {
                int i = attachmentUrl.lastIndexOf(47);
                String attachmentName = attachmentUrl.substring(i + 1);
                srcFiles.add(new BatchDownloadRequest.File(attachmentName, attachmentUrl));
            }
        }

        srcDir.setFiles((BatchDownloadRequest.File[])srcFiles.toArray(new BatchDownloadRequest.File[0]));
        BatchDownloadRequest bdr = new BatchDownloadRequest("test-batch-download");
        bdr.setDirs(new BatchDownloadRequest.Dir[]{srcDir});
        return bdr;
    }

    public static String download(String fileName, byte[] bytes) {
        InputStream in = new ByteArrayInputStream(bytes);
        return download(fileName, (InputStream)in);
    }

    public static String download(String fileName, InputStream in) {
        TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
        return cache.saveAsUrl(fileName, in, 120);
    }

    public static String downAllFile(String fileName, Object formId, String formBillno, String appid, String evalType) {
        fileName = fileName == null ? "attachments.zip" : (!fileName.toLowerCase(Locale.ENGLISH).endsWith(".zip") ? fileName + ".zip" : fileName);
        FileService fs = FileServiceFactory.getAttachmentFileService();
        String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36";

        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Throwable var8 = null;

            String var10;
            try {
                BatchDownloadRequest bdr = getBatchFile(formId, formBillno, appid, evalType);
                fs.batchDownload(bdr, out, userAgent);
                out.flush();
                var10 = download(fileName, out.toByteArray());
            } catch (Throwable var20) {
                var8 = var20;
                throw var20;
            } finally {
                if (out != null) {
                    if (var8 != null) {
                        try {
                            out.close();
                        } catch (Throwable var19) {
                            var8.addSuppressed(var19);
                        }
                    } else {
                        out.close();
                    }
                }

            }

            return var10;
        } catch (Exception var22) {
            return var22.getMessage();
        }
    }

    private static BatchDownloadRequest getBatchFile(Object formId, String formBillno, String appid, String evalType) {
        String secTionBillNo = "";
        String secTionNameKey = "";
        String isDarkTag = "";
        String supplierDarkTag = "";
        if (formBillno.contains("onlinebideval")) {
            secTionBillNo = "bidsectionenroll";
            secTionNameKey = "sectionname2";
            isDarkTag = "isdark";
            supplierDarkTag = "supplierdarkname_entry";
        } else if (formBillno.contains("decision")) {
            secTionBillNo = "bidsection";
            secTionNameKey = "sectionname";
        } else if (formBillno.contains("bidopen")) {
            secTionBillNo = "bidsection";
            secTionNameKey = "sectionname";
            isDarkTag = "isdark";
            supplierDarkTag = "darksuppliername";
        }

        List<BatchDownloadRequest.Dir> listDir = new ArrayList();
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(formId, formBillno);
        boolean isDark = false;
        if (!formBillno.contains("decision")) {
            isDark = dynamicObject.getBoolean(isDarkTag);
        }

        DynamicObject bidProject = dynamicObject.getDynamicObject("bidproject");
        DynamicObjectCollection bidsectionenrollCol = dynamicObject.getDynamicObjectCollection(secTionBillNo);
        Iterator var14 = bidsectionenrollCol.iterator();

        while(var14.hasNext()) {
            DynamicObject bidsectionenroll = (DynamicObject)var14.next();
            String sectionName = bidsectionenroll.getString(secTionNameKey);
            DynamicObjectCollection supplierentryCol = bidsectionenroll.getDynamicObjectCollection("supplierentry");
            Iterator var18 = supplierentryCol.iterator();

            while(var18.hasNext()) {
                DynamicObject supplierentry = (DynamicObject)var18.next();
                DynamicObject supplier = supplierentry.getDynamicObject("supplier");
                String supplierName;
                if (isDark) {
                    supplierName = supplierentry.getString(supplierDarkTag);
                } else {
                    supplierName = supplier.getString("name");
                }

                String fileZipName = getFileZipName(bidProject.getPkValue(), sectionName, supplierName, formBillno, formId, appid);
                BatchDownloadRequest.Dir srcDir = new BatchDownloadRequest.Dir(fileZipName);
                ArrayList<Long> attachmentIds = new ArrayList();
                getFileUrl(supplierentry, evalType, attachmentIds, formBillno, bidProject.getPkValue());
                List<BatchDownloadRequest.File> srcFiles = new ArrayList(attachmentIds.size());
                QFilter qFilter = new QFilter("id", "in", attachmentIds);
                DynamicObject[] attachments = BusinessDataServiceHelper.load("bd_attachment", "id,url", new QFilter[]{qFilter});
                String[] filePaths = (String[])Arrays.stream(attachments).map((attachment) -> {
                    return FileServiceExtFactory.getAttachFileServiceExt().getRealPath(attachment.getString("url"));
                }).toArray((x$0) -> {
                    return new String[x$0];
                });
                String[] var28 = filePaths;
                int var29 = filePaths.length;

                for(int var30 = 0; var30 < var29; ++var30) {
                    String attachmentUrl = var28[var30];
                    if (attachmentUrl.lastIndexOf(47) != -1) {
                        int i = attachmentUrl.lastIndexOf(47);
                        String attachmentName = attachmentUrl.substring(i + 1);
                        srcFiles.add(new BatchDownloadRequest.File(attachmentName, attachmentUrl));
                    }
                }

                srcDir.setFiles((BatchDownloadRequest.File[])srcFiles.toArray(new BatchDownloadRequest.File[0]));
                listDir.add(srcDir);
            }
        }

        BatchDownloadRequest bdr = new BatchDownloadRequest("test-batch-download");
        bdr.setDirs((BatchDownloadRequest.Dir[])listDir.toArray(new BatchDownloadRequest.Dir[0]));
        return bdr;
    }

    public static String getFileZipName(Object bidprojectId, String sectionName, String supplierName, String formBillno, Object formId, String appid) {
        return fileZipName(bidprojectId, sectionName, supplierName, formBillno, formId, appid);
    }

    public static void getFileUrl(DynamicObject supplierEntry, String evalType, ArrayList<Long> attachmentIds, String formBillno, Object bidprojectId) {
        String tecName = "";
        String comName = "";
        if (formBillno.contains("onlinebideval")) {
            tecName = "supplier_techattach";
            comName = "supplier_comattach";
        } else if (formBillno.contains("decision")) {
            tecName = "techfile_new";
            comName = "commfile_new";
        } else if (formBillno.contains("bidopen")) {
            tecName = "supplier_techattach";
            comName = "supplier_comattach";
        }

        DynamicObjectCollection supplierTechattachCol;
        if ("TECHNICAL".equals(evalType)) {
            supplierTechattachCol = supplierEntry.getDynamicObjectCollection(tecName);
            if (!supplierTechattachCol.isEmpty()) {
                supplierTechattachCol.forEach((attachment) -> {
                    DynamicObject fileFbasedataid = attachment.getDynamicObject("fbasedataid");
                    if (fileFbasedataid != null) {
                        Long o = (Long)fileFbasedataid.get("id");
                        attachmentIds.add(o);
                    }

                });
            }
        } else if ("BUSSINESS".equals(evalType)) {
            supplierTechattachCol = supplierEntry.getDynamicObjectCollection(comName);
            if (!supplierTechattachCol.isEmpty()) {
                supplierTechattachCol.forEach((attachment) -> {
                    DynamicObject fileFbasedataid = attachment.getDynamicObject("fbasedataid");
                    if (fileFbasedataid != null) {
                        Long o = (Long)fileFbasedataid.get("id");
                        attachmentIds.add(o);
                    }

                });
            }
        } else if ("MULTI".equals(evalType)) {
            supplierTechattachCol = supplierEntry.getDynamicObjectCollection(tecName);
            if (!supplierTechattachCol.isEmpty()) {
                supplierTechattachCol.forEach((attachment) -> {
                    DynamicObject fileFbasedataid = attachment.getDynamicObject("fbasedataid");
                    if (fileFbasedataid != null) {
                        Long o = (Long)fileFbasedataid.get("id");
                        attachmentIds.add(o);
                    }

                });
            }

            DynamicObjectCollection supplierComattachCol = supplierEntry.getDynamicObjectCollection(comName);
            if (!supplierComattachCol.isEmpty()) {
                supplierComattachCol.forEach((attachment) -> {
                    DynamicObject fileFbasedataid = attachment.getDynamicObject("fbasedataid");
                    if (fileFbasedataid != null) {
                        Long o = (Long)fileFbasedataid.get("id");
                        attachmentIds.add(o);
                    }

                });
            }
        }

        String entityName = "bid_project";
        if (formBillno.contains("rebm")) {
            entityName = "rebm_project";
        }

        if (formBillno.contains("bidopen")) {
            DynamicObject bidProject = BusinessDataServiceHelper.loadSingle(bidprojectId, entityName);
            String doctype = bidProject.getString("doctype");
            if ("BUSSINESS".equals(doctype) || "TECHNICAL".equals(evalType) || "MULTI".equals(evalType)) {
                DynamicObjectCollection tenAttach = supplierEntry.getDynamicObjectCollection("supplier_tenattach");
                DynamicObjectCollection otherAttach = supplierEntry.getDynamicObjectCollection("supplier_otherattach");
                if (!tenAttach.isEmpty()) {
                    tenAttach.forEach((attachment) -> {
                        DynamicObject fileFbasedataid = attachment.getDynamicObject("fbasedataid");
                        if (fileFbasedataid != null) {
                            Long o = (Long)fileFbasedataid.get("id");
                            attachmentIds.add(o);
                        }

                    });
                }

                if (!otherAttach.isEmpty()) {
                    otherAttach.forEach((attachment) -> {
                        DynamicObject fileFbasedataid = attachment.getDynamicObject("fbasedataid");
                        if (fileFbasedataid != null) {
                            Long o = (Long)fileFbasedataid.get("id");
                            attachmentIds.add(o);
                        }

                    });
                }
            }
        }

    }

    public static String fileZipName(Object bidprojectId, String sectionName, String supplierName, String formBillno, Object formId, String appid) {
        String projectName;
        if ("bid".equals(appid)) {
            projectName = "bid_project";
        } else {
            projectName = "rebm_project";
        }

        DynamicObject bidProject = BusinessDataServiceHelper.loadSingle(bidprojectId, projectName);
        String billnoProject = bidProject.getString("billno");
        if (sectionName.length() > 20) {
            sectionName = sectionName.substring(0, 20);
        }

        String formName = formBillno;
        String fileZipName = "";
        fileZipName = billnoProject + sectionName + supplierName + formName;
        fileZipName = String.format(ResManager.loadKDString("%s附件", "BidFileDownLoadNameUtil_0", "scm-bid-common", new Object[0]), fileZipName);
        if (fileZipName.length() > 255) {
            fileZipName = formName.substring(0, 255);
        }

        return fileZipName;
    }

}
