package com.zzsn.awx.service;

import com.alibaba.fastjson.JSON;
import com.zzsn.entity.DocInfo;
import com.zzsn.entity.SiteMsgTemple;
import com.zzsn.extractor.ContentFileFinder;
import com.zzsn.extractor.ExtEntity;
import com.zzsn.extractor.FileTag;
import com.zzsn.extractor.WeiXinDispatch;
import com.zzsn.job.JedisUtil;
import com.zzsn.util.Constants;
import com.zzsn.util.ContentUtility;
import com.zzsn.util.DateUtil;
import com.zzsn.util.WeixinUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * 爬虫service
 * 创建人：李东亮   
 * 创建时间：2016-4-13 下午2:52:20   
 * 公司 ：郑州数能软件科技有限公司
 * @version  1.0  
 *
 */
@Service
public class SiteService {

	private static final Logger Log = LoggerFactory.getLogger(SiteService.class);
	private static Long id=0L;

	

	public void sendUrlToweixin(SiteMsgTemple siteMsgTemple){
		String url=siteMsgTemple.getSiteUri();
		String weixinhaoid="";
		try {
			weixinhaoid = getParam(url);
			String msg= JSON.toJSONString(siteMsgTemple);
//			JedisUtil.setString(":"+weixinhaoid+"_"+siteMsgTemple.getId(),msg,0);
			JedisUtil.setString(":"+weixinhaoid,msg,0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(weixinhaoid!=null&&weixinhaoid.trim().length()>0){
			clearweixinhaoid(weixinhaoid);
		}
	    //20秒发送一次链接给微信
	    sendurl(url);
	    try {
			//将信息缓存到redis 以便后续查询使用

			Thread.sleep(1000*30);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public synchronized void  sendurl  (String url){
		try {
		WeixinUtil.sendWxMessage(Constants.WXSENDNAME, "点击链接:"+url, 1000002, "ww6bef1e81aacbf27a",
    			"ttZJ_KbO3QABs5Z7IDHNa_X4CZizaojherzwzfQ7wl0");
			Thread.sleep(30*1000);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			try {
				Thread.sleep(20*1000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
			}
			e.printStackTrace();
		}
		
	}
	

	
	public synchronized void  sendurl1  (String url,String wxname){
		try {
		WeixinUtil.sendWxMessage(wxname, "点击链接:"+url, 1000002, "ww6bef1e81aacbf27a",
    			"ttZJ_KbO3QABs5Z7IDHNa_X4CZizaojherzwzfQ7wl0");
			Thread.sleep(20*1000);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			try {
				Thread.sleep(20*1000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
			}
			e.printStackTrace();
		}
		
	}

	 public static void clearweixinhaoid(String weixinhaoid){
		try {
			JedisUtil.del(weixinhaoid);
		}catch (Exception e){

		}
	}

	public static Map<String,String> parse(String url) {
		 Map<String,String> map=new HashMap<String,String>();
		if (url == null) {
			return map;
		}
		url = url.trim();
		if (url.equals("")) {
			return map;
		}
		String[] urlParts = url.split("\\?");
		String uri = urlParts[0];
		//没有参数
		if (urlParts.length == 1) {
			return map;
		}
		//有参数
		String[] params = urlParts[1].split("&");
		for (String param : params) {
			String[] keyValue = param.split("=");
			map.put(keyValue[0], keyValue[1]);
		}

		return map;
	}
	public static String getParam(String url) {
		
		Map<String, String> map=new HashMap<String, String>();
		try {
			map = parse(url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(url);
		}
		return map.get("__biz");
	}
	public static String getParambyname(String url,String name) {

		Map<String,String> map=parse(url);
		return map.get(name);
	}
	public static String getweixinId(String s) {
			
		Integer start=s.indexOf("__biz=");
		Integer end=s.indexOf("#wechat");
		String ss=null;
		if(start>0 && end>0){
			
		 ss=s.substring(start+6, end);
		}
		return ss;
	}
	public static String getweixinId1(String s) {
		
		Integer start=s.indexOf("__biz=");
		Integer end=s.indexOf("&mid=");
		String ss=null;
		if(start>0 && end>0){
			
		 ss=s.substring(start+6, end);
		}
		return ss;
	}
	
	public void crawlerweixin(SiteMsgTemple siteMsgTemple) throws Exception{
		String weixinurl=siteMsgTemple.getSiteUri();
		
		//判断是否yipaqu
		String urlflag=JedisUtil.getString(weixinurl);
		if(!StringUtils.isEmpty(urlflag)){
			System.out.println("已爬取1"+weixinurl);
			return;
		}
		//查询组织
		String weixinid=getParam(weixinurl);
		String organdtids=JedisUtil.getString(weixinid);

		WeiXinDispatch wx=new WeiXinDispatch();
		ExtEntity extEntity=wx.getExtractorElement(weixinurl);
		 String contentNoTag = null;
	        Map<String, FileTag> imgDataMap= ContentFileFinder.getContentFileTag(extEntity.getContentWithTag(),"https://mp.weixin.qq.com/s/DePy9GFzh1tL844ik9YuWw");
			System.out.println(extEntity.getContentWithTag());
			String formatImgContent=extEntity.getContentWithTag();
			 for (String key : imgDataMap.keySet()) {
				 while (formatImgContent.contains(key)) {
		                //转换为绝对路径
		                formatImgContent = formatImgContent.replace(key, "");
		            }
			 }
			 extEntity.setContentWithTag(formatImgContent);
			 String contentWithTag = "";
  	         contentNoTag = ContentUtility.TransferHTML2Text(contentWithTag);
		    DocInfo docInfo=new DocInfo();
		 
	        docInfo.setSourceType("WeChat");
	       // docInfo.setLastModified(lastModified);
	        docInfo.setSourceaddress(weixinurl);
	        docInfo.setLang("zh_CN");
	        docInfo.setContentType("HTML");
	        docInfo.setSourceType("News");
	        docInfo.setCharset("utf-8");
	        docInfo.setTitle(extEntity.getTitle());
	        docInfo.setAuthor(extEntity.getAuthor());
	        docInfo.setPublishDate(extEntity.getPublishDate());
	        docInfo.setOrigin("微信公众号-"+extEntity.getAuthor());
	       // docInfo.setKeywords(extEntity.getKeywords());
	        //docInfo.setSummary(extEntity.getSummary());
	        StringBuffer sb = new StringBuffer();
			sb.append("<html><head>");
			sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
			sb.append("<title></title></head><body>");
			sb.append(extEntity.getContentWithTag());
			sb.append("</body></html>");

	        docInfo.setContentWithTag(sb.toString());
	        docInfo.setContentNoTag(contentNoTag);
	        docInfo.setContentImgCvtTag(sb.toString());
	        Iterator<String> it =null;
//	        Iterator<String> it = organdtids.iterator();
	        while (it.hasNext()) {
	          String str = it.next();
	          System.out.println(str);
	          //解析ITD ORGID
	         String[] ss= str.split("-");
	          if(ss.length!=3){
	        	  return;
	          }else{
	        	  System.out.println(str);
	        	  System.out.println(ss.toString());
	          }
	          String orgid=ss[0];
	          String tid=ss[1];
	          String sid=ss[2];
	          docInfo.setOrgId(Long.valueOf(orgid));
	          docInfo.setSid(Long.valueOf(sid));
	          Map<String, String> params = new HashMap<String, String>();
				params.put("fromWhere", "weixincraw");
				if (null!=tid&&!"null".equals(tid)) {
					params.put("tid", tid);
				}
				docInfo.setOtherParams(params);
				String week = DateUtil.getDateBeforeDays(new Date() , 2);
				if(docInfo.getTitle()==null){
					if(StringUtils.isEmpty(contentNoTag)){
						//空了继续爬 不空爬不下来记录了
					}else{
						JedisUtil.setString(weixinurl, 1+"",0);
					}
				}else if(docInfo.getPublishDate().compareTo(week)<0){
						//1天前外事办项目不推
						System.out.println("时间过期"+docInfo.getPublishDate());
					JedisUtil.setString(weixinurl, 1+"",0);
						//其他项目还是推
					}else{
					JedisUtil.setString(weixinurl, 1+"",0);
				}
	        }
		
	}
	
	public static void main(String[] args) {
		String s="https://mp.weixin.qq.com/mp/profile_ext?action=home&scene=114&__biz=MzAwODE2OTAwNg==#wechat_redirect";
		
		System.out.println(getParam(s));
		Integer start=s.indexOf("__biz=");
		Integer end=s.indexOf("#wechat");
		String ss=null;
		if(start>0 && end>0){
			
		 ss=s.substring(start+6, end);
		}
		
		System.out.println(ss);
		ss=getParam(s);
		System.out.println(ss);
		
		String time="2019-11-18 12:20:23";
		String week = DateUtil.getDateBeforeDays(new Date() , 1);
		System.out.println(time.compareTo(week));
		
		String sss="http://mp.weixin.qq.com/s?__biz=MzUxMzEzNjg1Ng==&mid=2247484003&idx=1&sn=965ca574850ab65be466c443bf8e2a3b&scene=0965ca574850ab65be466c443bf8e2a3b";
		
		sss=getParambyname(sss, "signature");
		System.out.println(sss);
		
	}

}