package com.zzsn.extractor;

import com.zzsn.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("/")){
        	//add lihuawei 增加双斜杠判断图片   如果开始时双斜杠就增加http:
        	if(imgPath.startsWith("//")){
        	
                return start+imgPath.replace("//", "");
        	}
            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
   */
   private 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.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 "";
   }
   
    /**
     * 获取正文中的文件标签，包含正文中的图片和附件
     * 创建人:  李东亮  
     * 创建时间:  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,a");
        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();
            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;
    }
    
    public static Map<String,FileTag> getContentFileTag(String content){
        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,a");
        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();
            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 = "";
            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;
    }
    public static void main(String[] args) {
         String str = "<img data-src=\"http://static.tianyaui.com/img/static/2011/imgloading.gif\" title=\"点击图片查看幻灯模式\"  original2=\"http://img3.laibafile.cn/p/l/246500759.jpg\" />";
         System.out.println(ContentFileFinder.getSuffix("http://www.baidu.com//a.xls"));
    }
}
