package com.zzsn.test;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.imageio.ImageIO;

import cn.hutool.core.codec.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import com.zzsn.util.Constants;

public class TestSougouYz {

	
	static ChromeOptions    options1=new ChromeOptions() ;
	static WebDriver driver;
	static{
		  System.setProperty("webdriver.chrome.driver",Constants.CHROMEDRIVE);//chromedriver服务地址
	        System.setProperty("webdriver.chrome.bin", Constants.CHROMEBIN); 
	       
	        options1.setBinary(Constants.CHROMEBIN); 
	        //options1.addArguments("--headless");
	      /*  Map<String, Object> contentSettings = new HashMap<String, Object>();
	        contentSettings.put("images", 2);
	         
	        Map<String, Object> preferences = new HashMap<String, Object>();
	        preferences.put("profile.default_content_settings", contentSettings);*/

	   

	        driver =new ChromeDriver(options1);
	}
	public static String post(JSONObject json, String url){
		String result = "";
		HttpPost post = new HttpPost(url);
		try{
			CloseableHttpClient httpClient = HttpClients.createDefault();
        
			post.setHeader("Content-Type","application/json;charset=utf-8");
			//post.addHeader("Authorization", "Basic YWRtaW46");
			StringEntity postingString = new StringEntity(json.toString(),"utf-8");
			post.setEntity(postingString);
			HttpResponse response = httpClient.execute(post);
			
			InputStream in = response.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
			StringBuilder strber= new StringBuilder();
			String line = null;
			while((line = br.readLine())!=null){
				strber.append(line+'\n');
			}
			br.close();
			in.close();
			result = strber.toString();
			if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
				result = "服务器异常";
			}
		} catch (Exception e){
			System.out.println("请求异常");
			throw new RuntimeException(e);
		} finally{
			post.abort();
		}
		return result;
	}

	public static void main(String[] args) throws Exception {
		 try {
				driver.get("https://www.baidu.com");
				//打开指定的网�?
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				//e1.printStackTrace();
				  driver =new ChromeDriver(options1);
				  driver.get("https://www.baidu.com");
			}
		// WebElement yzel  = driver.findElement(By.id("seccodeImage"));
		 
		 
		 String url="https://weixin.sogou.com/link?url=dn9a_-gY295K0Rci_xozVXfdMkSQTLW6cwJThYulHEtVjXrGTiVgS0-vU8xNAdDQ2HCx0RP8OECUC-sF-551H1qXa8Fplpd9-fH65l-_q1sMJS7yw40Cj1G8SCxT3BXIIUWNZm2vK8CGNWpR6jLDRRnKiS4q0AmI8AxsuruVk-kaNVuoV9UFrOBq4B2nHvhC3a17HfRP2y79c0BTt46SoQ_icUc-ZHQ1Br8ZKqG5S3YOS-gDa6AnjkbQBraRU3YeEZICS3xOCdvzAjcIGepUqA..&amp;type=2&amp;query=%E7%A5%9E%E6%B1%A0&amp;token=empty&amp;k=93&amp;h=0";
	
		 driver.get(url);
		 String script="document.getElementsByTagName('body')[0].style.zoom=1.5;";
		 Thread.sleep(1000L);
		 WebElement ele1  = driver.findElement(By.id("seccodeForm")).findElement(By.className("s1"));
		 Point point1 = ele1.getLocation();
		 ((JavascriptExecutor) driver).executeScript(script);
		 Thread.sleep(5000L);
		 File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
		 WebElement ele  = driver.findElement(By.id("seccodeImage"));
		String imgurl= ele.getAttribute("src");
		System.out.println(imgurl);
		//File file= ele .getScreenshotAs(OutputType.FILE);
		BufferedImage  fullImg = ImageIO.read(screenshot);
		Point point = ele.getLocation();
		int eleWidth = ele.getSize().getWidth();
		int eleHeight = ele.getSize().getHeight();
		int xlocation=(int) (point.x*1.25*1.5);
		int ylocation=(int) (point.y*1.25*1.5);
		BufferedImage eleScreenshot= fullImg.getSubimage(xlocation, ylocation+2,
			    188, 75);
		String savePath = "D:/1111.png";
		String savePath1 = "D:/1111222.png";
		
		 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			ImageIO.write(eleScreenshot, "png", new File(savePath));
			ImageIO.write(eleScreenshot, "jpg", outputStream);
            String base64Img = Base64.encode(outputStream.toByteArray());
            
            JSONObject json =new JSONObject();
            json.put("image", base64Img);
            String sendurl="http://localhost:19951/api2";
            String re=post(json, sendurl);
			System.out.println(re);
			
			JSONObject jsStr = new JSONObject(re);
			String code=jsStr.getString("message");
            String script1="document.getElementsByTagName('body')[0].style.zoom=1;";
            ((JavascriptExecutor) driver).executeScript(script1);
            Thread.sleep(2000);
            WebElement sendyzm  = driver.findElement(By.id("seccodeInput"));
            WebElement submit  = driver.findElement(By.id("submit"));
            sendyzm.sendKeys(code);
            Thread.sleep(2000);
            submit.click();
            Thread.sleep(2000);
            
            
		 try {
			 System.out.println(11);
	            //复制内容到指定文件中
	            FileUtils.copyFile(screenshot, new File(savePath1));
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
		 
		 
	}
}
