package com.zzsn.utility.util;


import com.zzsn.utility.index.Constants;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SeleniumTime {

//	public static ChromeOptions chromeOptions =new ChromeOptions() ;
//	public static ChromeDriver driver;
//	public static ChromeDriverService service;


	public SeleniumTime(){
//		System.setProperty("webdriver.chrome.driver", Constants.CHROMEDRIVE);
//		System.setProperty("webdriver.chrome.bin", Constants.CHROMEBIN);
//		System.setProperty("sun.net.client.defaultConnectTimeout", "95000");
//		System.setProperty("sun.net.client.defaultReadTimeout", "95000");
//
////		DesiredCapabilities capabilities = new DesiredCapabilities("chrome", "", Platform.ANY);
////		WebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:4444/wd/hub/"), capabilities);
////		 chromeOptions.addArguments("blink-settings=imagesEnabled=false");
////		 chromeOptions.addArguments("user-data-dir=C:\\Users\\WIN10\\AppData\\Local\\Google\\Chrome\\User Data\\Default");
//		 driver = new ChromeDriver(chromeOptions);
//		 service = new ChromeDriverService.Builder().
//				usingDriverExecutable(new File(Constants.CHROMEDRIVE)).usingAnyFreePort().build();
//		try {
//			service.wait(30000,30000);
//			service.start();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		driver = new ChromeDriver(service, chromeOptions);//生成实例

	}
	/**
	 * 根据网址获取网页html信息
	 * @param url
	 * @return
	 */

//	@Async("asyncTaskExecutorSelenium")
	public   String getScopehtml(String url){
		System.setProperty("webdriver.chrome.driver", Constants.CHROMEDRIVE);
		ChromeOptions chromeOptions =new ChromeOptions() ;
		ChromeDriver driver;
		if(!System.getProperty("os.name").toUpperCase().contains("WINDOWS")) {
			chromeOptions.addArguments("--disable-gpu", "--window-size=1290,1080");
			chromeOptions.addArguments("headless");//无界面参数
			chromeOptions.addArguments("no-sandbox");//禁用沙盒 就是被这个参数搞了一天
		}
		driver = new ChromeDriver(chromeOptions);//生成实例
		String html="";
		try{
			driver.manage ().timeouts().pageLoadTimeout (100 , TimeUnit.SECONDS ) ;
			driver.get(url);
			Thread.sleep(3000l);
			try {
//				File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); //转换时间格式
//				String time = dateFormat.format(Calendar.getInstance().getTime()); //获取当前时间
//				FileUtils.copyFile(src, new File("Screenshots", time + ".png"));// 拷贝截图文件到我们项目./Screenshots

				System.out.println("browser will be close");
				WebElement webElement = driver.findElement(By.xpath("/html"));
				html = webElement.getAttribute("outerHTML");
			}catch(Exception e){
				log.info("chromedriver 出现异常："+e.getMessage());
			}finally {

			}
		}catch(Exception e){
			log.info("chromedriver 出现异常："+e.getMessage());
		}finally {
			try {
				Thread.sleep(1000l);
				driver.quit();
				Thread.sleep(3000l);
			} catch (InterruptedException e) {

			}
		}

		return html;
	}

	//	@Async("asyncTaskExecutorSelenium")
//	public  static String getScopehtml(String url){
//		System.setProperty("webdriver.chrome.driver", Constants.CHROMEDRIVE); //chromederiver存放位置
//	    System.setProperty("webdriver.chrome.bin", Constants.CHROMEBIN); //chrome安装位置
//        ChromeOptions options = new ChromeOptions();
//		if(System.getProperty("os.name").toUpperCase().indexOf("WINDOWS")>0){
//
//		}else{
//			options.addArguments("--disable-gpu","--window-size=1290,1080");
//			options.addArguments("headless");//无界面参数
//			options.addArguments("no-sandbox");//禁用沙盒 就是被这个参数搞了一天
//		}
//        WebDriver driver ;
//
//		driver = new ChromeDriver(options);
//		String html="";
//		if(StringUtils.isEmpty(url)){
//			return html;
//		}
//		try{
//			driver.get(url);
//			Thread.sleep(3000l);
//	        WebElement webElement = driver.findElement(By.xpath("/html"));
//	        html = webElement.getAttribute("outerHTML");
////			System.out.println(html);
//		}catch(Exception e){
//			log.info("chromedriver 出现异常："+e.getMessage());
//		}finally {
//			driver.quit();
//			try {
//				Thread.sleep(3000l);
//			} catch (InterruptedException e) {
//			}
//		}
//
//		return html;
//	}

	public  void close(){
//		driver.close();
//		driver.quit();
//		service.stop();
	}
	public static void refresh(WebDriver driver) {
		Actions ctrl = new Actions(driver);
		ctrl.keyDown(Keys.CONTROL).perform();
		try {
			pressKeyEvent(KeyEvent.VK_F5);
		} catch (AWTException e) {
			e.printStackTrace();
		}
		ctrl.keyUp(Keys.CONTROL).perform();
		driver.navigate().refresh();
	}
	//按物理按键
	public static void pressKeyEvent(int keycode) throws AWTException {
		Robot robot = new Robot();
//		robot.keyPress(KeyEvent.VK_ENTER);//按下enter键
		robot.keyPress(keycode);
	}

	public static void main(String[] args) {

		//去除html中的相关标签
		/**
		 * 网上大多是说明直接使用正则表达式不能很好的适用于html
		 * 经过尝试我无法删除先关div中内容，只能自己通过字符串切割的形式获取
		 */

		SeleniumTime s = new SeleniumTime();
		String scopehtml = s.getScopehtml("http://www.flw.ph/thread-869016-1-1.html");

		String a = "<div class=\"attach_nopermission attach_tips\">";
		String b = "<span class=\"atips_close\" onclick=\"this.parentNode.style.display='none'\">x</span>";
		System.out.println("开始");
		if(scopehtml.contains(a)){
			System.out.println("包含a");
		}
		if(scopehtml.contains(a)){
			System.out.println("包含b");
		}
		System.out.println("结束");

		String[] split = scopehtml.split(a);
		String sa = split[0];
		System.out.println("首次截取的长度"+split.length);
		String[] split2 = split[1].split(b);
		String sb = split2[1];
		String substring = sb.substring(7);
		System.out.println("再次截取的长度"+split2.length);
		String sab = sa + substring ;

//		//解决方式    正则匹配删除标签
//		//   *.div[class="t_fsz"]
//		String regex = "<div class=\"attach_nopermission attach_tips\">(.*?)</div>";
//		//String regex = "<div.*?>(.*?)</div>";
//		//String regex = "*.div[class="+"attach_nopermission attach_tips"+"]";
//		
////		 boolean isMatch = regex.matches(scopehtml);
////	      System.out.println("字符串中是否包含了 'runoob' 子字符串? " + isMatch);
////		
//	   // 创建 Pattern 对象
//	      Pattern r = Pattern.compile(regex);
//	 
//	      // 现在创建 matcher 对象
//	      Matcher m = r.matcher(scopehtml);
//	      if (m.find( )) {
//	          System.out.println("Found value: " + m.group(0) );
//	          System.out.println("Found value: " + m.group(1) );
//	          System.out.println("Found value: " + m.group(2) );
//	          System.out.println("Found value: " + m.group(3) ); 
//	       } else {
//	          System.out.println("NO MATCH");
//	       }
//		
//		
		File file = new File("D:/123.txt");
		try {
			PrintStream ps = new PrintStream(new FileOutputStream(file));
			ps.println(sab);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}


}
