package com.activity.chaoran;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.chaoran.db.DBManager;
import com.chaoran.db.SqlHelpUtil;
import com.chaoran.entiry.UpdataInfo;
import com.chaoran.entiry.UserList;
import com.chaoran.lx.activity.DownDataActivity;
import com.chaoran.thread.DownApk;
import com.honeywell.aidc.AidcManager;
import com.honeywell.aidc.AidcManager.CreatedCallback;
import com.honeywell.aidc.BarcodeReader;
import com.sys.SysData;
import com.util.*;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends Activity {
	SqlHelpUtil db;
	SQLiteDatabase sDatabase;
	EditText name;
	EditText pwd;
	private CheckBox checkBox;
	private CheckBox islxScan;
	public ProgressDialog pd;
	private int loginTy;// 登录类型,1为在线登录 2为离线数据下载
	private TextView regts;
	public String versionStr;

	public static float def_pbl = 0.9f; // 屏幕比列

	//Honeywell 扫描设备控制
    private static BarcodeReader barcodeReader = null;
    private AidcManager manager = null;

	private Handler handler = new Handler() {
		@Override
		// 当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg) {
			if (msg.what == -1) {
				DialogUtil.builder(MainActivity.this, "错误信息", "连接服务器失败,请检查网络！"
						+ msg.obj,0);
			} else if (msg.what == -2) {
				DialogUtil.builder(MainActivity.this, "错误信息", "用户名或密码错误！",0);
			} else if (msg.what == -3) {
				DialogUtil.builder(MainActivity.this, "错误信息", "解析xml失败！",0);
			} else if (msg.what == -4) {
				DialogUtil.builder(MainActivity.this, "错误信息", "检查更新失败,请检查网络！",0);
			} else if (msg.what == -5) {
				DialogUtil.builder(MainActivity.this, "错误信息", "更新文件失败！",0);
			} else if (msg.what == 1) {
				UpdataInfo info = (UpdataInfo) msg.obj;
				if (info!=null&&!info.getVersion().equals(versionStr)) {
					showUpdataDialog(info);
				}
			} else if (msg.what == 2) {
				new InstallUtil().installApk((File) msg.obj, MainActivity.this);
			} else {
				if (msg.obj.equals("该功能未授权")) {
					DialogUtil.builder(MainActivity.this, "提示信息", "该功能未授权！",0);
				} else {
					UserList user = (UserList) msg.obj;
					if (user.getLgnname() == null) {
						String udesc = user.getUdesc();
						if (udesc.equals("0")) {
							DialogUtil.builder(MainActivity.this, "提示信息",
									"PDA未注册！",0);
						} else if (udesc.equals("1")) {
							DialogUtil.builder(MainActivity.this, "提示信息",
									"PDA还未授权使用！",0);
						} else if (udesc.equals("2")) {
							DialogUtil.builder(MainActivity.this, "提示信息",
									"试用期已过！",0);
						} else if (udesc.equals("3")) {
							DialogUtil.builder(MainActivity.this, "提示信息",
									"超出最大站点数,请联系管理员",0);
						} else if (udesc.equals("-1")) {
							DialogUtil.builder(MainActivity.this, "提示信息",
									"用户名或密码错误！",0);
						}

					} else {
						SysData.is_lx = false;
						login_end(user);
					}
				}
			}
			if (pd != null) {
				pd.dismiss();
			}
		}
	};
	private Handler regHandler = new Handler() {
		@Override
		// 当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg) {
			if (msg.what != -1) {
				if(msg.equals("-1")){
					regts.setText("正式 注册");
				}else{
					regts.setText("软件到期时间"+msg.obj);
				}
			}
		}
	};
	public void login_end(UserList user) {
		SysData.jigid = user.getJigid();
		SysData.lgnname = user.getLgnname();
		SysData.userid = String.valueOf(user.getUserid());
		SysData.scale = MainActivity.this.getResources().getDisplayMetrics().density + 1;
		SysData.t_scale = MainActivity.this.getResources().getDisplayMetrics().densityDpi >= 300f ? 1 : 300f * def_pbl / MainActivity.this.getResources().getDisplayMetrics().densityDpi;
		SysData.exectime=Integer.parseInt(user.getUdesc() == null ? "60" : user.getUdesc());
		SharedPreferences sp = MainActivity.this.getSharedPreferences(
				"userTxt", MODE_PRIVATE);
		if (checkBox.isChecked()) {
			Editor editor = sp.edit();
			editor.putString("name", name.getText().toString().trim());
			editor.putString("pwd", pwd.getText().toString().trim());
			editor.putBoolean("islxScan",islxScan.isChecked());
			editor.commit();
		} else {
			sp.edit().clear().commit();
			name.setText("");
			pwd.setText("");
		}
		if (loginTy == 1) {
			String islxscan="1";
			if(islxScan.isChecked()){
				islxscan="0";
			}
			Intent intent = new Intent();
			intent.putExtra("displaymode", user.getDisplaymode());
			intent.putExtra("islxscan", islxscan);
			intent.setClass(getApplicationContext(), DjActivity.class);
			startActivity(intent);
		} else if (loginTy == 2) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), DownDataActivity.class);
			startActivity(intent);
		}
		SysData.no = name.getText().toString().trim();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		System.setProperty("http.keepAlive", "false");
		setContentView(R.layout.activity_main);
		SharedPreferences sp = getSharedPreferences("userTxt", MODE_PRIVATE);
		name = (EditText) findViewById(R.id.name);
		pwd = (EditText) findViewById(R.id.pwd);
		regts=(TextView) findViewById(R.id.regts);
		checkBox = (CheckBox) findViewById(R.id.cb);
		islxScan=(CheckBox)findViewById(R.id.lxs);
		if (!sp.contains("name")) {
			checkBox.setChecked(false);
		} else {
			name.setText(sp.getString("name", ""));
			pwd.setText(sp.getString("pwd", ""));
			islxScan.setChecked(sp.getBoolean("islxScan", true));
		}
		TextView version = (TextView) findViewById(R.id.version);
		versionStr=getVersionName();
		version.setText("版本".concat(versionStr));
		SysData.clientid = SysUtil.getLocalMacAddress(MainActivity.this);
		db = new SqlHelpUtil(getApplicationContext());
		sDatabase = db.getWritableDatabase();
		String selectStr = "select col1,col2,col3 from systable where desc='network'";
		Cursor select_cursor = sDatabase.rawQuery(selectStr, null);
		if (select_cursor.moveToFirst()) {
			SysData.url = "http://".concat(select_cursor.getString(0))
					.concat(":").concat(select_cursor.getString(1)).concat("/")
					.concat(select_cursor.getString(2));
		}
		select_cursor.close();
		selectStr = "select col1 from systable where desc='pdaState'";
		select_cursor = sDatabase.rawQuery(selectStr, null);
		if (select_cursor.moveToFirst()) {
			SysData.isreg = select_cursor.getString(0);
		}
		select_cursor.close();
		if (SysData.url != null) {
			new Thread(new CheckVersionTask()).start();
			new Thread(queryZcrq).start();
		}
		BufferedReader br = null;
		BufferedWriter bw = null;
		File file = new File(getFilesDir().getAbsolutePath() + "/cr_pda_config");
		try {
	        if (!file.exists())
	        	file.createNewFile();
	        FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis);
			br = new BufferedReader(isr);
			String s = br.readLine();
			if (s == null || s.trim().length() < 1)
				throw new Exception("Update config data.");
			def_pbl = Float.parseFloat(s);
			if (def_pbl < 0.1 || def_pbl > 10.0)
				throw new Exception("请填写 0.1~10.0 之间的浮点数！");
		} catch (Exception e) {
			def_pbl = 0.9f;
			try {
				FileOutputStream fos = new  FileOutputStream(file);
				OutputStreamWriter osw = new OutputStreamWriter(fos);
				bw = new BufferedWriter(osw);
				bw.append(Float.toString(def_pbl));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		if ("scanpal eda50".equals(android.os.Build.MODEL.toLowerCase())) {
	        AidcManager.create(this, new CreatedCallback() {

	            @Override
	            public void onCreated(AidcManager aidcManager) {
	                manager = aidcManager;
	                barcodeReader = manager.createBarcodeReader();
	            }
	        });
		}

	}

    public static BarcodeReader getBarcodeObject() {
        return barcodeReader;
    }

	Runnable downloadRun = new Runnable() {
		public void run() {
			login(name.getText().toString().trim(), pwd.getText().toString()
					.trim());
		}
	};
	Runnable queryZcrq = new Runnable() {
		public void run() {
			try {
				String url = SysData.url + "/webservice/ServiceInterface?wsdl";
				String method = "regEndRq";
				SoapObject rpc = new SoapObject("", method);
				HttpTransportSE ht = new HttpTransportSE(url, SysData.timeout);
				ht.debug = true;
				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
						SoapEnvelope.VER11);
				envelope.bodyOut = rpc;
				envelope.dotNet = true;
				envelope.setOutputSoapObject(rpc);
				ht.call("", envelope);
				Message message = new Message();
				message.obj = envelope.getResponse().toString();
				regHandler.sendMessage(message);
			} catch (Exception e) {
				Message message = new Message();
				message.what = -1;
				message.obj = e.toString();
				regHandler.sendMessage(message);
			}

		}
	};
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/*
	 * 获取当前程序的版本号
	 */
	private String getVersionName() {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = null;
		try {
			packInfo = packageManager.getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			DialogUtil.builder(MainActivity.this, "错误信息", "获取版本号失败！",0);
		}
		return packInfo.versionName;
	}

	// 设置按钮监听
	public void onset(View v) {
		Intent intent = new Intent();
		intent.setClass(this, NetWorkSet.class);
		startActivity(intent);
	}

	public void onopentest(View v) {
		DialogUtil.builder(this, "测试标题","测试内容！open" + v.getLeft(), 18);
	}

	public void onclosetest(View v) {
		DialogUtil.builder(this, "测试标题","测试内容！close" + v.getLeft(), 18);
	}

	// 设置按钮监听
	public void onRotation(View v) {
		int i = MainActivity.this.getRequestedOrientation();
		if (i == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
			MainActivity.this
					.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}
		// 纵屏反方向
		else if (i == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || i == 3) {
			MainActivity.this
					.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
		}
	}

	public boolean isNull() {
		if (name.getText().toString().trim().equals("")) {
			DialogUtil.builder(this, "错误信息", "用户名不能为空！",0);
			name.requestFocus();
			return false;
		}
		if (pwd.getText().toString().trim().equals("")) {
			DialogUtil.builder(this, "错误信息", "密码不能为空！",0);
			pwd.requestFocus();
			return false;
		}
		return true;
	}

	// 设置按钮监听
	public void onsub(View v) {
		loginTy = 1;
		start_login();
	}

	public void start_login() {
		if (!isNull()) {
			return;
		}
		if (!SysUtil.isNetworkConnected(MainActivity.this)) {
			DialogUtil.builder(MainActivity.this, "提示", "网络没连接！请检查网络",0);
			return;
		}
		if (name.getText().toString().trim().equals("crtech")
				&& pwd.getText().toString().trim().equals("crtech")) {
			Intent pdaIntent = new Intent();
			pdaIntent.setClass(this, PdaRegActivity.class);
			startActivity(pdaIntent);
			return;
		}
		if (SysData.url == null || SysData.url.trim().length() < 1) {
			DialogUtil.builder(this, "错误信息", "请设置URL！",0);
			return;
		}
		if (SysData.clientid.trim().length() < 1) {
			DialogUtil.builder(this, "错误信息", "mac地址为空,请检查网络！",0);
			return;
		}
		if (pd == null) {
			pd = ProgressDialog.show(this, "提示", "正在登录……");
		} else {
			DialogUtil.setDialog(pd, "提示", "正在登录……");
		}
		new Thread(downloadRun).start();
	}

	public void login(String name, String pwd) {
		try {
			String url = SysData.url + "/webservice/ServiceInterface?wsdl";
			String method = "login";
			SoapObject rpc = new SoapObject("", method);
			rpc.addProperty("name", name);
			rpc.addProperty("pwd", pwd);
			rpc.addProperty("mac", SysData.clientid);
			HttpTransportSE ht = new HttpTransportSE(url, SysData.timeout);
			ht.debug = true;
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			ht.call("", envelope);
			if (envelope.getResponse() != null) {
				byte[] bb = org.kobjects.base64.Base64.decode(envelope
						.getResponse().toString());
				Message message = new Message();
				message.obj = IoUtil.byte_obj(bb);
				handler.sendMessage(message);
			} else {
				Message message = new Message();
				message.what = -2;
				handler.sendMessage(message);
			}
		} catch (Exception e) {
			Message message = new Message();
			message.what = -1;
			message.obj = e.toString();
			handler.sendMessage(message);
		}

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.KEYCODE_BACK == keyCode) {
			if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (db != null) {
			db.close();
			sDatabase.close();
		}
        if (barcodeReader != null) {
            // close BarcodeReader to clean up resources.
            barcodeReader.close();
            barcodeReader = null;
        }

        if (manager != null) {
            // close AidcManager to disconnect from the scanner service.
            // once closed, the object can no longer be used.
            manager.close();
        }
	}

	private void showUpdataDialog(final UpdataInfo info) {
		Builder builer = new Builder(this);
		builer.setTitle("版本升级");
		builer.setMessage(info.getDescription());
		// 当点确定按钮时从服务器上下载 新的apk 然后安装
		builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				downLoadApk(SysData.url.concat(info.getUrl()));
			}
		});
		// 当点取消按钮时进行登录
		builer.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		AlertDialog dialog = builer.create();
		dialog.show();
	}

	private void downLoadApk(String url) {
		ProgressDialog pd = new ProgressDialog(this);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载更新");
		pd.show();
		new Thread(new DownApk(pd, url, this.getApplicationContext(), handler))
				.start();
	}

	public class CheckVersionTask implements Runnable {
		public void run() {
			InputStream is = null;
			HttpURLConnection conn = null;
			try {
				String path = SysData.url + "/apk.xml";
				URL url = new URL(path);
				conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(5000);
				if (conn.getResponseCode() == 200) {
					is = conn.getInputStream();
					// UpdataInfo info = getUpdataInfo(is);
					Message msg = new Message();
					msg.what = 1;
					System.out.println(versionStr);
					msg.obj = Dom4jUtil.parserXml(is,versionStr);
					handler.sendMessage(msg);
				}
			} catch (Exception e) {
				Message msg = new Message();
				msg.what = -4;
				handler.sendMessage(msg);
			} finally {
				try {
					if (is != null)
						is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId())// 得到被点击的item的itemId
		{
		case R.id.lxdatadown:
			loginTy = 2;
			start_login();
			break;
		case R.id.lxlogin:
			if (!isNull()) {
				return true;
			}
			DBManager dbManager = new DBManager(this);
			if (dbManager.existsTable("userlist".toUpperCase()) < 1) {
				DialogUtil.builder(MainActivity.this, "信息提示", "请下载用户资料表!",0);
			} else {
				String sql = "select jigid,lgnname,userid from userlist where username='"
						+ name.getText().toString().trim()
						+ "' and pass='"
						+ pwd.getText().toString().trim() + "'";
				Cursor cur = dbManager.query(sql);
				if (cur.getCount() == 0) {
					DialogUtil.builder(MainActivity.this, "信息提示", "用户账号错误!",0);
				} else {
					SysData.is_lx = true;
					UserList user = new UserList();
					if (cur.moveToFirst()) {
						user.setJigid(cur.getString(0));
						user.setLgnname(cur.getString(1));
						user.setUserid(cur.getInt(2));
						user.setDisplaymode("grid");
						loginTy = 1;
						login_end(user);
					}
					if (dbManager.existsTable("TEMP_BI_DJHZ".toUpperCase()) < 1) {
						dbManager
								.exeSql("create table TEMP_BI_DJHZ(FIELDNAME varchar(200),FIELDVALUE VARCHAR(8000))");
					}
				}
				cur.close();
				cur = null;
			}
			dbManager.closeDB();
			break;
		default:
			break;
		}
		return true;
	}

	public void onConfigurationChanged(Configuration newConfig) {
	    super.onConfigurationChanged(newConfig);
	    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
	        Toast.makeText(this, "转换横屏", Toast.LENGTH_SHORT).show();
	    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
	        Toast.makeText(this, "转换竖屏", Toast.LENGTH_SHORT).show();
	    }
	}
}
