package com.jx.jyhd.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.game.webgame.network.Volleyinterface1;
import com.game.webgame.network.register;
import com.game.webgame.view.SpUtil;
import com.jx.jyhd.R;
import com.jx.jyhd.simcpux.Constants;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.jx.jyhd.R;
import com.jx.jyhd.simcpux.Constants;
import com.tsgame.tsgame_niuniu.system.WX_Myurl;
import com.tsgame.tsgame_niuniu.util.apputil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

	public static final String TAG = "WXEntryActivity";
	private IWXAPI api;
	TextView text;
	ImageView image;
	public static Handler sharehandler;

	SharedPreferences sp;

	// 分享成功
	public static final int sharesucces = 2;
	// 分享失败
	public static final int sharecancel = 3;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wxuserinfo);

		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
		try {
			Intent intent = getIntent();
			api.handleIntent(intent, this);
		} catch (Exception e) {
			e.printStackTrace();
		}

		sp = SpUtil.getSharePerference(WXEntryActivity.this);
		initview();
	}

	private void initview() {
		text = (TextView) findViewById(R.id.user);
		image = (ImageView) findViewById(R.id.image);

	}

	public static void setshareHandler(Handler handler) {
		sharehandler = handler;
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		setIntent(intent);
		api.handleIntent(intent, this);
	}

	// 微信发送请求到第三方应用时，会回调到该方法
	@Override
	public void onReq(BaseReq req) {
		switch (req.getType()) {
		case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
			// goToGetMsg();
			break;
		case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
			// goToShowMsg((ShowMessageFromWX.Req) req);
			break;
		default:
			break;
		}
	}

	// 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
	@Override
	public void onResp(BaseResp resp) {
		int result = 0;
		switch (resp.errCode){
			case BaseResp.ErrCode.ERR_OK:
				if (apputil.wxtype == 1) {// 分享
					sharehandler.sendEmptyMessage(sharesucces);
				}
				result = R.string.errcode_success;
				break;
			case BaseResp.ErrCode.ERR_USER_CANCEL:
				result = R.string.errcode_cancel;
				break;
			case BaseResp.ErrCode.ERR_AUTH_DENIED:
				result = R.string.errcode_deny;
				break;
			case BaseResp.ErrCode.ERR_UNSUPPORT:
				result = R.string.errcode_unsupport;
				break;
			default:
				result = R.string.errcode_unknown;
				break;
		}
		Log.e(TAG, getString(result) + ", type=" + resp.getType());
		if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
			SendAuth.Resp authResp = (SendAuth.Resp)resp;
			final String code = authResp.code;
			getaccess_token(code);
		}
		finish();
	}

	private void getaccess_token(String code) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("appid", Constants.APP_ID);
		map.put("secret", Constants.AppSecret);
		map.put("code", code);
		map.put("grant_type", "authorization_code");

		register.StringGETrequest(map, WX_Myurl.getwxaccess_token,
				new Volleyinterface1(this, Volleyinterface1.mlistener,
						Volleyinterface1.mErrorLisener) {

					@Override
					public void onsuccess(String result) {
						try {

							JSONObject object = new JSONObject(result);
							String access_token = object
									.optString("access_token");

							SpUtil.setStringSharedPerference(sp,
									"access_token", access_token);

							int expires_in = object.optInt("expires_in");

							String refresh_token = object
									.optString("refresh_token");

							SpUtil.setStringSharedPerference(sp,
									"refresh_token", refresh_token);

							String openid = object.optString("openid");
							// getuserinfo(access_token,openid);

							SpUtil.setStringSharedPerference(sp, "openid",
									openid);

							getUserInfo(access_token, openid);

							// Toast.makeText(
							// WXEntryActivity.this,
							// "access_token+=" + expires_in
							// + "refresh_token" + refresh_token,
							// Toast.LENGTH_LONG).show();

						} catch (JSONException e) {

							e.printStackTrace();
						}

					}

					@Override
					public void onerror(VolleyError arg0) {
						Log.i("WxError","Start");
						arg0.printStackTrace();
						Log.i("WxError",arg0.toString());
						Log.i("WxError",arg0.getMessage());
						Log.i("WxError","End");
					}
				});

	}

	protected void getuserinfo(String access_token, String openid) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("access_token", access_token);
		map.put("openid", openid);

		register.StringGETrequest(map, WX_Myurl.getwxuserinfo,
				new Volleyinterface1(this, Volleyinterface1.mlistener,
						Volleyinterface1.mErrorLisener) {
					@Override
					public void onsuccess(String result) {
						String str = null;
						try {
							try {
								// URLEncoder、URLDecoder进行URL参数的转码与解码
								URLEncoder.encode(result, "utf-8");
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							// EntityUtils.toString(response.getEntity(),HTTP.UTF_8);//在这里转换
							JSONObject object = new JSONObject(result);
							// Toast.makeText(WXEntryActivity.this,
							// "result=" + str, Toast.LENGTH_LONG).show();
						} catch (JSONException e) {

							e.printStackTrace();
						}

					}

					@Override
					public void onerror(VolleyError arg0) {

					}
				});

	}

	@SuppressWarnings("deprecation")
	public static String getWeixinUserinfo(String access_token, String openid) {
		String URLs = WX_Myurl.getwxuserinfo;// 微信登录地址
		String result = "";
		List<NameValuePair> list = new ArrayList<NameValuePair>();

		NameValuePair pairappid = new BasicNameValuePair("access_token",
				access_token);
		NameValuePair pairsecret = new BasicNameValuePair("openid", openid);
		list.add(pairappid);
		list.add(pairsecret);

		try {
			HttpEntity requestHttpEntity = new UrlEncodedFormEntity(list,
					HTTP.UTF_8);
			URL url = new URL(URLs);
			URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
					url.getQuery(), null);
			HttpPost httpPost = new HttpPost(uri);
			httpPost.setEntity(requestHttpEntity);
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);// 在这里转换
			}
			return result;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public interface OnGetUserInfoListener {
		void onGetUserInfo(String userInfo); // json字符串

		void onNetError();
	}

	static class GetUserInfoTask extends AsyncTask<Object, Void, String> {

		private OnGetUserInfoListener mListener;
		private String mUrl;

		public GetUserInfoTask(OnGetUserInfoListener listener,
				String getUserInfoUrl) {
			mListener = listener;
			mUrl = getUserInfoUrl;
		}

		@Override
		protected void onPreExecute() {

			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Object... params) {
			HttpURLConnection conn = null;
			BufferedReader in = null;
			StringBuilder result = new StringBuilder();

			try {
				conn = (HttpURLConnection) new URL(mUrl).openConnection();
				in = new BufferedReader(new InputStreamReader(
						conn.getInputStream(), "UTF-8"));
				String buf;
				while ((buf = in.readLine()) != null)
					result.append(buf);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (conn != null)
					conn.disconnect();

				// FileUtils.close(in);
			}
			return result.toString();
		}

		@Override
		protected void onPostExecute(String s) {
			Log.d("", "onPostExecute " + s);
			mListener.onGetUserInfo(s);
		}
	}

	private void getUserInfo(String accessToken, String openId) {
		String url = "https://api.weixin.qq.com/sns/userinfo?"
				+ "access_token=" + accessToken + "&openid=" + openId;
		GetUserInfoTask mGetUserInfoTask = new GetUserInfoTask(
				new OnGetUserInfoListener() {

					@Override
					public void onNetError() {

					}

					@Override
					public void onGetUserInfo(String userInfo) {
						// text.setText(userInfo);
						JSONObject object;
						try {
							object = new JSONObject(userInfo);
							System.out.println(userInfo);
							
							String url = object.optString("headimgurl");

							String unionid = object.optString("unionid");
							String openid = object.optString("openid");
							String nickname = object.optString("nickname");
							String sex = object.optString("sex");

							String country = object.optString("country");
							SpUtil.setStringSharedPerference(sp, "country",
									country);
							String city = object.optString("city");
							SpUtil.setStringSharedPerference(sp, "city", city);
							String province = object.optString("province");
							SpUtil.setStringSharedPerference(sp, "province",
									province);

							SpUtil.setStringSharedPerference(sp, "unionid",
									unionid);
							SpUtil.setStringSharedPerference(sp, "headimgurl",
									url);

							SpUtil.setStringSharedPerference(sp, "openid",
									openid);
							SpUtil.setStringSharedPerference(sp, "nickname",
									nickname);
							SpUtil.setStringSharedPerference(sp, "sex", sex);

							// ImageListener in1 = ImageLoader.getImageListener(
							// image, R.drawable.ic_launcher,
							// R.drawable.ic_launcher);
							// ImageCacheManager.loadImage(url, in1);

							sharehandler.sendEmptyMessage(1);

							finish();

						} catch (JSONException e) {
							e.printStackTrace();
						}
//						 Toast.makeText(WXEntryActivity.this,
//						 "result=" + userInfo, Toast.LENGTH_LONG).show();
					}
				}, url); // this代表WXEntryActivity.this

		mGetUserInfoTask.execute();
	}

	private void goToGetMsg() {

	}

	private void goToShowMsg(ShowMessageFromWX.Req showReq) {

	}
}