package com.example.mountaintravel.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.DragViewlayout;
import com.example.mountaintravel.view.MyLinearLayout;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.smart.gtstrvl.BindActivity;
import com.smart.gtstrvl.BrowseMapActivity;
import com.smart.gtstrvl.DeviceIntroduceActivity;
import com.smart.gtstrvl.DeviceManaActivity;
import com.smart.gtstrvl.GameListActivity;
import com.smart.gtstrvl.LoginActivity;
import com.smart.gtstrvl.MainActivity;
import com.smart.gtstrvl.PinfoActivity;
import com.smart.gtstrvl.R;
import com.smart.gtstrvl.TravelgradeActivity;
import com.smart.gtstrvl.WatchActivity;
import com.smart.gtstrvl.db.DBhelper;

public class MainUtil {
	private MainActivity main;
	private SwipeRefreshLayout swipeLayout;
	private ImageView main_ivleft;
	private ImageView main_ivleft2;
	private RelativeLayout layout;
	private WebView tv;
	private UpdateManager mUpdateManager;
	private TextView main_tv;
	private ImageView main_tvmine;
	private ImageView maintwo_imageViewhead;
	private TextView maintwo_tv;
	private ImageView main_tvlead;
	private ImageView main_tvguide;
	private ImageView main_tvguessing;
	TextView main_version;
	private ImageView main_rightivmenu;
	private MyLinearLayout mMainLayout;
	private DragViewlayout mDragLayout;
	private ImageView main_rightivadd;
	// private ImageView main_rightivshare;
	private DisplayImageOptions options;
	protected ImageLoader imageLoader;
	private SharedPreferences sp;
	DBhelper dbhelper;
	private String filePath = getSDPath() + "/share.db";
	private String pathStr = getSDPath() + "/";
	private String phone = "";

