package com.dcsoft.system.utils;


import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.entity.ContentType;
import org.apache.poi.util.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

//java将图片的url转换成File，File转换成二进制流byte
public class PictureUtils {
    //将Url转换为File
    public static File UrltoFile(String url) throws Exception {
        HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
        httpUrl.connect();
        InputStream ins=httpUrl.getInputStream();
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "xie.jpg");//System.getProperty("java.io.tmpdir")缓存
        if (file.exists()) {
            file.delete();//如果缓存中存在该文件就删除
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;

    }
    //将File对象转换为byte[]的形式
    public static byte[] FileTobyte(File file){
        FileInputStream fileInputStream = null;
        byte[] imgData = null;

        try {

            imgData = new byte[(int) file.length()];

            //read file into bytes[]
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(imgData);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return imgData;
    }

    /**
     * url转变为 MultipartFile对象
     * @param url 网络地址链接
     * @param fileName  文件名
     * @return
     * @throws Exception
     */
    public static MultipartFile createMultipartFile(String url, String fileName){
        FileItem item = null;
        CommonsMultipartFile commonsMultipartFile  = null;
        try {
            //HttpURLconnection是基于http协议的，支持get，post，put，delete等各种请求方式，最常用的就是get和post  这里是根据url发起一个HTTP请求
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setReadTimeout(30000); //设置从主机读取数据超时（单位：毫秒）
            conn.setConnectTimeout(30000); //设置连接主机超时（单位：毫秒）
            //设置应用程序要从网络连接读取数据
            conn.setDoInput(true);  //允许读入
            conn.setRequestMethod("GET"); //设置请求方式为GET
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {  //发起请求并获取响应码比对。
                //得到响应流
                InputStream is = conn.getInputStream();
                //采用参数指定临界值和系统临时文件夹构造文件项工厂对象。
                FileItemFactory factory = new DiskFileItemFactory(16, null);
                String textFieldName = "uploadfile";
                //根据DiskFileItemFactory相关配置将每一个请求消息实体项目创建成DiskFileItem 实例
                item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName);
                OutputStream os = item.getOutputStream();

                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }

                // 转换为MultipartFile对象
                commonsMultipartFile = new CommonsMultipartFile(item);
                os.close();
                is.close();
            }
        } catch (Exception e) {
            throw new RuntimeException("文件下载失败", e);
        }

        return commonsMultipartFile ;
    }

    //File转MultipartFile
    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }

    public static MultipartFile base64ToMultipartFile(String base64) {
        //base64编码后的图片有头信息所以要分离出来 [0]data:image/png;base64, 图片内容为索引[1]
        String[] baseStrs = base64.split(",");

        //取索引为1的元素进行处理
        byte[] b = Base64.decodeBase64(baseStrs[1]);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }

        //处理过后的数据通过Base64DecodeMultipartFile转换为MultipartFile对象
        return new Base64DecodeMultipartFile(b, baseStrs[0]);
    }


    public static MultipartFile base64ToMultipartFiles(String base64) {
        //base64编码后的图片有头信息所以要分离出来 [0]data:image/png;base64, 图片内容为索引[1]

        //取索引为1的元素进行处理
        byte[] b = Base64.decodeBase64(base64);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }

        //处理过后的数据通过Base64DecodeMultipartFile转换为MultipartFile对象
        return new Base64DecodeMultipartFile(b, "data:image/jpeg;base64,");
    }

}
