package nckd.jxccl.base.sit.helper;

import kd.bos.context.RequestContext;
import kd.bos.exception.KDBizException;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.url.UrlService;
import kd.bos.util.FileNameUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class SITExportDataHelper {

    private static Log logger = LogFactory.getLog(SITExportDataHelper.class);


    public static String storeFile(Workbook wb, String fileName) {
        ByteArrayOutputStream outStream = null;
        ByteArrayInputStream inStream = null;

        String url;
        try {
            fileName = fileName + ".xlsx";
            outStream = new ByteArrayOutputStream();
            wb.write(outStream);
            outStream.flush();
            inStream = new ByteArrayInputStream(outStream.toByteArray());
            FileService fileService = FileServiceFactory.getAttachmentFileService();
            RequestContext requestContext = RequestContext.get();
            String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(), requestContext.getAccountId(), "salaryFile", fileName);
            String path = fileService.upload(new FileItem(fileName, pathParam, inStream));
            url = UrlService.getAttachmentFullUrl(path);
        } catch (Exception var17) {
            logger.error("storeFile error", var17);
            throw new KDBizException(ExceptionUtils.getFullStackTrace(var17));
        } finally {
            closeSafely(outStream, inStream);

            try {
                wb.close();
            } catch (Exception e) {
            }

        }

        return url;
    }

    public static void closeSafely(OutputStream os, InputStream in) {
        if (os != null) {
            try {
                os.close();
            } catch (Exception e) {
            }
        }

        if (in != null) {
            try {
                in.close();
            } catch (Exception e1) {
            }
        }

    }

}
