package com.activity.chaoran;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.*;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.SoundPool;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.*;
import android.os.PowerManager.WakeLock;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.chaoran.component.ImageAdpter;
import com.chaoran.component.MyAdapter;
import com.chaoran.db.DBManager;
import com.chaoran.entiry.*;
import com.chaoran.listener.ImageClickListener;
import com.chaoran.listener.PzClickListener;
import com.chaoran.lx.thread.LxDJNrThread;
import com.chaoran.lx.thread.LxMenuQueryThread;
import com.chaoran.lx.thread.LxRunYmupThread;
import com.chaoran.thread.DownDJRun;
import com.cr5w.scan.CR5WScanControl;
import com.cr5w.scan.aht70.ScanHelper;
import com.device.zk_r322a.ZKR322AControl;
import com.honeywell.aidc.*;
import com.jiebao.h518.scan.BeepManager;
import com.jiebao.h518.scan.NewScanControler;
import com.lianxin.nr510.Engine;
import com.seuic.scan.SeuicScanKeyEventRunnable;
import com.seuic.scanner.DecodeInfo;
import com.seuic.scanner.DecodeInfoCallBack;
import com.seuic.scanner.ScannerFactory;
import com.seuic.scanner.ScannerKey;
import com.sys.SysData;
import com.util.*;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * 富力叶不兼容版本代码
 * import com.olc.scan.IScanCallBack;
 * import com.olc.scan.ScanManager;
 **/

/*
 * DecodeInfoCallBack 接口 是seuic的 扫描 后 的 回调接口 
 */
