package cn.gdou.edu.net;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import cn.gdou.edu.data.BookInfo;
import cn.gdou.edu.data.Cookie;
import cn.gdou.edu.data.NETADDRESS;
import cn.gdou.edu.data.SearchBook;
import cn.gdou.edu.data.SearchBookAddress;
import cn.gdou.edu.data.StudentInfo;

public class LibAPI {

	private String username; // 登陆用户
	private String password; // 登陆密码
	private int state;// 状态
	private String result;// 返回的数据
	private final static String HOST = "http://210.38.138.1:81";
	private final static String LOGIN_URL = "http://210.38.138.1:81/internalloginAjax.aspx";
	private final static String LOGIN_SU = "http://210.38.138.1:81/user/userinfo.aspx";
	private String cookie_id;
	private String cookie_id_end;
	private int n = 1;// 多页的计数器
	private int max = 1;// 总页数
	private String method;
	private String word;

	public LibAPI(String username, String password) {
		this.username = username;
		this.password = password;
	}

	public LibAPI() {

	}

	public String getCookie() {
		return cookie_id + ";" + cookie_id_end;
	}

	public void setCookie(String cookie){
		String[] strs=cookie.split(";");
		cookie_id=strs[0];
		cookie_id_end=strs[1];
	}
	public int getState() {
		return this.state;
	}

