package com.sifang.modules.platform.utils;

import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

public class Base64Url {

    private static Logger logger = LoggerFactory.getLogger(Base64Url.class);

    private static String URL;

    static {
        try {
            Configuration configuration = new PropertiesConfiguration("conf.properties");
            URL = configuration.getString("img.domain");
            logger.info("IMGURL: {}", URL);
        } catch (ConfigurationException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 在线图片转换成base64字符串
     *
     * @param imgURL    图片线上路径
     * @returnrepor
     *
     * @author ZHANGJL
     * @dateTime 2018-02-23 14:43:18
     */
    public static String ImageToBase64ByOnline(String imgURL) {
        if(StringUtil.isBlank(imgURL)){
            return "";
        }
        InputStream is = null;
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(URL+imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 对字节数组Base64编码
        return Base64.encodeBase64String(data.toByteArray());
    }

    /**
     * 验证字符串是否为空
     *
     * @param input
     * @return
     */
    private static boolean isEmpty(String input) {
        return input == null || input.equals("");
    }


    public static String encodeBase64Byte(byte[] buffer){
        return Base64.encodeBase64String(buffer);
    }


    public static byte[] openFile(String filePath) {
        int HttpResult; // 服务器返回的状态
        byte[] bytes = new byte[1024];
        try
        {
            URL url =new URL(URL+filePath); // 创建URL
            URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
            urlconn.connect();
            HttpURLConnection httpconn =(HttpURLConnection)urlconn;
            HttpResult = httpconn.getResponseCode();
            if(HttpResult != HttpURLConnection.HTTP_OK) {
                System.out.print("无法连接到");
            } else {
                int filesize = urlconn.getContentLength(); // 取数据长度
                System.out.println("取数据长度===="+filesize);
                urlconn.getInputStream();
                InputStream inputStream = urlconn.getInputStream();

                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                int ch;
                while ((ch = inputStream.read()) != -1) {
                    swapStream.write(ch);
                }
                bytes = swapStream.toByteArray();
            }
            System.out.println("文件大小===="+bytes.length);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return  bytes;
    }



    public static String PdfToBase64(String filePath) throws Exception {
        //使用分段上传的读取文件的方式将大文件转换为base64编码数据
        ByteArrayOutputStream os1 = new ByteArrayOutputStream();
        InputStream file1 = new FileInputStream(URL+filePath);
        byte[] byteBuf = new byte[3 * 1024 * 1024];
        byte[] base64ByteBuf;
        int count1; //每次从文件中读取到的有效字节数
        while ((count1 = file1.read(byteBuf)) != -1) {
            if (count1 != byteBuf.length) {//如果有效字节数不为3*1000，则说明文件已经读到尾了，不够填充满byteBuf了
                byte[] copy = Arrays.copyOf(byteBuf, count1); //从byteBuf中截取包含有效字节数的字节段
                base64ByteBuf = Base64.encodeBase64(copy); //对有效字节段进行编码
            } else {
                base64ByteBuf = Base64.encodeBase64(byteBuf);
            }
            os1.write(base64ByteBuf, 0, base64ByteBuf.length);
            os1.flush();
        }
        file1.close();
        System.out.println(os1.toString());
        return os1.toString();

    }

    public static void main(String[] args) throws Exception {
       // String strImg = getbase64Url("D:/Pictures/厦门/psb (1).jpg");
       // System.out.println(strImg);
        //System.out.println("==========================================================");
        String string = "pdf/20220829/ca7f4eacd15e4838b664c8e18e496549/王学义购电合同.pdf";
        PdfToBase64(string);
        //在线图片地址
     /*   String ste = PDFToBase64(string);
        System.out.println(ste);*/

      //  Base64ToImage(ste, "F:/迅雷云盘/test3.jpg");

    }
}