public class DjActivity extends TabActivity implements OnInitListener, DecodeInfoCallBack, 
															BarcodeReader.BarcodeListener,
															BarcodeReader.TriggerListener {			
	/* 振动 */
	public Vibrator vibrator;
	/* 拍照用的属性 */
	public PhotographUi photographUi;// 当前拍照的组件
	public String pzImgPath;// 照相的图片路径
	/*----------------------*/
	public String phoneModel;// 电话类型
	public Map djInitMap = null;
	public HashMap<String, String> pageMap = new HashMap<String, String>();// 页面参数
	public String mxTempTable;// 明细临时表
	public String mxSql;// 明细数据插入sql
	private String mxQuerySql;// 明细查询sql
	private String defaultFocus;// 初始化进入单据时的默认焦点
	private String defaultFocus2;// 初始化进入单据时的默认焦点
	private String nextFocusTag;// 下一个需要获得焦点组件Tag
	private WakeLock wakeLock = null;
	private WakeLock linghtScreen = null;// 点亮屏幕
	PowerManager pm = null;
	private boolean isLinghtScreen = false;
	private WifiLock wifiLock;
	/* 菜单栏变量 */
	private AbsListView menuList;
	private List menuData;
	private BaseAdapter menuAdapter;
	private String formlx;
	private int currentDjId;
	public ProgressDialog pd;

	public TabHost tabhost;
	public TabHost hzTab;
	public HashMap fangAMap = new HashMap();// 保存所有方案
	/* 明细内容 */
	private TextView mxTitle;
	private ListView mxList;
	public ArrayList mxData = new ArrayList();
	private MyAdapter mxAdapter;
	private Button mxRefreshBut;
	private int cur_pos = -1;// 当前选中的行

	/* 语音播放变量 */
	private int MY_DATA_CHECK_CODE = 0;
	private TextToSpeech tts;
	private MediaPlayer diPlayer = null;
	private MediaPlayer duPlayer = null;
	//
	public static View m_view = null;

	// 正在执行是否支持重复读取条形码
	private boolean reReadCode = true;
	
	/* 数据操作变量 */
	private DBManager dbManager;
	private String ttsNr;
	private OnCompletionListener completionListener = new OnCompletionListener() {
		// @Override
		public void onCompletion(MediaPlayer mp) {
			if (ttsNr != null) {
				if (tts != null) {
					tts.speak(ttsNr, TextToSpeech.QUEUE_ADD, null);
				}
				ttsNr = null;
			}
		}
	};
	/* 菜单栏查询 */
	Runnable menuRun = new Runnable() {
		public void run() {
			purview();
		}
	};
	/* 显示网络图片Handler */
	public Handler imgHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == -1) {
				DialogUtil.builder(DjActivity.this, "错误信息", "图片地址不正确", 0);
			} else {
				Map map = (Map) msg.obj;
				((SelfImage) map.get("image")).setBitmap((Bitmap) map.get("bitMap"));
			}
		}

	};
	/* 单据内容查询后更新页面 */
	private Handler handler = new Handler() {
		@Override
		// 当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == -1) {
				if (pd != null) {
					pd.cancel();
					DialogUtil.builder(DjActivity.this, "错误信息", "初始化失败:" + msg.obj, 0);
				}
			} else {
				Object initOb = msg.obj;
				if (initOb instanceof Map) {
					djInitMap = (Map) initOb;
					createDj(1);
				} else {
					if (initOb.equals("0")) {
						DialogUtil.builder(DjActivity.this, "提示信息", "PDA未注册！", 0);
					} else if (initOb.equals("1")) {
						DialogUtil.builder(DjActivity.this, "提示信息", "PDA还未授权使用！", 0);
					} else if (initOb.equals("2")) {
						DialogUtil.builder(DjActivity.this, "提示信息", "试用期已过！", 0);
					} else if (initOb.equals("该模块未授权")) {
						DialogUtil.builder(DjActivity.this, "提示信息", "该模块未授权！", 0);
					}
					pd.cancel();
				}
			}
		}

	};
	/* 菜单查询后更新页面 */
	private Handler menuHandler = new Handler() {
		@Override
		// 当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == -1) {
				DialogUtil.builder(DjActivity.this, "错误信息", "下载单据菜单失败！" + msg.obj, 0);
			} else {
				menuAdapter.notifyDataSetChanged();
			}
			pd.cancel();
		}

	};
	private Handler sqlHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == -1) {
				pd.cancel();
				DialogUtil.builder(DjActivity.this, "错误信息", "提取方案SQL失败!" + msg.obj, 0);
			} else {
				if (msg.arg1 == 0) {
					try {
						HashMap faMap = (HashMap) IoUtil.byte_obj((byte[]) msg.obj);
						Map map = SqlUtil.regSql(faMap.get("sql").toString(), hzTab, pageMap);
						pd.setMessage("正在执行检索方案");
						String audioFld = "";
						if (faMap.get("audioFld") != null) {
							audioFld = faMap.get("audioFld").toString().toUpperCase();
						}
						runSearch(map, faMap.get("return_one").toString(), audioFld);
					} catch (Exception e) {
						pd.cancel();
						DialogUtil.builder(DjActivity.this, "错误信息", "检索方案内容解析失败!", 0);
					}
				} else if (msg.arg1 == 1) {
					String sql = null;
					try {
						sql = (String) IoUtil.byte_obj((byte[]) msg.obj);
					} catch (Exception e) {
						pd.cancel();
						DialogUtil.builder(DjActivity.this, "错误信息", "页面修改方案内容解析失败!", 0);
						return;
					}
					Map map = SqlUtil.regSql(sql, hzTab, pageMap);
					map.put("gzid", pageMap.get("GZID"));
					map.put("mxTempTable", mxTempTable);
					Map hzData = DjUtil.organizationHzData(hzTab, pageMap.get("GZID"));
					hzData.putAll(pageMap);
					map.put("hzData", hzData);
					try {
						byte[] b = IoUtil.getbyte(map);
						String paramString = Base64.encode(b);
						pd.setMessage("正在执行页面修改方案");
						runYmup(paramString);
					} catch (Exception e) {
						pd.cancel();
						DialogUtil.builder(DjActivity.this, "错误信息", "页面修改方案组织数据失败!", 0);
					}
				} else if (msg.arg1 == 2) {// 页面提取方案
					Djselefa djselefa = null;
					try {
						djselefa = (Djselefa) IoUtil.byte_obj((byte[]) msg.obj);
					} catch (Exception e) {
						e.printStackTrace();
						pd.cancel();
						DialogUtil.builder(DjActivity.this, "错误信息", "提取方案内容解析失败!", 0);
						return;
					}
					HashMap map = SqlUtil.regSql(djselefa.getT_sql(), hzTab, pageMap);
					pd.cancel();
					Intent intent = new Intent();
					djselefa.setT_sql(map.get("sql").toString());
					HashMap paramMap = new HashMap();
					paramMap.put("djselefa", djselefa);
					paramMap.put("t_sqlParam", (HashMap) map.get("param"));
					paramMap.put("mxTempTable", mxTempTable);
					paramMap.put("GZID", pageMap.get("GZID"));
					intent.putExtra("paramMap", paramMap);
					intent.setClass(getApplicationContext(), DjtqActivity.class);
					startActivityForResult(intent, 2);
				}
			}
		}
	};
	public Handler runHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			View rootview = DjActivity.this.getWindow().getDecorView();
			View aaa = rootview.findFocus();
			if (aaa instanceof SelfEditText) {
				m_view = aaa;
				SelfEditText set = (SelfEditText)aaa;
				if (set.getText().length() > 0)
					set.selectAll();
			}
			if (msg.what == -1) {
				pd.cancel();
				DialogUtil.builder(DjActivity.this, "错误信息", "检索方案执行失败:" + msg.obj.toString(), 0);
			} else if (msg.what == -2) {
				pd.cancel();
				DialogUtil.builder(DjActivity.this, "错误信息", "页面修改方案执行失败:" + msg.obj.toString(), 0);
				WifiManager wifiManager = (WifiManager) DjActivity.this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
				wifiManager.disconnect();
				wifiManager.reconnect();
			} else if (msg.what == -3) {
				pd.cancel();
				DialogUtil.builder(DjActivity.this, "错误信息", "单据保存失败:" + msg.obj.toString(), 0);
			} else if (msg.what == -4) {
				pd.cancel();
				DialogUtil.builder(DjActivity.this, "错误信息", "单据退出失败:" + msg.obj.toString(), 0);
			} else if (msg.what == -5) {
				pd.cancel();
				DialogUtil.builder(DjActivity.this, "错误信息", "查询明细失败:" + msg.obj.toString(), 0);
			} else {
				if (msg.obj == null) {
					pd.cancel();
					DialogUtil.builder(DjActivity.this, "错误信息", "方案执行失败!", 0);
				} else {
					if (msg.arg1 == 1) {// 检索方案
						Map map = (Map) msg.obj;
						DataGrid dg = (DataGrid) map.get("dg");
						int len = dg.getTableData().size();
						if (len < 1) {
							pd.cancel();
							DialogUtil.builder(DjActivity.this, "提示信息", "当前查询没有记录！", 0);
							return;
						}
						String speakFld = (map.get("audioFld")).toString();
						if (map.get("return_one").equals("Y") && len < 2) {
							Map paramValueMap = (Map) dg.getTableData().get(0);
							play(paramValueMap, speakFld);
							DjUtil.setUiValue(hzTab, paramValueMap, pageMap, imgHandler);
						} else {
							Intent intent = new Intent();
							intent.setClass(getApplicationContext(), ParamActivity.class);
							intent.putExtra("dg", dg);
							intent.putExtra("audioFld", speakFld);
							startActivityForResult(intent, 1);
						}
						if (defaultFocus != null) {
							DjUtil.setFocus(hzTab, defaultFocus);
							defaultFocus = null;
						}
						pd.cancel();
					} else if (msg.arg1 == 2) {// 页面修改方案
						Object ob = msg.obj;
						if (ob instanceof Map) {
							Map map = (Map) ob;
							List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("hz");
							Map<String, Object> paramValueMap = new HashMap<String, Object>();
							for (Map<String, Object> tm : list) {
								if ("MESSAGE_A".equals(tm.get(" fieldname"))) {
									paramValueMap = tm;
								} else if ("MESSAGE_AUDIO".equals(tm.get("fieldname")))
									paramValueMap = tm;
							}
							play(paramValueMap, "fieldValue");
							DjUtil.setUiValue(hzTab, (List) map.get("hz"), pageMap, imgHandler);

							if (map.get("msg") != null) {
								String ymup_msg = map.get("msg").toString();
								if (ymup_msg.toUpperCase().indexOf("JUMP_") == 0) {
									String ymup_msgs[] = ymup_msg.split("_");
									String newOpenDjFromlx = ymup_msgs[1].toUpperCase();
									int dj_no = -1;
									int len = menuData.size();
									for (int i = 0; i < len; i++) {
										Map tempMap = (Map) menuData.get(i);
										String tempgn_no = tempMap.get("gn_no").toString().toUpperCase();
										if (newOpenDjFromlx.equals(tempgn_no)) {
											dj_no = i;
											break;
										}
									}
									if (dj_no == -1) {
										DialogUtil.builder(DjActivity.this, "提示信息", "当前操作员不具有" + newOpenDjFromlx + "单据操作权限!", 0);
									} else {
										tabhost.setCurrentTab(0);
										currentDjId = dj_no;
										DialogUtil.builderCancel(DjActivity.this, "提示", "是否退出该单据", okClick);
									}
								} else {
									String returnMsg[] = map.get("msg").toString().split("@");
									int fontsize = 0;
									if (returnMsg.length > 1) {
										fontsize = Integer.parseInt(returnMsg[1]);
									}
									DialogUtil.builder(DjActivity.this, "提示信息", returnMsg[0], fontsize);
								}
							}
						} else {
							DialogUtil.builder(DjActivity.this, "提示信息", ob.toString(), 0);
						}
						pd.cancel();
					} else if (msg.arg1 == 3) {
						String mess = msg.obj.toString();
						if (mess.substring(0, 2).equals("ok")) {
							String djbh = mess.substring(2, mess.length());
							mxData.clear();
							mxAdapter.notifyDataSetChanged();
							hzTab.setCurrentTab(0);
							hzTab.clearAllTabs();
							pageMap.clear();
							mxTempTable = null;
							mxSql = null;
							mxQuerySql = null;
							createDj(0);
							DialogUtil.builder(DjActivity.this, "提示信息", "单据保存成功\n单据编号:".concat(djbh), 0);
						} else {
							DialogUtil.builder(DjActivity.this, "提示信息", mess, 0);
						}
						pd.cancel();
					} else if (msg.arg1 == 4) {
						if (tabhost.getCurrentTab() != 0) {
							hzTab.clearAllTabs();
							mxData.clear();
							fangAMap.clear();
							djInitMap.clear();
							djInitMap = null;
							pageMap.clear();
							mxTempTable = null;
							mxSql = null;
							mxQuerySql = null;
							formlx = null;
							pd.cancel();
							tabhost.setCurrentTab(0);
						} else {
							pd.cancel();
							openNewDj();
						}
					} else if (msg.arg1 == 5) {
						mxData.clear();
						try {
							byte[] bb = Base64.decode(msg.obj.toString());
							mxData.addAll((List) IoUtil.byte_obj(bb));
						} catch (Exception e) {
							DialogUtil.builder(DjActivity.this, "提示信息", "数据转换失败", 0);
						}
						mxAdapter.notifyDataSetChanged();
						pd.cancel();
					}
				}

			}
			if (nextFocusTag != null) {
				setNextFocus(nextFocusTag);
				nextFocusTag = null;
			}
			if (isLinghtScreen) {
				releaseLinghtScreen();
			}
			if (newScanControler != null) {
				newScanControler.scanOnce();// 如果PDA是ht518 则一进入单据就打开扫描
			}
			if (seuicScanner != null && islxscan.equals("0")) {
				seuicScanner.startScan();
			}

			if (androidHandheldTerminal0 != null) {
				androidHandheldTerminal0.start();
			}
			if (cr5wScanControl != null)
				cr5wScanControl.start(DjActivity.this);
			if (androidHandheldTerminal != null)
				androidHandheldTerminal.start();
			if (nr510ScanControl != null)
				nr510ScanControl.start(DjActivity.this);
				
	        if (barcodeReader != null) {
	        	continuousScanning(true);
	        }
	        if (zkr322aControl != null) {
	        	zkr322aControl.start();
	        }
	        if (haixinN1SDemoReceiver != null) {
	        	haixinN1sStart();
	        }
	        reReadCode = true;
		}
	};

	/* 事件 */
	public OnFocusChangeEvent focusEvent;
	public OnClickEvent clickEvent;
	public PzClickListener pzClickEvent;// 拍照事件
	public ImageClickListener imgClickEvent;

	private void createDj(int ty) {
		if (ty == 1) {// 为0表示保存后新开单据
			fangAMap.clear();
			if (!SysData.is_lx) {
				DjUtil.assembleFangA(fangAMap, (ArrayList) djInitMap.get("searchList"));
				DjUtil.assembleFangA(fangAMap, (ArrayList) djInitMap.get("ymupList"));
				DjUtil.assembleFangA(fangAMap, (ArrayList) djInitMap.get("djtqList"));
				djInitMap.remove("searchList");
				djInitMap.remove("ymupList");
				djInitMap.remove("djtqList");
			} else {
				fangAMap = (HashMap) djInitMap.get("fangAMap");
				djInitMap.remove("fangAMap");
			}
		}
		Sys_DanJuFormsOptions danju = (Sys_DanJuFormsOptions) djInitMap.get("danju");
		ByteArrayInputStream in = null;
		try {
			DanJuEntity dj = (DanJuEntity) IoUtil.byte_obj2(danju.getFORM());
			if (SysData.is_lx) {// 如果是离线单据就在PDA上生成临时表
				System.out.println(danju.getFORMbs() + "-----" + formlx);
				String tableName = "CR_DJBS_".concat(danju.getFORMbs()).concat(formlx);
				String createMxTableSql = "create table ".concat(tableName).concat("(gzid char(11),dj_sn int null default 0,");
				HashMap mxFiledMap = null;
				for (int i = 0; i < dj.mxzdArray.size(); i++) {
					mxFiledMap = (HashMap) dj.mxzdArray.get(i);
					createMxTableSql = createMxTableSql.concat(mxFiledMap.get("fdname").toString());
					String fdtype = mxFiledMap.get("fdtype").toString();
					if (fdtype.equals("字符")) {
						createMxTableSql = createMxTableSql.concat("varchar (").concat(mxFiledMap.get("fdsize").toString()).concat(") null default '',");
					} else if (fdtype.equals("整型") || fdtype.equals("整数")) {
						createMxTableSql = createMxTableSql.concat(" int null default 0,");
					} else if (fdtype.equals("时间")) {
						createMxTableSql = createMxTableSql.concat(" datetime null ,");
					} else if (fdtype.equals("位图") || fdtype.equals("二进")) {
						createMxTableSql = createMxTableSql.concat(" blob null ,");
					} else if (fdtype.equals("文本")) {
						createMxTableSql = createMxTableSql.concat(" text ,");
					} else if (fdtype.equals("实数")) {
						createMxTableSql = createMxTableSql.concat(" decimal(").concat(mxFiledMap.get("fdsize").toString()).concat(",")
								.concat(mxFiledMap.get("fddec").toString()).concat(") null default 0 ,");
					}
				}
				createMxTableSql = createMxTableSql.concat(" CONSTRAINT cr_").concat(danju.getFORMbs()).concat("_").concat(formlx)
						.concat("_PK PRIMARY KEY (gzid,dj_sn))");
				System.out.println(dj.mxzdArray.size() + "------------sql:" + createMxTableSql);
				if (dbManager.existsTable(tableName) > 0) {
					dbManager.exeSql("drop table ".concat(tableName));
				}
				dbManager.exeSql(createMxTableSql);
			}
			String[] arrs = dj.pageNr.split("\\^");
			if (arrs.length > 1) {
				dj.pageNr = arrs[0];
			}
			in = new ByteArrayInputStream(dj.pageNr.getBytes());
			pageMap.put("RQ", djInitMap.get("RQ").toString());
			Dom4jUtil.testParseXMLData(in, DjActivity.this);
			if (dj.mxzdArray.size() > 0) {
				mxTitle.setText(((Map) dj.mxzdArray.get(0)).get("chnname").toString().trim());
				if (mxAdapter != null) {
					mxAdapter.clear();
				}
				mxAdapter = new MyAdapter(DjActivity.this, mxData, ((Map) dj.mxzdArray.get(0)).get("fdname").toString().trim().toUpperCase());
				mxList.setAdapter(mxAdapter);
			}
			mxTempTable = "CR_DJBS_".concat(danju.getFORMbs()).concat(formlx);
			mxSql = DjUtil.createMxSql(dj.mxzdArray, mxTempTable);
			mxQuerySql = DjUtil.createMxQuerySql(dj.mxzdArray, mxTempTable);
			if (mxQuerySql == null) {
				mxRefreshBut.setEnabled(false);
				mxTempTable = null;
			} else {
				mxRefreshBut.setEnabled(true);
			}
			pageMap.put("GZID", djInitMap.get("GZID").toString().trim());
			pageMap.put("DJLX", formlx);
			pageMap.put("DJBH", danju.getFORMbs().trim().concat("草"));
			pageMap.put("DJBS", danju.getFORMbs().trim());
			pageMap.put("RQ", djInitMap.get("RQ").toString());
			pageMap.put("ONTIME", djInitMap.get("ONTIME").toString());
			pageMap.put("JIGID", SysData.jigid);
			pageMap.put("ZHIYID", SysData.userid);
			pageMap.put("USERID", SysData.userid);
			pageMap.put("USERNAME", SysData.lgnname);
			pageMap.put("CLIENTID", SysData.clientid);
			DjUtil.setUiValue2(hzTab, pageMap, imgHandler);
			String newDjInit = null;
			if (dj.fangAtyjkVO != null) {
				newDjInit = dj.fangAtyjkVO.newDjInit.trim();
			}
			if (newDjInit != null && newDjInit.length() > 0) {
				defaultFocus = danju.getDefaultFouseField();
				defaultFocus2 = defaultFocus;
				eventHandler(newDjInit, null);
			} else {
				defaultFocus2 = danju.getDefaultFouseField();
				DjUtil.setFocus(hzTab, danju.getDefaultFouseField());
			}
			pd.cancel();
		} catch (Exception e) {
			e.printStackTrace();
			DialogUtil.builder(this, "错误信息", "生成单据页面失败！" + e.toString(), 0);
			pd.cancel();
		} finally {
			try {
				if (in != null) {
					in.close();
					in = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public DialogInterface.OnClickListener okClick = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			new DjMenuFun().exitDj(DjActivity.this);
		}
	};
	public DialogInterface.OnClickListener cancelClick = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
		}
	};

	public void queryMx(View v) {
		if (mxQuerySql == null) {
			return;
		}
		DialogUtil.setDialog(pd, "正在查询单据内容", "正在查询明细……");
		new ExitThread(pageMap.get("GZID"), mxQuerySql, runHandler, "queryMx").start();
	}

	public void openNewDj() {
		if (SysData.is_lx) {
			if (dbManager.existsTable("sys_DanJuFormsOptions".toUpperCase()) < 1) {
				DialogUtil.builder(DjActivity.this, "提示信息", "请下载单据表", 0);
				return;
			}
		}
		DialogUtil.setDialog(pd, "正在查询单据内容", "正在下载……");
		Map map = (Map) menuData.get(currentDjId);
		formlx = map.get("gn_no").toString();
		mxData.clear();
		pageMap.clear();
		if (djInitMap != null) {
			djInitMap.clear();
			djInitMap = null;
		}
		fangAMap.clear();
		mxTempTable = null;
		mxSql = null;
		tabhost.setCurrentTab(1);
		hzTab.clearAllTabs();
		if (SysData.is_lx) {
			new Thread(new LxDJNrThread(dbManager, handler, formlx)).start();
		} else {
			new Thread(new DownDJRun(formlx, handler)).start();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dj);
		if (SysData.url != null) {
			this.setTitle(SysData.no + "    " + SysData.url.substring(SysData.url.indexOf("//") + 2, 24));
		}
		focusEvent = new OnFocusChangeEvent();
		clickEvent = new OnClickEvent();
		imgClickEvent = new ImageClickListener(this);
		pzClickEvent = new PzClickListener(this);
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
		mxRefreshBut = (Button) findViewById(R.id.mxbut);
		pd = ProgressDialog.show(DjActivity.this, "正在查询单据菜单", "正在下载……");
		pd.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				if (m_view != null) {
					if (m_view instanceof SelfEditText) {
						((SelfEditText)m_view).selectAll();
					}
					m_view = null;
				}
			}
		});
		menuData = new ArrayList();
		if (SysData.is_lx) {
			dbManager = new DBManager(this);
			new Thread(new LxMenuQueryThread(dbManager, menuHandler, menuData)).start();
		} else {
			new Thread(menuRun).start();// 查询单据菜单
		}
		tabhost = getTabHost();
		tabhost.addTab(tabhost.newTabSpec("djmenu").setIndicator("菜单").setContent(R.id.djmenu));
		tabhost.addTab(tabhost.newTabSpec("hz").setIndicator("汇总").setContent(R.id.hz));
		tabhost.addTab(tabhost.newTabSpec("mx").setIndicator("明细").setContent(R.id.mx));
		TabWidget tabwidget = tabhost.getTabWidget();
		setTabwidgetAtt(tabwidget);
		Intent intent = getIntent();
		String displaymode = intent.getStringExtra("displaymode");
		islxscan = intent.getStringExtra("islxscan");
		if (displaymode.equals("grid")) {
			menuAdapter = new ImageAdpter(menuData, this);
			menuList = new GridView(this);
			GridView gv = (GridView) menuList;
			gv.setNumColumns(3);
			gv.setVerticalSpacing(20);
			((AdapterView) menuList).setAdapter(menuAdapter);
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			layoutParams.topMargin = 0;
			layoutParams.leftMargin = 0;
			((LinearLayout) findViewById(R.id.djmenu)).addView(menuList, layoutParams);
		} else {
			menuAdapter = new SimpleAdapter(this, menuData, R.layout.activity_menu, new String[] { "mname" }, new int[] { R.id.title });
			menuList = new ListView(this);
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			layoutParams.topMargin = 0;
			layoutParams.leftMargin = 0;
			((LinearLayout) findViewById(R.id.djmenu)).addView(menuList, layoutParams);
			((AdapterView) menuList).setAdapter(menuAdapter);
		}
		OnItemClickListener lis1 = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (formlx != null) {
					currentDjId = arg2;
					DialogUtil.builderCancel(DjActivity.this, "提示", "是否退出该单据", okClick);
				} else {
					currentDjId = arg2;
					openNewDj();
				}
			}
		};
		menuList.setOnItemClickListener(lis1);

		hzTab = (TabHost) findViewById(R.id.hz);
		hzTab.setup();
		mxTitle = (TextView) findViewById(R.id.mxtitle);
		mxList = (ListView) findViewById(R.id.mxlist);
		mxList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);// 一定要设置这个属性，否则ListView不会刷新
		mxList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
				cur_pos = position;// 更新当前行
				mxAdapter.cur_pos = cur_pos;
			}
		});

		tabhost.getTabWidget().getChildAt(2).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				((Button) findViewById(R.id.mxbut)).performClick();
				tabhost.setCurrentTab(2);
			}
		});

		tabhost.getTabWidget().getChildAt(1).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				tabhost.setCurrentTab(1);
				if (defaultFocus2 != null) {
					DjUtil.setFocus(hzTab, defaultFocus2);
				}
			}
		});

		phoneModel = android.os.Build.MODEL.toLowerCase();
		if (phoneModel.equals("zk-r322a") || phoneModel.equals("zk-r322")|| phoneModel.equals("zk-r323")|| phoneModel.equals("zk-r323a")) {
			zkr322aNew();
		}else if (phoneModel.equals("ht518")) {
			ht518InitNew();
		} else if (phoneModel.equals("al9")) {
			seuicIint();
		} else if ("cr-5w".equals(phoneModel)) {
			cr5wScanControl = new CR5WScanControl();
			cr5wScanControl.init(DjActivity.this);
		}  else if("android handheld terminal".equals(phoneModel)) {
			androidHandheldTerminal0 = new AndroidHandheldTerminal0(DjActivity.this);
		} else if ("nr510".equals(phoneModel) || "android".equals(phoneModel)) {
			nr510ScanControl = new Nr510ScanControl();
		} else if ("scanpal eda50".equals(phoneModel)) {
		        barcodeReader = MainActivity.getBarcodeObject();
	
		        if (barcodeReader != null) {
	
		            barcodeReader.addBarcodeListener(this);
	
		            try {
		                barcodeReader.setProperty(BarcodeReader.PROPERTY_TRIGGER_CONTROL_MODE,
		                        BarcodeReader.TRIGGER_CONTROL_MODE_CLIENT_CONTROL);
		            } catch (UnsupportedPropertyException e) {
		                Toast.makeText(this, "Failed to apply properties", Toast.LENGTH_SHORT).show();
		            }
		            // register trigger state change listener
		            barcodeReader.addTriggerListener(this);
	
		            Map<String, Object> properties = new HashMap<String, Object>();
		            // Set Symbologies On/Off
		            properties.put(BarcodeReader.PROPERTY_CODE_128_ENABLED, true);
		            properties.put(BarcodeReader.PROPERTY_GS1_128_ENABLED, true);
		            properties.put(BarcodeReader.PROPERTY_QR_CODE_ENABLED, true);
		            properties.put(BarcodeReader.PROPERTY_CODE_39_ENABLED, true);
		            properties.put(BarcodeReader.PROPERTY_DATAMATRIX_ENABLED, true);
		            properties.put(BarcodeReader.PROPERTY_UPC_A_ENABLE, true);
		            properties.put(BarcodeReader.PROPERTY_EAN_13_ENABLED, true);
		            properties.put(BarcodeReader.PROPERTY_AZTEC_ENABLED, true);
		            properties.put(BarcodeReader.PROPERTY_CODABAR_ENABLED, true);
		            properties.put(BarcodeReader.PROPERTY_INTERLEAVED_25_ENABLED, true);
		            properties.put(BarcodeReader.PROPERTY_PDF_417_ENABLED, true);
		            // Set Max Code 39 barcode length
		            properties.put(BarcodeReader.PROPERTY_CODE_39_MAXIMUM_LENGTH, 10);
		            // Turn on center decoding
		            properties.put(BarcodeReader.PROPERTY_CENTER_DECODE, true);
		            // Enable bad read response
		            properties.put(BarcodeReader.PROPERTY_NOTIFICATION_BAD_READ_ENABLED, false);
		            properties.put(BarcodeReader.PROPERTY_EAN_13_CHECK_DIGIT_TRANSMIT_ENABLED, true);
		            // Apply the settings
		            barcodeReader.setProperties(properties);
		        }
	            try {
	            	barcodeReader.claim();
	            } catch (ScannerUnavailableException e) {
	                e.printStackTrace();
	                Toast.makeText(this, "Scanner unavailable", Toast.LENGTH_SHORT).show();
	            }
		}
		acquireWakeLock();
		WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
		wifiLock = wifiManager.createWifiLock("crtechWIFI");
		wifiLock.acquire();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == MY_DATA_CHECK_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				tts = new TextToSpeech(this, this);
			} else {
				Intent installIntent = new Intent();
				installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);
			}
		} else if (requestCode == 1) {
			if (resultCode == 1) {
				Map map = (Map) data.getSerializableExtra("param");
				String speakFld = data.getSerializableExtra("audioFld").toString();
				if (tts != null) {
					play(map, speakFld);
				}
				DjUtil.setUiValue(hzTab, map, pageMap, imgHandler);
			}
		} else if (requestCode == 2) {
			if (resultCode == 2) {
				DjUtil.setUiValue(hzTab, (HashMap) data.getSerializableExtra("param"), pageMap, imgHandler);
				if (nextFocusTag != null) {
					setNextFocus(nextFocusTag);
					nextFocusTag = null;
				}
			}
		} else if (requestCode == 3) {
			if (resultCode == 3) {
				HashMap tempmap = (HashMap) data.getSerializableExtra("param");
				DjUtil.setUiValue(hzTab, tempmap, pageMap, imgHandler);
			}
		} else if (requestCode == 4) {
			View view = null;
			if (data != null) {
				String uiId = data.getExtras().getString("uiId");
				view = hzTab.findViewWithTag(uiId.toUpperCase());
				if (view != null && view instanceof EditText) {
					view.requestFocus();
					((EditText) view).setText(data.getExtras().getString("tm"));
				}
			}
			if (nextFocusTag != null) {
				if (view != null) {
					view.clearFocus();
				}
				setNextFocus(nextFocusTag);
				nextFocusTag = null;
			}
		}
		if (requestCode == 8888) {
			Bitmap bitmap = BitmapFactory.decodeFile(pzImgPath, null);
			photographUi.setImageBitmap(bitmap);
		}
	}

	public void setTabwidgetAtt(TabWidget tabwidget) {
		for (int i = 0; i < tabwidget.getChildCount(); i++) {
			// 设置页签高度和页签内字体属性
			TextView tv = (TextView) tabwidget.getChildAt(i).findViewById(android.R.id.title);
			tabwidget.getChildAt(i).getLayoutParams().height = UnitConversionUtil.convertDIP2PX(20.0);
			tv.setTextColor(Color.WHITE);
			tv.setGravity(Gravity.CENTER_HORIZONTAL);
		}
	}

	public void purview() {
		try {
			String url = SysData.url + "/webservice/ServiceInterface?wsdl";
			System.out.println(url);
			String method = "selectAndroidPurview";
			SoapObject rpc = new SoapObject("", method);
			rpc.addProperty("userid", SysData.userid);
			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 = Base64.decode(envelope.getResponse().toString());
				List list = (List) IoUtil.byte_obj(bb);
				menuData.addAll(list);
				Message message = new Message();
				menuHandler.sendMessage(message);
			}
		} catch (Exception e) {
			Message message = new Message();
			message.what = -1;
			message.obj = e.toString();
			menuHandler.sendMessage(message);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		System.out.println("onResume");
		if (cr5wScanControl != null)
			cr5wScanControl.start(DjActivity.this);
		else if (androidHandheldTerminal != null)
			androidHandheldTerminal.start();
		else if (nr510ScanControl != null)
			nr510ScanControl.start(DjActivity.this);
		else if (androidHandheldTerminal0 != null) {
			androidHandheldTerminal0.start();
		} else if (haixinN1SDemoReceiver != null) {
        	haixinN1sStart();
        }
		if (seuicScanner != null) {// seuic PDA操作
			boolean b = seuicScanner.open();
			System.out.println(b + "----seuicScanner.open()");
			seuicScanner.setDecodeInfoCallBack(this);
		}
        if (barcodeReader != null) {
        	continuousScanning(true);
        }
        if (zkr322aControl != null) {
        	zkr322aControl.start();
        }
        reReadCode = true;
	}

	@Override
	protected void onStart() {
		super.onStart();
		System.out.println("onStart");
		if (newScanControler != null) {
			newScanControler.scanOnce();
		}
		else if (seuicScanner != null) {
			seuicScanner.setDecodeInfoCallBack(this);
			seuicScanner.open();
		}
		else if (cr5wScanControl != null)
			cr5wScanControl.start(DjActivity.this);
		else if (nr510ScanControl != null)
			nr510ScanControl.start(DjActivity.this);
		else if (androidHandheldTerminal != null)
			androidHandheldTerminal.start();
		else if (barcodeReader != null)
			continuousScanning(true);
		else if (haixinN1SDemoReceiver != null) {
        	haixinN1sStart();
        }
        if (zkr322aControl != null) {
        	zkr322aControl.start();
        }
        reReadCode = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (newScanControler != null) {
			newScanControler.stopScan();
		}
		else if (cr5wScanControl != null)
			cr5wScanControl.stop(DjActivity.this);
		else if (nr510ScanControl != null)
			nr510ScanControl.stop(DjActivity.this);
		else if (androidHandheldTerminal != null)
			androidHandheldTerminal.stop();
		else if (androidHandheldTerminal0 != null) {
			androidHandheldTerminal0.stop();
		} else if (haixinN1SDemoReceiver != null) {
        	haixinN1sStop();
        }
		System.out.println("onPause");
		if (seuicScanner != null) {// seuic PDA操作
			System.out.println("seuicScanner.close");
			seuicScanner.stopScan();
			seuicScanner.close();
			seuicScanner.setDecodeCallBack(null);
		}
        if (barcodeReader != null) {
        	continuousScanning(false);
        }
        if (zkr322aControl != null) {
        	zkr322aControl.stop();
        }
	}

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

	public void onDestroy() {
		super.onDestroy();
        if (barcodeReader != null) {
        	barcodeReader.release();
           barcodeReader.removeBarcodeListener(this);

           barcodeReader.removeTriggerListener(this);
           barcodeReader = null;
        }
		
		if (diPlayer != null) {
			diPlayer.stop();
			diPlayer.release();
			diPlayer = null;
		}
		if (duPlayer != null) {
			duPlayer.stop();
			duPlayer.release();
			duPlayer = null;
		}
		if (vibrator != null) {
			vibrator.cancel();
		}
		completionListener = null;
	}

	private void exitClear() {
		if (dbManager != null) {
			dbManager.closeDB();
			dbManager = null;
		}
		if (djInitMap != null) {
			djInitMap.clear();
			djInitMap = null;
		}
		fangAMap.clear();
		fangAMap = null;
		pageMap.clear();
		pageMap = null;
		if (menuList != null) {
			menuList = null;
		}
		if (menuAdapter != null) {
			menuAdapter = null;
		}
		if (menuData != null) {
			menuData.clear();
			menuData = null;
		}
		if (menuAdapter != null) {
			menuAdapter = null;
		}
		if (mxList != null) {
			mxList = null;
		}
		mxData.clear();
		mxData = null;
		if (mxAdapter != null) {
			mxAdapter.clear();
			mxAdapter = null;
		}
		releaseWakeLock();
		linghtScreen = null;
		wifiLock.release();
		wifiLock = null;
		if (pm != null) {
			pm = null;
		}
		if (tts != null) {
			tts.shutdown();
		}
		if (phoneModel.equals("ht518")) {
			ht518Clear();
		}
		if (zkr322aControl != null) {
			zkr322aClear();
		}
	}

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

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId())// 得到被点击的item的itemId
		{
		case R.id.updatePwd: // 对应的ID就是在add方法中所设定的Id
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), UpdatePwdActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
		return true;
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (!isKeyDown) {
			isKeyDown = true;
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		super.onKeyDown(keyCode, event);
		String temp = String.valueOf(keyCode);
		if (temp.equals("132")) {// ht518专用
			event.startTracking();// 加了这句 键盘长按事件才有效
			return true;
		}
		if (seuicScanner != null && temp.equals("0") && isKeyDown) {
			seuicScanner.startScan();
			isKeyDown = false;
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private boolean isCurrentFocus_EditText() {// 判断当前焦点组件是否是输入框
		View view = DjActivity.this.getCurrentFocus();
		if (view != null && view instanceof EditText) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int keyCode = event.getKeyCode();
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (keyCode) {
			case 120:
				break;
			case 211:
				break;
			case 212:
				break;
			case 113:
				View view = DjActivity.this.getCurrentFocus();
				if (view != null && view instanceof EditText) {
					setFcous(view);
				}
				break;
			case KeyEvent.KEYCODE_BACK:
				dialog();
				break;
			case KeyEvent.KEYCODE_ENTER:
				View view1 = DjActivity.this.getCurrentFocus();
				if (view1 != null && view1 instanceof EditText) {
					setFcous(view1);
				}
				break;
			case 132:
				if (newScanControler != null) {
					newScanControler.scanOnce();
				}
				break;
			case 510:
				if (nr510ScanControl != null) {
					nr510ScanControl.start(DjActivity.this);
				}
				break;
			default:
				return super.dispatchKeyEvent(event);
			}
		} else if (event.getAction() == KeyEvent.ACTION_UP) {
			if (keyCode == 120 || keyCode == 211 || keyCode == 212) {
			} else if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { // 阻止系统的enter事件
				return true;
			}
		}
		return super.dispatchKeyEvent(event);
	}

	public boolean onKeyLongPress(int keyCode, KeyEvent event) {
		super.onKeyLongPress(keyCode, event);
		String temp = String.valueOf(keyCode);
		if (temp.equals("132")) {
		}
		return true;
	}

	protected void dialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(DjActivity.this);
		builder.setMessage("确定要退出吗?");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (pageMap.containsKey("GZID")) {
					new ExitThread(pageMap.get("GZID"), mxTempTable, null, "clearDj").start();
				}
				dialog.cancel();
				DjActivity.this.finish();
				exitClear();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		builder.create().show();
	}

	class OnFocusChangeEvent implements View.OnFocusChangeListener {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			if (hasFocus) {
				if (v instanceof SelfEditText) {
					SelfEditText focusInSet = (SelfEditText) v;
					if (focusInSet.closeKeyBoard) {
						InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(focusInSet.getWindowToken(), 0);
					}
					if (focusInSet.isTextChange) {
						focusInSet.isTextChange = false;
					}
					focusInSet.selectAll();
					eventHandler(focusInSet.focusInFun, v);
				}
			} else {
				if (v instanceof SelfEditText) {
					SelfEditText set = (SelfEditText) v;
					if (set.isTextChange) {
						nextFocusTag = set.nextFocus;
						eventHandler(((SelfEditText) v).focusOutFun, v);
					}
				}
			}
		}
	}

	class OnClickEvent implements OnClickListener {

		@Override
		public void onClick(View v) {
			View view = DjActivity.this.getCurrentFocus();
			if (view instanceof SelfEditText) {
				if (((SelfEditText) view).isTextChange) {
					DjActivity.this.hzTab.requestFocus();
					return;
				}
			}
			SelfButton selfBut = (SelfButton) v;
			nextFocusTag = selfBut.nextFocus;
			eventHandler(selfBut.clickFun, null);
		}

	}

	public void openRunWin() {
		DialogUtil.builder(DjActivity.this, "提示信息", "PDA不兼容", 0);
	}

	public void eventHandler(String funName, View view) {
		if (!SysData.isreg.equals("Y")) {
			openRunWin();
		}
		if (funName == null) {
			return;
		}
		funName = funName.trim();
		if (funName.length() < 1) {
			return;
		}
		String funType = "";
		if (funName.indexOf("_") > -1) {
			funType = funName.substring(0, funName.indexOf("_")).toUpperCase();
		}
		HashMap faMap = (HashMap) fangAMap.get(funName.toUpperCase());
		if (faMap == null && (funType.equals("SEARCH") || funType.equals("YMUP") || funType.equals("DJTQ"))) {
			DialogUtil.builder(DjActivity.this, "错误信息", "方案不存在!", 0);
			return;
		}
		if (funType.equals("SEARCH")) {// 检索方案函数
			if (cr5wScanControl != null)
				cr5wScanControl.stop(DjActivity.this);
			else if (androidHandheldTerminal != null)
				androidHandheldTerminal.stop();
			else if (nr510ScanControl != null)
				nr510ScanControl.stop(DjActivity.this);
			else if (haixinN1SDemoReceiver != null) {
	        	haixinN1sStop();
	        }
	        if (barcodeReader != null) {
	        }
	        if (zkr322aControl != null) {
	        	zkr322aControl.stop();
	        }
			DialogUtil.setDialog(pd, "检索方案", "正在执行检索方案……");
			Map map = SqlUtil.regSql(faMap.get("zdysql").toString(), hzTab, pageMap);
			String audioFld = "";
			if (faMap.get("audioFld") != null) {
				audioFld = faMap.get("audioFld").toString().toUpperCase();
			}
			runSearch(map, faMap.get("return_one").toString(), audioFld);
		} else if (funType.equals("YMUP")) {// 页面修改函数
			if (cr5wScanControl != null)
				cr5wScanControl.stop(DjActivity.this);
			else if (nr510ScanControl != null)
				nr510ScanControl.stop(DjActivity.this);
			else if (androidHandheldTerminal != null)
				androidHandheldTerminal.stop();
			else if (haixinN1SDemoReceiver != null) {
	        	haixinN1sStop();
	        }
	        if (barcodeReader != null) {
	        }
	        if (zkr322aControl != null) {
	        	zkr322aControl.stop();
	        }
			DialogUtil.setDialog(pd, "页面修改方案", "正在执行页面修改方案");
			Map map = SqlUtil.regSql(faMap.get("zdysql").toString(), hzTab, pageMap);
			map.put("gzid", pageMap.get("GZID"));
			map.put("mxTempTable", mxTempTable);
			Map hzData = DjUtil.organizationHzData(hzTab, pageMap.get("GZID"));
			((HashMap) hzData.get("hzData")).putAll(pageMap);
			map.put("hzData", hzData);
			try {
				if (!SysData.is_lx) {
					byte[] b = IoUtil.getbyte(map);
					String paramString = Base64.encode(b);
					runYmup(paramString);
				} else {
					new Thread(new LxRunYmupThread(dbManager, faMap.get("zdysql").toString(), (Map) hzData.get("hzData"), runHandler)).start();
				}
			} catch (Exception e) {
				pd.cancel();
				DialogUtil.builder(DjActivity.this, "错误信息", "页面修改方案组织数据失败!", 0);
			}
		} else if (funType.equals("DJTQ")) {
			DialogUtil.setDialog(pd, "提取方案", "加载提取方案函数……");
			Djselefa djselefa = new Djselefa();
			djselefa.setT_sql(faMap.get("t_sql").toString());
			djselefa.setHz_sql(faMap.get("hz_sql").toString());
			djselefa.setMx_sql(faMap.get("mx_sql").toString());
			djselefa.setFangamch(faMap.get("fangamch").toString());
			HashMap map = SqlUtil.regSql(djselefa.getT_sql(), hzTab, pageMap);
			pd.cancel();
			Intent intent = new Intent();
			djselefa.setT_sql(map.get("sql").toString());
			HashMap paramMap = new HashMap();
			paramMap.put("djselefa", djselefa);
			paramMap.put("t_sqlParam", (HashMap) map.get("param"));
			paramMap.put("mxTempTable", mxTempTable);
			paramMap.put("GZID", pageMap.get("GZID"));
			intent.putExtra("paramMap", paramMap);
			intent.setClass(getApplicationContext(), DjtqActivity.class);
			startActivityForResult(intent, 2);
		} else {
			DjMenuFun menufun = new DjMenuFun();
			Class cla = menufun.getClass();
			Method method = null;
			try {
				if (funName.substring(0, 1).equals("M")) {
					method = cla.getDeclaredMethod(funName, DjActivity.class);
					method.invoke(menufun, DjActivity.this);
				} else if (funName.substring(0, 4).toUpperCase().equals("SCAN")) {
					method = cla.getDeclaredMethod(funName.substring(0, 4), DjActivity.class, String.class);
					method.invoke(menufun, DjActivity.this, funName);
				} else {
					method = cla.getDeclaredMethod(funName);
					if (method != null && view instanceof EditText) {
						((EditText) view).setText(method.invoke(menufun).toString());
					}
				}
			} catch (Exception e) {
				DialogUtil.builder(DjActivity.this, "系统错误", "生成函数失败", 0);
				e.printStackTrace();
			}
		}
	}

	/* 运行检索方案 */
	public void runSearch(Map map, String return_one, String audioFld) {
		try {
			new RunSearchThread(map.get("sql").toString(), IoUtil.ob_base64(map.get("param")), runHandler, return_one, audioFld).start();
		} catch (IOException e) {
			DialogUtil.builder(this, "错误信息", "转换成Base64编码失败！", 0);
		}
	}

	/* 运行页面修改过方案 */
	public void runYmup(String param) {
		new RunYmupThread(param, runHandler, "runYmup", 0).start();
	}

	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {
			tts.setLanguage(Locale.CHINA);
		}

		else if (status == TextToSpeech.ERROR) {
			Toast.makeText(DjActivity.this, "始化文本到语音引擎时发生错误", Toast.LENGTH_LONG).show();
		}
	}

	public void play(Map map, String speakFld) {
		if (map.containsKey(speakFld)) {
			String speakNr = map.get(speakFld).toString();
			int isZd = 0;
			if (speakNr.indexOf("退药") > -1 || speakNr.indexOf("批次错误") > -1) {
				if (diPlayer == null) {
					diPlayer = MediaPlayer.create(this, R.raw.didi);
					diPlayer.setOnCompletionListener(completionListener);
				}
				ttsNr = map.get(speakFld).toString();
				diPlayer.start();
			} else if (speakNr.indexOf("错误") > -1) {
				if (duPlayer == null) {
					duPlayer = MediaPlayer.create(this, R.raw.dudu);
					duPlayer.setOnCompletionListener(completionListener);
				}
				ttsNr = map.get(speakFld).toString();
				duPlayer.start();
			} else {
				isZd = 1;
				if (tts != null) {
					tts.speak(map.get(speakFld).toString(), TextToSpeech.QUEUE_ADD, null);
				}
			}
			if (isZd == 0) {
				if (vibrator == null) {
					vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				}
				vibrator.vibrate(2000);
			}
		}

	}

	private void setFcous(View view) {
		((EditText) view).clearFocus();
		setNextFocus(((SelfEditText) view).nextFocus);
	}

	private void setNextFocus(String focusName) {
		View nextView = hzTab.findViewWithTag(focusName);
		if (nextView != null) {
			nextView.requestFocus();
		}
	}

	private void zyFcous(String tiaoma) {
		if (!reReadCode) {
			return;
		}
		View view = DjActivity.this.getCurrentFocus();
		if (view != null && view instanceof EditText) {
			reReadCode = false;
			((EditText) view).setText(tiaoma);
			setFcous(view);
		}
	}

	@SuppressLint("InvalidWakeLockTag")
	public void acquireWakeLock() {
		if (pm == null) {
			pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		}
		if (wakeLock == null) {
			wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "crtech");
		}
		if (linghtScreen == null) {
			linghtScreen = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
		}
		if (wakeLock != null) {
			wakeLock.acquire();
		}
	}

	// 释放设备电源锁
	public void releaseWakeLock() {
		if (wakeLock != null) {
			wakeLock.release();
			wakeLock = null;
		}
	}

	public void releaseLinghtScreen() {
		if (isLinghtScreen) {
			isLinghtScreen = false;
			linghtScreen.release();
		}
	}

	// 富力叶 android handheld terminal 扫描头
	AndroidHandheldTerminal0 androidHandheldTerminal0 = null;
	public class AndroidHandheldTerminal0 {
		public boolean running = true;
		public AndroidHandheldTerminal0(final Context context) {
			ScanHelper.setScanSwitchLeft(context, true);
			ScanHelper.setScanSwitchRight(context, true);
			ScanHelper.setBarcodeReceiveModel(context, 2);	
			m_Broadcastname = "com.barcode.sendBroadcast";
			final IntentFilter intentFilter = new IntentFilter();
			intentFilter.addAction(m_Broadcastname);
			registerReceiver(myCodeReceiver, intentFilter);
		}
		
		
		public void start() {
			running = true;
		}
		
		public void stop() {
			running = false;
		}
	}
	
	private String m_Broadcastname = null;
	private MyCodeReceiver myCodeReceiver = new MyCodeReceiver();
	public class MyCodeReceiver extends BroadcastReceiver 
	{
		private static final String TAG = "MycodeReceiver";
		@Override
		public void onReceive(Context context, Intent intent) {
			if(androidHandheldTerminal0.running && intent.getAction().equals(m_Broadcastname)) {
				String str = intent.getStringExtra("BARCODE");
					if (!"".equals(str)) {
						View rootview = DjActivity.this.getWindow().getDecorView();
						View aaa = rootview.findFocus();
						if (aaa instanceof SelfEditText) {
							SelfEditText set = (SelfEditText)aaa;
							set.setText(str);
		    				new Thread(new Runnable() {
								
								@Override
								public void run() {
				                    Instrumentation inst = new Instrumentation();
				                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);  
								}
							}).start();
						}
					}
			}
		}
	}


	// 海信 n1s 设备扫描头控制
	public static final String HAIXIN_N1S_ACTION_SCAN_RESULT = "android.provider.sdlMessage";
	public static boolean haixinN1SStart = false;
	
	 private static IntentFilter haixinN1SMakeDemoIntentFilter() {
	        final IntentFilter intentFilter = new IntentFilter();
	        intentFilter.addAction(HAIXIN_N1S_ACTION_SCAN_RESULT);
	        return intentFilter;
	}
	 
	 private BroadcastReceiver haixinN1SDemoReceiver = null;
	   
	   public void haixinN1SInit() {
		   haixinN1SDemoReceiver = new BroadcastReceiver() {
		        @Override
		        public void onReceive(Context context, Intent intent) {
		        	//
		            final String action = intent.getAction();
		            if (HAIXIN_N1S_ACTION_SCAN_RESULT.equals(action)) {
		            	final String scanResultStr = intent.getStringExtra("msg");
		            	
		            	if (scanResultStr != null && scanResultStr.trim().length() > 0) {
							handler.post(new Runnable() {
								public void run() {
									View rootview = DjActivity.this.getWindow().getDecorView();
									View aaa = rootview.findFocus();
									if (aaa instanceof SelfEditText) {
										SelfEditText set = (SelfEditText)aaa;
										set.setText(scanResultStr);
										//
					    				new Thread(new Runnable() {
											
											@Override
											public void run() {
							                    Instrumentation inst = new Instrumentation();
							                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);
											}
										}).start();
									}
								}
							});
		            	}
		            }
		            //
		        }
		   };   
	   }
	   
	   public void haixinN1sStart() {
		   if (!haixinN1SStart) {
			   haixinN1SStart = true;
			   registerReceiver(haixinN1SDemoReceiver, haixinN1SMakeDemoIntentFilter());
		   }
	   }
	   
	   public void haixinN1sStop() {
		   if (haixinN1SStart) {
			   haixinN1SStart = false;
			   unregisterReceiver(haixinN1SDemoReceiver);
		   }
	   }
	   

	// 富力叶 android handheld terminal 扫描头
	public static AndroidHandheldTerminal androidHandheldTerminal = null;

	public class AndroidHandheldTerminal {

		public void start() {
		}

		public void stop() {
		}

		public void restart() {
			stop();
			start();
		}
	}

	/**
	 * zkr322a 大屏 工业一体机
	 */
	private boolean zkr322aIsReciverThread = true;
	private Thread zkr322aReciverThread = null;
	private ZKR322AControl  zkr322aControl = null;
	private Handler zkr322aHandler = new Handler() {
		@Override
		// 当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg) {
			zyFcous(msg.obj.toString());
		}
	};

	private void zkr322aNew() {
		try {
			zkr322aControl = new ZKR322AControl();
			zkr322aControl.initScan();
			zkr322aReciverThread = new Thread(zkr322aReciverDataRunable);
			zkr322aReciverThread.start();
		} catch (Exception e) {
			DialogUtil.builder(DjActivity.this, "错误信息", "[ZKR322A]初始化失败:" + e.getMessage(), 0);
		}
	}
	
	public void zkr322aClear() {
		zkr322aIsReciverThread = false;
		zkr322aReciverThread = null;
		zkr322aControl.stop();
		zkr322aControl.close();
		zkr322aControl = null;
		zkr322aHandler = null;
	}

	Runnable zkr322aReciverDataRunable = new Runnable() {
		@Override
		public void run() {
			while (zkr322aIsReciverThread && zkr322aControl != null) {
				String msg = zkr322aControl.getData();
				if (msg != null && msg.length() > 0) {
					Message message = new Message();
					message.obj = msg;
					zkr322aHandler.sendMessage(message);
				}
			}

		}
	};
	/**
	 * cr5w 设备扫描头控制
	 * */
	public static CR5WScanControl cr5wScanControl = null;
	
	/**
	 * 联新 nr510 控制
	 */
	public static  Nr510ScanControl nr510ScanControl = null;
	
	public class Nr510ScanControl extends BroadcastReceiver {
		private boolean usecloseState = true;
		private Engine engine = new Engine();
		private boolean islxScan = false;
		
		public Nr510ScanControl() {
			Intent intent = getIntent();
			String checkBox = intent.getStringExtra("islxscan");
			islxScan = "0".equals(checkBox) ? true : false;
		}
		
		public void start(Context context) {
			if (usecloseState) {
				usecloseState = false;
				if (islxScan)
					engine.start(context);
				IntentFilter filter = new IntentFilter();
				filter.addAction("lachesis_barcode_value_notice_broadcast");
				registerReceiver(this, filter);
			}
		}
		
		public void stop(Context context) {
			if (!usecloseState) {
				unregisterReceiver(this);
				if (islxScan)
					engine.stop(context);
				usecloseState = true;
			}
		}
		
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			final String value = arg1
					.getStringExtra("lachesis_barcode_value_notice_broadcast_data_string");
			if (value.length() > 10) {
				handler.post(new Runnable() {
					public void run() {
						View rootview = DjActivity.this.getWindow().getDecorView();
						View aaa = rootview.findFocus();
						if (aaa instanceof SelfEditText) {
							SelfEditText set = (SelfEditText)aaa;
							if (set.closeKeyBoard) {
								set.setText(value);
								set.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
								set.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)); 
							}
						}
					}
				});
			}
		}
	}
	
	/**
	 * Honeywell 设备扫描头控制
	 */
	public static BarcodeReader barcodeReader = null;
	/*
	 * ht518初始化(带新版扫描头) 包括android_serialport_api包和android.gpio包
	 * 和com.jiebao.h518.scan.NewScanControler类
	 */
	private NewScanControler newScanControler;
	private Thread reciverThread;
	private boolean isReciverThread = true;
	private BeepManager bManager;
	private Handler ht518handler = new Handler() {
		@Override
		// 当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg) {
			bManager.playBeepSoundAndVibrate();
			zyFcous(msg.obj.toString());
			newScanControler.stopScan();
		}
	};

	public void ht518Clear() {
		isReciverThread = false;
		reciverThread = null;
		newScanControler.stopScan();
		newScanControler.close();
		newScanControler = null;
		ht518handler = null;
		bManager.release();
	}

	private void ht518InitNew() {
		try {
			newScanControler = new NewScanControler();
			newScanControler.initScan();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		reciverThread = new Thread(ReciverDataRunable);
		reciverThread.start();
		bManager = new BeepManager(this);
	}

	Runnable ReciverDataRunable = new Runnable() {
		@Override
		public void run() {
			while (isReciverThread) {
				String msg = newScanControler.getData();
				if (msg != null && msg.length() > 0) {
					Message message = new Message();
					message.obj = msg;
					ht518handler.sendMessage(message);
				}
			}

		}
	};

	/*
	 * seuic PDA
	 */
	private com.seuic.scanner.Scanner seuicScanner;
	private SoundPool soundpool = null;
	private int soundid;
	private boolean isKeyDown = true;
	private String islxscan;

	private SeuicScanKeyEventRunnable seuicScannerThread;

	public void seuicIint() {
		soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
		soundid = soundpool.load(this, R.raw.beep, 1);
		if (seuicScanner == null) {
			seuicScanner = ScannerFactory.getScanner(DjActivity.this);
		}
		ScannerKey.close();
		seuicScannerThread = new SeuicScanKeyEventRunnable(seuicScanner);
		new Thread(seuicScannerThread).start();
	}

	@Override
	public void onDecodeComplete(DecodeInfo info) {
		if (!SysData.isreg.equals("Y")) {
			openRunWin();
		}
		soundpool.play(soundid, 1, 1, 0, 0, 1);
		zyFcous(info.barcode);
	}

	@Override
	public void onTriggerEvent(TriggerStateChangeEvent event) {
	}

	@Override
	public void onBarcodeEvent(BarcodeReadEvent event) {

		final BarcodeReadEvent event2 = event;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            	if (barcodeReader == null) return;
    			View rootview = DjActivity.this.getWindow().getDecorView();
    			if (rootview != null) {
	    			View aaa = rootview.findFocus();
	    			if (aaa != null && aaa instanceof SelfEditText) {
	    				final SelfEditText set = (SelfEditText)aaa;
	    				set.setText(event2.getBarcodeData());
	    				new Thread(new Runnable() {
							
							@Override
							public void run() {
			                    Instrumentation inst = new Instrumentation();
			                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);  
							}
						}).start();
	    			} else {
	    			}
    			} else {
    			}
    			continuousScanning(true);
            }
        });
	}
	
    public void continuousScanning(final boolean bState){

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
		        try {
		            barcodeReader.light(bState);      //turn on/off backlight
		            barcodeReader.aim(bState);		//开关瞄准线
		            barcodeReader.decode(bState);	    //开关解码功能
		        } catch (ScannerUnavailableException e) {
		            e.printStackTrace();
		        } catch (ScannerNotClaimedException e) {
		            e.printStackTrace();
		        }
            }
        }).start();
    }

	@Override
	public void onFailureEvent(BarcodeFailureEvent arg0) {
	}

}
