package com.zzsn.search.extractor;

import com.zzsn.utility.model.FileTag;
import com.zzsn.utility.util.DateUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 获取正文中的图片或者文件
 * 创建人：李东亮   
 * 创建时间：2016-8-30 下午5:25:04   
 * 公司 ：郑州数能软件科技有限公司
 * @version  1.0  
 *
 */
public class ContentFileFinder {
    /**
     * 获取父路径
     * 创建人:  李东亮  
     * 创建时间:  2015-7-6 下午3:17:44 
     * @version 1.0
     * @param path
     * @return
     * @throws IOException 
     */
    public static String getDirPath(String path) {
        path = path.substring(0, path.lastIndexOf("/")) ;
        return path;
    }
    
    /**
     * 去除路径中的./
     * 创建人:  李东亮  
     * 创建时间:  2015-7-6 下午3:43:00 
     * @version 1.0
     * @param path
     * @return
     * @throws IOException 
     */
    public static String formatPath(String currentPageURL,String imgPath) {
        String start="";
        if(currentPageURL.indexOf("http://")!=-1){
            start = "http://";
        }else if(currentPageURL.indexOf("https://")!=-1){
            start = "https://";
        }
        //绝对路径
        if(imgPath.startsWith("/")){
            currentPageURL = currentPageURL.replace(start, "");
            int subIndex = currentPageURL.indexOf("/");
            if(subIndex==-1){
                subIndex = currentPageURL.length();
            }
            String domain = currentPageURL.substring(0, subIndex);
            return start+domain+imgPath;
        }
        
        //相对路径
        String path = currentPageURL+"/"+imgPath;
    
        path = path.replaceAll(start, "D:/");
        File f = new File(path);
        String filePath="";
        try {
            filePath = f.getCanonicalPath();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String result = filePath.replaceAll("D:\\\\", start);
        result = result.replaceAll("\\\\", "/");
        return result;
    }
    
    
    /**
     * 生成图片文件保存路径
     * 创建人:  李东亮  
     * 创建时间:  2016-3-23 下午2:50:33 
     * @version 1.0
     * @return
     */
   private static String genImgFileName(String suffix){
       String dir = DateUtil.format(new Date(), "yyyy-MM-dd");
       String uuid = UUID.randomUUID().toString();
       return dir+"/"+uuid+suffix;
   }
   
   /**
    * 确保有src属性并且src属性指向正确的图片地址
    * 创建人:  李东亮  
    * 创建时间:  2016-6-6 下午1:46:03 
    * @version 1.0
    * @param rawTag
    * @return
    */
   public static Element ensureSrc(Element imgTag){
      // Document doc =  Jsoup.parseBodyFragment(rawTag);
       String firstSrcAtt=null;
       if(imgTag.hasAttr("original")){
           firstSrcAtt = "original";
       }else if(imgTag.hasAttr("data-src")){
           firstSrcAtt = "data-src";
       }else if(imgTag.hasAttr("_src")){
           firstSrcAtt = "_src";
       }else if(imgTag.hasAttr("src")){
           firstSrcAtt ="src";
       }
       if(firstSrcAtt==null){
           return null;
       }
       imgTag.attr("src", imgTag.attr(firstSrcAtt));
       return imgTag;
   }
   
  /**
   * 获取图片的绝对路径
   * 创建人:  李东亮  
   * 创建时间:  2016-6-6 下午2:05:02 
   * @version 1.0
   * @param element
   * @param uri
   * @return
   */
   public static String getAbsolutePath(Element element,String uri,String linkAtt){
      String absolutePath = element.attr(linkAtt);
       if(absolutePath.startsWith("data:image")){
           return null;
       }
       if(absolutePath.startsWith("file:")){
           return null;
       }
       if (absolutePath.matches("(?i)^javascript.*|#")) {
           return null;
       }
       if(absolutePath!=null && absolutePath.trim().length()>0 && !absolutePath.startsWith("http://")&&!absolutePath.startsWith("https://")&&uri!=null){
           String puriDir = getDirPath(uri);
           absolutePath = formatPath(puriDir,absolutePath);
       }
       return absolutePath;
   }
   
   /**
    * 获取后缀名
    * 创建人:  李东亮  
    * 创建时间:  2016-8-30 下午5:00:39 
    * @version 1.0
    * @param uri
    * @return
    */
   public static String getSuffix(String uri){
       uri = uri.replaceAll("http://|https://", "");
       Pattern p = Pattern.compile("/.+(\\.\\w{1,4})$");
       Matcher m =  p.matcher(uri);
       if(m.find()){
           return m.group(1);
       }
       return "";
   }
    public static Map<String,String> getContentImgTag(String content,String sourceaddress){
        Map<String,String> imgMap = new HashMap<String,String>();
        if(content==null||content.length()==0){
            return imgMap;
        }
        String absolutePath;
        Document doc = Jsoup.parse(content);
        Elements imgTags = doc.select("img");
        Element imgTag;
        String filePathAttr="";
        for (Iterator<Element> iterator = imgTags.iterator(); iterator.hasNext();) {
            imgTag =  iterator.next();
            if(imgTag.tagName().toLowerCase().equals("img")){
                filePathAttr = "src";
                //使src指向正确的图片显示路径
                imgTag = ensureSrc(imgTag);
            }
            String relativePath=imgTag.attr(filePathAttr);
            //获取图片的绝对路径，并且使src指向图片的绝对路径
            absolutePath = getAbsolutePath(imgTag,sourceaddress,filePathAttr);
            if(absolutePath==null){
                continue;
            }
            //key为图片完整路径
            imgMap.put(relativePath, absolutePath);
        }
        return imgMap;
    }
    /**
     * 获取正文中的文件标签，包含正文中的图片和附件
     * 创建人:  李东亮  
     * 创建时间:  2016-9-8 下午3:01:09 
     * @version 1.0
     * @param content
     * @param sourceaddress
     * @return
     */
    public static Map<String,FileTag> getContentFileTag(String content,String sourceaddress){
        Map<String,FileTag> imgMap = new HashMap<String,FileTag>();
        if(content==null||content.length()==0){
            return imgMap;
        }
        String rawTag;
        String absolutePath;
        FileTag fileTag;
        String savePath;
        Document doc = Jsoup.parse(content);
        Elements imgTags = doc.select("img");
        Element imgTag;
        String suffix = "";
        String filePathAttr;
        String preFixPath;
        for (Iterator<Element> iterator = imgTags.iterator(); iterator.hasNext();) {
            fileTag = new FileTag();
            imgTag =  iterator.next();
            rawTag = imgTag.outerHtml().replaceAll("\"", "'").replaceAll("'>", "' \\/>");
            if(imgTag.tagName().toLowerCase().equals("img")){
                filePathAttr = "src";
                //使src指向正确的图片显示路径
                imgTag = ensureSrc(imgTag);
                preFixPath="IMG_SERVER/";
            }else
            {
                filePathAttr="href";
                fileTag.setFileName(imgTag.text());
                preFixPath="FILE_SERVER/";
            }
            //获取图片的绝对路径，并且使src指向图片的绝对路径
            absolutePath = getAbsolutePath(imgTag,sourceaddress,filePathAttr);
            if(absolutePath==null){
                continue;
            }
            imgTag.attr(filePathAttr,absolutePath);
            fileTag.setAbsolutePath(absolutePath);
            fileTag.setAbsoluteTag(imgTag.outerHtml());
            //图片保存路径
            suffix = ContentFileFinder.getSuffix(absolutePath);
            savePath = genImgFileName(suffix);
            fileTag.setSavePath(savePath);
            //图片保存标签
            imgTag.attr(filePathAttr,preFixPath+fileTag.getSavePath());
            fileTag.setSaveTag(imgTag.outerHtml());
            //key为图片完整路径
            imgMap.put(rawTag, fileTag);
        }
        return imgMap;
    }
    
    /**
     * 得到网页中图片的地址
     * @param sets html字符串
     */
    public static Set<String> getImgStr(String htmlStr) {
     Set<String> pics = new HashSet<String>();
     String img = "";
     Pattern p_image;
     Matcher m_image;
     String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
     p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
     m_image = p_image.matcher(htmlStr);
     while (m_image.find()) {
      // 得到<img />数据
      img = m_image.group();
      System.out.println(img);
      // 匹配<img>中的src数据
      Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
      while (m.find()) {
       pics.add(m.group(1));
      }
     }
     return pics;
    }
    public static String rmHtmlImgOrAtag(String htmlStr) {
    	//匹配img标签的正则表达式
    	String regxpForImgTag = "<img\\s[^>]+/>|<img.*>(.*?)</img>|<a.*>(.*?)</a>|<a.*/>";
    	Pattern pattern = Pattern.compile(regxpForImgTag);
    	Matcher matcher = pattern.matcher(htmlStr);
    	while (matcher.find()) {
    	    String temp = matcher.group();
    	     
    	    htmlStr = htmlStr.replace(temp, " ");
    	}
        return htmlStr;
    }
    

    public static void main(String[] args) {
         String str = "<span></span><img data-src=\"http://static.tianyaui.com/img/static/2011/imgloading.gif\" title=\"点击图片查看幻灯模式\"  original2=\"http://img3.laibafile.cn/p/l/246500759.jpg\" /> "
         		+ "<div>hello<div/><img data-src=\"http://static.tianyaui.com/img/static/2011/imgloading.gif\" title=\\\"点击图片查看幻灯模式\\\"  original2=\\\"http://img3.laibafile.cn/p/l/246500759.jpg\\\" >qew</img>";
//         System.out.println(ContentFileFinder.getSuffix("http://www.baidu.com//a.xls"));
//         getContentFileTag(str,"");
           str=rmHtmlImgOrAtag(str);
           System.out.println(str);
         String aString=str+"<div class=\"_3L5YSq\" title=\"vue兼容ie11的解决方法  2021年最新解决方案\">"
         		+ "<a class=\"_1-HJSV _1OhGeD\" href=\"/p/4718213d9373\" target=\"_blank\" rel=\"noopener noreferrer\">vue兼容ie11的解决方法  2021年最新解决方案</a>"
         		+ "<span>qwqe<a href='qwe'/></span</div>";

         aString=rmHtmlImgOrAtag(aString);
         System.out.println(aString);
         
         
         
    }
}









