package cn.net.caoyao.cpzshandset.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
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.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
import cn.net.caoyao.cpzshandset.R;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.ConfigCreateService;
import cn.net.caoyao.cpzshandset.common.config.HandsetVersionConstant;
import cn.net.caoyao.cpzshandset.common.util.CacheGet;
import cn.net.caoyao.cpzshandset.common.util.CachePut;
import cn.net.caoyao.cpzshandset.common.util.NetWorkUtils;
import cn.net.caoyao.cpzshandset.service.apkupdate.CreateApkUrl;
import cn.net.caoyao.cpzshandset.service.apkupdate.DownloadManager;
import cn.net.caoyao.cpzshandset.service.apkupdate.UpdateInfoEntity;
import cn.net.caoyao.cpzshandset.service.apkupdate.UpdateInfoService;

/** 自动更新 */
public class SplashActivity extends Activity {

	/** 获取应用程序的版本号失败 */
	private final int ERROR_GET_VERSION = 0;

	/** 获取服务器上的最新版本信息失败 */
	private final int ERROR_GET_UPDATEINFO = 1;

	/** 显示是否升级对话框---从而升级 */
	private final int SHOW_UPDATE_DIALOG = 2;

	/** 显示是否升级对话框---必须升级 */
	private final int SHOW_MUST_UPDATE_DIALOG = 7;

	/** 显示是否升级对话框---测试升级显示 */
	private final int SHOW_TEST_UPDATE_DIALOG = 8;

	/** 没有升级信息，进入主界面 */
	private final int NOT_SHOW_UPDATE_DIALOG = 3;

	/** 下载最新apk失败 */
	private final int ERROR_DOWNLOAD_APK = 4;

	/** 成功下载最新的apk。。。自动安装最新apk */
	private final int SUCCESS_DOWNLOAD_APK = 5;

	/** sdCard不存在 */
	private final int SDCARD_NOT_EXIST = 6;

	private long startTime;
	private PackageManager pm;
	private UpdateInfoService updateInfoService;// xml数据解析
	private UpdateInfoEntity updateInfo;// 升级数据domain
	private String version;// 版本号
//	private SharedPrefUtil sharedPrefUtil;
	private ProgressDialog mPd;// 进度条对话框
	private boolean isNetConnect = true;
	private CacheGet cacheG = new CacheGet();
	private CachePut cacheP = new CachePut();
	private Context context;
	private CreateApkUrl createApkUrl = new CreateApkUrl();
	private ConfigCreateService createService;

	// 广告位信息
//	private String newBannerJson;
//
//	private ArrayList<BannerEntity> bannerParcelables;

	@SuppressLint("HandlerLeak")
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ERROR_GET_VERSION:
				loginMainUI();
				break;
			case ERROR_GET_UPDATEINFO:
				loginMainUI();
				break;
			case SHOW_UPDATE_DIALOG:
				// 显示是否升级对话框
//				showUpdateDialog(0);
				break;
			case SHOW_MUST_UPDATE_DIALOG:
				// 必须升级
				showUpdateDialog(1);
				break;
			case SHOW_TEST_UPDATE_DIALOG:
				// 测试升级
				showUpdateDialog(2);
				break;
			case NOT_SHOW_UPDATE_DIALOG:
				loginMainUI();
				break;
			case ERROR_DOWNLOAD_APK:
				mPd.dismiss();
				loginMainUI();
				break;
			case SUCCESS_DOWNLOAD_APK:
				mPd.dismiss();
				// 安装应用程序
				DownloadManager.installApk(SplashActivity.this, updateInfo);
				break;
			case SDCARD_NOT_EXIST:
				mPd.dismiss();
				loginMainUI();
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {

		setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
		super.onCreate(savedInstanceState);
		if (Build.VERSION.SDK_INT>=23) {
			String[] pms = new String[] { Manifest.permission.ACCESS_WIFI_STATE,
					Manifest.permission.ACCESS_NETWORK_STATE,
					Manifest.permission.CHANGE_WIFI_STATE,
					Manifest.permission.WRITE_EXTERNAL_STORAGE,
					Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
					Manifest.permission.READ_PHONE_STATE,
					Manifest.permission.CAMERA,
					Manifest.permission.READ_EXTERNAL_STORAGE ,
					Manifest.permission.REQUEST_INSTALL_PACKAGES,
					Manifest.permission.SYSTEM_ALERT_WINDOW,
					Manifest.permission.MODIFY_AUDIO_SETTINGS,
					};
			requestPermissions(pms, 100);
		}
		context = this;
		createService = new ConfigCreateService();
//		Gson gson = new Gson();
//		String parameter = gson.toJson(PhoneParameterUtils.getHandsetParameter(context));
//		LogUtil.e(TConfig.Echo, parameter.length() +" 手持机参数信息：" + parameter);
		/*CallBackUtils.getBannerInfo(new CallBackOK() {

			@Override
			public void ok(Object object) {
				newBannerJson = (String) object;
			}
		}, new CallBackError() {

			@Override
			public void error() {
				Toast.makeText(SplashActivity.this, "获取数据失败！", 0).show();
			}
		}, 0);*/
		setContentView(R.layout.activity_splash);

		if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			Toast.makeText(SplashActivity.this, "SD卡不存在", Toast.LENGTH_SHORT).show();
		}
		pm = getPackageManager();
		boolean networkConnected = NetWorkUtils.isNetworkConnected(SplashActivity.this);

