package com.trs.web2frame.myutils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.trs.web2frame.tool.tyjyh.ConnectionUtil;
import com.trs.web2frame.tool.tyjyh.FujianUtil;
import com.trs.web2frame.util.Log_Exception;


public class DownloadFilesToFullUrl_txt_zf {

//	public static String SITEIDALL = " w.SITEID in(19,6,37,38,7,20) ";
//	public static String SITEIDWZ = " w.SITEID in(19,6,37,38) ";
//	public static String SITEIDGK = " w.SITEID in(7,20) ";
	public static String SITEIDALL = " w.SITEID in(24) ";
	public static String SITEIDWZ = " w.SITEID in(24) ";
	public static String SITEIDGK = " w.SITEID in(24) ";
	public static String SQLTYPE = "oracle";
	public static void main(String[] args) throws Exception {
		DownloadFilesToFullUrl_txt_zf df = new DownloadFilesToFullUrl_txt_zf();
		df.StartMethord();
	}
	
	 public void StartMethord() {
		 //1、按照站点id遍历wcmappendix中的数据，按照w0下载到本地
		 downloadAppendix();
		 //2、遍历wcmdocument.dochtmlcon
//		 List list = findAllChannelid();
/*		 for(int i =0;i<list.size();i++) {
			 downloadHtmlFile(list.get(i).toString());
//			 downloadHtmlFileGK(list.get(i).toString());
			 //下载文件型文档
			 downloadDocFileName(list.get(i).toString());
		 }*/
	 }
	 
	 private void downloadDocFileName(String channelid) {
		 Connection connection = null;
		 Statement statement = null;
		 ResultSet set = null;
		 String sb = "";
		 try {
			 connection = ConnectionUtil.getConnection(SQLTYPE);
	         statement = connection.createStatement();
	         sb = "select w.docpuburl,DOCFILENAME from wcmdocument w where  ("+SITEIDWZ+") and w.docstatus=10 and w.doctype=40 and w.DOCCHANNEL="+channelid;
	         set = statement.executeQuery(sb.toString());
	         while (set.next()){
	             String docpuburl = set.getString("docpuburl");
	             String DOCFILENAME = set.getString("DOCFILENAME");
	             docpuburl = docpuburl.substring(0,docpuburl.lastIndexOf("/")+1);
	             if("".equals(docpuburl))continue;
	             Log_Exception.Logger_txt_allow(docpuburl+DOCFILENAME);
	         }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ConnectionUtil.closeConnection(set, statement, connection);
		}
	}

	private List findAllChannelid() {
		 Connection connection = null;
		 Statement statement = null;
		 ResultSet set = null;
		 String sb = "";
		 List list = new ArrayList();
		 try {
			 connection = ConnectionUtil.getConnection(SQLTYPE);
	         statement = connection.createStatement();
	         sb = "select w.channelid from WCMCHANNEL w where ("+SITEIDALL+") order by channelid";
	         set = statement.executeQuery(sb.toString());
	         while (set.next()){
	             String channelid = set.getString("channelid");
	             list.add(channelid);
	         }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ConnectionUtil.closeConnection(set, statement, connection);
		}
		return list;
	}

	private void downloadHtmlFile(String channelid) {
		 Connection connection = null;
		 Statement statement = null;
		 ResultSet set = null;
		 String sb = "";
		 Log_Exception.Logger_txt("导入完成：channelid：" + channelid  );
		 try {
			 connection = ConnectionUtil.getConnection(SQLTYPE);
	         statement = connection.createStatement();
	         sb = "select w.DOCHTMLCON from wcmdocument w where  ("+SITEIDGK+") and w.docstatus=10 and w.DOCCHANNEL="+channelid;
	         set = statement.executeQuery(sb.toString());
	         while (set.next()){
	             String htmlContent = set.getString("DOCHTMLCON");
	             if("".equals(htmlContent))continue;
	             GetRetHtmlContent(htmlContent); 
	         }
		 } catch (Exception e) {
			e.printStackTrace();
		 } finally {
			ConnectionUtil.closeConnection(set, statement, connection);
		 }
	}
	
	
	private void downloadHtmlFileGK(String channelid) {
		 Connection connection = null;
		 Statement statement = null;
		 ResultSet set = null;
		 String sb = "";
		 Log_Exception.Logger_txt("导入完成：channelid：" + channelid  );
		 try {
			 connection = ConnectionUtil.getConnection(SQLTYPE);
	         statement = connection.createStatement();
	         sb = "select wg.content from wcmdocument w "
	         		+ " left join WCMMETATABLEGOVINFO wg on w.docid=wg.METADATAID "
	         		+ " where  ("+SITEIDGK+") and w.docstatus=10 and w.DOCCHANNEL="+channelid;
	         set = statement.executeQuery(sb.toString());
	         while (set.next()){
	             String htmlContent = set.getString("content");
	             if("".equals(htmlContent))continue;
	             GetRetHtmlContent(htmlContent); 
	         }
		 } catch (Exception e) {
			e.printStackTrace();
		 } finally {
			ConnectionUtil.closeConnection(set, statement, connection);
		 }
	}

