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


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;

import cilico.tools.barcode.PhoneCilicoSoundUtils;
import cilico.tools.barcode.PhoneScanner;
import cilico.tools.barcode.Scanner;
import cilico.tools.barcode.ddjc.BroadcastConfig;
import cilico.tools.barcode.ddjc.ListnerBiz;
import cn.jymf.scan.idatascanlibrary.IdataScanSetting;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.common.util.VibratorUtil;
import cn.net.caoyao.cpzshandset.ui.activity.InputQRCodeActivity;
import cn.net.cpzslibs.label.LabelUtils;
import cn.net.handsetlib.common.HandsetConstant;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public abstract class BaseScanActivity extends BaseActivity {

	private long firstTime = 0;
	private boolean isHomePage = false;
	// 当前界面是否需要侧面的按钮
	protected boolean isNeedScanKey = true;
	private boolean isForbiddenScanKey = false;
	private int ddjcScannerKey = 142;
	private Handler bHandler;
	private boolean hasDown = false;// true：执行了keydown事件 false:不执行keydown事件
	private int inputQrCodeReqCode = 90001;
	private SharedPreferences sp;
	private Context context;
	public boolean isShow = true;// 判断当前界面是否可见，不可见时，不处理广播读取到的内容
    IdataScanSetting idataScanSetting;
//	
//	private static int scanmode = -1;
//	private static boolean bleft = false;
//	private static boolean bright = false;
//	private boolean bsound = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
//		if (Build.VERSION.SDK_INT >= 23) {
			initQRSetting();
//		}

		bHandler = initHandler();
		Log.e("当前Activity", getClass().getName());
        idataScanSetting = new IdataScanSetting().onCreate(this, new IdataScanSetting.ScanCodeResult() {
            @Override
            public void scanCodeIdataResultByBroadcastReceiver(String barcode) {
                Message msg = new Message();
                if (!StringUtils.isEmpty(barcode)) {
                    msg.what = barcode.length() > 0 ? PhoneScanner.BARCODE_READ : PhoneScanner.BARCODE_NOREAD;
                    // Log.d(TAG, "StartASYC ReadSCAAuto: 读取数据完成" + str);
                    /*
                     * if (str.endsWith("\n")) { Log.i("Scanner", "换行符"); }
                     */

                    String str = LabelUtils.getLabelSplits(barcode);
                    if (PhoneScanner.isNumber(str)) {
                        // 这里要判断扫描的是否为数字
                        if (LabelUtils.checkLabelLength(str)) {// 简单验证追溯码的合法性
                            msg.obj = str;
                        } else {
                            msg.what = PhoneScanner.BARCODE_ERR_LABEL;
                            msg.obj = str;
                        }
                    } else {
                        if (PhoneScanner.isDeviceId) {
                            String deviceId = ReadDeviceIDUtil.readScanDecrypt(barcode);
                            if (PhoneScanner.isNumber(deviceId) || deviceId.contains(Scanner.splitStr)) {
                                // 是设备id加密文件||商城模式,tab前为设备id，后为产品id
                                msg.obj = str;
                            } else {
                                msg.what = PhoneScanner.BARCODE_ERR_DeviceID;
                                msg.obj = "扫描设备id错误";
                            }
                        } else {
                            msg.what = PhoneScanner.BARCODE_ERR_LABEL;
                            msg.obj = barcode;
                        }
                    }
                    if (null!=bHandler){
                        bHandler.sendMessage(msg);
                    }
                }
            }
        });
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// Intent intent = new Intent(BroadcastConfig.SCAN_STOP);
		// context.sendBroadcast(intent);
//		if (Build.VERSION.SDK_INT >= 23) {
			unregisterReceiver(receiver);
//		}
		idataScanSetting.onDestroy(this);
	}

	private void initQRSetting() {
		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
		initBroadcastReciever();
		registerReceiver();
		// ListnerBiz.setScanClick(context, btn_scanner);
		ListnerBiz.setSound(context, sp, Config.canSound);
		ListnerBiz.setVibrate(context, sp, true);
		ListnerBiz.setExposure(context, 0);
		ListnerBiz.setContinue(context, sp, false);

	}

	/**
	 * 需要自定义的广播接收器
	 */
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (!isShow)
				return;
			if (bHandler != null) {
				String barcode = intent.getStringExtra("BARCODE");
				Log.d("barcode", "StartASYC ReadSCAAuto: 读取数据完成" + barcode);
				Message msg = new Message();
				if (!StringUtils.isEmpty(barcode)) {
					msg.what = barcode.length() > 0 ? PhoneScanner.BARCODE_READ : PhoneScanner.BARCODE_NOREAD;
					// Log.d(TAG, "StartASYC ReadSCAAuto: 读取数据完成" + str);
					/*
					 * if (str.endsWith("\n")) { Log.i("Scanner", "换行符"); }
					 */

					String str = LabelUtils.getLabelSplits(barcode);
					if (PhoneScanner.isNumber(str)) {
						// 这里要判断扫描的是否为数字
						if (LabelUtils.checkLabelLength(str)) {// 简单验证追溯码的合法性
							msg.obj = str;
						} else {
							msg.what = PhoneScanner.BARCODE_ERR_LABEL;
							msg.obj = str;
						}
					} else {
						if (PhoneScanner.isDeviceId) {
							String deviceId = ReadDeviceIDUtil.readScanDecrypt(barcode);
							if (PhoneScanner.isNumber(deviceId) || deviceId.contains(Scanner.splitStr)) {
								// 是设备id加密文件||商城模式,tab前为设备id，后为产品id
								msg.obj = str;
							} else {
								msg.what = PhoneScanner.BARCODE_ERR_DeviceID;
								msg.obj = "扫描设备id错误";
							}
						} else {
							msg.what = PhoneScanner.BARCODE_ERR_LABEL;
							msg.obj = barcode;
						}
					}
					bHandler.sendMessage(msg);
				}
			}
		}
	};

	/**
	 * 初始化广播接收器，AUTOID系列安卓产品上的系统软件扫描工具相对应
	 */
	private void initBroadcastReciever() {
		// 发送广播到扫描工具内的应用设置项
		Intent intent = new Intent(BroadcastConfig.BROADCAST_SETTING);
		// 修改扫描工具内应用设置中的开发者项下的广播名称
		intent.putExtra(BroadcastConfig.TYPE_BARCODE_BROADCAST_ACTION, BroadcastConfig.CUSTOM_NAME);
		// 修改扫描工具内应用设置下的条码发送方式为 "广播"
		intent.putExtra(BroadcastConfig.SEND_KEY, "BROADCAST");
		intent.putExtra(BroadcastConfig.BROADCAST_KEY, "BARCODE");
		// 修改扫描工具内应用设置下的结束符为 "NONE
		intent.putExtra(BroadcastConfig.END_KEY, "NONE");
		// intent.putExtra(TYPE_SCAN_CONTINUE, enable);
		intent.putExtra(BroadcastConfig.SOUND_KEY, Config.canSound);
		// 设置开机自启动
		intent.putExtra(BroadcastConfig.TYPE_BOOT_START, true);
		sendBroadcast(intent);
	}

	/**
	 * 注册自定义的广播
	 */
	private void registerReceiver() {
		IntentFilter filter = new IntentFilter(BroadcastConfig.CUSTOM_NAME);
		registerReceiver(receiver, filter);
	}

	public void setHomePage(boolean isHomePage) {
		this.isHomePage = isHomePage;
	}

	protected abstract Handler initHandler();

	@Override
	protected void onResume() {
		super.onResume();
		isShow = true;
		if (null != idataScanSetting) {
			idataScanSetting.onResume(this);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		isShow = false;
	}

	@Override
	protected void onStart() {
		super.onStart();
		// 初始化设备
		if (bHandler == null) {
			return;
		}
//		if (HandsetConstant.isHHW()) {
//			HHWScanner.onResumeRun(bContext, bHandler);
//		} else {
//			PhoneScanner.m_handler = bHandler;
//			PhoneScanner.InitSCA();
//		}
	}

	@Override
	protected void onStop() {
		super.onStop();
//		if (HandsetConstant.isHHW()) {
//			HHWScanner.onStopRun(bContext);
//		}
		idataScanSetting.onStop(this);
	}

	private long firstScannerTime = 0;

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// 中国追溯手持机调用，内部需要处理，当前先不改，有需求再说
		// LogUtil.d(TConfig.Echo, "onKeyUp:"+keyCode );
		if (isForbiddenScanKey && keyCode == ddjcScannerKey) {
			// LogUtil.e(TConfig.Echo, "onKeyUp isForbiddenScanKey:");
			return true;
		}
		if (isNeedScanKey && !hasDown) {
			if (HandsetConstant.isHHWUpKeyCode(keyCode)) {
				// hasDown = false;
				// LogUtil.i(TConfig.Echo, "执行onKeyUp中的读取方法" );
				long secondTime = System.currentTimeMillis();
				// LogUtil.w(TConfig.Echo, "间隔时间：" +(secondTime -
				// firstScannerTime) );
				if (doubleScanner(secondTime - firstScannerTime, keyCode)) {
					// finish();
				} else {
					// lastKey = keyCode;
					firstScannerTime = secondTime;
					PhoneScanner.Read(super.createService, super.cacheG, bContext);
				}

				return true;
			}
		}
		return super.onKeyUp(keyCode, event);
	}

	/**
	 * 点击两次后才返回或者退出 2014-7-22下午9:16:14
	 * 
	 * @param difTime
	 *            时间差 1s内点击两次作为退出
	 * @param context
	 * @return
	 */
	public boolean doubleScanner(Long difTime, int keyCode) {
		if (difTime < 1000) {
			return true;
		}
		return false;
	}

	public boolean isForbiddenScanKey() {
		return isForbiddenScanKey;
	}

	public void setForbiddenScanKey(boolean isForbiddenScanKey) {
		this.isForbiddenScanKey = isForbiddenScanKey;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// LogUtil.d(TConfig.Echo, isForbiddenScanKey +" onKeyDown keyCode:" +
		// keyCode);
		// 142
		if (isForbiddenScanKey && keyCode == ddjcScannerKey) {
			// LogUtil.e(TConfig.Echo, "isForbiddenScanKey:");
			return true;
		}
		if (isNeedScanKey) {
			if (HandsetConstant.isHHWKeyCode(keyCode)) {
				// LogUtil.i(TConfig.Echo,"isHHWKeyCode");
				PhoneScanner.Read(super.createService, super.cacheG, bContext);
				return true;
			} else if (HandsetConstant.isFLYKeyCode(keyCode)) {
				// LogUtil.i(TConfig.Echo,"isFLYKeyCode");
				PhoneScanner.Read(super.createService, super.cacheG, bContext);
			} else if (HandsetConstant.isHHWUpKeyCode(keyCode)) {
				// 监测有些手持机给的扫描按钮是up信号的情况
				hasDown = true;// 表示当前keydown事件被执行了
				PhoneScanner.Read(super.createService, super.cacheG, bContext);
				return true;
			} else {
				if (isHomePage) {
					return onScanKeyDown(keyCode, event);
				} else {
					return super.onKeyDown(keyCode, event);
				}
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 扫描监听 <br/>
	 * 2015-5-14上午10:24:04
	 * 
	 * @param keyCode
	 * @param event
	 * @return
	 */
	private boolean onScanKeyDown(int keyCode, KeyEvent event) {
		if (event.getRepeatCount() == 0) {
			if (PhoneScanner.isShieldKey(keyCode)) {
				long secondTime = System.currentTimeMillis();
				if (PhoneScanner.doubleBack(secondTime - firstTime, bContext)) {
					finish();
				} else {
					firstTime = secondTime;
				}
			}
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == inputQrCodeReqCode && resultCode == inputQrCodeReqCode) {
			if (data != null) {
				String inputQRCodeStr = data.getStringExtra("InputQRCodeStr");
				if (!StringUtils.isEmpty(inputQRCodeStr)) {
					Message msg = bHandler.obtainMessage(Scanner.BARCODE_READ);
					msg.obj = inputQRCodeStr;
					bHandler.sendMessage(msg);
				}

			}
		}

	}

	/**
	 * 手输二维码
	 */
	public void inputQRCode() {
		Intent intent = new Intent(this, InputQRCodeActivity.class);
		startActivityForResult(intent, inputQrCodeReqCode);
	}

	/**
	 * 振动和声音
	 * 
	 * @param duration
	 */
	public void vibrateReadQRComplete(int duration) {
		PhoneCilicoSoundUtils.play();
		VibratorUtil.Vibrate(this, duration); // 震动100ms
	}

	/*
	 * private long firstTime = 0; private boolean isHomePage = false; //
	 * 当前界面是否需要侧面的按钮 protected boolean isNeedScanKey = true; private Handler
	 * bHandler; private boolean hasDown = false; //true：执行了keydown事件
	 * false:不执行keydown事件 private int inputQrCodeReqCode = 90001;
	 * 
	 * @Override protected void onCreate(Bundle savedInstanceState) {
	 * super.onCreate(savedInstanceState); bHandler = initHandler(); }
	 * 
	 * public void setHomePage(boolean isHomePage) { this.isHomePage =
	 * isHomePage; }
	 * 
	 * 
	 * 
	 * protected abstract Handler initHandler();
	 * 
	 * @Override protected void onStart() { super.onStart(); // 初始化设备 if
	 * (bHandler == null) { return; } if (HandsetConstant.isHHW()) {
	 * HHWScanner.onResumeRun(bContext, bHandler); } else {
	 * PhoneScanner.m_handler = bHandler; PhoneScanner.InitSCA(); } }
	 * 
	 * @Override protected void onStop() { super.onStop(); if
	 * (HandsetConstant.isHHW()) { HHWScanner.onStopRun(bContext); } } private
	 * long firstScannerTime = 0;
	 * 
	 * @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
	 * //中国追溯手持机调用，内部需要处理，当前先不改，有需求再说 LogUtil.d(TConfig.Echo, "onKeyUp:"+keyCode
	 * ); if (isNeedScanKey && !hasDown) { if
	 * (HandsetConstant.isHHWUpKeyCode(keyCode)) { // hasDown = false; //
	 * LogUtil.i(TConfig.Echo, "执行onKeyUp中的读取方法" ); long secondTime =
	 * System.currentTimeMillis(); // LogUtil.w(TConfig.Echo, "间隔时间："
	 * +(secondTime - firstScannerTime) ); if (doubleScanner(secondTime -
	 * firstScannerTime,keyCode)) { // finish(); } else { // lastKey = keyCode;
	 * firstScannerTime = secondTime; PhoneScanner.Read(super.createService,
	 * super.cacheG, bContext); }
	 * 
	 * return true; } } return super.onKeyUp(keyCode, event); }
	 * 
	 *//**
		 * 点击两次后才返回或者退出 2014-7-22下午9:16:14
		 * 
		 * @param difTime
		 *            时间差 1s内点击两次作为退出
		 * @param context
		 * @return
		 */
	/*
	 * public boolean doubleScanner(Long difTime, int keyCode) { if (difTime <
	 * 1000) { return true; } return false; }
	 * 
	 * @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
	 * //LogUtil.d(TConfig.Echo, "onKeyDown  keyCode:" + keyCode); if
	 * (isNeedScanKey) { if (HandsetConstant.isHHWKeyCode(keyCode)) { //
	 * LogUtil.i(TConfig.Echo,"isHHWKeyCode");
	 * PhoneScanner.Read(super.createService, super.cacheG, bContext); return
	 * true; } else if (HandsetConstant.isFLYKeyCode(keyCode)) { //
	 * LogUtil.i(TConfig.Echo,"isFLYKeyCode");
	 * PhoneScanner.Read(super.createService, super.cacheG, bContext); }else if
	 * (HandsetConstant.isHHWUpKeyCode(keyCode)){ //监测有些手持机给的扫描按钮是up信号的情况
	 * hasDown = true;//表示当前keydown事件被执行了 PhoneScanner.Read(super.createService,
	 * super.cacheG, bContext); return true; } else { if (isHomePage) { return
	 * onScanKeyDown(keyCode, event); } else { return super.onKeyDown(keyCode,
	 * event); } } } return super.onKeyDown(keyCode, event); }
	 * 
	 *//**
		 * 扫描监听 <br/>
		 * 2015-5-14上午10:24:04
		 * 
		 * @param keyCode
		 * @param event
		 * @return
		 */
	/*
	 * private boolean onScanKeyDown(int keyCode, KeyEvent event) { if
	 * (event.getRepeatCount() == 0) { if (PhoneScanner.isShieldKey(keyCode)) {
	 * long secondTime = System.currentTimeMillis(); if
	 * (PhoneScanner.doubleBack(secondTime - firstTime, bContext)) { finish(); }
	 * else { firstTime = secondTime; } } } return true; }
	 * 
	 * @Override protected void onActivityResult(int requestCode, int
	 * resultCode, Intent data) { super.onActivityResult(requestCode,
	 * resultCode, data); if (requestCode == inputQrCodeReqCode && resultCode ==
	 * inputQrCodeReqCode) { if (data != null) { String inputQRCodeStr =
	 * data.getStringExtra("InputQRCodeStr"); if
	 * (!StringUtils.isEmpty(inputQRCodeStr)) { Message msg =
	 * bHandler.obtainMessage(Scanner.BARCODE_READ); msg.obj = inputQRCodeStr;
	 * bHandler.sendMessage(msg); }
	 * 
	 * } }
	 * 
	 * }
	 * 
	 *//**
		 * 手输二维码
		 */
	/*
	 * public void inputQRCode(){ Intent intent = new
	 * Intent(this,InputQRCodeActivity.class); startActivityForResult(intent,
	 * inputQrCodeReqCode); }
	 *//**
		 * 振动和声音
		 * 
		 * @param duration
		 */
	/*
	 * public void vibrateReadQRComplete(int duration) {
	 * PhoneCilicoSoundUtils.play(); VibratorUtil.Vibrate(this, duration);
	 * //震动100ms }
	 * 
	 */}
