package com.trs.web2frame.tool.tyjyh.tonglaozheng;

import com.trs.web2frame.WCMServiceCaller;
import com.trs.web2frame.dispatch.Dispatch;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

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

public class JsoupUtilsView {


    /*
     * 下载a标签对应的文件
     * */
    public String rexStringHtml(String url) throws Exception {
        url = ColumnConfig.docHtmlUrl + url;
        Document doc = Jsoup.parse(new URL(url), 10000);
        String html = doc.toString();
        html = html.replace("amp;","");
        try {
            Elements links = doc.select("a[href]");
            System.out.println("==============");
            System.out.println("=============="+links.text());
            for (Element link : links) {
                String text = link.attr("href");
                int inw = text.indexOf("www.");
                if (inw >= 0){
                    continue;
                }
                int inh1 = text.indexOf("http://preview.mail.163.com");
                if (inh1 >= 0){
                    continue;
                }
                int inh2 = text.indexOf("@");
                if (inh2 >= 0){
                    continue;
                }
                String name = link.text();
                System.out.println(name);
                try {
                    name = name + getId(text);
                }catch (Exception e){
                    e.printStackTrace();
                }
                try {
                    String fileType = getFileType(text);
                    if(fileType != null && fileType !=""){
                        name = name+"."+fileType;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                try {
                    String shrefOrSrc = updateFile(name,text);
                    if(shrefOrSrc != null && shrefOrSrc != ""){
                        html = html.replace(text,shrefOrSrc);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
            Elements linksrc = doc.select("img[src]");
            for (Element element : linksrc) {
                String textsrc = element.attr("src");
                int inw = textsrc.indexOf("www.");
                if (inw >= 0){
                    continue;
                }
                int inh1 = textsrc.indexOf("http://preview.mail.163.com");
                if (inh1 >= 0){
                    continue;
                }
                int inh2 = textsrc.indexOf("@");
                if (inh2 >= 0){
                    continue;
                }
                try {
                    String hrefOrSrc = ColumnConfig.dowBaseUrlTow+textsrc;
                    String name = hrefOrSrc.substring(hrefOrSrc.lastIndexOf("/")+1);
                    String shrefOrSrc = updateFile(name,textsrc);
                    System.out.println(shrefOrSrc);
                    if(shrefOrSrc != null && shrefOrSrc != ""){
                        html = html.replace(textsrc,shrefOrSrc);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            Elements linkimg = doc.select("IMG[src]");
            for (Element element : linkimg) {
                String textsrc = element.attr("src");
                int inw = textsrc.indexOf("www.");
                if (inw >= 0){
                    continue;
                }
                int inh1 = textsrc.indexOf("http://preview.mail.163.com");
                if (inh1 >= 0){
                    continue;
                }
                int inh2 = textsrc.indexOf("@");
                if (inh2 >= 0){
                    continue;
                }
                try {
                    String hrefOrSrc = ColumnConfig.dowBaseUrlTow+textsrc;
                    String name = hrefOrSrc.substring(hrefOrSrc.lastIndexOf("/")+1);
                    String shrefOrSrc = updateFile(name,textsrc);
                    System.out.println(shrefOrSrc);
                    if(shrefOrSrc != null && shrefOrSrc != ""){
                        html = html.replace(textsrc,shrefOrSrc);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            Elements linkvideo = doc.select("video[src]");
            for (Element element : linkvideo) {
                String shtml = element.toString();

                String[] split1 = html.split("<video");
                System.out.println("+++++++++++++++++++++++++++");
                String s1 = split1[0];
                System.out.println(s1);
                String s2 = split1[1];
                String s3 = s2.split("</video>")[1];
                System.out.println(s3);

                String textsrc = element.attr("src");
                try {
                    String[] splitMp4 = textsrc.split("id=");
                    String str = splitMp4[1];
                    String[] split = str.split("&type=");
                    String mp4 = split[0]+".mp4";
                    System.out.println("====================="+mp4);
                    String iframeHtml = "<p>\n" +
                            "<iframe frameborder=\"0\" src=\"/masvod/public/video/player.html?data-src=oldvideo/"+mp4+"\" width=\"640\" height=\"480\" style=\"width:640px;height:480px;margin:auto;text-align: center;display:block\"></iframe>\n" +
                            "</p><p>\n" +
                            "<br/>\n" +
                            "</p>";
                    html = s1 + iframeHtml + s3;
                    System.out.println("=============================new ");
                    System.out.println(html);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        Document parse = Jsoup.parse(html);
        try {
            Elements linkH = parse.select("a[href]");
            for (Element element : linkH) {
                String href = element.attr("href");
                int i = href.indexOf("down.asp");
                if(i >= 0){
                    continue;
                }
                int i1 = href.indexOf("_data/");
                if(i1 >=0){
                    continue;
                }
                int ia = href.indexOf("_Data/");
                if(ia >=0){
                    continue;
                }
                int ii = href.indexOf("/app-editor/");
                if(ii >=0){
                    continue;
                }

                int iiii = href.indexOf("_data/file");
                if(iiii >=0){
                    continue;
                }

                int iiiii = href.indexOf("/uploads/soft/");
                if(iiiii >=0){
                    continue;
                }
                int iiiiii = href.indexOf("common/preview_resource.action");
                if(iiiiii >=0){
                    continue;
                }
                String fileType = getFileTypeText(href);
                if(fileType != null && fileType != ""){
                    element.attr("appendix","true");
                    element.attr("needdownload","true");
                }
            }
            Elements linkImg = parse.select("img[src]");
            for (Element element : linkImg) {
                String src = element.attr("src");
                int i = src.indexOf("images/doc.gif");
                if(i >= 0){
                    continue;
                }
                String fileType = getFileTypeText(src);
                if(fileType != null && fileType != ""){
                    element.attr("needdownload","true");
                }
            }
            Elements linkHImg = parse.select("IMG[src]");
            for (Element element : linkHImg) {
                String src = element.attr("src");
                String fileType = getFileTypeText(src);
                if(fileType != null && fileType != ""){
                    element.attr("needdownload","true");
                }
            }
            Elements linkHvideo= parse.select("video[src]");
            for (Element element : linkHvideo) {
                String src = element.attr("src");
                String fileType = getFileTypeText(src);
                if(fileType != null && fileType != ""){
                    element.attr("needdownload","true");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return parse.toString();
    }

    private String getFileType(String text) {
        String suffixes="avi,mpeg,3gp,mp3,mp4,wav,jpeg,gif,jpg,png,apk,exe,pdf,rar,zip,docx,doc,txt,xls,rar,ppt,XLS,RAR,PDF," +
                "AVI,MPEG,3GP,MP3,MP4,WAV,JPEG,GIF,JPG,PNG,APK,EXE,PDF,RAR,ZIP,DOCX,DOC,TXT,XLS,RAR,PPT,XLS,RAR,PDF,PPT,XLSX,xlsx"
                ;
        String[] split = suffixes.split(",");
        String type = null;
        for (String st : split) {
            int i = text.indexOf(st);
            if(i >=0){
                type = st;
            }
        }
        return type;
    }


    private String getFileTypeText(String text) {
        String suffixes="avi,mpeg,3gp,mp3,mp4,wav,jpeg,gif,jpg,png,apk,exe,pdf,rar,zip,docx,doc,txt,xls,rar,ppt,XLS,RAR,PDF," +
                "AVI,MPEG,3GP,MP3,MP4,WAV,JPEG,GIF,JPG,PNG,APK,EXE,PDF,RAR,ZIP,DOCX,DOC,TXT,XLS,RAR,PPT,XLS,RAR,PDF,PPT,XLSX,xlsx"
                ;
        String[] split = suffixes.split(",");
        String type = null;
        for (String st : split) {
            int i = text.indexOf(st);
            if(i >=0){
                type = st;
            }
        }
        return type;
    }

    private String getId(String url){
        String id = null;
        String[] split = url.split("id=");
        try {
            if(split.length > 1){
                id = split[1];
            }
        }catch (Exception e){

        }

        return id;
    }

    public String updateFile(String hrefOrSrc,String name,String textsrc) throws Exception {
        System.out.println("==============");
        System.out.println(hrefOrSrc);
        String fileNameRe = null;
        if(textsrc != null && textsrc != ""){
            System.out.println(textsrc);
            System.out.println("_data_data_data_data_data_data_data_data");
            String dowUrl = null;
            int i = textsrc.indexOf("_data/");
            if(i >=0){
                dowUrl = zgunayi("http://10.21.245.114"+textsrc) ;
            }
            int ia = textsrc.indexOf("_Data/");
            if(ia >=0){
                dowUrl = zgunayi("http://10.21.245.114"+textsrc) ;
            }
            int ii = textsrc.indexOf("/app-editor/");
            if(ii >=0){
                dowUrl = zgunayi("http://10.21.245.114:81/home/cmsadmin/UCMSServer/webapps"+textsrc) ;
            }
            if(dowUrl != null && dowUrl != ""){
                URL url = new URL(dowUrl);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setConnectTimeout(300*10000);
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                InputStream inputStream = conn.getInputStream();
                File file = new File(ColumnConfig.dowPath + name);
                FileOutputStream outputStream = new FileOutputStream(file);
                IOUtils.copy(inputStream, outputStream);
                outputStream.close();
                inputStream.close();
                System.out.println("文件已保存为：" + file.getAbsolutePath());
                //将对应的文件上传到海云
                String  fileName = ColumnConfig.dowPath + name;
                Dispatch dispatch = WCMServiceCaller.UploadFile(fileName);
                System.out.println("-----------"+dispatch.getUploadShowName());
                fileNameRe = dispatch.getUploadShowName();
                //上传完成后将文件删除
                file.delete();
                if(fileNameRe != null && fileNameRe != ""){
                    return fileNameRe;
                }
            }
        }

        try {
            URL url = new URL(zgunayi(hrefOrSrc));
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(300*10000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream inputStream = conn.getInputStream();
            File file = new File(ColumnConfig.dowPath + name);
            FileOutputStream outputStream = new FileOutputStream(file);
            IOUtils.copy(inputStream, outputStream);
            outputStream.close();
            inputStream.close();
            System.out.println("文件已保存为：" + file.getAbsolutePath());
            //将对应的文件上传到海云
            String  fileName = ColumnConfig.dowPath + name;
            Dispatch dispatch = WCMServiceCaller.UploadFile(fileName);
            System.out.println("-----------"+dispatch.getUploadShowName());
            fileNameRe = dispatch.getUploadShowName();
            //上传完成后将文件删除
            file.delete();
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("=============="+fileNameRe);
        return fileNameRe;
    }

    public String updateFile(String name,String textsrc) throws Exception {
        System.out.println("==============");
        String fileNameRe = null;
        try {
            if(textsrc != null && textsrc != ""){
                System.out.println(textsrc);
                String dowUrl = null;
                int i = textsrc.indexOf("_data/");
                if(i >=0){
                    dowUrl = zgunayi("http://10.21.245.114"+textsrc) ;
                }
                int ia = textsrc.indexOf("_Data/");
                if(ia >=0){
                    dowUrl = zgunayi("http://10.21.245.114"+textsrc) ;
                }
                int ii = textsrc.indexOf("/app-editor/");
                if(ii >=0){
                    dowUrl = zgunayi("http://10.21.245.114:81/home/cmsadmin/UCMSServer/webapps"+textsrc) ;
                }

                int iiii = textsrc.indexOf("_data/file");
                if(iiii >=0){
                    dowUrl = zgunayi("http://221.199.189.183:5555"+textsrc) ;
                }

                int iiiii = textsrc.indexOf("/uploads/soft/");
                if(iiiii >=0){
                    dowUrl = zgunayi("http://221.199.189.183:5555"+textsrc) ;
                }

                int iiiiii = textsrc.indexOf("common/preview_resource.action");
                if(iiiiii >=0){
                    dowUrl = zgunayi("http://221.199.189.183:5555/"+textsrc) ;
                }

                int iii = textsrc.indexOf("type=");
                if(iii >=0){
                    String fileType = getFileType(name);
                    try {
                        String sName = name.split("//?")[1];
                        String[] split = sName.split("&type=png");
                        String sNN = split[0];
                        if(fileType != null && fileType !=""){
                            name = sNN+"."+fileType;
                        }
                    }catch (Exception e){
                        if(fileType != null && fileType !=""){
                            name = Math.random()+"."+fileType;
                        }
                    }
                    try {
                        String sName = name.split("//?")[1];
                        String[] split = sName.split("&type=jpg");
                        String sNN = split[0];
                        if(fileType != null && fileType !=""){
                            name = sNN+"."+fileType;
                        }
                    }catch (Exception e){
                        if(fileType != null && fileType !=""){
                            name = Math.random()+"."+fileType;
                        }
                    }
                    dowUrl = ColumnConfig.dowBaseUrl+textsrc ;
                }
                if(i < 0 && ii < 0 && iii < 0 && ia < 0){
                    dowUrl =ColumnConfig.dowBaseUrlTow+textsrc ;
                }
                System.out.println("=================="+dowUrl);
                if(dowUrl != null && dowUrl != ""){
                    String fileV = null;
                    try {
                        name = name.replace("/","");
                        fileV = downLoadFromUrl(dowUrl,name,ColumnConfig.dowPath);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    System.out.println(fileV);
                    //将对应的文件上传到海云
                    if(fileV != null && fileV != ""){
                        Dispatch dispatch = WCMServiceCaller.UploadFile(fileV);
                        System.out.println("-----------"+dispatch.getUploadShowName());
                        fileNameRe = dispatch.getUploadShowName();
                        //上传完成后将文件删除
                        try {
                            new File(fileV).delete();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        if(fileNameRe != null && fileNameRe != ""){
                            return fileNameRe;
                        }
                    }

                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return fileNameRe;
    }

    public String updateFileUrl(String dowUrl,String name) throws Exception {
        System.out.println("==============");
        System.out.println(dowUrl);
        System.out.println(name);
        String fileNameRe = null;
        try {

            if(dowUrl != null && dowUrl != ""){
                String fileV = null;
                try {
                    fileV = downLoadFromUrl(dowUrl,name,ColumnConfig.dowPath);
                }catch (Exception e){

                }
                System.out.println(fileV);
                //将对应的文件上传到海云
                if(fileV != null && fileV != ""){
                    Dispatch dispatch = WCMServiceCaller.UploadFile(fileV);
                    System.out.println("-----------"+dispatch.getUploadShowName());
                    fileNameRe = dispatch.getUploadShowName();
                    //上传完成后将文件删除
                    try {
                        new File(fileV).delete();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    if(fileNameRe != null && fileNameRe != ""){
                        return fileNameRe;
                    }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return fileNameRe;
    }



    public String zgunayi(String downloadUrl) throws Exception {

        System.out.println(downloadUrl);
        int lastIndexOf = downloadUrl.lastIndexOf('/');

        String fileName = downloadUrl.substring(lastIndexOf + 1);

        String newFileName = URLEncoder.encode(fileName, "utf-8");

        String subUrl = downloadUrl.substring(0,lastIndexOf + 1);

        String newUrl = subUrl + newFileName;

        return newUrl;
    }

    /**
     * 从网络Url中下载文件
     *
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public  String downLoadFromUrl(String urlStr, String fileName, String savePath) {
        try {
            System.out.println("下载："+urlStr);
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            // 得到输入流
            InputStream inputStream = conn.getInputStream();
            // 获取字节数组
            byte[] getData = readInputStream(inputStream);

            // 文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            // System.out.println("info:"+url+" download success");
            return saveDir + File.separator + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";

    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

 }
