package com.trs.web2frame.myutils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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.ConnectionUtil2;
import com.trs.web2frame.tool.tyjyh.FujianUtil;
import com.trs.web2frame.util.Log_Exception;


public class DownloadSwfTotext {

	public static String SITEID = " w.SITEID in(41,29,31) ";
	public static String SQLTYPE = "oracle";
	public static void main(String[] args) throws Exception {
		DownloadSwfTotext df = new DownloadSwfTotext();
		df.StartMethord();
	}
	
	 public void StartMethord() {
		 //1、按照站点id遍历wcmappendix中的数据，按照w0下载到本地
		 //2、遍历wcmdocument.dochtmlcon
		 List list = findAllChannelid();
		 for(int i =0;i<list.size();i++) {
			 downloadHtmlFile(list.get(i).toString());
		 }
	 }
	 
	 private void downloadDocFileName(String channelid) {
		 Connection connection = null;
		 Statement statement = null;
		 ResultSet set = null;
		 String sb = "";
		 try {
			 connection = ConnectionUtil2.getConnection();
	         statement = connection.createStatement();
	         sb = "select w.DOCFILENAME from wcmdocument w where  ("+SITEID+") and w.docstatus=10 and w.doctype=40 and w.DOCCHANNEL="+channelid;
	         set = statement.executeQuery(sb.toString());
	         while (set.next()){
	             String DOCFILENAME = set.getString("DOCFILENAME");
	             if("".equals(DOCFILENAME))continue;
	             FujianUtil.getLocalFullPathDownload(DOCFILENAME);
	         }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ConnectionUtil2.closeConnection(set, statement, connection);
		}
	}

	private List findAllChannelid() {
		 Connection connection = null;
		 Statement statement = null;
		 ResultSet set = null;
		 String sb = "";
		 List list = new ArrayList();
		 try {
			 connection = ConnectionUtil2.getConnection();
	         statement = connection.createStatement();
	         sb = "select w.channelid from WCMCHANNEL w where ("+SITEID+") 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 {
			ConnectionUtil2.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 = ConnectionUtil2.getConnection();
	         statement = connection.createStatement();
	         sb = "select w.DOCHTMLCON from wcmdocument w where  ("+SITEID+") 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 {
			ConnectionUtil2.closeConnection(set, statement, connection);
		 }
	}

	public void downloadAppendix() {
		 Connection connection = null;
		 Statement statement = null;
		 ResultSet set = null;
		 String sb = "";
		try {
			connection = ConnectionUtil2.getConnection();
	         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 ("+SITEID+") 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 {
			ConnectionUtil2.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 ("embed".equals(Node.nodeName())) {
                    //如果是相对路径
                    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(!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]);
                }
            }
            
            return ret_htmlContent;
        } catch (Exception e) {
            Log_Exception.Error_txt("GetAllFileInfoInContent()方法异常" + e.getMessage());
            return null;
        }
    }
    
    
	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;
		Logger_txt_allow(result);
		} catch (Exception e) {
		}
	}
	
	public static void Logger_txt_allow(String content) {
		System.out.println(content);
		String dirName = "C:\\Users\\admin\\Desktop\\";
		File file = new File(dirName);
		if (!file.exists()) {
			file.mkdirs();
		}
		String path = dirName + "path.txt";
		FileWriter fw = null;
		try {
			File F = new File(path);
			// 如果文件不存在,就动态创建文件
			if (!F.exists()) {
				F.createNewFile();
			}
			String writeDate = content;
			// 设置为:True,表示写入的时候追加数据
			fw = new FileWriter(F, true);
			// 回车并换行
			fw.write(writeDate + "\r\n");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
