package nckd.base.helper;

import kd.bos.bundle.BosRes;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.TempFileCache;
import kd.bos.exception.BosErrorCode;
import kd.bos.exception.ErrorCode;
import kd.bos.exception.KDException;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.config.FileServiceConfig;
import kd.bos.fileservice.enums.PreviewParams;
import kd.bos.fileservice.excelpreview.ExcelPreviewFactory;
import kd.bos.fileservice.impl.*;
import kd.bos.fileservice.multiserver.Dispatcher;
import kd.bos.fileservice.multiserver.DispatcherFactory;
import kd.bos.fileservice.path.DecodeFileFactory;
import kd.bos.fileservice.preview.PreviewService;
import kd.bos.fileservice.utils.*;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.url.UrlService;
import kd.bos.util.FileUtils;
import kd.bos.util.RevProxyUtil;
import kd.bos.util.StringUtils;
import kd.bos.util.resource.Resources;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.*;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;


public class DefaultPreviewCusServiceImpl  implements PreviewService {
    private static Log logger = LogFactory.getLog(DefaultPreviewCusServiceImpl.class);
    private static final String MAGIC_STRING = "frSheet";
    private static final String COOKIE = "Cookie";
    private static final String BOS_FILESERVICE_SDK = "bos-fileservice-sdk";
    private static final String PREVIEW_CACHE_REFRESH = "filepreview.refresh.enable";
    private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");
    private boolean isPreviewcacheEnable;
    private boolean isPreviewcacheRefresh;
    private int uploadTimeout;
    private FileService fileService;
    private YunHomeService yunHomeService;
    private Dispatcher fileServerDispatcher;
    private Dispatcher previewServerDispatcher;


    public DefaultPreviewCusServiceImpl() {
    }

    public void init(FileService fileService) {
        logger.info("DefaultPreviewCusServiceImpl：" + fileService.toString());
        this.fileService = fileService;
        this.isPreviewcacheEnable = AttachmentFileService.isPreviewcacheEnable() && fileService instanceof AttachmentFileService;
        this.isPreviewcacheRefresh = Boolean.parseBoolean(System.getProperty("filepreview.refresh.enable"));
        this.uploadTimeout = AttachmentFileService.getUploadTimeout();
        this.fileServerDispatcher = DispatcherFactory.build("attachmentServer.url", BosErrorCode.fileServerNotConfigured);
        this.previewServerDispatcher = DispatcherFactory.build("yunpan.previewUrl", BosErrorCode.previewFailed);
        this.yunHomeService = new YunHomeService(fileService);
    }

    /**
     * 文件流预览模式
     * 系统参数预览方式可选择 默认方式 / 自定义
     */
    @Override
    public Map<String, Object> preview(String fileName, String path, String userAgent) {
        return null;
    }

    @Override
    public void removePreview(String id) {
    }

    /**
     * 文件流预览模式 - 临时文件预览
     * 系统参数预览方式选择 云之家
     */
    @Override
    public Map<String, Object> previewFromCache(String fileName, String path, String userAgent, InputStream cacheIn) {
        return null;
    }

