package com.gh.gamecenter.personal;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.TokenUtils;
import com.gh.common.util.Utils;
import com.gh.gamecenter.CropImageActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.SettingActivity;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.volley.extended.StringExtendedRequest;
import com.tencent.stat.StatConfig;

import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author 温冠超
 * @email 294299195@qq.com
 * @date 2015-8-8 主页fragment3页面
 */
public class PersonalFragment extends Fragment implements View.OnClickListener, ViewPager.OnPageChangeListener {

	public static final String TAG = PersonalFragment.class.getSimpleName();

	private View view;
	private ViewPager me_vp_show;

	private ImageView me_iv_top_setting;
	private ImageView me_iv_top_icon;
	private TextView me_tv_top_install;
	private TextView me_tv_top_concern;
	private TextView me_tv_top_name;
	private View me_top_slide_line;

	private RelativeLayout.LayoutParams top_line_rparams;

	private int leftMargin;
	private int dis;

	private boolean isLogin;
	private boolean isDestroy;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			SharedPreferences sp = getActivity().getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
			String name = sp.getString("user_name", null);
			if (!TextUtils.isEmpty(name)) {
				me_tv_top_name.setText(name);
			}
			String icon = sp.getString("user_icon", null);
			if (!TextUtils.isEmpty(icon)) {
				ImageUtils.getInstance(getActivity()).display(icon, me_iv_top_icon, R.drawable.user_default_icon);
			}
			isLogin = true;
			checkDeviceInfo();
		}
	};

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("currentItem", me_vp_show.getCurrentItem());
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		isDestroy = false;

		view = View.inflate(getActivity(), R.layout.home3_fragment, null);

		me_iv_top_icon = (ImageView) view.findViewById(R.id.me_iv_top_icon);
		me_iv_top_icon.setOnClickListener(this);
		me_tv_top_name = (TextView) view.findViewById(R.id.me_tv_top_name);
		me_tv_top_name.setOnClickListener(this);

		me_iv_top_setting = (ImageView) view.findViewById(R.id.me_iv_top_setting);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) me_iv_top_setting.getLayoutParams();
			params.topMargin = DisplayUtils.getInternalDimensionSize(getResources(), "status_bar_height")
					+ DisplayUtils.dip2px(getActivity(), 15);
			me_iv_top_setting.setLayoutParams(params);

			LinearLayout me_ll_info = (LinearLayout) view.findViewById(R.id.me_ll_info);
			me_ll_info.setPadding(0, DisplayUtils.getInternalDimensionSize(getResources(), "status_bar_height"), 0, 0);
		}
		me_iv_top_setting.setOnClickListener(this);

		DisplayMetrics outMetrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(outMetrics);

		me_tv_top_install = (TextView) view.findViewById(R.id.me_tv_top_install);
		me_tv_top_install.setOnClickListener(this);
		RelativeLayout.LayoutParams rparams1 = (RelativeLayout.LayoutParams) me_tv_top_install.getLayoutParams();
		int width = outMetrics.widthPixels / 4;
		rparams1.width = width;
		rparams1.leftMargin = width - DisplayUtils.dip2px(getActivity(), 10);
		me_tv_top_install.setLayoutParams(rparams1);

		me_tv_top_concern = (TextView) view.findViewById(R.id.me_tv_top_concern);
		me_tv_top_concern.setOnClickListener(this);
		RelativeLayout.LayoutParams rparams2 = (RelativeLayout.LayoutParams) me_tv_top_concern.getLayoutParams();
		rparams2.width = width;
		rparams2.rightMargin = width - DisplayUtils.dip2px(getActivity(), 10);
		me_tv_top_concern.setLayoutParams(rparams2);

		int currentItem = 0;
		if (savedInstanceState != null) {
			currentItem = savedInstanceState.getInt("currentItem");
		}

		me_top_slide_line = view.findViewById(R.id.me_top_slide_line);
		top_line_rparams = (RelativeLayout.LayoutParams) me_top_slide_line.getLayoutParams();
		top_line_rparams.width = outMetrics.widthPixels / 6;
		leftMargin = outMetrics.widthPixels / 8 * 3 - outMetrics.widthPixels / 12 - DisplayUtils.dip2px(getActivity(), 10);
		dis = outMetrics.widthPixels / 4 + DisplayUtils.dip2px(getActivity(), 20);
		top_line_rparams.leftMargin = dis * currentItem + leftMargin;
		me_top_slide_line.setLayoutParams(top_line_rparams);

		if (currentItem == 0) {
			me_tv_top_install.setTextColor(getActivity().getResources().getColor(R.color.theme));
			me_tv_top_concern.setTextColor(getActivity().getResources().getColor(R.color.title));
		} else {
			me_tv_top_install.setTextColor(getActivity().getResources().getColor(R.color.title));
			me_tv_top_concern.setTextColor(getActivity().getResources().getColor(R.color.theme));
		}

		me_vp_show = (ViewPager) view.findViewById(R.id.me_vp_show);
		me_vp_show.setAdapter(new FragmentAdapter(getChildFragmentManager()));
		me_vp_show.addOnPageChangeListener(this);
		me_vp_show.setCurrentItem(currentItem);

		isLogin = false;

		new Thread() {
			@Override
			public void run() {
				TokenUtils.getToken(getActivity());
				handler.sendEmptyMessage(0);
			}
		}.start();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container != null) {
			container.removeView(view);
		}
		return view;
	}

	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {
		if (positionOffset != 0) {
			top_line_rparams.leftMargin = (int) (dis * (positionOffset + position)) + leftMargin;
			me_top_slide_line.setLayoutParams(top_line_rparams);
		}
	}

	@Override
	public void onPageSelected(int position) {
		if (position == 0) {
			me_tv_top_install.setTextColor(getActivity().getResources().getColor(R.color.theme));
			me_tv_top_concern.setTextColor(getActivity().getResources().getColor(R.color.title));
		} else {
			me_tv_top_install.setTextColor(getActivity().getResources().getColor(R.color.title));
			me_tv_top_concern.setTextColor(getActivity().getResources().getColor(R.color.theme));
		}
	}

	@Override
	public void onPageScrollStateChanged(int state) {

	}

	private class FragmentAdapter extends FragmentPagerAdapter {

		public FragmentAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			if (position == 0) {
				return new InstallFragment();
			} else {
				return new ConcernFragment();
			}
		}

		@Override
		public int getCount() {
			return 2;
		}

	}

	@Override
	public void onClick(View v) {
		final int id = v.getId();
		if (id == R.id.me_iv_top_setting) {
			DataUtils.onEvent(getActivity(), "主页", "设置图标");

			Map<String, Object> map = new HashMap<>();
			map.put("location", "设置图标");
			map.put("page", "主页");
			DataCollectionManager.onEvent(getActivity(), "click-item", map);

			startActivity(new Intent(getActivity(), SettingActivity.class));
		} else if (id == R.id.me_tv_top_install
					|| v.getId() == R.id.me_tv_topbar_install) {
			me_vp_show.setCurrentItem(0);
		} else if (id == R.id.me_tv_top_concern
					|| v.getId() == R.id.me_tv_topbar_concern) {
			me_vp_show.setCurrentItem(1);
		} else if (id == R.id.me_tv_top_name) {
			DataUtils.onEvent(getActivity(), "主页", "用户昵称");

			Map<String, Object> map = new HashMap<>();
			map.put("location", "用户昵称");
			map.put("page", "主页");
			DataCollectionManager.onEvent(getActivity(), "click-item", map);

			if (isLogin) {
				showModifyNicknameDialog(me_tv_top_name.getText().toString());
			}
		} else if (id == R.id.me_iv_top_icon) {
			DataUtils.onEvent(getActivity(), "主页", "用户头像");

			Map<String, Object> map = new HashMap<>();
			map.put("location", "用户头像");
			map.put("page", "主页");
			DataCollectionManager.onEvent(getActivity(), "click-item", map);

			if (isLogin) {
				Intent intent = new Intent(Intent.ACTION_PICK,
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(intent, 0x123);
			}
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 0x123 && data != null) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getActivity().getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			if (cursor == null) {
				return;
			}
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();

			Utils.log("picturePath = " + picturePath);
			// 上传头像
			Intent intent = new Intent(getActivity(), CropImageActivity.class);
			intent.putExtra("path", picturePath);
			startActivityForResult(intent, 0x124);
		} else if (requestCode == 0x124 && data != null) {
			String url = data.getExtras().getString("url");
			SharedPreferences sp = getActivity().getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
			sp.edit().putString("user_icon", url).apply();
			ImageUtils.getInstance(getActivity()).display(url, me_iv_top_icon, R.drawable.user_default_icon);
		}
	}

	private void showModifyNicknameDialog(String name) {
		final Dialog dialog = new Dialog(getActivity());

		View view = View.inflate(getActivity(), R.layout.dialog_modify_nickname, null);

		final EditText input = (EditText) view.findViewById(R.id.dialog_nickname_input);
		input.setText(name);
		input.setSelection(input.getText().length());

		input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					String nickname = input.getText().toString().trim();
					if (TextUtils.isEmpty(nickname)) {
						Toast.makeText(getActivity(), "请输入昵称", Toast.LENGTH_SHORT).show();
						return true;
					}
					modifyNickname(nickname);
					dialog.dismiss();
					return true;
				}
				return false;
			}
		});

		// 取消按钮
		TextView cancel = (TextView) view.findViewById(R.id.dialog_nickname_cannel);
		cancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		// 确定按钮
		TextView confirm = (TextView) view.findViewById(R.id.dialog_nickname_confirm);
		confirm.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String nickname = input.getText().toString().trim();
				if (TextUtils.isEmpty(nickname)) {
					Toast.makeText(getActivity(), "请输入昵称", Toast.LENGTH_SHORT).show();
					return;
				}
				dialog.dismiss();
				modifyNickname(nickname);
			}
		});

		dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
			}
		});

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(view);
		dialog.show();

		new Thread(){
			@Override
			public void run() {
				try {
					sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				InputMethodManager imm = (InputMethodManager) getActivity()
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(input, InputMethodManager.SHOW_FORCED);
			}
		}.start();
	}

	private void modifyNickname(final String nickname) {
		final Dialog waitDialog = DialogUtils.showWaitDialog(getActivity(), "修改中...");
		new Thread(){
			@Override
			public void run() {
				HashMap<String, String> params = new HashMap<>();
				params.put("name", nickname);
				StringExtendedRequest request = new StringExtendedRequest(Request.Method.POST,
						"http://user.ghzhushou.com/v1d0/name", new JSONObject(params).toString(),
						new Response.Listener<String>() {
							@Override
							public void onResponse(String response) {
								Utils.log("onResponse = " + response);
								waitDialog.dismiss();
								SharedPreferences sp = getActivity().getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
								sp.edit().putString("user_name", nickname).apply();
								Toast.makeText(getActivity(), "修改成功", Toast.LENGTH_SHORT).show();
								me_tv_top_name.setText(nickname);
							}
						}, new Response.ErrorListener() {
							@Override
							public void onErrorResponse(VolleyError error) {
								Utils.log("onErrorResponse = " + error);
								waitDialog.dismiss();
								if (error.networkResponse != null
										&& error.networkResponse.statusCode == HttpStatus.SC_FORBIDDEN) {
									try {
										JSONObject response = new JSONObject(new String(error.networkResponse.data));
										String detail = response.getString("detail");
										if ("too long".equals(detail)) {
											Toast.makeText(getActivity(), "昵称太长", Toast.LENGTH_SHORT).show();
										} else if ("invalid".equals(detail)) {
											Toast.makeText(getActivity(), "非法字符", Toast.LENGTH_SHORT).show();
										} else if ("repeat".equals(detail)) {
											Toast.makeText(getActivity(), "昵称已存在", Toast.LENGTH_SHORT).show();
										} else if ("no change".equals(detail)) {
											Toast.makeText(getActivity(), "昵称一致", Toast.LENGTH_SHORT).show();
										} else if ("too frequent".equals(detail)) {
											Toast.makeText(getActivity(), "修改太频繁，请稍后再试", Toast.LENGTH_SHORT).show();
										}
									} catch (JSONException e) {
										e.printStackTrace();
										Toast.makeText(getActivity(), "修改失败", Toast.LENGTH_SHORT).show();
									}
								} else {
									Toast.makeText(getActivity(), "修改失败", Toast.LENGTH_SHORT).show();
								}
							}
						});
				request.setShouldCache(false);
				request.addHeader("TOKEN", TokenUtils.getToken(getActivity()));
				AppController.addToRequestQueue(request, TAG);
			}
		}.start();
	}

	/*
	 * 检查设备信息是否已经上传完整
	 */
	private void checkDeviceInfo() {
		SharedPreferences sp = getActivity().getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
		final HashMap<String, String> params = new HashMap<>();
		if (!sp.getBoolean("isUploadMac", true)) {
			WifiManager wm = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
			String mac = wm.getConnectionInfo().getMacAddress();
			if (!TextUtils.isEmpty(mac)) {
				params.put("MAC", mac);
			}
		}
		if (!sp.getBoolean("isUploadMid", true)) {
			String mid = StatConfig.getMid(getActivity());
			if (!TextUtils.isEmpty(mid) || !"0".equals(mid)) {
				params.put("MTA_ID", mid);
			}
		}
		if (params.size() != 0) {
			new Thread(){
				@Override
				public void run() {
					StringExtendedRequest request = new StringExtendedRequest(Request.Method.POST,
							"http://user.ghzhushou.com/v1d0/device/" + TokenUtils.getDeviceId(getActivity()),
							new JSONObject(params).toString(), null, null);
					request.addHeader("TOKEN", TokenUtils.getToken(getActivity()));
					AppController.addToRequestQueue(request, TAG);
				}
			}.start();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		isDestroy = true;
		AppController.canclePendingRequests(TAG);
		view = null;
	}

}