	public void downloadAppendix() {
		 Connection connection = null;
		 Statement statement = null;
		 ResultSet set = null;
		 String sb = "";
		try {
			connection = ConnectionUtil.getConnection(SQLTYPE);
	         statement = connection.createStatement();
	         sb = "select wa.appfile,wa.APPENDIXID from wcmappendix wa\r\n" + 
	         		"left join wcmdocument w on wa.APPDOCID=w.docid\r\n" + 
	         		"where ("+SITEIDALL+") and w.docstatus=10 order by APPENDIXID ";
	         set = statement.executeQuery(sb.toString());
	         while (set.next()){
	             String appfile = set.getString("appfile");
	             String APPENDIXID = set.getString("APPENDIXID");
	             FujianUtil.getLocalFullPathDownload(appfile);
	             Log_Exception.Logger_txt("导入完成：APPENDIXID：" + APPENDIXID+";appfile"+appfile  );
	             System.out.println("APPENDIXID"+APPENDIXID);
	         }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ConnectionUtil.closeConnection(set, statement, connection);
		}
	 } 	
    /**
     * 处理内容中的附件
     * @param htmlContent
     * @param doctitle 
     * @return
     */
    public String GetRetHtmlContent(String htmlContent){
        String ret_htmlContent=htmlContent;
        //1.找出内容中的所有图片 2.找出内容中的附件 3.调接口上传图片/附件并记录返回的信息 4.替换正文中的对应图片/附件信息
        try {
            Document doc = Jsoup.parse(htmlContent);
            Elements sectionNodes = doc.getAllElements();
            String imgStr="";
            String fileStr="";
            for (int i = 0; i < sectionNodes.size(); i++){
                Element Node = sectionNodes.get(i);
                //找图片
                if ("img".equals(Node.nodeName())||Node.nodeName().equals("IMG")) {
                    //如果是相对路径
                    if (Node.attr("src") != null) {
                        String temp = Node.attr("src");
                        if(temp.startsWith("W0")||temp.startsWith("P0")) {
                            if(imgStr.equals("")){
                                imgStr+=temp;
                            }else if(!imgStr.contains(temp)){
                                imgStr+=","+temp;
                            }
                        }
                    }
                }
                //找文件
                if("a".equals(Node.nodeName())){
                    if (Node.attr("href") != null && !Node.attr("href").equals("")&&Node.hasText()){
                        //判断该链接是否是文件
                        String temp=Node.attr("href");
                        if(temp.startsWith("W0")||temp.startsWith("P0")) {
                            if(fileStr.equals("")){
                                fileStr+=temp;
                            }else if(!fileStr.contains(temp)){
                                fileStr+=","+temp;
                            }
                        }
                    }
                }
            }
            if(!imgStr.equals("")){
//            	System.out.println("zheng wen tu pian"+imgStr);
                String[] imagArray=imgStr.split(",");
                for (int i = 0; i < imagArray.length; i++) {
                	getLocalFullPathDownload(imagArray[i]);
                }
            }
            
            if(!fileStr.equals("")){
                String[] fileArray=fileStr.split(",");
                for (int i = 0; i < fileArray.length; i++) {
                	getLocalFullPathDownload(fileArray[i]);
                }
            }
            
            return ret_htmlContent;
        } catch (Exception e) {
            Log_Exception.Error_txt("GetAllFileInfoInContent()方法异常" + e.getMessage());
            return null;
        }
    }

    //判断字符串中是否包含附件
    public static Boolean IsContainFile(String content){
        if(content!=null&&!content.equals("")) {
            String regExImg = "(.txt|.doc|.xls|.zip|.rar|.pdf|.ppt|.TXT|.DOC|.XLS|.ZIP|.RAR|.PDF|.PPT)";
            Pattern patternImg = Pattern.compile(regExImg);
            Matcher matcherImg = patternImg.matcher(content);

            if(matcherImg.find()) {
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
	public static void getLocalFullPathDownload(String file) {
//		String root2="http://lcj.shanxi.gov.cn/";
//		String root2="http://fgw.shanxi.gov.cn/";
//		String root2="http://nynct.shanxi.gov.cn/";
		String root2="http://www.shanxi.gov.cn/";
		String rootstr = "";
		try {
			String type = file.substring(0, 2);
		if ("W0".equals(type)) {
			root2 += "webpic/";
			rootstr = "webpic/";
		} else {
			root2 += "protect/";
			rootstr = "protect/";
		}
		String first = file.substring(0, 8);
		String second = file.substring(0, 10);
		String result = root2 + first + "/" + second + "/" + file;
		Log_Exception.Logger_txt_allow(result);
		} catch (Exception e) {
		}
	}
}