    /**
     * WPS预览模式
     * 如返回第三方预览url
     */
    @Override
    public Map<String, Object> previewWPS(String fileName, String path, String userAgent, Map<String, String> config) {
        logger.info("testpreviewWPS...");

        path = DecodeFileFactory.getDecodeService().getDecodeFilePath(path);
        path = path.replaceAll("//", "/");
        InputStream in = null;
        new HashMap();
        Map<String, Object> previewResult = new HashMap(3);
        String ext = fileName.substring(fileName.lastIndexOf(46) + 1);
        long startTime = 0L;
        long endTime = 0L;
        Map result;
        logger.info("testpreviewWPS..." + path + ", " + ext);

        if (YunHomeService.isNotNeedDeal(ext)) {
            logger.info("testpreviewWPS...10001001");

            Map<String, String> headerMap = new HashMap();
            if (userAgent != null) {
                headerMap.put("USER-AGENT", userAgent);
            }

            try {
                in = this.fileService.download(path, headerMap, new HashMap());

                in = FileSECUtils.processFileWithSEC(path, in);
            } catch (Exception var19) {
                result = ExceptionUtil.setErrorInfo(var19.getMessage());
                previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
                previewResult.put(PreviewParams.RESULT.getEnumName(), result);
                return previewResult;
            }

            previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.NOT_NEED_CHANGE.getEnumName());
            previewResult.put(PreviewParams.RESULT.getEnumName(), in);
            if ("txt".equalsIgnoreCase(ext)) {
                previewResult.put(PreviewParams.CHARSET.getEnumName(), FileUtil.getFilecharsetNew(in));
            }

            return previewResult;
        } else if (this.isPreviewcacheRefresh) {
            logger.info("testpreviewWPS...10001002");

            return this.getYunPanCovertRs(path, fileName, ext, userAgent, false);
        } else {
            if (this.isPreviewcacheEnable) {
                logger.info("testpreviewWPS...10001003");
                startTime = System.currentTimeMillis();
                String previewUrl = path + (!"xls".equalsIgnoreCase(ext) && !"xlsx".equalsIgnoreCase(ext) ? ".pdf" : ".zip");
                String previewMetaUrl = path + ".meta";

                try {
                    Map<String, String> headerMap = new HashMap();
                    headerMap.put("preview", "true");
                    headerMap.put("preview.url", URLEncoder.encode(previewUrl, StandardCharsets.UTF_8.name()));
                    headerMap.put("preview.metaUrl", URLEncoder.encode(previewMetaUrl, StandardCharsets.UTF_8.name()));
                    Map<String, String> resHeader = new HashMap();

                    logger.info("testpreviewWPS...10001003下载");

                    in = this.fileService.download(path, headerMap, resHeader);

                    logger.info("testpreviewWPS...10001003解密");

                    endTime = System.currentTimeMillis();
                    if (!"xls".equalsIgnoreCase(ext) && !"xlsx".equalsIgnoreCase(ext)) {
                        previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.PDF_SUCCESS.getEnumName());
                        previewResult.put(PreviewParams.RESULT.getEnumName(), in);
                        logger.info(String.format("从缓存中获取%s所耗费的时间为%s毫秒", fileName, endTime - startTime));
                        return previewResult;
                    }

                    String id = (String)resHeader.get("cacheId");
                    if (StringUtils.isNotEmpty(id)) {
                        result = ExcelPreviewFactory.getExcelPreview().preview(id, in);
                        if (result.containsKey("url")) {
                            String accountId = TAUtil.getAccountId();
                            String url = (String)result.get("url");
                            url = url + "?kdcdc=" + accountId;
                            result.put("url", url);
                        }

                        previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.XLSX_SUCCESS.getEnumName());
                        previewResult.put(PreviewParams.RESULT.getEnumName(), result);
                        logger.info(String.format("从缓存中获取%s所耗费的时间为%s毫秒", fileName, endTime - startTime));
                        return previewResult;
                    }
                } catch (Exception var20) {
                    logger.error("无法从文件服务器获取预览数据，执行getYunPanCovertRs方法，进行文件预览云盘转换{}", var20.getMessage());
                }
            }

            logger.info("testpreviewWPS...10001004");

            return this.getYunPanCovertRs(path, fileName, ext, userAgent, false);
        }
    }

    /**
     * wps预览模式 - 临时文件url预览
     * 如返回第三方预览url
     */
    @Override
    public Map<String, Object> previewFromCacheWPS(String fileName, String path, String userAgent, InputStream cacheIn, Map<String, String> config) {
        logger.info("testpreviewFromCacheWPS...");

        String ext = fileName.substring(fileName.lastIndexOf(46) + 1);
        if (YunHomeService.isNotNeedDeal(ext)) {
            logger.info("testpreviewFromCacheWPS...10001001");

            InputStream in = DecodeFileFactory.getDecodeService().getDecodeFileStream(cacheIn);
            return YunHomeService.getNotNeedTransferRs(in, ext);
        } else {
            logger.info("testpreviewFromCacheWPS...10001002");

            String decodeFilePath = DecodeFileFactory.getDecodeService().getDecodeFilePath(path);
            return this.getYunPanCovertRs(decodeFilePath, fileName, ext, userAgent, true);
        }
    }

    private Map<String, Object> getYunPanCovertRs(String path, String fileName, String ext, String userAgent, boolean temp) {
        InputStream in = null;
        new HashMap();
        Map<String, Object> previewResult = new HashMap();
        long startTime = System.currentTimeMillis();
        Map<String, String> detail = new HashMap();
        Map result;
        long limitMax;
        if (FileServiceConfig.PREVIEW_SIZE_LIMIT_ENABLE.getBoolean()) {
            try {
                limitMax = Math.min(FileServiceConfig.PREVIEW_SIZE_LIMIT_MAX.getLong(), (Long)FileServiceConfig.PREVIEW_SIZE_LIMIT_MAX.getDefault());
                long limit = Math.min(FileServiceConfig.PREVIEW_SIZE_LIMIT.getLong(), limitMax);
                InputStream checkInputStream;

                logger.info("getYunPanCovertRs...10001001");

                if (temp) {
                    logger.info("getYunPanCovertRs...1000100111");
                    TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
                    checkInputStream = cache.getInputStream(path);
                } else {
                    checkInputStream = this.fileService.getInputStream(path);
                }


                logger.info("getYunPanCovertRs...100010012");

                boolean checkResult = checkFileSize(checkInputStream, fileName, limit == 0L ? limitMax : limit);
                if (!checkResult) {
                    ((Map)previewResult).put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
                    ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), ExceptionUtil.setExceedInfo(limitMax));
                    return (Map)previewResult;
                }
            } catch (Exception var20) {
                result = ExceptionUtil.setErrorInfo(var20.getMessage());
                ((Map)previewResult).put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
                ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), result);
                return (Map)previewResult;
            }
        }

        try {
            logger.info("getYunPanCovertRs...100010013");

            in = this.yunPanConvert(path, fileName, userAgent, detail, temp);
            logger.info("getYunPanCovertRs...100010014");


        } catch (Exception var19) {
            result = ExceptionUtil.setErrorInfo(var19.getMessage());
            ((Map)previewResult).put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
            ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), result);
            return (Map)previewResult;
        }

        limitMax = System.currentTimeMillis();
        logger.info(String.format("%s在云盘转换中所耗费的时间为%s毫秒", fileName, limitMax - startTime));
        if (!"xlsx".equalsIgnoreCase(ext) && !"xls".equalsIgnoreCase(ext)) {
            if (this.isPreviewcacheEnable && !temp) {
                previewResult = this.saveAndPreview(in, fileName, path, (String)null);
            } else {
                ((Map)previewResult).put(PreviewParams.STATUS.getEnumName(), PreviewParams.PDF_SUCCESS.getEnumName());
                ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), in);
            }
        } else {
            if (FileServiceConfig.PREVIEW_TRANS_EXCEL_ENABLE.getBoolean()) {
                in = transferByReplaceContent(in, fileName, detail);
            }

            if (this.isPreviewcacheEnable && !temp && !((String)detail.get("id")).endsWith("tip")) {
                previewResult = this.saveAndPreview(in, fileName, path, (String)detail.get("id"));
            } else {
                result = ExcelPreviewFactory.getExcelPreview().preview((String)detail.get("id"), in);
                ((Map)previewResult).put(PreviewParams.STATUS.getEnumName(), PreviewParams.XLSX_SUCCESS.getEnumName());
                ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), result);
            }

            try {
                Map<String, Object> res = (Map)((Map)previewResult).get(PreviewParams.RESULT.getEnumName());
                if (res != null && res.containsKey("url")) {
                    String url = (String)res.get("url");
                    if (StringUtils.isNotEmpty(url)) {
                        String accountId = TAUtil.getAccountId();
                        url = url + "?kdcdc=" + accountId;
                        res.put("url", url);
                        ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), res);
                    }
                }
            } catch (Exception var18) {
                logger.error("Error concatenating kdcdc: " + var18.getMessage());
            }
        }

        return (Map)previewResult;
    }

    private static boolean checkFileSize(InputStream inputStream, String fileName, Long limitSize) {
        long totalBytesWritten = 0L;

        boolean var7;
        try {
            byte[] buffer = new byte[1024];

            int read;
            while((read = inputStream.read(buffer)) != -1) {
                totalBytesWritten += (long)read;
                if (totalBytesWritten > limitSize) {
                    var7 = false;
                    return var7;
                }
            }

            var7 = true;
        } catch (IOException var17) {
            throw new RuntimeException("checkFileSize error fileName=" + fileName, var17);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException var16) {
                }
            }

        }

        return var7;
    }

    private InputStream yunPanConvert(String path, String fileName, String userAgent, Map<String, String> rs, boolean temp) {
        String previewUrlPrefix = null;
        InputStream in = null;
        String ext = fileName.substring(fileName.lastIndexOf(46) + 1);

        try {
            previewUrlPrefix = this.previewServerDispatcher.select();
        } catch (KDException var20) {
            throw new KDException(BosErrorCode.previewFailed, BosRes.get("bos-fileservice-sdk", "DefaultPreviewServiceImpl_0", "访问云盘接口服务的ip没有配置,或是配置的地址不可用", new Object[0]), var20);
        }

        new HashMap();
        StringBuilder uri = (new StringBuilder(previewUrlPrefix)).append(previewUrlPrefix.endsWith("/") ? "" : "/").append("api/officeToPdf?");

        Map paramResult;
        String fileDownloadUrl;
        try {
            fileDownloadUrl = "";
            if (temp) {
                if (isLog()) {
                    logger.info("yunpan temp downLoadUrl=" + path);
                }

                fileDownloadUrl = URLEncoder.encode(path, StandardCharsets.UTF_8.name());
            } else {
                fileDownloadUrl = URLEncoder.encode(this.getDownloadUrl(URLEncoder.encode(path, StandardCharsets.UTF_8.name())), StandardCharsets.UTF_8.name());
            }

            logger.info("yunPanConvert...fileDownloadUrl" + fileDownloadUrl);

            paramResult = ParameterUtil.concatUrl(uri, fileName, ext, fileDownloadUrl);

            logger.info("yunPanConvert...paramResult" + paramResult.toString());
        } catch (Exception var19) {
            throw new KDException(BosErrorCode.previewFailed, new Object[]{BosRes.get("bos-fileservice-sdk", "DefaultPreviewServiceImpl_1", "filename或download_url encode出错:", new Object[0]) + var19});
        }

        uri = (StringBuilder)paramResult.get("uri");
        fileDownloadUrl = (String)paramResult.get("id");
        rs.put("id", fileDownloadUrl);
        CloseableHttpClient client = HttpFileClient.getHttpClient(previewUrlPrefix);
        HttpGet get = new HttpGet(uri.toString());
        get.setConfig(RequestConfig.custom().setSocketTimeout(this.uploadTimeout * 1000).setConnectTimeout(this.uploadTimeout * 1000).build());
        this.setCookie(get);
        HeaderUtil.setHttpGet(get, userAgent);

        CloseableHttpResponse response;
        try {
            response = client.execute(get);
            in = response.getEntity().getContent();
        } catch (Exception var18) {
            throw new KDException(BosErrorCode.previewFailed, new Object[]{BosRes.get("bos-fileservice-sdk", "DefaultPreviewServiceImpl_2", "云盘服务响应失败:", new Object[0]) + var18.getMessage()});
        }

        logger.info("yunPanConvert...fileName" + fileName);

        if (in == null) {
            throw new KDException(BosErrorCode.previewFailed, new Object[]{BosRes.get("bos-fileservice-sdk", "DefaultPreviewServiceImpl_3", "从云盘中未获取到pdf流数据,pdf转换失败:", new Object[0])});
        } else {
            int statusCode = response.getStatusLine().getStatusCode();

            logger.info("yunPanConvert...statusCode" + statusCode);
            logger.info("yunPanConvert...response" + response.toString());

            logger.info("yunPanConvert...in：" + in);

            if (statusCode != 200) {
                try {
                    if (isLog()) {
                        logger.error("yunpan return msg:" + IOUtils.toString(in, "utf-8"));
                    }

                    in.close();
                } catch (IOException var17) {
                    logger.error("logger error info fail");
                }

                throw new KDException(BosErrorCode.previewFailed, new Object[]{this.getErrorMsg(statusCode)});
            } else {
                return in;
            }
        }
    }

    private void setCookie(HttpGet get) {
        if (this.fileService.needAuth()) {
            String ticket = this.fileService.getTicket();
            get.addHeader("Cookie", "ticket=" + ticket);
        }

    }

    public Map<String, Object> saveAndPreview(InputStream in, String fileName, String path, String excelId) {
        if (excelId != null)
        {
            fileName = fileName + ".zip";
            path = path + ".zip";
        }
        else
        {
            fileName = fileName + ".pdf";
            path = path + ".pdf";
        }
        Map<String, Object> result = new HashMap();
        Map<String, Object> previewResult = new HashMap();
        String tmpfilePath = null;
        InputStream tempFileStream = null;
        FileItem fileItem = null;
        try{
            tmpfilePath = FileUtil.writeFileToDisk(in, fileName);
            tempFileStream = new FileInputStream(tmpfilePath);
            try
            {
                in.close();
            }
            catch (IOException e)
            {
                logger.error(e);
            }
            fileItem = new FileItem(fileName, path, tempFileStream);
        }
        catch (Exception e){
            result = ExceptionUtil.setErrorInfo(Resources.getString("云盘转换流缓存到磁盘中失败:", "AbstractFileService_12", "bos-fileservice-sdk", new Object[0]) + e);
            previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
            previewResult.put(PreviewParams.RESULT.getEnumName(), result);

            return previewResult;
        }
        finally
        {
            try
            {
                in.close();
            }
            catch (IOException e)
            {
                logger.error(e);
            }
        }
        Object headers = new HashMap();
        ((HashMap)headers).put("uploadCache", "true");
        if (excelId != null) {
            ((HashMap)headers).put("cacheId", excelId);
        }
        try
        {
            try
            {
                upload(fileItem, (Map)headers);
            }
            catch (Exception t)
            {
                logger.error("Save cache file to FileServer error.", t);
            }
            finally
            {
                fileItem.close();
                if (tempFileStream != null) {
                    tempFileStream.close();
                }
            }
            in = new FileInputStream(tmpfilePath);

            FileTimeoutUtil.removeFile(tmpfilePath, in, 120000L);
            if (excelId != null)
            {
                result = ExcelPreviewFactory.getExcelPreview().preview(excelId, in);

                previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.XLSX_SUCCESS.getEnumName());
                previewResult.put(PreviewParams.RESULT.getEnumName(), result);
            }
            else
            {
                previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.PDF_SUCCESS.getEnumName());
                previewResult.put(PreviewParams.RESULT.getEnumName(), in);
            }
        }
        catch (Exception e)
        {
            result = ExceptionUtil.setErrorInfo(Resources.getString("云盘转换流缓存到磁盘中失败:", "AbstractFileService_12", "bos-fileservice-sdk", new Object[0]) + e);
            previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
            previewResult.put(PreviewParams.RESULT.getEnumName(), result);

            return previewResult;
        }
        return previewResult;
    }

    private String upload(FileItem item, Map<String, String> headers) {
        String httpUrlPrefix = this.fileServerDispatcher.select();
        String httpUploadUrlPrefix = httpUrlPrefix + (httpUrlPrefix.endsWith("/") ? "" : "/") + "file/upload.do";
        Map<String, String> arg = new HashMap();
        arg.put("version", FileServiceVersion.VERSION1.toString());
        arg.put("url", item.getPath());
        arg.put("fileName", item.getFileName());
        arg.put("createNewFileWhenExists", String.valueOf(item.isCreateNewFileWhenExists()));
        if (headers != null) {
            arg.putAll(headers);
        }

        String description;
        try {
            if (item.getFileName() != null && item.getFileName().lastIndexOf(".") <= 0) {
                throw new KDException(BosErrorCode.uploadFailed, new Object[]{"upload file " + item.getPath() + Resources.getString(" failed. description: 文件扩展名不能为空", "AbstractFileService_0", "bos-fileservice-sdk", new Object[0])});
            }

            if (this.fileService.needAuth()) {
                arg.put("ticket", this.fileService.getTicket());
            }

            Map<String, String> result = HttpFileClient.sendFile(httpUploadUrlPrefix, this.uploadTimeout * 1000, item.getInputStream(), arg);
            item.close();
            if (result == null) {
                throw new KDException(BosErrorCode.uploadFailed, new Object[]{"upload timeout within " + this.uploadTimeout + " seconds" + item.getPath()});
            }

            String url = (String)result.get("url");
            if (StringUtils.isEmpty(url)) {
                description = (String)result.get("description");
                if (StringUtils.isNotEmpty(description)) {
                    throw new KDException(BosErrorCode.uploadFailed, new Object[]{"upload " + item.getPath() + " failed. description:" + description});
                }
            }

            description = this.fileService.getFileServiceExt().save(url);
        } catch (KDException var13) {
            throw var13;
        } catch (Exception var14) {
            throw new KDException(var14, BosErrorCode.uploadFailed, new Object[]{"upload " + item.getPath() + " failed."});
        } finally {
            item.close();
        }

        return description;
    }


    private static InputStream transferByReplaceContent(InputStream source, String fileName, Map<String, String> detail) {
        String value = "frSheet" + System.currentTimeMillis();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String tempFilePath = FileUtils.checkFileUrl(TEMP_DIR + "/tempExcel" + uuid);
        String targetFilePath = FileUtils.checkFileUrl(TEMP_DIR + "/tempTarget" + uuid);

        FileOutputStream out;
        try {
            out = new FileOutputStream(targetFilePath);
        } catch (FileNotFoundException var32) {
            throw new RuntimeException("transferByReplaceContent error fileName=" + fileName, var32);
        }

        ZipOutputStream zos = new ZipOutputStream(out, Charset.forName("GBK"));
        ZipFile zipFile = null;
        try {
            long limitSize = FileServiceConfig.PREVIEW_SIZE_LIMIT_4_EXCEL.getLong();
            limitSize = limitSize <= 0L ? (Long)FileServiceConfig.PREVIEW_SIZE_LIMIT_4_EXCEL.getDefault() : limitSize;
            File tempFile = new File(tempFilePath);
            FileTimeoutUtil.removeFile(tempFilePath, (InputStream)null, 120000L);
            org.apache.commons.io.FileUtils.copyToFile(source, tempFile);
            zipFile = new ZipFile(tempFile);
            long totalSize = totalZipFileSize(zipFile);
            if (totalSize > limitSize) {
                String tipHtml = tipHtml(limitSize, totalSize);
                String id = (String)detail.get("id") + "tip";
                detail.put("id", id);
                zos.putNextEntry(new ZipEntry((String)detail.get("id") + ".html"));
                zos.write(tipHtml.getBytes(Charset.forName("GBK")));
                zos.closeEntry();
            } else {
                for(Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements(); zos.closeEntry()) {
                    ZipEntry ze = (ZipEntry)e.nextElement();
                    String name = ze.getName();
                    zos.putNextEntry(new ZipEntry(name));
                    InputStream currentFileInputStream = zipFile.getInputStream(ze);
                    if (!name.endsWith(".html") && !name.endsWith(".htm")) {
                        byte[] buf = new byte[8196];

                        int size;
                        while((size = currentFileInputStream.read(buf)) > 0) {
                            zos.write(buf, 0, size);
                        }
                    } else {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(currentFileInputStream, Charset.forName("GBK")));
                        String line;
                        String line1;
                        if (name.contains("sheet")) {
                            while((line = reader.readLine()) != null) {
                                line1 = line.replace("window.name!=\"frSheet\"", "window.name!=\"" + value + "\"");
                                zos.write(line1.getBytes(Charset.forName("GBK")));
                                zos.write(System.getProperty("line.separator").getBytes());
                            }
                        } else if (name.contains("tabstrip")) {
                            while((line = reader.readLine()) != null) {
                                line1 = line.replace("target=\"frSheet\"", "target=\"" + value + "\"");
                                zos.write(line1.getBytes(Charset.forName("GBK")));
                                zos.write(System.getProperty("line.separator").getBytes());
                            }
                        } else {
                            while((line = reader.readLine()) != null) {
                                line1 = line.replace("name=\"frSheet\"", "name=\"" + value + "\"");
                                String line2 = line1.replace("target=\\\"frSheet\\\"", "target=\\\"" + value + "\\\"");
                                String line3 = line2.replace("name=\\\"frSheet\\\"", "name=\\\"" + value + "\\\"");
                                zos.write(line3.getBytes(Charset.forName("GBK")));
                                zos.write(System.getProperty("line.separator").getBytes());
                            }
                        }

                        reader.close();
                    }
                }
            }

            InputStream in = new FileInputStream(targetFilePath);
            FileTimeoutUtil.removeFile(targetFilePath, in, 120000L);
            return in;
        } catch (Exception var33) {
            throw new RuntimeException("transferByReplaceContent error fileName=" + fileName, var33);
        } finally {
            try {
                zos.close();
                if (zipFile != null) {
                    zipFile.close();
                }
            } catch (IOException var31) {
            }

        }
    }

    public static long totalZipFileSize(ZipFile zipFile) {
        long total = 0L;
        if (zipFile != null) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();

            while(entries.hasMoreElements()) {
                ZipEntry ze = (ZipEntry)entries.nextElement();
                if (!ze.isDirectory()) {
                    total += ze.getSize();
                }
            }
        }

        return total;
    }

    private String getErrorMsg(Integer statusCode) {
        switch (statusCode) {
            case 401:
                return Resources.getString("云盘服务响应401,URL传参错误,请检查sdk代码", "AbstractFileService_7", "bos-fileservice-sdk", new Object[0]);
            case 402:
                return Resources.getString("云盘服务响应402,云盘服务下载文档失败", "AbstractFileService_8", "bos-fileservice-sdk", new Object[0]);
            case 502:
                return Resources.getString("云盘服务响应502,文件已被加密,无法进行pdf转换,预览失败", "AbstractFileService_9", "bos-fileservice-sdk", new Object[0]);
            case 503:
                return Resources.getString("云盘服务响应503,文件转换失败,请查看云盘日志", "AbstractFileService_10", "bos-fileservice-sdk", new Object[0]);
            default:
                return Resources.getString("云盘服务响应" + statusCode + ",文件无法进行pdf转换,预览失败", "AbstractFileService_11", "bos-fileservice-sdk", new Object[0]);
        }
    }

    private static boolean isLog() {
        return Boolean.getBoolean("yunpan.debug.enable.log");
    }

    private static String tipHtml(long limitSize, long totalSize) {
        return "<!DOCTYPE html>\n<html>\n<head>\n    <title>Tips Page</title>\n    <style>\n        body {\n            display: flex;\n            justify-content: center;\n            align-items: center;\n            height: 100vh;\n            margin: 0;\n            background-color: #f7f7f7;\n            font-family: Arial, sans-serif;\n        }\n        \n        .container {\n            max-width: 400px;\n            text-align: center;\n            padding: 20px;\n            background-color: #ffffff;\n            border-radius: 8px;\n            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);\n        }\n        \n        h1 {\n            color: #333333;\n            font-size: 24px;\n            margin-bottom: 10px;\n        }\n        \n        p {\n            color: #666666;\n            font-size: 16px;\n            margin-bottom: 20px;\n        }\n        \n        .btn {\n            display: inline-block;\n            padding: 10px 20px;\n            background-color: #007bff;\n            color: #ffffff;\n            text-decoration: none;\n            border-radius: 4px;\n            transition: background-color 0.3s ease;\n        }\n        \n        .btn:hover {\n            background-color: #0056b3;\n        }\n    </style>\n</head>\n<body>\n    <div class=\"container\">\n        <h1>Tips</h1>\n        <p>Exceeded the preview limit, please download to view</p>\n        <p>System Excel content limit is：" + BigDecimal.valueOf(limitSize).divide(BigDecimal.valueOf(1048576L), 2, RoundingMode.UP) + "M</p>\n        <p>Current Excel content size is：" + BigDecimal.valueOf(totalSize).divide(BigDecimal.valueOf(1048576L), 2, RoundingMode.UP) + "M</p>\n    </div>\n</body>\n</html>\n";
    }

    @Override
    public void deletePreviewCacheWps(String url, Map<String, String> config) {
    }

    @Override
    public void deletePreviewWps(String path, Map<String, String> config) {
    }



    private String getDownloadUrl(String path) {
        try {
            Class<?> clazzUrlService = Class.forName("kd.bos.url.UrlService");
            Method getAttachmentFullUrl = clazzUrlService.getMethod("getAttachmentFullUrl", String.class);
            String url = (String)getAttachmentFullUrl.invoke(clazzUrlService.newInstance(), path);
            Class<?> clazzEncreptSessionUtils = Class.forName("kd.bos.session.EncreptSessionUtils");
            Method encryptSession = clazzEncreptSessionUtils.getMethod("encryptSession", String.class);
            String downUrl = (String)encryptSession.invoke(clazzEncreptSessionUtils.newInstance(), url);
            downUrl = downUrl + RevProxyUtil.getHttpParamCollectFlag(downUrl) + "source=preview";
            if (isLog()) {
                logger.info("yunpan downLoadUrl=" + downUrl);
            }

            return downUrl;
        } catch (Exception var8) {
            throw new KDException(BosErrorCode.fileserviceException, "getDownloadUrl error", var8);
        }
    }
}