		if (networkConnected) {
			isNetConnect = true;
		} else {
			isNetConnect = false;
		}
//		sharedPrefUtil = new SharedPrefUtil(SplashActivity.this);

		startTime = System.currentTimeMillis();

		updateInfoService = new UpdateInfoService();// 解析xml文件
		SharedPreferences user_token = getSharedPreferences("data", 0);
		String token = user_token.getString("appToken", "");
		if (token.equals("")){
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
		}else {
			Intent intent = new Intent(this, HomeActivity.class);
			startActivity(intent);
		}
		// 获得程序版本号
//		version = getVersion();
//		mPd = new ProgressDialog(this);
//		new Thread(new CheckVersionTask()).start();
	}

	/**
	 * 获取应用程序的版本号
	 * 
	 * @return 版本号
	 */
	public String getVersion() {
		try {
			PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
			return packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			Message msg = new Message();
			msg.what = ERROR_GET_VERSION;
			mHandler.sendMessage(msg);
		}
		return null;
	}

	/**
	 * 检查版本的任务
	 */
	private final class CheckVersionTask implements Runnable {
		@Override
		public void run() {
			// 如果没有更新,让别人看3秒钟
			long endTime = System.currentTimeMillis();
			long sleepTime = endTime - startTime;
			if (sleepTime < 3000) {
				SystemClock.sleep(3000 - sleepTime);
			}
//			boolean isAutoUpdate = sharedPrefUtil.getBoolean(SharedPrefUtil.Keys.isAutoUpdate, true);
			boolean isAutoUpdate = cacheG.getCacheBooleanG(SplashActivity.this, Config.configSPName, Config.isAutoUpdate, true);
			if (isAutoUpdate) {
				isAutoUpdate = isNetConnect;
			}
			if (isAutoUpdate) {
				try {
//					String language = LanguageUtil.getLanguage(getApplicationContext()).toLowerCase();
					updateInfo = updateInfoService.getUpdateInfo(createApkUrl.getApkUrl());
					
					isNoErr = true;
					if (updateInfo == null) {
						Message msg = new Message();
						msg.what = ERROR_GET_UPDATEINFO;
						mHandler.sendMessage(msg);
					} else {
						   String[] split = updateInfo.getVersion().split("\\.");
	                        String[] split1 = version.split("\\.");
	                        String netVersion = split[0] + split[1] + split[2];
	                        String version = split1[0] + split1[1] + split1[2];
	                        Integer yun = Integer.valueOf(netVersion);
	                        Integer ben = Integer.valueOf(version);
	                        Log.d("我我我我我哦", netVersion);
	                        Log.d("我我我我我哦", version);
						if (ben>=yun) {
							// 不用显示更新的对话框
//							LogUtil.e(TConfig.ECHO_BITMAP,"不用显示更新的对话框" + sleepTime);
							Message msg = new Message();
							msg.what = NOT_SHOW_UPDATE_DIALOG;
							mHandler.sendMessage(msg);
						} else {
							if (0 == updateInfo.getiMust()) {
								// 显示更新的对话框
								Message msg = new Message();
								msg.what = SHOW_UPDATE_DIALOG;
								mHandler.sendMessage(msg);

							} else if (1 == updateInfo.getiMust()) {
								// 必须升级
								Message msg = new Message();
								msg.what = SHOW_MUST_UPDATE_DIALOG;
								mHandler.sendMessage(msg);
							} else if (2 == updateInfo.getiMust()) {
								// 测试的不升级
								Message msg = new Message();
								msg.what = SHOW_TEST_UPDATE_DIALOG;
								mHandler.sendMessage(msg);
							}
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (!isNoErr) {
						loginMainUI();
					}
				}
			} else {
				loginMainUI();
			}
		}
	}

	/**
	 * 没有错误
	 */
	private boolean isNoErr = false;

	/**
	 * 直接进入主界面
	 */
	private void loginMainUI() {
		int handsetVersion = createService.getHandsetVersionMode(cacheG, context);
		switch (handsetVersion) {
		case HandsetVersionConstant.HANDSET_YTH_LOGIN_SHIPMENT_VERSION_MODE :
		case HandsetVersionConstant.HANDSET_YTH_SCANNER_SHIPMENT_VERSION_MODE:
		case HandsetVersionConstant.HANDSET_YTH_SCANNER_SHIPMENT_PUNIT_VERSION_MODE:
		case HandsetVersionConstant.HANDSET_LIQUEUR_SFY_VERSION_MODE:
			Intent loginIntent1 = new Intent(this, LoginActivity.class);
			startActivity(loginIntent1);
			break;
		default:
			Intent intent = new Intent(this, HomeActivity.class);
			startActivity(intent);
			break;
		}

		SplashActivity.this.finish();
		overridePendingTransition(R.anim.enter_default, R.anim.exit_default);
	}

	/**
	 * 下载apk的任务
	 */
	private final class DownloadApkTask implements Runnable {

		@Override
		public void run() {
			// 判断sdcard是否存在
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				try {
					boolean result = DownloadManager.download(updateInfo.getUrl(), mPd);
					if (result) {
						Message msg = new Message();
						msg.what = SUCCESS_DOWNLOAD_APK;
						mHandler.sendMessage(msg);
					} else {
						Message msg = new Message();
						msg.what = ERROR_DOWNLOAD_APK;
						mHandler.sendMessage(msg);
					}
				} catch (Exception e) {
					Message msg = new Message();
					msg.what = ERROR_DOWNLOAD_APK;
					mHandler.sendMessage(msg);
				}
			} else {
				Message msg = new Message();
				msg.what = SDCARD_NOT_EXIST;
				mHandler.sendMessage(msg);
			}
		}
	}

	/**
	 * 显示更新的提示对话框
	 */
	private void showUpdateDialog(final int updateModel) {

		String strTitle = context.getResources().getString(R.string.splash_update_apk_dialog_title);
		String strMsg = updateInfo.getDescription();
		String strEnsure = context.getResources().getString(R.string.splash_update_apk_dialog_btn_sure_str);
		String strCancel = context.getResources().getString(R.string.splash_update_apk_dialog_btn_cancel_str);
		switch (updateModel) {
		case 1:
			strEnsure = context.getResources().getString(R.string.splash_update_apk_dialog_btn_update_str);
			strCancel = context.getResources().getString(R.string.splash_update_apk_dialog_btn_exit_str);
			break;
		case 2:
			strMsg = context.getResources().getString(R.string.splash_update_apk_dialog_tips_msg_str);
			strEnsure = context.getResources().getString(R.string.splash_update_apk_dialog_btn_enter_str);
			strCancel = context.getResources().getString(R.string.splash_update_apk_dialog_btn_cancel_str);
			break;
		}
		new AlertDialog.Builder(SplashActivity.this).setTitle(strTitle).setMessage(strMsg).setCancelable(false)
				.setPositiveButton(strEnsure, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (updateModel == 2) {
							loginMainUI();
						} else {
							mPd = new ProgressDialog(SplashActivity.this);
							mPd.setCancelable(false);
							mPd.setMessage(context.getResources().getString(R.string.splash_update_apk_dialog_tips_msg_download_str));
							mPd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
							mPd.show();
							new Thread(new DownloadApkTask()).start();
						}
					}
				}).setNegativeButton(strCancel, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (1 == updateModel) {
							finish();
						} else {
							loginMainUI();
						}
					}
				}).create().show();
	}

	@Override
	protected void onStop() {
		SplashActivity.this.finish();
		super.onStop();
	}

}