package com.zzsn.utils;

import com.zzsn.config.Global;
import com.zzsn.constant.FileConstant;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.DigestUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ImgBaseUtil {
    /**
     * 将本地图片转换成Base64编码字符串
     *
     * @param imgFile 图片目录路径
     * @return
     */
    public static String getImgFileToBase64(String imgFile) {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream inputStream = null;
        byte[] buffer = null;
        //读取图片字节数组
        try {
            inputStream = new FileInputStream(imgFile);
            int count = 0;
            while (count == 0) {
                count = inputStream.available();
            }
            buffer = new byte[count];
            inputStream.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    // 关闭inputStream流
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对字节数组Base64编码
        return new BASE64Encoder().encode(buffer);
    }
    /**
     * 将网络图片转换成Base64编码字符串
     *
     * @param imgUrl 网络图片Url
     * @return
     */
    public static String getImgUrlToBase64(String imgUrl) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        byte[] buffer = null;
        try {
            // 创建URL
            URL url = new URL(imgUrl);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10000);
            inputStream = conn.getInputStream();
            outputStream = new ByteArrayOutputStream();
            // 将内容读取内存中
            buffer = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            buffer = outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    // 关闭inputStream流
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    // 关闭outputStream流
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对字节数组Base64编码
        return new BASE64Encoder().encode(buffer);
    }

    /**
     * 将图片Base64编码转换成img图片文件
     *
     * @param imgBase64 图片Base64编码
     * @param imgPath   图片生成路径
     * @return
     */
    public static boolean getImgBase64ToImgFile(String imgBase64, String imgPath) {
        boolean flag = true;
        OutputStream outputStream = null;
        try {
            // 解密处理数据
            byte[] bytes = new BASE64Decoder().decodeBuffer(imgBase64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            outputStream = new FileOutputStream(imgPath);
            outputStream.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        } finally {
            if (outputStream != null) {
                try {
                    // 关闭outputStream流
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }
    /**
     * 根据指定大小压缩图片
     *
     * @param imagePath  源图片地址（网络地址）
     * @param desFileSize 指定图片大小，单位kb
     * @param imageId     影像编号
     * @return 压缩质量后的图片字节数组
     */

    public static String compressPicForScale(String imagePath, long desFileSize, String imageId) {
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] data = getBytesFromHost(imagePath);

        System.out.println("原始数据大小=======" + data.length);

        if (data.length < desFileSize * 1024) {
            return encoder.encode(data);
        }
        long srcSize = data.length;
        double accuracy = getAccuracy(srcSize / 1024);
        try {
            while (data.length > desFileSize * 1024) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
                Thumbnails.of(inputStream)
                        .scale(0.9f)
                        .outputQuality(accuracy)
                        .toOutputStream(outputStream);
                data = outputStream.toByteArray();

            }
            log.debug("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb",
                    imageId, srcSize / 1024, data.length / 1024);
        } catch (Exception e) {
            log.error("【图片压缩】msg=图片压缩失败!", e);
        }
        System.out.println("原始数据后=======" + data.length);

        return encoder.encode(data);
    }
    /**
     * 根据指定大小压缩图片
     *
     * @param imagePath  源图片地址（网络地址）
     * @return 压缩质量后的图片字节数组
     */

    public static String compressVideoForScale(String imagePath) {
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] data = getBytesFromHost(imagePath);
        System.out.println("原始数据大小=======" + data.length);
        return encoder.encode(data);
    }
    /**
     * 根据指定大小压缩图片
     *
     * @param imagePath  源图片地址（网络地址）
     * @param desFileSize 指定图片大小，单位kb
     * @param imageId     影像编号
     * @return 压缩质量后的图片字节数组
     */

    public static byte[] compressPicForScale1(String imagePath, long desFileSize, String imageId) {
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] data = getBytesFromHost(imagePath);

        System.out.println("原始数据大小=======" + data.length);

        if (data.length < desFileSize * 1024) {
            return data;
        }
        long srcSize = data.length;
        double accuracy = getAccuracy(srcSize / 1024);
        try {
            while (data.length > desFileSize * 1024) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
                Thumbnails.of(inputStream)
                        .scale(0.9f)
                        .outputQuality(accuracy)
                        .toOutputStream(outputStream);
                data = outputStream.toByteArray();
                System.out.println(data.length);

            }
            log.debug("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb",
                    imageId, srcSize / 1024, data.length / 1024);
        } catch (Exception e) {
            log.error("【图片压缩】msg=图片压缩失败!", e);
        }
        System.out.println("原始数据后=======" + data.length);

        return data;
    }
    /**
     * 获取网络图片的大小
     *
     * @param imgUrl 网络图片Url
     * @return
     */
    public static byte[] getBytesFromHost(String imgUrl) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        byte[] buffer = null;
        try {
            // 创建URL
            URL url = new URL(imgUrl);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            int status =  ((HttpURLConnection) conn).getResponseCode();
            if(status !=200){
                //状态码不是200，说明图片源地址可能已经失效
                return null;
            }
            inputStream = conn.getInputStream();
            outputStream = new ByteArrayOutputStream();
            // 将内容读取内存中
            buffer = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            buffer = outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    // 关闭inputStream流
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    // 关闭outputStream流
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }
    /**
     * 自动调节精度(经验数值)
     *
     * @param size 源图片大小
     * @return 图片压缩质量比
     */
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 900) {
            accuracy = 0.85;
        } else if (size < 2047) {
            accuracy = 0.6;
        } else if (size < 3275) {
            accuracy = 0.44;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }
    /**
     * 将图片转换为base64格式
     *
     * @param imageUrl：图片路径
     * @param sizeLimit：原图大小上限，当图片原图大小超过该值时先将图片大小 设置为该值以下再转换成base64格式,单位kb
     * @return
     */
    public static String convertImageToBase64(String imageUrl, Integer sizeLimit) throws IOException {
        //默认上限为50k
        if (sizeLimit == null) {
            sizeLimit = 50;
        }
        sizeLimit = sizeLimit * 1024;
        String base64Image;
        DataInputStream dataInputStream = null;
        ByteArrayOutputStream outputStream = null;
        ByteArrayInputStream inputStream = null;
        try {
            //从远程读取图片
            URL url = new URL(imageUrl);
            dataInputStream = new DataInputStream(url.openStream());
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            byte[] context = outputStream.toByteArray();

            //将图片数据还原为图片
            inputStream = new ByteArrayInputStream(context);
            BufferedImage image = ImageIO.read(inputStream);
            int imageSize = context.length;
            int type = image.getType();
            int height = image.getHeight();
            int width = image.getWidth();

            BufferedImage tempImage;
            //判断文件大小是否大于size,循环压缩，直到大小小于给定的值
            while (imageSize > sizeLimit) {
                //将图片长宽压缩到原来的90%
                height = new Double(height * 0.9).intValue();
                width = new Double(width * 0.9).intValue();
                tempImage = new BufferedImage(width, height, type);
                // 绘制缩小后的图
                tempImage.getGraphics().drawImage(image, 0, 0, width, height, null);
                //重新计算图片大小
                outputStream.reset();
                ImageIO.write(tempImage, "JPEG", outputStream);
                imageSize = outputStream.toByteArray().length;
            }

            //将图片转化为base64并返回
            byte[] data = outputStream.toByteArray();
            //此处一定要使用org.apache.tomcat.util.codec.binary.Base64，防止再linux上出现换行等特殊符号
            base64Image = Base64.encodeBase64String(data);
        } catch (Exception e) {
            //抛出异常
            throw e;
        } finally {
            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64Image;
    }
    /**
     * 将图片转换为base64格式
     *
     * @param imageUrl：图片路径
     * @param sizeLimit：原图大小上限，当图片原图大小超过该值时先将图片大小 设置为该值以下再转换成base64格式,单位kb
     * @return
     */
    public static byte[] convertImageToBase642(String imageUrl, Integer sizeLimit) throws IOException {
        //默认上限为50k
        if (sizeLimit == null) {
            sizeLimit = 50;
        }
        sizeLimit = sizeLimit * 1024;
        String base64Image;
        DataInputStream dataInputStream = null;
        ByteArrayOutputStream outputStream = null;
        ByteArrayInputStream inputStream = null;
        try {
            //从远程读取图片
            URL url = new URL(imageUrl);
            dataInputStream = new DataInputStream(url.openStream());
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            byte[] context = outputStream.toByteArray();

            //将图片数据还原为图片
            inputStream = new ByteArrayInputStream(context);
            BufferedImage image = ImageIO.read(inputStream);
            int imageSize = context.length;
            int type = image.getType();
            int height = image.getHeight();
            int width = image.getWidth();

            BufferedImage tempImage;
            //判断文件大小是否大于size,循环压缩，直到大小小于给定的值
            while (imageSize > sizeLimit) {
                //将图片长宽压缩到原来的90%
                height = new Double(height * 0.9).intValue();
                width = new Double(width * 0.9).intValue();
                tempImage = new BufferedImage(width, height, type);
                // 绘制缩小后的图
                tempImage.getGraphics().drawImage(image, 0, 0, width, height, null);
                //重新计算图片大小
                outputStream.reset();
                ImageIO.write(tempImage, "JPEG", outputStream);
                imageSize = outputStream.toByteArray().length;
            }

            //将图片转化为base64并返回
            byte[] data = outputStream.toByteArray();
            return data;
            //此处一定要使用org.apache.tomcat.util.codec.binary.Base64，防止再linux上出现换行等特殊符号
//            base64Image = Base64.encodeBase64String(data);
        } catch (Exception e) {
            //抛出异常
            throw e;
        } finally {
            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 将图片写入到磁盘
     *
     * @param img 图片数据流
     * @param zipImageUrl 文件保存时的名称
     */
    public static void writeImageToDisk(byte[] img, String zipImageUrl) {
        if(img ==null || img.length<0){
            return ;
        }
        try {
            File file = new File(zipImageUrl);
           if(!file.exists()){
               //自动创建父级文件夹
               file.getParentFile().mkdirs();
           }
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();
            System.out.println("图片已经写入"+zipImageUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param id   下载id
     * @param url  下载链接
     * @param referer  Referer，告诉服务器该网页是从哪个页面链接过来的
     * @param path  下载地址
     * @param vname  下载文件名
     */
    public static void sendDownloadInfo(String id,String url,String referer,String path,String vname ){
        for (int i = 0; i < 3; i++) {
            try {
                String param = "{\"jsonrpc\": \"2.0\", \"id\": \"" + id + "\", \"method\": \"aria2.addUri\","
                        + "\"params\": [[\"" + url + "\"], {\"referer\":\"" + referer + "\" , \"dir\": \"" + path + "\",\"out\":\"" + vname + "\"}]}";
                sendPost_body("http://localhost:6800/jsonrpc", param);
            }catch (Exception e){

            }
        }
    }

    public static String sendPost_body(String arl, String s) {
        // 创建url资源
        OutputStreamWriter out = null;
        URL url;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        System.out.println("请求地址:"+arl);
        try {
            url = new URL(arl);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            return "";
        }
        try {
            // 建立http连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置允许输出
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestMethod("POST"); // 设置请求方式
            conn.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            conn.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");//设置消息头，解决508错误
//   		conn.setConnectTimeout(1000*60*10);
//   		conn.setReadTimeout(1000*60*10);
            // 开始连接请求
            conn.connect();
            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8"); // utf-8编码
            // 写入请求的字符串
            out.append(s);
            out.flush();
            out.close();
            System.out.println(s);
            if(conn.getResponseCode()==200){
                // System.out.println("success");
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
            }

        } catch (Exception e) {
            // System.out.println("发送 POST 请求出现异常！" + e);
            String body="";
            e.printStackTrace();
            // log.error("远程服务未开启", e);
//   		result.append("");
            return body;
        }finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("发送 POST 请求结果数据" + result.toString());
        return result.toString();

    }

    public static void main(String[] args) throws IOException {

//        String savePath = FileConstant.IMG_VIR_PATH +"ceshi.jpg";
//        String savePath = FileConstant.IMG_VIR_PATH +"ceshi2.mp4";
//        byte[] bytes = compressPicForScale1("https://mts.huawangzhixun.com/video/military/20220420/fbe1db89-d0a6-4961-857b-e176370541bd.mp4?auth_Key=1678437608-0-0-b676018e005e13f701444d799ab18b5a", 5000, "1111111");
//        byte[] bytes = compressPicForScale1("http://www.csicl.com.cn/n332/n336/c23793/part/28631.mp4", 5000, "1111111");
//        byte[] bytes1 = convertImageToBase642("http://comec.cssc.net.cn/upload_img/b1e4d3063309f395f4d85fc0193d064.jpg", 50);
//        writeImageToDisk(bytes,savePath);
//        byte[] bytes = getBytesFromHost("http://www.cggc.ceec.net.cn/picture/0/s_14f1a1a063434205bd17b8769e0746f0.jpg");
//        System.out.println(bytes.toString());
        String  content="<div class=\"article_text\" id=\"zoom\">\n" +
                "            <p>　　8月8日，央视《朝闻天下》聚焦中国船舶集团建造的船舶海工装备带动海洋产业提速，在蔚蓝的大海上“蓝色粮仓”源源不断产出优质海产品，全产业链新装备增强油气供给能力。 <br> <br> 　　<strong>01 “蓝色粮仓”</strong></p> \n" +
                "<p style=\"TEXT-ALIGN: center\">\n" +
                " <video controls=\"controls\" loop=\"loop\" width=\"600\" height=\"338\" src=\"../../../n332/n335/c24530/part/28796.mp4\" autoplay=\"autoplay\">\n" +
                "  <object classid=\"clsid:6bf52a52-394a-11d3-b153-00c04f79faa6\" width=\"600\" height=\"338\"> <param name=\"url\" value=\"../../../n332/n335/c24530/part/28796.mp4\"> <param name=\"autostart\" value=\"true\"> <param name=\"uimode\" value=\"full\"><embed type=\"application/x-mplayer2\" src=\"../../../n332/n335/c24530/part/28796.mp4\" width=\"600\" height=\"338\" autostart=\"true\" uimode=\"full\" pluginspage=\"http://microsoft.com/windows/mediaplayer/en/download/\"></object>\n" +
                " </video></p> \n" +
                "<p>　　我国是一个海洋大国，拥有300万平方公里的蓝色疆域和1.8万公里的海岸线。记者近日在我国沿海采访时发现，海工装备的大型化智能化，正在撬动海洋相关产业的提速。 <br> <br> 　　在山东半岛，一个个建成投产的移动“海洋牧场”，已经完全改变了传统的渔业养殖模式，新模式正在促进我国优质海产品的供给能力不断增强。&nbsp;</p> \n" +
                "<p style=\"TEXT-ALIGN: center\"><img style=\"HEIGHT: 232px; BORDER-TOP-COLOR: ; WIDTH: 450px; BORDER-LEFT-COLOR: ; BORDER-BOTTOM-COLOR: ; FILTER: none; BORDER-RIGHT-COLOR: \" border=\"0\" src=\"../../../n332/n335/c24530/part/28798.png\"></p> \n" +
                "<p>　　八月份，我国建造的全球首艘10万吨级智慧养殖工船将迎来收获季。与网箱养殖不同的是，它自带动力装置，可随着不同季节，不同海水温度，沿着我国从南到北的海域切换。</p> \n" +
                "<p style=\"TEXT-ALIGN: center\"><img style=\"HEIGHT: 231px; BORDER-TOP-COLOR: ; WIDTH: 450px; BORDER-LEFT-COLOR: ; BORDER-BOTTOM-COLOR: ; FILTER: none; BORDER-RIGHT-COLOR: \" border=\"0\" src=\"../../../n332/n335/c24530/part/28799.png\"></p> \n" +
                "<p>　　中国船舶集团旗下中国重工子公司青岛北海造船生产运行部部长巩洋：一年投产的话，500克以上的大黄鱼能够产大约3700吨以上。&nbsp;<br> <br> 　　今年以来，一批深海渔业养殖装备的交付，为我国深远海养殖探索出一条可复制的新模式。数据显示，目前，我国已建成国家级海洋牧场示范区153个，未来我国优质海产品的供给能力将不断增强。 <br> <br> 　　<strong>02 全产业链新装备</strong></p> \n" +
                "<p style=\"TEXT-ALIGN: center\">\n" +
                " <video controls=\"controls\" loop=\"loop\" width=\"600\" height=\"338\" src=\"../../../n332/n335/c24530/part/28797.mp4\" autoplay=\"autoplay\">\n" +
                "  <object classid=\"clsid:6bf52a52-394a-11d3-b153-00c04f79faa6\" width=\"600\" height=\"338\"> <param name=\"url\" value=\"../../../n332/n335/c24530/part/28797.mp4\"> <param name=\"autostart\" value=\"true\"> <param name=\"uimode\" value=\"full\"><embed type=\"application/x-mplayer2\" src=\"../../../n332/n335/c24530/part/28797.mp4\" width=\"600\" height=\"338\" autostart=\"true\" uimode=\"full\" pluginspage=\"http://microsoft.com/windows/mediaplayer/en/download/\"></object>\n" +
                " </video></p> \n" +
                "<p>　　海上浮式生产储油船相当于一个海上油品加工厂，它漂浮在海上，可以为石油的加工、储存提供很好的解决方案。&nbsp;</p> \n" +
                "<p style=\"TEXT-ALIGN: center\"><img style=\"HEIGHT: 245px; BORDER-TOP-COLOR: ; WIDTH: 450px; BORDER-LEFT-COLOR: ; BORDER-BOTTOM-COLOR: ; FILTER: none; BORDER-RIGHT-COLOR: \" border=\"0\" src=\"../../../n332/n335/c24530/part/28800.png\"></p> \n" +
                "<p>　　中国船舶集团旗下中国重工子公司大连船舶重工集团有限公司项目经理倪建伟：这一侧管系是海底的输油系统，所有的原油通过这些系统输入到加工的模块，然后通过原油的处理进入到储存舱室。我们这个船每天的加工量在22万桶。&nbsp;</p> \n" +
                "<p style=\"TEXT-ALIGN: center\"><img style=\"HEIGHT: 231px; BORDER-TOP-COLOR: ; WIDTH: 450px; BORDER-LEFT-COLOR: ; BORDER-BOTTOM-COLOR: ; FILTER: none; BORDER-RIGHT-COLOR: \" border=\"0\" src=\"../../../n332/n335/c24530/part/28801.png\"></p> \n" +
                "<p>　　中国船舶集团旗下中国重工子公司大连船舶重工集团有限公司项目经理李吉明：原油船的甲板是非常空旷的，所有的管线都集中在中部，甲板以下这个位置就是我们的货油仓，这个船30万吨的载重量，相当于所说的国际原油200万桶（装载）。&nbsp;<br> <br> 来源：央视新闻</p>\n" +
                "       </div>";
        String address="http://www.csicl.com.cn/n332/n335/c24530/content.html";
        videoHandler(content,address);

    }

    public static Map<String, Object> videoHandler(String  content,String address) {
        Map<String, Object> map = new HashMap<>();
        Map<String, FileTag> contentFileTag = null;

        try {
            contentFileTag = ContentFileFinder.getContentVideoFileTag(content, address);
            if (contentFileTag == null || contentFileTag.size() < 1) {

            }
            Document document = Jsoup.parse(content);
            for (String key:contentFileTag.keySet()){
                FileTag value = contentFileTag.get(key);
                //使用MD5加密：ID+图片的原网址
                String md5 = DigestUtils.md5DigestAsHex((value.getAbsolutePath()).getBytes(StandardCharsets.UTF_8));
                System.out.println("加密后的md5值{}"+md5);
                // 图片保存到本地先关闭
                // 图片保存路径：
//                String savePath = Global.getProfile() + md5 + ".mp4";
                String savePath = "aa"; //保存路径
                String id = "111"; //
                String url = value.getAbsolutePath(); //视频链接
                String referer = address; //资讯地址
                String path = savePath;
                String vname = md5 + ".mp4"; //视频名称
                ImgBaseUtil.sendDownloadInfo(id, url, referer, path, vname);
                //保存图片到本地，本地路径文件夹
                Document keyDoc = Jsoup.parse(key);
                String src = keyDoc.select("video").attr("src");
                Elements elements = document.select("*[src=\"" + src + "\"]");
                for (Element e : elements) {
                    e.attr("src","/static/video/" + vname );
                }
            }
            System.out.println(document.outerHtml());
        }catch (Exception e){

        }
        return map;
    }

}
