package com.bcxin.identify.util.file;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.identify.util.codes.CommonConst;
import com.bcxin.identify.util.common.StringUtil;
import com.bcxin.identify.util.file.obs.OBSUtil;
import com.bcxin.identify.util.file.oss.OSSServiceExecutor;
import com.bcxin.identify.util.file.oss.OSSServiceInternetExecutor;
import com.bcxin.identify.util.sys.ConfigUtil;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Slf4j
public class BcxinFileUtils {

    /**
     * 默认文件上传路径
     */
    private final static String DEFAULT_UPLOAD_DIR = "upload";
    //暂存目录
    private final static String DEFAULT_TEMP_UPLOAD_DIR = "uploadidentify";

    private final static String DEFAULT_UPLOAD_LINUX = "/data/upload/saas/";

    private final static String DEFAULT_TEMP_DIR = "temp";

    private final static String QRCODE_DIR = "qrcode";

    /**
     * <b>Function </b> 本地文件存储
     *
     * @return
     * @author 罗鹏
     * @date 2017年1月3日 下午8:34:36
     * @注意事项 </b>
     * <b>
     */
    public static Map<String, String> saveFile(String uploadPath, MultipartFile multipartFile) {
        if (multipartFile != null) {
            try {
                Date now = new Date();
                String materialFileName = now.getTime() + BcxinStringUtils.random(5) + "."; // 20100101123123.
                String fileType = Files.getFileExtension(multipartFile.getOriginalFilename()); // jpg
                materialFileName = materialFileName + fileType; // 20100101123123.jpg
                String dirDate = DateUtil.today();
                File dir = new File(uploadPath + dirDate);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                String url = "public/common/file/get-resource?path=" + dirDate + "/" + materialFileName;
                String targetPath = uploadPath + dirDate + "/" + materialFileName;
                File targetFile = new File(targetPath);
                log.info("执行本地文件上传..." + targetFile);
                multipartFile.transferTo(targetFile);
                Map<String, String> map = Maps.newHashMap();
                map.put("url", url);
                map.put("key", "local_" + now.getTime());
                if (map == null || map.size() < 2) {
                    log.info("本地文件上传失败！");
                } else {
                    log.info("本地文件上传成功!");
                }
                return map;
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.getMessage(), e);
                return null;
            }
        }
        return null;
    }


    /**
     * 阿里OSS文件上传存储（同步）
     *
     * @param xFile
     * @return
     */
    public static String aliOSSFileUpload(MultipartFile xFile, String envi) {
        /* 获得文件后缀名 jpg*/
        String fileType = Files.getFileExtension(xFile.getOriginalFilename());
		/* 生成随机文件名 12345*/
        String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
		/* 组装成随机文件名称 12345.jpg */
        String fileName = randomNumber + CommonConst.DOT + fileType;
		/* 生成目录 */
        String directoryName = DateUtil.today();
        String ossKey = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/" + fileName;
        OSSServiceExecutor ossExecutor = new OSSServiceExecutor(envi);
        if (!ossExecutor.isExitsDirectory(directoryName)) {
            ossExecutor.createDirectory(directoryName);
        }
		/* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = xFile.getInputStream()) {
            ossExecutor.put(ossKey, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
		/* 返回全文件路径 */
        return ossExecutor.getServer() + ossKey;
    }

    /**
     * 华为OBS文件上传存储（同步）
     *
     * @return
     */
    public static String huaweiOBSFileUpload(MultipartFile xFile, String envi) {
		/* 获得文件后缀名 jpg*/
        String fileType = Files.getFileExtension(xFile.getOriginalFilename());
        if(StringUtils.isEmpty(fileType)){
            fileType = "aac";
        }
		/* 生成随机文件名 12345*/
        String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
		/* 组装成随机文件名称 12345.jpg */
        String fileName = randomNumber + CommonConst.DOT + fileType;
		/* 生成目录 */
        String directoryName = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/";
        String ossKey = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/" + fileName;
        OBSUtil obsUtil = new OBSUtil(envi);
		/* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = xFile.getInputStream()) {
            return obsUtil.put(directoryName, ossKey, inputStream);
        } catch (Exception e) {
//            e.printStackTrace();
            log.error(e.getMessage(), e);
            log.error("========> huaweiOBSFileUpload开始二次重试");
            //重新创建客户端
            obsUtil = new OBSUtil(envi);
            /* 利用jdk7的特性，执行完后自动关闭流对象 */
            try (InputStream inputStream = xFile.getInputStream()) {
                return obsUtil.put(directoryName, ossKey, inputStream);
            } catch (Exception e1) {
                e.printStackTrace();
                log.error("========> huaweiOBSFileUpload二次重试失败-"+e.getMessage(), e);
            }
        }
        return "";
    }

    private static String envi = ConfigUtil.getValue("ENVI_PROD");
    private static OBSUtil obsUtil = new OBSUtil(envi);;
    /**
     * 华为OBS文件上传存储（同步）
     *
     * @return
     */
    public static String huaweiOBSFileUploadAndSign(MultipartFile xFile, String envi, String isTemp) {
        /* 获得文件后缀名 jpg*/
        //String fileType = Files.getFileExtension(xFile.getOriginalFilename());
        String originalFilename = xFile.getOriginalFilename();
        String fileType = null;
        try {
            fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        }
        catch (Exception ex){
            if (StringUtils.isEmpty(fileType)) {
                fileType = "aac";
            }
        }

        /* 生成随机文件名 12345*/
        //String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
        String randomNumber = UUID.randomUUID().toString();
        /* 组装成随机文件名称 12345.jpg */
        String fileName = randomNumber + CommonConst.DOT + fileType;
        /* 生成目录 */
        //如果isTemp=1表示存临时目录可定时清理
        String headPath = DEFAULT_UPLOAD_DIR;
        if ("1".equals(isTemp)) {
            headPath = DEFAULT_TEMP_UPLOAD_DIR;
        }
        headPath = String.format("%s/%s", headPath, "common");
        String directoryName = headPath + "/" + DateUtil.today() + "/";
        String ossKey = headPath + "/" + DateUtil.today() + "/" + fileName;

        /* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = xFile.getInputStream()) {
            return obsUtil.put(directoryName, ossKey, inputStream);
        } catch (Exception e) {
            log.error("========> huaweiOBSFileUpload开始二次重试:{}", e.getMessage(), e);
            //重新创建客户端
            obsUtil = new OBSUtil(envi);
            /* 利用jdk7的特性，执行完后自动关闭流对象 */
            try (InputStream inputStream = xFile.getInputStream()) {
                return obsUtil.put(directoryName, ossKey, inputStream);
            } catch (Exception e1) {
                log.error("========> huaweiOBSFileUpload二次重试失败-：{}", e.getMessage(), e);
            }
        }

        return "";
    }

    /**
     * 华为OBS文件上传存储（同步）
     *
     * @return
     */
    public static String huaweiOBSBase64FileUpload(String filename,String base64, String envi) {
        /* 获得文件后缀名 jpg*/
        String originalFilename = filename;
        String fileType = null;
        try {
            fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        }
        catch (Exception ex) {
            if (StringUtils.isEmpty(fileType)) {
                fileType = "aac";
            }
        }

        if(base64.startsWith("data:")){
            base64 = base64.split(",")[1];
        }
        /* 生成随机文件名 12345*/
        String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
        /* 组装成随机文件名称 12345.jpg */
        String fileName = randomNumber + CommonConst.DOT + fileType;
        /* 生成目录 */
        String directoryName = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/";
        String ossKey = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/" + fileName;
        OBSUtil obsUtil = new OBSUtil(envi);
        BASE64Decoder decrypt = new BASE64Decoder();
        /* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = new ByteArrayInputStream(decrypt.decodeBuffer(base64))) {
            return obsUtil.put(directoryName, ossKey, inputStream);
        } catch (Exception e) {
//            e.printStackTrace();
            log.error(e.getMessage(), e);
            log.error("========> huaweiOBSBase64FileUpload开始二次重试");
            //重新创建客户端
            obsUtil = new OBSUtil(envi);
            /* 利用jdk7的特性，执行完后自动关闭流对象 */
            try (InputStream inputStream = new ByteArrayInputStream(decrypt.decodeBuffer(base64))) {
                return obsUtil.put(directoryName, ossKey, inputStream);
            } catch (Exception e1) {
                e.printStackTrace();
                log.error("========> huaweiOBSBase64FileUpload二次重试失败-"+e.getMessage(), e);
            }
        }
        return "";
    }

    public static String thumb_huaweiOBSFileUpload(MultipartFile xFile,String readPath, String envi) {
        readPath = readPath.replace("%2F","/");
        String floot = readPath.split(DEFAULT_UPLOAD_DIR + "/")[1];
        String fileType = Files.getFileExtension(floot);
		/* 生成目录 */
        String directoryName = DEFAULT_UPLOAD_DIR + "/" + floot.split("/")[0] + "/";
        String ossKey = DEFAULT_UPLOAD_DIR + "/" + floot.replace(CommonConst.DOT + fileType,"_THUMB" + CommonConst.DOT + fileType);
        OBSUtil obsUtil = new OBSUtil(envi);
		/* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = xFile.getInputStream()) {
            String thumb = DEFAULT_UPLOAD_LINUX+ UUID.randomUUID().toString()+ CommonConst.DOT + fileType;
            imageOp(inputStream,thumb,100,100);
            return obsUtil.put(directoryName, ossKey, new FileInputStream(new File(thumb)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        return "";
    }


    /**
     * <b>  </b>
     * @param inFilePath 图片原路径 /data/upload/blb/report/1575615964667.jpg
     * @author ZXF
     * @create 2020/06/15 0015 17:35
     * @version
     * @注意事项 </b>
     */
    public static void imageOp(InputStream inputStream,String outPath, int width, int height){
        Image image = null;
        try {
            image = ImageIO.read(inputStream);
        } catch (IOException e) {
            System.out.println("file path error...");
        }

        int originalImageWidth = image.getWidth(null);
        int originalImageHeight = image.getHeight(null);

        BufferedImage originalImage = new BufferedImage(
                originalImageWidth,
                originalImageHeight,
                BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g2d = originalImage.createGraphics();
        g2d.drawImage(image, 0, 0, null);

        BufferedImage changedImage =
                new BufferedImage(
                        width,
                        height,
                        BufferedImage.TYPE_3BYTE_BGR);

        double widthBo = (double)width/originalImageWidth;
        double heightBo = (double)width/originalImageHeight;

        AffineTransform transform = new AffineTransform();
        transform.setToScale(widthBo, heightBo);

        AffineTransformOp ato = new AffineTransformOp(transform, null);
        ato.filter(originalImage, changedImage);
        FileOutputStream smallImage = null;
        try {
            smallImage = new FileOutputStream(outPath);
            ImageIO.write(changedImage, "jpeg",smallImage);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (smallImage != null) {
                try {
                    smallImage.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 华为OBS文件上传存储（同步）
     *
     * @return
     */
    public static String huaweiOBSFileUploadForBlob(MultipartFile xFile, String envi) {
		/* 获得文件后缀名 jpg*/
        String originalFilename = xFile.getOriginalFilename();
        String fileType = null;
        try {
            fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        }
        catch (Exception ex){
            if (StringUtils.isEmpty(fileType)) {
                fileType = "aac";
            }
        }

        //如果是blob文件强制换成MP3后缀
        if(CommonConst.BLOB.equals(fileType)){
            fileType = CommonConst.MP3;
        }
		/* 生成随机文件名 12345*/
        String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
		/* 组装成随机文件名称 12345.jpg */
        String fileName = randomNumber + CommonConst.DOT + fileType;
		/* 生成目录 */
        String directoryName = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/blob/";
        String ossKey = directoryName + fileName;
		/* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = xFile.getInputStream()) {
            return obsUtil.put(directoryName, ossKey, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        return "";
    }

    /**
     * 华为OBS文件上传存储（同步）
     *
     * @return
     */
    public static String huaweiOBSFileUpload(File file, String envi, String fileType) {

		/* 生成随机文件名 12345*/
        String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
		/* 组装成随机文件名称 12345.jpg */
        String fileName = randomNumber + CommonConst.DOT + fileType;
		/* 生成目录 */
        String directoryName = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/";
        String ossKey = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/" + fileName;
		/* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = FileUtil.getInputStream(file)) {
            return obsUtil.put(directoryName, ossKey, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        return "";
    }


    /**
     * 华为OBS文件上传存储（本地文件上传到华为公共云）
     *
     * @return
     */
    public static String huaweiLocalFileUpload(File file, String date, String envi) {
		/* 生成目录 */
        String directoryName = DEFAULT_UPLOAD_DIR + "/" + date + "/";
        String ossKey = DEFAULT_UPLOAD_DIR + "/" + date + "/" + file.getName();
        OBSUtil obsUtil = new OBSUtil(envi);
		/* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = FileUtil.getInputStream(file)) {
            return obsUtil.put(directoryName, ossKey, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        return "";
    }


    /**
     * 阿里OSS临时文件上传存储（同步）
     *
     * @param xFile
     * @return
     */
    public static String aliOSSFileTempUpload(File xFile, String envi) {
		/* 获得文件后缀名 jpg*/
        String fileType = Files.getFileExtension(xFile.getName());
		/* 生成随机文件名 12345*/
        String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
		/* 组装成随机文件名称 12345.jpg */
        String fileName = randomNumber + CommonConst.DOT + fileType;
		/* 生成目录 */
        String directoryName = DateUtil.today();
        String ossKey = DEFAULT_TEMP_DIR + "/" + DateUtil.today() + "/" + fileName;
        OSSServiceExecutor ossExecutor = new OSSServiceExecutor(envi);
        if (!ossExecutor.isExitsDirectory(directoryName)) {
            ossExecutor.createDirectory(directoryName);
        }
		/* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = new FileInputStream(xFile)) {
            ossExecutor.put(ossKey, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
		/* 返回全文件路径 */
        return ossExecutor.getServer() + ossKey;
    }

    /**
     * 阿里OSS临时固定文件上传存储（不修改文件名）
     *
     * @param xFile
     * @return
     */
    public static String aliOSSFixFileTempUpload(File xFile, String envi) {
        String fileName = xFile.getName();
		/* 生成目录 */
        String directoryName = DateUtil.today();
        String ossKey = DEFAULT_TEMP_DIR + "/" + DateUtil.today() + "/" + fileName;
        OSSServiceExecutor ossExecutor = new OSSServiceExecutor(envi);
        if (!ossExecutor.isExitsDirectory(directoryName)) {
            ossExecutor.createDirectory(directoryName);
        }
		/* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = new FileInputStream(xFile)) {
            ossExecutor.put(ossKey, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
		/* 返回全文件路径 */
        return ossExecutor.getServer() + ossKey;
    }


    /**
     * 阿里OSS文件上传存储（同步）二维码
     *
     * @param xFile
     * @return
     */
    public static String aliOSSFileQrCodeUpload(File xFile, String envi) {
		/* 获得文件后缀名 jpg*/
        String fileType = Files.getFileExtension(xFile.getName());
		/* 生成随机文件名 12345*/
        String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
		/* 组装成随机文件名称 12345.jpg */
        String fileName = randomNumber + CommonConst.DOT + fileType;
		/* 生成目录 */
        String directoryName = DateUtil.today();
        String ossKey = QRCODE_DIR + "/" + DateUtil.today() + "/" + fileName;
        OSSServiceExecutor ossExecutor = new OSSServiceExecutor(envi);
        if (!ossExecutor.isExitsDirectory(directoryName)) {
            ossExecutor.createDirectory(directoryName);
        }
		/* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = new FileInputStream(xFile)) {
            ossExecutor.put(ossKey, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
		/* 返回全文件路径 */
        return ossExecutor.getServer() + ossKey;
    }


    /**
     * 阿里OSS文件上传存储（异步）
     *
     * @param xFile
     * @return
     */
    public static String aliOSSFileUploadAsync(MultipartFile xFile, String envi) {
		/* 获得文件后缀名 jpg*/
        String fileType = Files.getFileExtension(xFile.getOriginalFilename());
		/* 生成随机文件名 12345*/
        String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
		/* 组装成随机文件名称 12345.jpg */
        String fileName = randomNumber + CommonConst.DOT + fileType;
		/* 生成目录 */
        String directoryName = DateUtil.today();
        String ossKey = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/" + fileName;
        OSSServiceExecutor ossExecutor = new OSSServiceExecutor(envi);
        if (!ossExecutor.isExitsDirectory(directoryName)) {
            ossExecutor.createDirectory(directoryName);
        }
        new Thread(() -> {
			/* 利用jdk7的特性，执行完后自动关闭流对象 */
            try (InputStream inputStream = xFile.getInputStream()) {
                ossExecutor.put(ossKey, inputStream);
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.getMessage(), e);
            }
        }).start();
		/* 返回全文件路径 */
        return ossExecutor.getServer() + ossKey;
    }


    /**
     * 阿里OSS文件上传存储
     * （内网)
     *
     * @param xFile
     * @return
     */
    public static String aliOSSFileUploadInternet(MultipartFile xFile, String envi) {
		/* 获得文件后缀名 jpg*/
        String fileType = Files.getFileExtension(xFile.getOriginalFilename());
		/* 生成随机文件名 12345*/
        String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
		/* 组装成随机文件名称 12345.jpg */
        String fileName = randomNumber + CommonConst.DOT + fileType;
		/* 生成目录 */
        String directoryName = DateUtil.today();
        String ossKey = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/" + fileName;
        OSSServiceInternetExecutor ossExecutor = new OSSServiceInternetExecutor(envi);
        if (!ossExecutor.isExitsDirectory(directoryName)) {
            ossExecutor.createDirectory(directoryName);
        }
		/* 利用jdk7的特性，执行完后自动关闭流对象 */
        try (InputStream inputStream = xFile.getInputStream()) {
            ossExecutor.put(ossKey, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
			/* 有异常，返回空的路径 */
            return "";
        }
		/* 返回全文件路径 */
        return ossExecutor.getServer() + ossKey;
    }

    /**
     * 通过文件url生成base64字符串
     *
     * @param imgURL
     * @return
     * @auth llc
     * @date 2019-04-17
     */
    public static String getInputStreamByUrl(String imgURL) {
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        try {
            // 创建URL
            URL url = new URL(imgURL);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);

            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                //连接失败/链接失效/图片不存在
                return "fail";
            }
			/* jdk7自动关闭流 */
            try (InputStream inStream = conn.getInputStream();) {
                int len = -1;
                while ((len = inStream.read(data)) != -1) {
                    outPut.write(data, 0, len);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outPut.toByteArray());
    }

    public static void downloadBase64(HttpServletResponse response, String base64Code) throws IOException {
        try (ServletOutputStream out = response.getOutputStream()) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + DateUtil.current(true) + ".pdf");
            byte[] bytes = new BASE64Decoder().decodeBuffer(base64Code);
            try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
                byte[] buffer = new byte[1024];
                int byteRead = 0;
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
                out.flush();
            }
        }
    }
        /**
         * MultipartFile 转 File
         * @param file
         * @throws Exception
         */

    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            if (file.equals("") || file.getSize() <= 0) {
                return null;
            } else {
                is = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                os = new FileOutputStream(toFile);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (is != null) {
                try {
                    is.close(); // 输入流关闭
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close(); // 输出流关闭
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return toFile;
    }


    public static void deleteFolder(File file) {
        if(file.exists()) {
            if(file.isDirectory()) {
                for(File f : file.listFiles()) {
                    deleteFolder(f);
                }
                file.delete();
            } else {
                file.delete();
            }
        }
    }

    /**
     *
     * @param fileType 文件类型
     * @param fileUrl 第三方文件访问地址
     * @return
     */
    public static String getFileUrl(String fileType, String fileUrl) {
        try {
            /* 生成随机文件名 12345*/
            String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
            /* 组装成随机文件名称 12345.jpg */
            String fileName = randomNumber + CommonConst.DOT + fileType;
            /* 生成目录 */
            String directoryName = DEFAULT_UPLOAD_DIR + "/" + DateUtil.today() + "/tjbg/";
            String ossKey = directoryName + fileName;

            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000); // 连接超时时间（毫秒）
            connection.setReadTimeout(10000);    // 读取超时时间（毫秒）
            // 下载远程文件到本地临时路径
            try (InputStream inputStream = connection.getInputStream()) {
                return obsUtil.put(directoryName, ossKey, inputStream);
            } catch (IOException e) {
                throw new Exception("文件下载过程中发生IO异常", e);
            }
        } catch (Exception e) {
            log.error("文件处理失败: {}", fileUrl, e);
        }
        return "";
    }

}
