package com.zzsn.awx.service;


import com.zzsn.entity.Wxurl;
import com.zzsn.job.JedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 爬虫service
 * 创建人：李东亮   
 * 创建时间：2016-4-13 下午2:52:20   
 * 公司 ：郑州数能软件科技有限公司
 * @version  1.0  
 *
 */
@Service
public class ApiService {
	
	@Autowired
	private SiteService siteService;
	
	
	public  Boolean suo_flag=true;// 单个请求锁，只允许一个人访问
	

	public String getNurl(String oldurl){
		if(!suo_flag) {
			return "0";
		}
		suo_flag=false;
		try {
			Wxurl url=new Wxurl();
			
			url.setFlag(0L);
			url.setOurl(oldurl);
			//15秒内轮巡数据库 是否转换成功，
			for (int i = 0; i < 15; i++) {
				List<Wxurl> list1=new ArrayList<>();
				if(list1.size()>0) {
					Long flag=list1.get(0).getFlag();
					String nurl=list1.get(0).getNurl();
					if(flag.longValue()==1&& StringUtils.isNotEmpty(nurl)) {
						return nurl;
					}
				Thread.sleep(1000L);
				System.out.println(i);
				
				}else {
//					wxurlDao.save(url);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		suo_flag=true;
		
		return "0";
	}
	
	public static String apiflag="apiflag";
	public void zhuanhuanurl(String wxurl){
		Thread t = new Thread(new Runnable(){
			public void run(){
				do {
					
					try {
						Wxurl wxurl=new Wxurl();
					
					List<Wxurl> list=new ArrayList<>();
						list.add(wxurl);
					if(list.size()>0){
						Wxurl b=list.get(0);
						//判断是否已转换,已转换则不去处理
						Long flag=b.getFlag();
						if(1L==flag) {
							System.out.println("meiyouxin_url");
							Thread.sleep(5*1000);
						}

						String souceid=SiteService.getParambyname(b.getOurl(), "signature");
						JedisUtil.setString(souceid,b.getId()+"",600);
						JedisUtil.setString(apiflag+souceid,b.getId()+"",600);
						//判断是否url正常
						if(StringUtils.isNotEmpty(souceid)) {
						siteService.sendurl(b.getOurl());
						}else {
							System.out.println("wentiurl"+b.getOurl());
						}
					}
						Thread.sleep(5*1000);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
				} while (true);
			}
		});
		t.start();
		
	}
	

}