	public void loginURL() {
		HttpClient client = new DefaultHttpClient();
		HttpResponse response;
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("username", username));
		formparams.add(new BasicNameValuePair("password", password));
		try {
			UrlEncodedFormEntity entity;
			entity = new UrlEncodedFormEntity(formparams, "UTF-8");
			HttpPost post = new HttpPost(LOGIN_URL);
			post.addHeader("Referer",
					"http://210.38.138.1:81/internal_login.aspx");
			post.addHeader("Accept",
					"text/javascript, text/html, application/xml, text/xml");
			post.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
			post.addHeader("Accept-Encoding", "gzip,deflate,sdch");
			post.addHeader("Connection", "Keep-Alive");
			post.addHeader("Cache-Control", "no-cache");
			post.addHeader("Cookie", cookie_id);
			post.addHeader("Host", "210.38.138.1:81");
			post.setEntity(entity);

			response = client.execute(post);
			HttpEntity entity2 = response.getEntity();
			// System.out.println(EntityUtils.toString(entity2));
			result = EntityUtils.toString(entity2);
			state = response.getStatusLine().getStatusCode();
			if (result.length() < 2) {
				System.out.println("登陆成功！");
				Header h = response.getFirstHeader("Set-Cookie");
				// System.out.println(h);
				HeaderElementIterator it = new BasicHeaderElementIterator(
						response.headerIterator("Set-Cookie"));
				while (it.hasNext()) {
					HeaderElement elem = it.nextElement();
					cookie_id_end = elem.getName() + "=" + elem.getValue();
					// System.out.println("----------");
					// System.out.println(cookie_id_end);
				}

			} else {
				System.out.println(result);
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void Get() {
		HttpClient c = new DefaultHttpClient();
		HttpGet get = new HttpGet("http://210.38.138.1:81/login.aspx");
		get.addHeader("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		get.addHeader("Connection", "keep-alive");
		get.addHeader("Host", "210.38.138.1:81");
		get.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
		get.addHeader("Accept-Encoding", "gzip,deflate,sdch");
		get.addHeader("Accept-Language", "zh-CN,zh;q=0.8");

		try {
			HttpResponse re = c.execute(get);
			/*
			 * System.out.println(get.getAllHeaders().length);
			 * 
			 * Header[] hs=re.getAllHeaders(); for(Header h:hs){
			 * System.out.println(h); }
			 */
			// System.out.println(re.getFirstHeader("Set-Cookie"));

			HeaderElementIterator it = new BasicHeaderElementIterator(
					re.headerIterator("Set-Cookie"));
			Cookie cookie = new Cookie();
			while (it.hasNext()) {
				HeaderElement he = it.nextElement();
				// System.out.println(he.getName()+"="+he.getValue());
				cookie_id = he.getName() + "=" + he.getValue();
				Map<String, String> tmp = new HashMap<String, String>();
				tmp.put(he.getName(), he.getValue());
				cookie.setName(tmp);
				NameValuePair[] params = he.getParameters();
				for (int i = 0; i < params.length; i++) {
					// System.out.println(" " + params[i]);
				}
			}
			// System.out.println(cookie.getName().toString());

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public StudentInfo Get_User() {
		HttpClient c = new DefaultHttpClient();
		HttpGet get = new HttpGet("http://210.38.138.1:81/user/userinfo.aspx");
		addHttpGetHeader(get);
		StudentInfo s = new StudentInfo();
		try {
			HttpResponse response = c.execute(get);
			HttpEntity entity = response.getEntity();
			System.out.println("----------html-------------");
			// System.out.println(EntityUtils.toString(entity));
			s = JsoupUtils.getUserInfo(EntityUtils.toString(entity));

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// System.out.println(s);
		return s;
	}

	// 修改密码
	public int changPass(String oldpass,String newpass,String renewpass) {
		HttpClient c = new DefaultHttpClient();
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();

		formparams.add(new BasicNameValuePair("__EVENTTARGET", ""));
		formparams.add(new BasicNameValuePair("__EVENTARGUMENT", ""));
		formparams
				.add(new BasicNameValuePair(
						"__VIEWSTATE",
						"/wEPDwULLTEwMTE3MDkwNDAPZBYCZg9kFg4CAQ8PFgIeCEltYWdlVX" +
						"JsBRt+XGltYWdlc1xoZWFkZXJvcGFjNGdpZi5naWZkZAICDw8WAh4EV" +
						"GV4dAUt5bm/5Lic5rW35rSL5aSn5a2m5Zu+5Lmm6aaG5Lmm55uu5qOA57Si" +
						"57O757ufZGQCAw8PFgIfAQUcMjAxMuW5tDA25pyIMTPml6UgIOaYn+acn+S4iWRkA" +
						"gQPZBYEAgEPFgIeC18hSXRlbUNvdW50AgcWDgIBD2QWAmYPFQMOLi4vc2VhcmNoLmFzcH" +
						"gADOebruW9leajgOe0omQCAg9kFgJmDxUDES4uL2Nsc2Jyb3dzZS5hc3B4AAzliIbnsbvlr7z" +
						"oiKpkAgMPZBYCZg8VAxEuLi9ib29rX3JhbmsuYXNweAAM6K+75Lmm5oyH5byVZAIED2QWAmYPFQ" +
						"MMLi4veHN0Yi5hc3B4AAzmlrDkuabpgJrmiqVkAgUPZBYCZg8VAxcuLi9yZWFkZXJyZWNvbW1lbmQ" +
						"uYXNweAAM6K+76ICF6I2Q6LStZAIGD2QWAmYPFQMWLi4vb3ZlcmR1ZWJvb2tzX2YuYXNweAAM5o+Q6Y" +
						"aS5pyN5YqhZAIHD2QWAmYPFQMVLi4vdXNlci91c2VyaW5mby5hc3B4DmNsYXNzPSJzZWxlY3QiD+aIkeea" +
						"hOWbvuS5pummhmQCAw8WAh8CZmQCBQ9kFgICAQ9kFgICAQ8WAh8CAhAWIAIBD2QWBAIBD2QWAmYPFQMNd" +
						"XNlcmluZm8uYXNweAAM5Liq5Lq65L+h5oGvZAIDDxYCHgdWaXNpYmxlaGQCAg9kFgQCAQ9kFgJmDxUDD" +
						"mNoYW5nZXBhcy5hc3B4DmNsYXNzPSJzZWxlY3QiDOS/ruaUueWvhueggWQCAw8WAh8DaGQCAw9kFgQCAQ" +
						"9kFgJmDxUDC2dzY2FyZC5hc3B4AA/mjILlpLHmiJboh6rlgZxkAgMPFgIfA2hkAgQPZBYEAgEPZBYCZg8" +
						"VAxBjbHNjYXRlZ29yeS5hc3B4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HDw" +
						"8WAh8BBaUBQ29weXJpZ2h0ICZjb3B5OzIwMDgtMjAwOS4gU1VMQ01JUyBPUEFDIDQuMDEgb2YgU2hlbnpoZW4gVW5" +
						"pdmVyc2l0eSBMaWJyYXJ5LiAgQWxsIHJpZ2h0cyByZXNlcnZlZC48YnIgLz7niYjmnYPmiYDmnInvvJrmt7HlnLPlpKf" +
						"lrablm77kuabppoYgRS1tYWlsOnN6dWxpYkBzenUuZWR1LmNuZGRk4aNgA5TrgV9Qobb95Of0rsFcncc="));
		formparams
				.add(new BasicNameValuePair("__EVENTVALIDATION",
						"/wEWBQKH2Kn4AwLcydT4DALPsvtQArTWz7IDAvn4+uQInkEsI8oxvtQ6L/UKLUlqTANkLEk="));
		formparams.add(new BasicNameValuePair("ctl00$cpRight$txtOldPass", oldpass));
		formparams.add(new BasicNameValuePair("ctl00$cpRight$txtNewPass", newpass));
		formparams.add(new BasicNameValuePair("ctl00$cpRight$txtRepNewPass",renewpass));
		formparams.add(new BasicNameValuePair("ctl00$cpRight$btnSubmit", "提交"));

		HttpPost post = new HttpPost(NETADDRESS.CHANGEPASS);
		UrlEncodedFormEntity entity;

		try {
			entity = new UrlEncodedFormEntity(formparams, "UTF-8");
			// post.addHeader("Referer",
			// "http://210.38.138.1:81/user/changepas.aspx");
			post.addHeader("Accept",
					"text/javascript, text/html, application/xml, text/xml");
			post.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
			post.addHeader("Accept-Encoding", "gzip,deflate,sdch");
			post.addHeader("Connection", "Keep-Alive");
			post.addHeader("Cache-Control", "no-cache");
			post.addHeader("Content-Type", "application/x-www-form-urlencoded");
			post.addHeader("Cookie", cookie_id + ";" + cookie_id_end);
			post.addHeader("Host", "210.38.138.1:81");
			post.addHeader("Origin", "http://210.38.138.1:81");
			post.setEntity(entity);
			HttpResponse response = c.execute(post);
//			System.out.println(response.getStatusLine().getStatusCode());
			System.out.println(response.getFirstHeader("Location"));
			return response.getStatusLine().getStatusCode();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return -1;

	}

	public HttpGet addHttpGetHeader(HttpGet get) {
		get.addHeader("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		get.addHeader("Connection", "keep-alive");
		get.addHeader("Cache-Control", "max-age=0");
		get.addHeader("Host", "210.38.138.1:81");
		get.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
		get.addHeader("Accept-Encoding", "gzip,deflate,sdch");
		get.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
		get.addHeader("Cookie", cookie_id + ";" + cookie_id_end);
		return get;
	}

	// 借阅情况
	public List<BookInfo> getBorrowedContent() {
		HttpClient c = new DefaultHttpClient();
		HttpGet get = new HttpGet(NETADDRESS.BOOKBORROWED);
		addHttpGetHeader(get);
		try {
			HttpResponse response = c.execute(get);
			HttpEntity entity = response.getEntity();
			return JsoupUtils.getBorrowedContent(EntityUtils.toString(entity));
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	// 借书历史
	public void borrowedHistory() {
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(NETADDRESS.BOOKBORROWEDHISTORY + "?page=" + n);
		addHttpGetHeader(get);
		try {
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			JsoupUtils.getBorrowedHistory(EntityUtils.toString(entity));
			max = JsoupUtils.getBorrowedmax();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void nextBorrowedHistory() {
		if (n < max) {
			n++;
			borrowedHistory();
		}
	}

	// 图书检索
	/*
	 * anywords:java dt:ALL cl:ALL dp:20 sf:M_PUB_YEAR ob:DESC sm:table dept:ALL
	 */
	public List<SearchBook> searchBook(String method, String word) {
		return searchBook(method, word, 1);
	}

	public List<SearchBook> searchBook(String method, String word, int page) {
		this.method = method;
		this.word = word;
		HttpClient client = new DefaultHttpClient();
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(new BasicNameValuePair(method, word));
		qparams.add(new BasicNameValuePair("dt", "ALL"));
		qparams.add(new BasicNameValuePair("cl", "ALL"));
		qparams.add(new BasicNameValuePair("dp", "20"));
		qparams.add(new BasicNameValuePair("sf", "M_PUB_YEAR"));
		qparams.add(new BasicNameValuePair("ob", "DESC"));
		qparams.add(new BasicNameValuePair("sm", "table"));
		qparams.add(new BasicNameValuePair("dept", "ALL"));
		qparams.add(new BasicNameValuePair("page", page + ""));
		URI uri;

		try {
			uri = URIUtils.createURI("http", "210.38.138.1:81", -1,
					"/searchresult.aspx",
					URLEncodedUtils.format(qparams, "GBK"), null);
			HttpGet httpget = new HttpGet(uri);
			System.out.println(httpget.getURI());
			addHttpGetHeader(httpget);
			HttpResponse response = client.execute(httpget);
			HttpEntity entity = response.getEntity();
			// System.out.println(EntityUtils.toString(entity));
			return JsoupUtils.getSearchBook(EntityUtils.toString(entity));
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<SearchBook> nextSearchBook() {
		double pg = JsoupUtils.getSearchNumber();
		if (n <= (int) Math.ceil(pg / 20)) {
			n++;
			System.out.println("-------------");
			return searchBook(method, word);
		} else {
			return null;
		}

	}
	
	public List<SearchBookAddress> getBookInfo(String number){
		HttpClient client=new DefaultHttpClient();
		HttpGet get=new HttpGet("http://210.38.138.1:81/bookinfo.aspx?ctrlno="+number);
		addHttpGetHeader(get);
		try {
			HttpResponse response=client.execute(get);
			HttpEntity entity=response.getEntity();
			return JsoupUtils.getSearch_book_info(EntityUtils.toString(entity));
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