	public MainUtil(MainActivity main) {
		this.main = main;
		dbhelper = new DBhelper(main);
		sp = main.getSharedPreferences("variable", Context.MODE_PRIVATE);
		findView(main);
	}

	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		}
		return sdDir.toString();
	}

	/*
	 * 设置按钮影藏
	 */
	public void ifloginorfasle(boolean iflogin, boolean ifguide, boolean ifguess) {
		// TODO Auto-generated method stub
		if (sp.getBoolean("isloginsuccess", false)) {
			if (iflogin) {
				swipeLayout.setVisibility(View.VISIBLE);

			}
			if (!iflogin) {
				if (!ifguide) {
					swipeLayout.setVisibility(View.VISIBLE);
					if (ifguess
							&& maintwo_tv.getText().toString().trim()
									.equals("竞赛")) {
						main_rightivadd.setVisibility(View.VISIBLE);
						main_rightivadd.setOnClickListener(main);
						swipeLayout.setVisibility(View.VISIBLE);
					}
					if (!ifguess) {
						main_rightivadd.setVisibility(View.GONE);
						main_rightivadd.setOnClickListener(null);
						swipeLayout.setVisibility(View.VISIBLE);
					}
				}

				if (ifguide) {
					swipeLayout.setVisibility(View.INVISIBLE);
					swipeLayout.setOnClickListener(null);
				}
			}
		} else {
			if (iflogin) {
				swipeLayout.setVisibility(View.VISIBLE);
			}
			if (!iflogin) {
				if (!ifguide) {
					swipeLayout.setVisibility(View.VISIBLE);
					if (ifguess
							&& maintwo_tv.getText().toString().trim()
									.equals("竞赛")) {
						main_rightivadd.setVisibility(View.VISIBLE);
						main_rightivadd.setOnClickListener(main);
						swipeLayout.setVisibility(View.VISIBLE);
					}
					if (!ifguess) {
						main_rightivadd.setVisibility(View.GONE);
						main_rightivadd.setOnClickListener(null);
						swipeLayout.setVisibility(View.VISIBLE);
					}
				}
				if (ifguide) {
					swipeLayout.setVisibility(View.GONE);
					swipeLayout.setOnClickListener(null);
				}
			}
		}
		/*
		 * 头像昵称显示
		 */
		if (sp.getBoolean("isloginsuccess", false)) {
			if (sp.getString("nick_name", "").equals("")) {
				String nick_name = sp.getString("nick_name", "");
				main_tv.setText(nick_name);
				main_tv.setOnClickListener(main);
				maintwo_imageViewhead.setImageDrawable(main.getResources()
						.getDrawable(R.drawable.head));
			}
		}
	}

	private void findView(MainActivity main) {
		main_rightivmenu = (ImageView) main.findViewById(R.id.main_rightivmenu);
		mDragLayout = (DragViewlayout) main.findViewById(R.id.slidingLayout);
		mMainLayout = (MyLinearLayout) main.findViewById(R.id.mll);
		mMainLayout.setDraglayout(mDragLayout);// 设置引用
		main_tvmine = (ImageView) main.findViewById(R.id.main_tvmine);
		main_ivleft = (ImageView) main.findViewById(R.id.main_leftivmenu);
		main_ivleft2 = (ImageView) main.findViewById(R.id.main_leftivback);
		main_tv = (TextView) main.findViewById(R.id.maintwo_tvnicknanme);
		main_version = (TextView) main.findViewById(R.id.main_version);
		maintwo_imageViewhead = (ImageView) main
				.findViewById(R.id.maintwo_imageViewhead);
		tv = (WebView) main.findViewById(R.id.main_webtv1);
		WebSettings wSet = tv.getSettings();
		wSet.setJavaScriptEnabled(true);
		tv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		tv.getSettings().setDomStorageEnabled(true);
		tv.getSettings().setAppCacheEnabled(true);
		maintwo_tv = (TextView) main.findViewById(R.id.maintwo_tv);
		main_tvlead = (ImageView) main.findViewById(R.id.main_tvlead);
		main_tvguide = (ImageView) main.findViewById(R.id.main_tvguide);
		main_tvguessing = (ImageView) main.findViewById(R.id.main_tvguessing);
		swipeLayout = (SwipeRefreshLayout) main
				.findViewById(R.id.swipe_container);
		main_rightivadd = (ImageView) main.findViewById(R.id.main_rightivadd);
		// main_rightivshare = (ImageView) main
		// .findViewById(R.id.main_rightivshare);
	}

	/*
	 * 点击选项设置颜色
	 */
	public void ifclick(boolean iflogin, boolean ifguide, boolean ifguess,
			boolean ifvisit, boolean iflead) {
		// TODO Auto-generated method stub
		if (iflogin) {
			main_tvmine.setImageDrawable(main.getResources().getDrawable(
					R.drawable.myivdown));

		} else {
			main_tvmine.setImageDrawable(main.getResources().getDrawable(
					R.drawable.myivup));

		}

		if (ifguess) {
			main_tvguessing.setImageDrawable(main.getResources().getDrawable(
					R.drawable.suggssivdown));

		} else {
			main_tvguessing.setImageDrawable(main.getResources().getDrawable(
					R.drawable.suggssivup));

		}
		if (iflead) {
			main_tvlead.setImageDrawable(main.getResources().getDrawable(
					R.drawable.leadivdown));

		} else {
			main_tvlead.setImageDrawable(main.getResources().getDrawable(
					R.drawable.leadivup));

		}
		/*
		 * if (ifvisit) {
		 * main_tvvist.setBackgroundColor(getResources().getColor(
		 * R.color.holo_blue_bright)); } else {
		 * main_tvvist.setBackgroundColor(getResources().getColor(
		 * R.color.holo_black_light)); }
		 */
	}

	public void listenerurlpager(String url) {
		// TODO Auto-generated method stub
		if (url.contains("terminal/memberindex")) {
			maintwo_tv.setText("我的个人中心");
			main_ivleft.setVisibility(View.VISIBLE);
			main_ivleft.setOnClickListener(main);
			main_ivleft2.setVisibility(View.INVISIBLE);
			main_ivleft2.setOnClickListener(null);
			// main_rightivshare.setVisibility(View.GONE);
			swipeLayout.setVisibility(View.VISIBLE);
			tv.setVisibility(View.VISIBLE);
			main_rightivadd.setVisibility(View.GONE);
			main_rightivadd.setOnClickListener(null);
			main_rightivmenu.setVisibility(View.VISIBLE);
			main_rightivmenu.setOnClickListener(main);
			sp.edit().putBoolean("geturlpager", true).commit();
			return;
		}
		if (url.contains("notice/notice_info")) {
			maintwo_tv.setText("公告详情");
			main_ivleft.setVisibility(View.INVISIBLE);
			main_ivleft2.setVisibility(View.VISIBLE);
			main_ivleft2.setOnClickListener(main);
			sp.edit().putBoolean("geturlpager", true).commit();
			return;
		}

		else if (url.contains("event/introduce_index")) {
			main_rightivmenu.setVisibility(View.INVISIBLE);
			main_rightivmenu.setOnClickListener(null);
			main_rightivadd.setVisibility(View.VISIBLE);
			main_rightivadd.setOnClickListener(main);
			main_ivleft.setVisibility(View.VISIBLE);
			main_ivleft.setOnClickListener(main);
			main_ivleft2.setVisibility(View.INVISIBLE);
			main_ivleft2.setOnClickListener(main);
			// main_rightivshare.setVisibility(View.GONE);
			maintwo_tv.setText("竞赛");
			sp.edit().putBoolean("geturlpager", true).commit();
			return;
		}
		if (url.contains("weixin.qq.com/mp/homepage?__biz=MzAxNDMwNjA1Ng")) {
			maintwo_tv.setText("公告列表");
			main_ivleft.setVisibility(View.INVISIBLE);
			main_ivleft.setOnClickListener(null);
			main_ivleft2.setVisibility(View.VISIBLE);
			main_ivleft2.setOnClickListener(main);
			sp.edit().putBoolean("geturlpager", true).commit();
			return;
		}

		/*
		 * if (url.contains("area_info?id=")) { maintwo_tv.setText("景区详情");
		 * main_ivleft.setVisibility(View.INVISIBLE);
		 * main_ivleft.setOnClickListener(null);
		 * main_ivleft2.setVisibility(View.VISIBLE);
		 * main_ivleft2.setOnClickListener(main);
		 * sp.edit().putBoolean("geturlpager", true).commit(); int a =
		 * StringUtils.indexOf(url, "id="); String id = url.substring(a + 3);
		 * System.out.println(id + "哈哈 "); SQLiteDatabase db = openDatabase();
		 * Cursor cursor = db.rawQuery("select * from scene where id=?", new
		 * String[] { id }); if (cursor.moveToNext()) { String name =
		 * cursor.getString(cursor.getColumnIndex("name"));
		 * System.out.println(name); maintwo_tv.setText(name); } cursor.close();
		 * db.close(); return; }
		 */

		if (url.contains("mp.weixin.qq.com/s?__biz=MzAxNDMwNjA1Ng")) {
			maintwo_tv.setText("公告详情");
			main_ivleft.setVisibility(View.INVISIBLE);
			main_ivleft.setOnClickListener(null);
			main_ivleft2.setVisibility(View.VISIBLE);
			main_ivleft2.setOnClickListener(main);
			sp.edit().putBoolean("geturlpager", true).commit();
			return;
		}

		if (url.contains("scenic/introduce_index")) {
			maintwo_tv.setText("景区详情");
			main_ivleft.setVisibility(View.INVISIBLE);
			main_ivleft.setOnClickListener(null);
			main_ivleft2.setVisibility(View.VISIBLE);
			main_ivleft2.setOnClickListener(main);
			sp.edit().putBoolean("geturlpager", true).commit();
			return;
		}
		if (url.contains("terminal/index")) {
			maintwo_tv.setText("首页");
			main_ivleft.setVisibility(View.VISIBLE);
			main_ivleft.setOnClickListener(main);
			main_ivleft2.setVisibility(View.INVISIBLE);
			main_ivleft2.setOnClickListener(null);
			sp.edit().putBoolean("geturlpager", true).commit();
			return;
		}

		if (url.contains("terminal/startevent")) {
			maintwo_tv.setText("我的");
			main_ivleft.setVisibility(View.VISIBLE);
			main_ivleft.setOnClickListener(main);
			main_ivleft2.setVisibility(View.INVISIBLE);
			main_ivleft2.setOnClickListener(null);
			sp.edit().putBoolean("geturlpager", true).commit();
			return;
		}
	}

	public void listenerurlshould(String url) {
		// TODO Auto-generated method stub
		if (url.contains("error?err=1") && !url.contains("error?err=11")
				&& !url.contains("error?err=12")) {
			ToastUtil.show(main, "请先登录");
			Intent intent = new Intent(main, LoginActivity.class);
			main.startActivity(intent);
			sp.edit().putBoolean("geturl", true).commit();
			return;
		}
		if (url.contains("scenic/area_info?type=ditu")) {

			String name = url.substring(url.indexOf("name=") + 5,
					url.indexOf("&code"));

			String code = url.substring(url.indexOf("code=") + 5,
					url.indexOf("&keyword"));
			/*int codeId = StringUtils.indexOf(url, "code=");
			String code = url.substring(codeId + 5);*/
			try {
				name = java.net.URLDecoder.decode(name, "utf-8");
				Intent intent = new Intent(main, BrowseMapActivity.class);
				intent.putExtra("name", name);
				intent.putExtra("code", code);
				main.startActivity(intent);
				sp.edit().putBoolean("getcode", true).commit();
				sp.edit().putBoolean("geturl", true).commit();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return;
		}
		if (url.contains("terminal/bracelet_report")) {
			if (sp.getString("braceletSn", "").equals("")) {
				AlertDialog isExit = new AlertDialog.Builder(main).create();
				isExit.setCancelable(false);
				isExit.setMessage("暂无绑定手表，去绑定我的智能手表?");
				isExit.setButton("确定", listener);
				isExit.setButton2("取消", listener);
				isExit.show();
				sp.edit().putBoolean("geturl", true).commit();
				return;
			} else {
				Intent intent = new Intent(main, WatchActivity.class);
				main.startActivity(intent);
				sp.edit().putBoolean("geturl", true).commit();
				return;
			}
		}

		if (url.contains("terminal/addBracelet")) {
			Intent intent = new Intent(main, BindActivity.class);
			sp.edit().putString("adddevice", "addBracelet").commit();
			main.startActivityForResult(intent, 1);
			sp.edit().putBoolean("geturl", true).commit();
			return;
		}
		// 我的未登录登录捕获
		if (url.contains("startevent_login")) {
			Intent intent = new Intent(main, LoginActivity.class);
			main.startActivity(intent);
			sp.edit().putBoolean("geturl", true).commit();

			return;
		}
		if (url.contains("error?err=12")) {

			ToastUtil.show(main, "赛事已经开始，不能申请");
			sp.edit().putBoolean("geturl", true).commit();
			return;
		}
		if (url.contains("error?err=10")) {
			ToastUtil.show(main, "请先登录");
			Intent intent = new Intent(main, LoginActivity.class);
			main.startActivity(intent);
			sp.edit().putBoolean("geturl", true).commit();
			return;
		}
		if (url.contains("error?err=3")) {

			ToastUtil.show(main, "请先绑定登山设备");
			Intent intent = new Intent(main, BindActivity.class);
			main.startActivity(intent);
			sp.edit().putBoolean("geturl", true).commit();

			return;
		}
		if (url.contains("error?err=4")) {

			ToastUtil.show(main, "您所申请的赛事，存在时间上的冲突，不能申请");
			sp.edit().putBoolean("geturl", true).commit();
			return;
		}
		if (url.contains("error?err=2")) {

			ToastUtil.show(main, "请先登录");
			Intent intent = new Intent(main, LoginActivity.class);
			main.startActivity(intent);
			sp.edit().putBoolean("geturl", true).commit();
			return;
		}

		if (url.contains("error?err=9")) {
			ToastUtil.show(main, "请先完善用户信息");
			Intent intent = new Intent(main, PinfoActivity.class);
			main.startActivity(intent);
			sp.edit().putBoolean("geturl", true).commit();
			return;
		} else if (url.contains("error?err=7")) {
			ToastUtil.show(main, "操作失败");
			sp.edit().putBoolean("geturl", true).commit();
			return;
		} else if (url.contains("error?err=5")) {
			sp.edit().putBoolean("geturl", true).commit();
			ToastUtil.show(main, "您已超出赛事的允许报名时间,请选择其它赛事报名");
			return;
		} else if (url.contains("error?err=6")) {
			ToastUtil.show(main, "缺少必要参数请填写完整");
			sp.edit().putBoolean("geturl", true).commit();
			return;
		} else if (url.contains("terminal/adddevice")) {
			Intent intent = new Intent(main, BindActivity.class);
			sp.edit().putString("adddevice", "adddevice").commit();
			main.startActivityForResult(intent, 1);

			sp.edit().putBoolean("geturl", true).commit();

			return;
		} else if (url.contains("terminal/touserinfo")) {
			Intent intent = new Intent(main, PinfoActivity.class);
			main.startActivity(intent);
			sp.edit().putBoolean("geturl", true).commit();

			return;
		} else if (url.contains("terminal/mydevice")) {
			Intent intent = new Intent(main, DeviceManaActivity.class);
			sp.edit().putString("mydevice", "mydevice").commit();
			main.startActivityForResult(intent, 1);
			sp.edit().putBoolean("geturl", true).commit();
			return;
		} else if (url.contains("terminal/myBracelet")) {

			Intent intent = new Intent(main, DeviceManaActivity.class);
			sp.edit().putString("mydevice", "myBracelet").commit();
			main.startActivity(intent);
			sp.edit().putBoolean("geturl", true).commit();
			return;
		}
		if (url.contains("terminal/eventscore")) {
			Intent intent = new Intent(main, TravelgradeActivity.class);
			main.startActivity(intent);
			sp.edit().putBoolean("geturl", true).commit();
			return;
		}
		if (url.contains("terminal/deviceshow")) {
			Intent intent = new Intent(main, DeviceIntroduceActivity.class);
			main.startActivity(intent);
			sp.edit().putBoolean("geturl", true).commit();

			return;
		}
		/*
		 * 调到赛事列表页
		 */
		if (url.contains("terminal/myindexevent")) {
			Intent intent = new Intent(main, GameListActivity.class);
			main.startActivity(intent);

			sp.edit().putBoolean("geturl", true).commit();
			return;
		}
	}

	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				Intent intent = new Intent(main, BindActivity.class);
				sp.edit().putString("adddevice", "addBracelet").commit();
				main.startActivityForResult(intent, 1);
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
				break;

			}
		}
	};

	/*
	 * public SQLiteDatabase openDatabase() { File jhPath = new File(filePath);
	 * 
	 * if (jhPath.exists()) {// 查看数据库文件是否存在 // Log.i("test", "存在数据库"); return
	 * SQLiteDatabase.openOrCreateDatabase(jhPath, null);// 存在则直接返回打开的数据库 } else
	 * {// 不存在先创建文件夹 File path = new File(pathStr);
	 * 
	 * Log.i("test", "pathStr=" + path); if (path.mkdir()) { Log.i("test",
	 * "创建成功"); } else { Log.i("test", "创建失败"); }
	 * 
	 * try { AssetManager am = main.getAssets();// 得到资源 InputStream is =
	 * am.open("share.db"); // 得到数据库的输入流 // Log.i("test", is + "");
	 * FileOutputStream fos = new FileOutputStream(jhPath);// 用输出流写到SDcard上面 //
	 * Log.i("test", "fos=" + fos); // Log.i("test", "jhPath=" + jhPath); byte[]
	 * buffer = new byte[1024];// 创建byte数组 用于1KB写一次 int count = 0; while ((count
	 * = is.read(buffer)) > 0) { // Log.i("test", "得到"); fos.write(buffer, 0,
	 * count); } // 最后关闭就可以了 fos.flush(); fos.close(); is.close(); } catch
	 * (IOException e) { // TODO Auto-generated catch block e.printStackTrace();
	 * return null; } // 如果没有这个数据库 我们已经把他写到SD卡上了，然后在执行一次这个方法 就可以返回数据库了 return
	 * openDatabase(); } }
	 */

	public void getAppVersionName() {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager pm = main.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(main.getPackageName(), 0);
			versionName = pi.versionName;
			main_version.setText("版本号:" + versionName);
			if (versionName == null || versionName.length() <= 0) {
				main_version.setText("版本号:" + "1.1");
			}
		} catch (Exception e) {
		}
	}

}
