package com.cwbuyer.main;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.cwbuyer.format.EMode;
import com.cwbuyer.format.IDateDialog;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.PItemData;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DBUtil;
import com.cwbuyer.lib.DateUtil;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.GalleryViewO;
import com.cwbuyer.lib.GalleryViewP;
import com.cwbuyer.lib.GalleryViewS;
import com.cwbuyer.lib.PosUtilis;
import com.cwbuyer.lib.QHis;
import com.cwbuyer.lib.QPosSave;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.lib.QPosSave.PsaveWhere;
import com.cwbuyer.main.QCustff.QCustfMode;
import com.cwbuyer.main.QPosff.GroupMode;
import com.pwbuyer.main.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

@SuppressLint({ "DefaultLocale", "HandlerLeak" })
@SuppressWarnings("unused")
	public class APos extends Activity{
	
		private ListView mListView = null;		
		private PItemAdapter mAdapter = null;
			
		public interface PItemMode{
			public int ADD = 0;
			public int EDIT = 1;
			public int SEARCH =2;
		}
		public interface PItemKind{
			public int TR10 = 10;	//進貨單
			public int TR20 = 20;	//門市出貨單
			public int TR21 = 21;	//門市出貨單			
			public int TR30 =30;	//會員銷貨單  
			public int TR31 =31;	//門市銷貨單
			public int TR40 =40;	//員工自購
			public int TR41 =41;	//員工自購
			public int TR50 =50;	//專櫃出貨單			
		}
		public interface PItemWhere{  //未來擴充 廠商進貨單維護,門市出貨單 櫃員自購單 專櫃出貨單 
			public int Qposf = 0;  //銷貨總表單
			public int  Qcust= 1;  //會員檔
			public int DataManage=2;

		}
		//交易價別方式 千萬不可以在第一時間就以 getResources().getText(R.string.str.....)方式帶入
		private final String[] tradeStr =Utilis.getIni(this,"SYS","TRADENAME",9).split("!&!");
		private final String[] Ps1Str =Utilis.getIni(this,"QRP","6X3QR",9).split("!&!");
		private final String[] backout =Utilis.getIni(this,"SYS","BACKOUT",9).split("!&!");
		private final String [] DISC  =Utilis.getIni(APos.this, "QRP", "5X2QR", 9).split("!&!");
		private String[] deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");
		private final String[] importStr =Utilis.getIni(this,"SYS", "IMPORT",9).split("!&!");

		//private int PSWD=0;
		private String mBankn="";
		
		private final int RESULT_QFACT = 1020;		//廠商檔回傳口令
		private final int RESULT_QCUSTFF = 9999;		//會員檔回傳口令
		private final int RESULT_QEMPFF = 8888;		//交易員檔回傳口令
		private final int RESULT_QDEPTNO = 7777;  //門市檔回傳口令
		private final int RESULT_GALLERY=6666; 		//GALLERY 
		private final int RESULT_GALLERYO=5566; 		//GALLERY 
		private final int RESULT_QPOSAVE=5555; 		//GALLERY
		private final int RESULT_INCOME=1005; 		//INCOME 備用	
		private final int RESULT_QHIS=1009; 		//INCOME 備用	
		protected static final int REFRESH_DATA = 0x00000001;
		
		public final String[] pKind=Utilis.getIni(this,"SYS","PKIND",9).split("!&!");
		String[] menu_ok={ "追蹤","返回" };
		//String[] menu_E={ "單筆編輯", " 總編輯","單筆刪除","本款刪除","預購品查詢","商品追蹤","保留","保留","補印單據","返回" };
		String[] menu_30={ "本款編輯", "總編輯","單筆刪除","本款刪除","本單轉預購","本單轉留貨","補印單據","追蹤","單筆轉預購","單筆轉留貨","返回" };
		String[] menu_X={ "本款編輯", "總編輯","單筆刪除","本款刪除","本單轉預購","本單轉留貨","補印單據","追蹤","單筆轉預購","單筆轉留貨","返回" };

		private  int mMode = PItemMode.ADD;  //預設為 ADD		
		private int mWhere=PItemWhere.Qposf;  //預設來自銷貨流覽主程式
		private String edInput=null;
		private String Firstgood="";
		private int nPart=0; //0總店 1分店 
		//判斷 段 & 件
	    int f123=0;  //0整數 1.小數點
		double counts=0;
		int nUnit=0;
		int isUnit=0;
		int isOver=0;
		int chkChang=0;
		//供歷史價專用
		private double hisDiscount=100;
		private double hisUnitprice=0;
		private double hisP0=0;
		boolean bQHIS=false;
		private static String CTIME=DateUtil.getSystemTime().substring(2,14);
		
		//恆用的變數 除非會員/員工/門市
		private String msCust=null;
		private String cust_no=null; //只是進入QCUSTFF帶回的值,不一定是會員
		private static int myKind=PItemKind.TR30;  //預設為會員銷貨
		private static String msKind=""+myKind;  //預設為會員銷貨
		private String msFno=null;  //本單單號
		private String msFD=Utilis.getIni(this,"SYS","DEV",8);  //開單日期
		private int mFD=0;
		private int msTrade=5;
		String aInput="";
		String edPs="";
		int selectM=Utilis.toInt(Utilis.getIni(APos.this,"SYS","DATA_SEND",7));
		
		int selectP=0;
		String mDept=null;
		String aDept=deptStr[0];
		String rDept=deptStr[0];
		int mGroup = 0; //預設暫存單		
		
		private int mRestoreChoice = 0;
		String[] NNlist;		
		//BTN_使用的變數
		private int PlusMinus=1;//進/退
		private int nSingle=Utilis.toInt(Utilis.getIni(this,"INIH","SW_UNIT",myKind/10));  //1表單量 0表大宗
		private int nHintDisc=Utilis.toInt(Utilis.getIni(APos.this,"SYS","DEPT_SEND",5));  //1不隱藏 0表隱藏
//		public int nSingleAuto=1;  //表單量自動
		private int nQhis=0; //標準價 =1.歷史價
		
		//0歷史價 1.歷史價取其小 2.標準價(隱藏) 4啟動批發對照表 5啟動零售對照表
		private int sQhis=Utilis.toInt(backout[8]);
		//if (((sQhis==4 && msTrade==3) || (sQhis==5 && msTrade==5))  && myKind==31){
		
		private String fQhis="1"; //會員指定: 1.標準價 0.歷史價
		//注意相反 fQhis nQhis
		
		private int mYear = 0;
		private int mMonth = 0;
		private int mDay = 0;
		
		final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);
		int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
		
		private PItemData data = new PItemData(); //##格式化需考量內容增刪
		private PItemData dataO = new PItemData(); //##格式化需考量內容增刪
		private PItemData datax = new PItemData(); //##格式化需考量內容增刪
		
		EditText pInput;
		
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent dataR) {
			// TODO Auto-generated method stub
			super.onActivityResult(requestCode, resultCode, dataR);
			
		switch (requestCode){
			case RESULT_QPOSAVE:  //結帳返回的各種可能性
			{	
				if (resultCode == RESULT_OK) {
					if (dataR.getIntExtra("QPosSave_modify",0)==1){
						if (mMode==PItemMode.ADD){
							//紀錄 櫃員/單量大宗/  Utilis.getIni(this,"INIH","EMPID",(myKind/10))
							Utilis.putIni(this, "INIH", "EMPID", datax.mEmpid, (myKind/10));
							Utilis.putIni(this, "INIH", "EMPNAME", datax.mEmpname, (myKind/10));
						}
						
						mMode = PItemMode.ADD;
			        	iniHead();  	//一張新的單據
			        	iniItems();	//一筆新的商品
			        	mAdapter.getData(APos.this,msFno);
			        	
						if (Utilis.haveInternet(APos.this) && of_line==1 ) {
							DBCloud.aa1_aa0_update_HI(APos.this);
						}
					}
				}
				break;
			}	
			case RESULT_QCUSTFF:
			{
			if (resultCode == RESULT_OK) {				
				cust_no=dataR.getStringExtra("qcust_key");
    			//檢查mMode== 查詢2 不進一步處理  
    			//新增或編輯==0.1 是可以將原有的ITEM 及HEAD 全部改為新的會員資訊
    			//對話框尋問YN 當ITEMS>0時,表示有資料
				if (!msCust.equalsIgnoreCase(cust_no)){	
					if (datax.dAtot>0 && mMode!=PItemMode.SEARCH) { 
						//有異動非查詢且已輸入商品時
						//不考慮預購留貨轉銷貨影響
					
			   			 String[] dlgMenu=  { "變更交易對象" ,"放棄變更"  };
			   	        new AlertDialog.Builder(APos.this)
			   	        .setTitle("是否變更交易對象成為"+cust_no+"?")
			   	        .setItems(dlgMenu, mListener1)
			   	        .setPositiveButton(R.string.str_cancel,
			   	        new DialogInterface.OnClickListener()
			   	        {
			   	          public void onClick(DialogInterface dialog, int which)
			   	          {
			   	        	 switch (which) {
			   	        	  case 0:  //變更交易對象
			   	        		updateDBHI(APos.this, cust_no, msFno, msKind, 0);
			   	        	 }	  
			   	          }
			   	        }).show();	
	    				
					}else {//可以直接變更,注意事項:USERNO NAME TRADETYPE OUNT
						//但是擔心的是 datax.dAtot==0 流水號有可能被占用
						if (mMode==PItemMode.ADD){
							//新增交易時,先檢查有否暫存單存在,並詢問開啟暫存單,或續開新單
							//checkNN();
							NNlist=getNNList(cust_no);
							if (NNlist !=null && NNlist.length>0){
								//顯示對話框
								String msgTitle="請選擇"+cust_no+"_暫存單清冊,或開新單";
								AlertDialog.Builder sortDlg = new AlertDialog.Builder(APos.this);
						        sortDlg.setTitle(msgTitle)
						        .setSingleChoiceItems(NNlist, 0, new DialogInterface.OnClickListener() {
						            public void onClick(DialogInterface dialog, int item) {
						            	mRestoreChoice = item;
						            }
						        }) 
						        .setPositiveButton("開啟暫存單", new DialogInterface.OnClickListener() {
						            public void onClick(DialogInterface dialog, int which) { //確認
						            	String path = NNlist[mRestoreChoice];  //日期,單號
						            	msFno = path.substring(path.lastIndexOf(",")+1);
						            	mAdapter.getData(APos.this,msFno);
						            }
						          })
						        .setNegativeButton("續開新單", new DialogInterface.OnClickListener() {
						            public void onClick(DialogInterface dialog, int which) { //取消
					   	        		updateDBHI(APos.this, cust_no, msFno, msKind, 0);
						            }
						          }).show();
								
							}else{
								updateDBHI(APos.this, cust_no, msFno, msKind, 0);
							}
						}else if (mMode!=PItemMode.SEARCH){
		   	        		updateDBHI(APos.this, cust_no, msFno, msKind, 0);
						}
					}
				}else if (mMode==PItemMode.ADD && datax.dAtot==0){
					//既有的新單 又尚未交易 可能被 留貨轉銷貨 佔用了 單號
					//所以需要再 重新取得單號
					
				}
			}	
				break;
			}
			case RESULT_QEMPFF:
			{

				if (resultCode == RESULT_OK) {				
					cust_no=dataR.getStringExtra("qcust_key");
					if (datax.mEmpid.equalsIgnoreCase(cust_no)){}else{	
						if (mMode!=PItemMode.SEARCH){
							Toast.makeText(APos.this, cust_no+"已成功更新櫃員", Toast.LENGTH_SHORT).show();							
							updateDBHI(APos.this, cust_no, msFno, ""+PItemKind.TR40, 1); //0.USER 1.EMPID 2.DEPTNO
						}
					}
				}
				break;				
			}
			case RESULT_QFACT:
			{
				
				if (resultCode == RESULT_OK) {
					cust_no=dataR.getStringExtra("qfact_key");
					
					if (msCust.equalsIgnoreCase(cust_no)){}else{	
						if (mMode!=PItemMode.SEARCH){ 
							updateDBHI(APos.this, cust_no, msFno, msKind, 4); //0.USER 1.EMPID 2.DEPTNO 3.單的日期 4.QFACT
						}
					}
				}
				break;				
			}
			case RESULT_GALLERY:
			{
					//如果傳回代表需要
					//if(dataR.getIntExtra("GVP_modify",0)==1 && mMode != PItemMode.SEARCH){
					if(mMode != PItemMode.SEARCH){
			        	mAdapter.getData(this,msFno);					
						String Toot=recountHead(APos.this,msFno,""); //嘗試給GalleryViewP呼叫 但不用如下顯示段
						String[] arrayFieldH = Toot.toString().split(";");
						((Button)findViewById(R.id.btn_receive)).setText(arrayFieldH[0]);
						((Button)findViewById(R.id.btn_inc)).setText(arrayFieldH[1]);  //強制轉型	
						((Button)findViewById(R.id.btn_mic)).setText(arrayFieldH[2]); //強制轉型
						
					}else{
			        	mAdapter.getData(this,msFno);					
					}
				break;
			}
			
			case RESULT_GALLERYO:{
				if (resultCode == RESULT_OK) {
					if (dataR.getIntExtra("GalleryMode",0)==2 && dataR.getIntExtra("GVPO_modify",0)==1){
						//@@@理應依舊是原暫存單 也只會在暫存單 產生
						msFno=dataR.getStringExtra("FormNo");
						mAdapter.getData(this,msFno);
					}
				}
						break;
			}
			case RESULT_QHIS:
			{
	        	mAdapter.getData(this,msFno);					
				break;
				
			}
			
		}
			
		}
		
		
		
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if (!deptStr[0].equalsIgnoreCase(deptStr[5])) nPart=1;  //門市版
        if (Utilis.getIni(this,"SYS","SDB",7).equalsIgnoreCase("1")) f123=1; //需要小數位

        //1028放棄折123 改為 (單量/大宗) (累加/) 
        //日報:可以讀取日報表,顯示今天所有交易(二層式:合計層+明細層)如採購商品主畫面
        //上行:(依單據)(依會員)(暫存單)(依訂單)
        //(依單據)第一層為銷貨單	[第二層]為商品明細
        //(依會員)第一層為會員清單[第二層]為商品明細
        //(依訂單)第一層為訂單		[第二層]為商品明細
        //(暫存單)第一層為暫存單	[第二層]為商品明細        
        //第一層輕按將拉出或收回第二層
        //可以長按item(第一層) 出現選項
        //(編輯):只要是單據才可以帶著單子進場)
        //(刪除):只要是單據(出現對話框,確認後刪除)
        //(結帳):只有暫存單和訂單才可以帶著單子進場)(返回:僅收窗)]
        //第二層輕按(庫存分析:單品各色尺寸進銷存)(追蹤:單品所有交易)(返回)
        //下行:(查詢)()()(新增)(結束)
        //故障退貨回總公司(一般由總部開單)再匯入資料,這項操作無關門市銷貨操作
        //故障折損單,也可以在銷貨另設一欄(折損單),應該有別於(盤損單) (QKIND=60 70等)
    	myKind = getIntent().getIntExtra("pos_qkind", PItemKind.TR30); //單別 這是一個重要的關鍵值
    	msKind=""+myKind;
        
    	if (myKind==10) setContentView(R.layout.posmain10);
    	else if (myKind==20 || myKind==21) setContentView(R.layout.posmain20);
    	else setContentView(R.layout.posmain);
       	
		if (nHintDisc==1 ) {
			tradeStr[2]=tradeStr[3];
			((Button)findViewById(R.id.btn_100)).setVisibility(View.INVISIBLE);
		}
        
        ((Button)findViewById(R.id.btn_his)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_save)).setOnClickListener(new MainClick()); //(買單)進入另一畫面
        
        //涵蓋定金收入或結算或餘額訊息或入金概念  
        //過去強大功能加權平均結帳法,可以在參數設定權衡之,結帳畫面是否需另設專用的按鈕(重度考慮)
        //##將所有事件集中到new MainClick()再一一CASE判斷
        ((Button)findViewById(R.id.btn_nsave)).setOnClickListener(new MainClick()); //暫存
        //其實運作的原理只是另開出視窗ADAPTER,顯示目前保留的清單,[下方按鈕(新增)](返回)]
        ((Button)findViewById(R.id.btn_dels)).setOnClickListener(new MainClick());
        //棄單
        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());
//        ((Button)findViewById(R.id.btn_dept)).setOnClickListener(new MainClick());			//只可顯示
        ((Button)findViewById(R.id.btn_emp)).setOnClickListener(new MainClick());
        //可拉出櫃員檔換手
        ((Button)findViewById(R.id.btn_custp)).setOnClickListener(new MainClick());
        //會員可以查詢新增流覽(按鈕高度加高)不好按
        //整合會員QSTFF 但是輸入方式及及傳回需要大幅修改 一定要便利 快速
        ((ImageButton)findViewById(R.id.ibtn_date)).setOnClickListener(new MainClick());
        //可以改變開單日期,但是需店長級的權限 且只限新單及非已結帳的單
        ((Button)findViewById(R.id.btn_date)).setOnClickListener(new MainClick());
        //可以改變開單日期,但是需店長級的權限 且只限新單及非已結帳的單
        ((ImageButton)findViewById(R.id.ibtn_fno)).setOnClickListener(new MainClick()); //aa0_aa1下載雲端同步
        //FORMNO 由系統產生 不可編輯
        
        ((Button)findViewById(R.id.btn_receive)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_inc)).setOnClickListener(new MainClick());        
        ((Button)findViewById(R.id.btn_mic)).setOnClickListener(new MainClick());
        ((ImageButton)findViewById(R.id.ibtn_input)).setOnClickListener(new MainClick());
        ((ImageButton)findViewById(R.id.ibtn_input)).setOnLongClickListener(new MainLongClick());
        pInput = (EditText)findViewById(R.id.edIn);
		pInput.requestFocus();

        //輸入核心判斷 $會員(編號 名稱 電話) /櫃員 
        //貨品(含貨號,品名 關鍵字) 二維條碼時,檢查","存在 則取之前的文字視為貨號
        //以上凡是單筆都可直接帶入,多筆時帶入 多筆流覽視窗供選定傳回
        //再維護一次list清單
        ((Button)findViewById(R.id.btn_dis01)).setOnClickListener(new MainClick());
        //01-03 為系統預設的常用折數按鈕
        //似乎針對單一張編輯中的單據進行全面折扣,但需警語告知
        //@@如果單據改了一半,反悔了,如何還原,是否考慮修改時,其實是複製一張一模一樣的單,然後
        //@@經過確認後,刪除原單,寫入新單,如果半途反悔,只要刪除新單
        //@@另類考慮 LIST 和 DB 不同調
        ((Button)findViewById(R.id.btn_dis02)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_dis03)).setOnClickListener(new MainClick()); //
        ((Button)findViewById(R.id.btn_dis04)).setOnClickListener(new MainClick());

        ((Button)findViewById(R.id.btn_chg)).setOnClickListener(new MainClick());  //銷/退
        //當切換時,不會改變已輸入的項目,而是再輸入的時候會判斷銷貨退
        //以上和(專櫃出貨單)(員工自購)(甚至是廠商進貨單維護等)技術規則差很大,如何共用程式碼,是一大考驗
        //java擁有的共同部份繼承後再分支,是未來的目標

        ((Button)findViewById(R.id.btn_100)).setOnClickListener(new MainClick());

        //是不用按的
		((Button)findViewById(R.id.btn_fno)).setClickable(false);
		((Button)findViewById(R.id.btn_dept)).setClickable(false);
		
        mListView = (ListView)findViewById(R.id.list_pitem);  //將在畫面流覽的欄位們
				
	   	mAdapter = new PItemAdapter(this);
		mListView.setAdapter(mAdapter);
        mMode = getIntent().getIntExtra("pos_mode", PItemMode.ADD);  //預設新增
        mDept = getIntent().getStringExtra("pos_dept");  //SOS 或門市NO
		//PSWD=Utilis.toInt(deptStr[4]);
		mBankn=deptStr[0]+deptStr[1];
        if (nQhis==1 && sQhis!=2){
        	((Button)findViewById(R.id.btn_dis03)).setText("歷史");
        }else{
        	((Button)findViewById(R.id.btn_dis03)).setText("標準");
        }
		//歷史價  DISCOUNT 同步於 BTN_100
     	hisDiscount=Utilis.toDouble(Utilis.getIni(this,"INIH","DISBTN6",myKind/10));
 
        if (QPosff.PSWD==1 && (myKind==10 || myKind==20 || myKind==21))  //密碼不OK 
        	((Button)findViewById(R.id.btn_receive)).setVisibility(View.INVISIBLE);
        
        //啟動初始開單日期
       String SWH=Utilis.getIni(this,"SYS","DEV",7);
   		if (SWH !=null && SWH.equalsIgnoreCase("1") && (myKind==30 || myKind==31)){
        	mFD=1;
        	msFD=Utilis.getIni(this,"SYS","DEV",8);
        }
     	
    	iniKind(); //依單別不同而初始化
    	iniMode();
    	mWhere =getIntent().getIntExtra("pos_where",PItemWhere.Qposf); //來自何方軟件
    	mGroup =getIntent().getIntExtra("pos_group",GroupMode.NUMBER); //來自何方軟件
    	
        if((mMode == PItemMode.EDIT) || (mMode == PItemMode.SEARCH)){ //需先讀取該單HEAD & ITEMS
        	msFno = getIntent().getStringExtra("pos_formno"); //單號 這是一個最重要的關鍵值
        	mAdapter.getData(this,msFno);
        	 
        }else { //new add 這是只跑一次的地方
        	mMode = PItemMode.ADD;
        	iniHead();  	//一張新的單據
        	iniItems();	//一筆新的商品
        }

        mListView.setOnItemLongClickListener(new OnItemLongClickListener(){

			@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int position, long arg3) {
				// TODO Auto-generated method stub
			Utilis.runVibrate(APos.this);
			final int locations=position;
			if (mMode==PItemMode.SEARCH) menu_X=menu_ok;
			else {
				menu_X=menu_30;
				//0編輯1總編輯2單筆刪除3本款刪除6補印單據7追蹤
				//4本單轉預購5本單轉留貨8單筆轉預購9單筆轉留貨"

				if (mGroup!=GroupMode.COMPANY || (myKind!=30 && myKind!=31) || of_line!=0){
					
					menu_X[4]="保留";menu_X[5]="保留";menu_X[8]="保留";menu_X[9]="保留";
				}
			}

			DialogUtilis.showDialog(APos.this, "請選擇以下功能", -1,
			menu_X, new IDialog() {
				@Override
				public void onDialogFinish(int pos, String choice) {
					switch (pos) {
						case 0: // 單款編輯
						{
						if (mMode!=PItemMode.SEARCH){
							data = (PItemData) mAdapter.getItem(locations);
							Intent intent = new Intent();
							Bundle bundle = new Bundle();
							bundle = new Bundle();
							bundle.putString("GalleryChild",data.mGoodsNo+","+nQhis+","+((Button)findViewById(R.id.btn_100)).getText().toString()+","+msFno+","+msKind+",2,"+deptStr[8]+","+mDept+","+data.mTime);

							intent.setClass(APos.this, GalleryViewP.class);
							intent.putExtras(bundle);
							startActivityForResult(intent, RESULT_GALLERY);
						}else{//追蹤
							data = (PItemData) mAdapter.getItem(locations);
							Intent intent = new Intent();
							intent.putExtra("QHis_kind", myKind);
							intent.putExtra("QHis_mode", 1);
							intent.putExtra("QHis_User","" );
							intent.putExtra("QHis_Goods",data.mGoodsNo );
							intent.setClass(APos.this, QHis.class);
							startActivity(intent);

						}
						break;
						}
						case 1: // 本單商品編輯
						{
						if (mMode!=PItemMode.SEARCH){													
							data = (PItemData) mAdapter.getItem(locations);
							Intent intent = new Intent();
							Bundle bundle = new Bundle();
							bundle = new Bundle();
							bundle.putString("GalleryChild",data.mGoodsNo+","+nQhis+","+((Button)findViewById(R.id.btn_100)).getText().toString()+","+msFno+","+msKind+",0,"+deptStr[8]+","+mDept+","+data.mTime);
							intent.setClass(APos.this, GalleryViewP.class);
							intent.putExtras(bundle);
							startActivityForResult(intent, RESULT_GALLERY);
						}	
						break;
						}
						case 2://單筆刪除
						{
						if(mMode!=PItemMode.SEARCH){											
							SQLiteDatabase db = Utilis.getDB(APos.this);
							try{
								data = (PItemData) mAdapter.getItem(locations);
								//@@@@
								//if (data.mIscheck.equalsIgnoreCase("Y") && of_line==1)
									//db.execSQL("update qitems set TR='Y2' where FORMNO='" +msFno +"'  and GOODSNOS='"+data.mGoodsNos+"' and CREATEDATETIME='"+data.mTime+"'" );
								//else
									db.execSQL("delete from qitems where FORMNO='" +msFno +"'  and GOODSNOS='"+data.mGoodsNos+"' and CREATEDATETIME='"+data.mTime+"'" );
								
								String Toot=recountHead(APos.this,msFno,"");
								
								String[] arrayFieldH = Toot.toString().split(";");
								((Button)findViewById(R.id.btn_receive)).setText(arrayFieldH[0]);
								((Button)findViewById(R.id.btn_inc)).setText(arrayFieldH[1]);  //強制轉型	
								((Button)findViewById(R.id.btn_mic)).setText(arrayFieldH[2]); //強制轉型
								
					        	mAdapter.getData(APos.this,msFno);					
								Toast.makeText(APos.this, data.mGoodsNos+data.mTime+"已刪除成功", Toast.LENGTH_SHORT).show();
								
							}catch(Exception e){
								e.printStackTrace();
							}finally{
							 db.close();
							}
						} else {
							Toast.makeText(APos.this, "這裡不能執行刪除功能,請先轉入暫存區!!", Toast.LENGTH_SHORT).show();
						}
							break;
						}	
						case 3://單款刪除
						{
							if(mMode!=PItemMode.SEARCH){											
							SQLiteDatabase db = Utilis.getDB(APos.this);
							try{
								data = (PItemData) mAdapter.getItem(locations);
								//@@@@應檢查是否為ORNY
								//if (data.mIscheck.equalsIgnoreCase("Y") && of_line==1)
									//db.execSQL("update qitems set TR='Y2' where FORMNO='" +msFno +"' and GOODSNO='"+data.mGoodsNo+"'" );
								//else
									db.execSQL("delete from qitems where FORMNO='" +msFno +"' and GOODSNO='"+data.mGoodsNo+"'" );

								String Toot=recountHead(APos.this,msFno,""); //嘗試給GalleryViewP呼叫 但不用如下顯示段
								
								String[] arrayFieldH = Toot.toString().split(";");
								((Button)findViewById(R.id.btn_receive)).setText(arrayFieldH[0]);
								((Button)findViewById(R.id.btn_inc)).setText(arrayFieldH[1]);  //強制轉型	
								((Button)findViewById(R.id.btn_mic)).setText(arrayFieldH[2]); //強制轉型
								
					        	mAdapter.getData(APos.this,msFno);					
								Toast.makeText(APos.this, data.mGoodsNo+"已整款刪除成功", Toast.LENGTH_SHORT).show();
								
							}catch(Exception e){
								e.printStackTrace();
							}finally{
							 db.close();
							}
							} else {
								Toast.makeText(APos.this, "這裡不能執行刪除功能,請先轉入暫存區!!", Toast.LENGTH_SHORT).show();
							}
							break;
						}	
						case 4: //暫存轉預購
						{
							if(mMode!=PItemMode.SEARCH){											
								if ((myKind==30 || myKind==31) && mGroup==GroupMode.COMPANY && of_line!=1){
									data = (PItemData) mAdapter.getItem(locations);
									changeItems(0,0);
						        	Intent intentS = new Intent();
						        	intentS.putExtra("POS_modify",1);
						        	APos.this.setResult(RESULT_OK,intentS);
									finish();
								}
								else Toast.makeText(APos.this, "只限暫存銷貨單,或非雲端版,才可以轉單!!", Toast.LENGTH_SHORT).show();
							}
							break;
						}
						case 5://暫存轉留貨
						{
							if(mMode!=PItemMode.SEARCH){											
								if ((myKind==30 || myKind==31) && mGroup==GroupMode.COMPANY  && of_line!=1){
									data = (PItemData) mAdapter.getItem(locations);
									changeItems(0,1);
						        	Intent intentS = new Intent();
						        	intentS.putExtra("POS_modify",1);
						        	APos.this.setResult(RESULT_OK,intentS);
									finish();
								}
								else Toast.makeText(APos.this, "只限暫存銷貨單,或非雲端版,才可以轉單!!", Toast.LENGTH_SHORT).show();
							}
						break;
						}
						case 6://補印單據
						{
							Intent intent = new Intent();
							intent.putExtra("pos_npart",nPart);
							intent.putExtra("pos_mode",PItemMode.SEARCH);
							intent.putExtra("pos_formno",msFno);
							intent.putExtra("pos_qkind",myKind);//int @@TR30 
							intent.putExtra("pos_where",PsaveWhere.Repeat);
							intent.putExtra("pos_group",mMode);
							intent.setClass(APos.this,QPosSave.class);
						startActivity(intent);

							break;
						}	
						case 7:  //追蹤
						{
							data = (PItemData) mAdapter.getItem(locations);
							Intent intent = new Intent();
							intent.putExtra("QHis_kind", myKind);
							intent.putExtra("QHis_mode", 1);
							intent.putExtra("QHis_User",msCust );
							intent.putExtra("QHis_Goods",data.mGoodsNo );
							intent.setClass(APos.this, QHis.class);
							startActivityForResult(intent,RESULT_QHIS);
						break;	
						}
						case 8: //單筆暫存轉預購
						{
							if(mMode!=PItemMode.SEARCH){											
								if ((myKind==30 || myKind==31) && mGroup==GroupMode.COMPANY   && of_line!=1){
									data = (PItemData) mAdapter.getItem(locations);
									changeItems(1,0);
								}
								else Toast.makeText(APos.this, "只限暫存銷貨單,或非雲端版,才可以轉單!!", Toast.LENGTH_SHORT).show();
							}
							break;
						}
						case 9://單筆暫存轉留貨
						{
							if(mMode!=PItemMode.SEARCH){											
								if ((myKind==30 || myKind==31) && mGroup==GroupMode.COMPANY  && of_line!=1 ){
									data = (PItemData) mAdapter.getItem(locations);
									changeItems(1,1);
								}
								else Toast.makeText(APos.this, "只限暫存銷貨單,或非雲端版,才可以轉單!!", Toast.LENGTH_SHORT).show();
							}
						break;
						}
						case 10:////返回
						{
						}
					} //end with switch
				}
			});
				return true;
			}
		});
        
	mListView.setOnItemClickListener(new OnItemClickListener(){
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(APos.this);
			if(mMode!=PItemMode.SEARCH){											
			data = (PItemData) mAdapter.getItem(position);
			chkItems();
			}else{
				Toast.makeText(APos.this, "這裡不能執行編輯功能,請先轉入暫存區!!", Toast.LENGTH_SHORT).show();
			}
		}
	});
	

	((Button)findViewById(R.id.edps1)).setOnClickListener(new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(APos.this);
		 if(mMode != PItemMode.SEARCH){
			DialogUtilis.showDialog(APos.this, "請選擇以下交易方式", -1,
					Ps1Str, new IDialog() {
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch (pos) {
								case 0:{datax.mhPs1=Ps1Str[0];	break;}
								case 1:{datax.mhPs1=Ps1Str[1];	break;}
								case 2:{datax.mhPs1=Ps1Str[2];	break;}
								case 3:{datax.mhPs1=Ps1Str[3];	break;}
								case 4:{datax.mhPs1=Ps1Str[4];	break;}
								case 5:{datax.mhPs1=Ps1Str[5];	break;}
								case 6:{datax.mhPs1=Ps1Str[6];	break;}
								case 7:{datax.mhPs1=Ps1Str[7];	break;}
								case 8:{datax.mhPs1=Ps1Str[8];	break;}
							}
							((Button)findViewById(R.id.edps1)).setText(datax.mhPs1);
							SQLiteDatabase db = Utilis.getDB(APos.this);
							db.execSQL("update qhead set PS1='"+datax.mhPs1+"' where FORMNO='"+msFno+"'");
							db.close();
						}	
					});
		 }			
		}
	});
	
	((Button)findViewById(R.id.edps)).setOnClickListener(new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(APos.this);
		 if(mMode != PItemMode.SEARCH){

					LayoutInflater factory = LayoutInflater.from(APos.this);
				    final View v1 = factory.inflate(R.layout.fbatch, null);
				    final EditText edtReg = (EditText) v1.findViewById(R.id.edtsh);
				    edtReg.setText(datax.mhPs);
 				      new AlertDialog.Builder(APos.this).setTitle("請不要輸入特殊符號,字元如(@%^,;/)等").setView(v1).setNeutralButton("備註:", new DialogInterface.OnClickListener() {
					      public void onClick(DialogInterface dialog, int which) {
				    	  		if (edtReg.getText().toString().length()>0){
				    	  			datax.mhPs=DBCloud.chkStrB(edtReg.getText().toString());	
									((Button)findViewById(R.id.edps)).setText(datax.mhPs);
					      	
				    	  			SQLiteDatabase db = Utilis.getDB(APos.this);
									db.execSQL("update qhead set PS='"+datax.mhPs+"' where FORMNO='"+msFno+"'");
									db.close();
				    	  		}	
					     }
					    }).setNegativeButton("離開", new DialogInterface.OnClickListener() {
						      public void onClick(DialogInterface dialog, int which) {

						      }
					    })
					    .show(); 			 

		 }			
		}
	});
	

pInput.setOnKeyListener(new View.OnKeyListener() {
	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
	//監視鍵盤按鍵
		 if(event.getAction()== KeyEvent.ACTION_DOWN){ 
			if  (keyCode==KeyEvent.KEYCODE_ENTER && pInput.getText().toString().length()>0){
				String xx=pInput.getText().toString();
				aInput=xx.toUpperCase();
				chkKeyin(aInput);
				return true;
			}
		 }
	return false;
	}
	
});

mListView.setOnFocusChangeListener(new View.OnFocusChangeListener(){
	  public void onFocusChange(View view, boolean hasFocus){
	    if(hasFocus){
			pInput.requestFocus();
	    } else {
	    }
	  }
	});



((Button)findViewById(R.id.btn_dis02)).setOnFocusChangeListener(new View.OnFocusChangeListener(){
	  public void onFocusChange(View view, boolean hasFocus){
	    if(hasFocus){
			pInput.requestFocus();
			//Log.i("DOWNLOAD_2", "pInput欄位切換回位啟動");
	    } else {
	    }
	  }
	});

((Button)findViewById(R.id.btn_dis01)).setOnFocusChangeListener(new View.OnFocusChangeListener(){
	  public void onFocusChange(View view, boolean hasFocus){
	    if(hasFocus){
			pInput.requestFocus();
	    } else {
	    }
	  }
	});

((Button)findViewById(R.id.edps)).setOnFocusChangeListener(new View.OnFocusChangeListener(){
	  public void onFocusChange(View view, boolean hasFocus){
	    if(hasFocus){
			pInput.requestFocus();
	    } else {
	    }
	  }
	});

((Button)findViewById(R.id.edps1)).setOnFocusChangeListener(new View.OnFocusChangeListener(){
	  public void onFocusChange(View view, boolean hasFocus){
	    if(hasFocus){
			pInput.requestFocus();
	    } else {
	    }
	  }
	});

	} //主程式段結束
	
	public void onResume(){
		super.onResume();
		
		deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");
        mDept = getIntent().getStringExtra("pos_dept");  //SOS 或門市NO
		//QPosff.PSWD=Utilis.toInt(deptStr[4]);
		mBankn=deptStr[0]+deptStr[1];
		//歷史價  DISCOUNT 同步於 BTN_100
/* 
        if (!deptStr[4].equalsIgnoreCase("0") && (myKind==10 || myKind==20 || myKind==21)){  //密碼OK 或不用密碼
        	PSWD=1;  //表示不OK
        	((Button)findViewById(R.id.btn_receive)).setVisibility(View.INVISIBLE);
        }else if (!deptStr[4].equalsIgnoreCase("0") && backout[8].equalsIgnoreCase("2")){
        	PSWD=1;  //表示不OK
        }
*/        
    	if (mDept.equalsIgnoreCase("SOS"))
    		datax.mDeptno =deptStr[0]; //門市代號
    	else 
    		datax.mDeptno =mDept; //門市代號
    	
		rDept=datax.mDeptno; //不變的該單的門市代號
		
		//多久沒有同步時,應該再下載一次
		String Tnow =DateUtil.getSystemTime().substring(2, 12);
		String T[]=Utilis.getIni(this, "SYS", "SEASON", 9).split("!&!");

		if (Utilis.haveInternet(APos.this) && of_line==1 && (Utilis.toDouble(Tnow)-Utilis.toDouble(T[3]))>6)  //逾3分鐘沒有同步
			DBCloud.aa0_aa1_auto_HI(APos.this,myKind);
		
		if (Utilis.haveInternet(APos.this) && of_line==1 && (Utilis.toDouble(Tnow)-Utilis.toDouble(T[1]))>6)  //逾6分鐘沒有同步
			DBCloud.aa0_aa1_auto_qdetail_n(APos.this);

	}
	
	public String[] getNNList(String CustNO){
		//新增時,傳回會員後,搜尋有否暫存單
		//必備條件
		try{
			String[] lists=null;
			StringBuffer lst=new StringBuffer();
			SQLiteDatabase db = Utilis.getDB(APos.this);
			Cursor cs;
			StringBuffer buf=new StringBuffer();
			buf.append("select FORMDATE,FORMNO from qhead where TR<>'Y2' and ISCONFIRM='N' and ISCHECK='N' and USER='"+CustNO+"' and (FORMNO not like '"+aDept+"5%"+"' and  FORMNO not like '"+aDept+"6%"+"')");
			//buf.append(" and HANDNO!='+0' ");
			cs=db.rawQuery(buf.toString(), null);
			if (cs.getCount()>0){
				while (cs.moveToNext()){
					lst.append(cs.getString(0)).append(",").append(cs.getString(1)).append(";");
				}
				lists=lst.toString().substring(0,lst.toString().length()-1).split(";");
			}
			buf.delete(0, buf.toString().length());
			buf.append("select FORMDATE,FORMNO from qhead where ISCONFIRM='R' and ISCHECK='Y' and USER='"+CustNO+"' and ATOT>0 ");
			cs=db.rawQuery(buf.toString(), null);
			if (cs.getCount()>0){
				Toast.makeText(APos.this,CustNO+"有留貨資料,請留意!!", Toast.LENGTH_SHORT).show();
			}
			
			cs.close();
			db.close();
		return lists;
		}catch(Exception e){
			return null;
		}
	}
	
	private void iniHead(){ //初始化單頭
		//先檢查有無同一會員(其實大都為預設會員)但為空單(表示ITEMS_尚未輸入),且isComfirm isCheck	都不為"Y"
		//是否為同一天者,不用,是因為既然為空單也確實存在,就是引用,但是需注意日期
		SQLiteDatabase db = Utilis.getDB(APos.this);
		Cursor cursorC=null;
		String inih=null;
		//QKIND=21 表示為 轉貨單
		//在門市為門市轉貨單時,轉貨對象為總倉
		if (nPart==1 && myKind==20)
			datax.mUser=deptStr[0];
		else if (nPart==0 && myKind==31){
			//在總倉&&專櫃銷貨 可以指定Z+門市代號
			datax.mUser="Z"+mDept;
		//如果沒有檔案存在,應拜訪門市通訊錄,複製
		}else
			datax.mUser=Utilis.getIni(this,"INIH","USER",(myKind/10));
		
		msCust=datax.mUser;
		
		if (myKind!=10)
			cursorC=db.rawQuery("select * from qcust where CUSTNO='"+msCust+"'",null);
		else	
			cursorC=db.rawQuery("select * from qfact where FACTNO='"+msCust+"'",null);
		
		if (cursorC.getCount()>0){
			cursorC.moveToFirst();
			datax.nTrade=cursorC.getInt(cursorC.getColumnIndex("TRADETYPE"));
			datax.dDiscount=cursorC.getDouble(cursorC.getColumnIndex("DISCOUNT"));
			if (myKind!=10){
				datax.mUsername=cursorC.getString(cursorC.getColumnIndex("CUSTNAME"));
			}else {
				datax.mUsername=cursorC.getString(cursorC.getColumnIndex("FACTNAME"));
			}
		}else {
			datax.mUsername=Utilis.getIni(this,"INIH","USERNAME",(myKind/10));
			datax.nTrade=Utilis.toInt(Utilis.getIni(this,"INIH","USERTRADE",(myKind/10)));
			if (DBUtil.CFact.isQFactExist(APos.this, msCust,"",myKind) == false) {
				DBUtil.CFact.createNewFact(APos.this, msCust,mDept, 1,myKind);
			}//遇到不存在的預設(廠商或會員)自動建立之
		
		}
		datax.mKind=msKind;
		msTrade=datax.nTrade;
		
		cursorC.close();
		
		int NisEmpty=0;
		Cursor cs = null;
		Cursor csi =null;
		StringBuffer mySqlBuf = new StringBuffer();
		//有2種 qfact(10) qcust(202130314041) 當預設不存在於主檔時,自動建立
		mySqlBuf.delete(0,mySqlBuf.toString().length());
		mySqlBuf.append("select FORMNO,HANDNO from qhead");
		mySqlBuf.append(" where TR<>'Y2' and ISCONFIRM='N' and ISCHECK='N' and FORMNO like '"+(mBankn+msKind.substring(0,1)+DateUtil.getCurrentYearFormat1().substring(0, 2))+"%'");
		mySqlBuf.append(" and ATOT=0 and ASUM=0 and CASH=0 and CARD=0 and ORDCASH=0 and ORDCARD=0 and ATM=0 and TRCASH=0");			
		mySqlBuf.append(" order by FORMNO desc LIMIT 10");  //找有否空單,消化
		cs = db.rawQuery(mySqlBuf.toString(), null);

		
		if (cs.getCount()>0) { //表示有空單可沿用,但要求證
		while (cs.moveToNext()) {
			msFno=cs.getString(cs.getColumnIndex("FORMNO"));
			mySqlBuf.delete(0,mySqlBuf.toString().length());
			mySqlBuf.append("select FORMNO from qitems");
			mySqlBuf.append(" where FORMNO ='"+msFno+"'");
			csi=db.rawQuery(mySqlBuf.toString(), null);
			if (csi==null || csi.getCount()<=0){
				NisEmpty=1;
				//cs.moveToLast();
				break;
			}
			   csi.close();
		 }  
		}
		   db.close();
		   cs.close();
 
		mMode=PItemMode.ADD;  //設定為新增單據		
    	datax.mTR=msKind;  //視為新的空單到存入都OK
    	datax.nID=0;
    	//一旦被按了異動,第一時間應該改為11好讓系統知道這是以存檔後被按了異動,如果TR=00
    	if (mDept.equalsIgnoreCase("SOS"))
    		datax.mDeptno =deptStr[0]; //門市代號
    	else 
    		datax.mDeptno =mDept; //門市代號
    	
		rDept=datax.mDeptno; //不變的該單的門市代號

    	
    	datax.mIslist = deptStr[1]; //機號    	
    	nQhis=0; //標準價
    	fQhis="1"; //標準價
       	((Button)findViewById(R.id.btn_dis03)).setText("標準");
    		if (NisEmpty==0){ //新單號
    			msFno = Utilis.getNFormno(APos.this,msKind.substring(0,1)); //新單號 以門市代號2+機號1+單別1+年1,做為流水號的基礎
    		}
    		
    	if(mFD==1 && msFD.length()>0 && (myKind==30 || myKind==31)) datax.mFormdate=msFD;
    	else{
    		String FormD=DateUtil.getCurrentDate();  //2012/10/22
    		int Ttime=Utilis.toInt(DateUtil.getSystemTime().substring(8, 10));  //取得目前幾點
			if (Ttime<=5)  FormD = DateUtil.addDate(FormD, -1);
			FormD = FormD.replace("/", "-");
			datax.mFormdate=FormD;
    	}
    	datax.mIsconfirm="N";
    	datax.mIscheck="N";
    	datax.mEmpid=Utilis.getIni(this,"INIH","EMPID",(myKind/10)); //預設櫃員代號
    	datax.mEmpname=Utilis.getIni(this,"INIH","EMPNAME",(myKind/10)); //櫃員名稱
    	//也可以這樣寫 1-6個別 9全部

    	datax.mBankno=Utilis.getIni(this,"INIH","BANK",(myKind/10));
    	datax.mBankname=mBankn;
    	datax.dRate=Utilis.toDouble(Utilis.getIni(this,"INIH","BANKRATE",(myKind/10))); //交易的匯率
    	
//HEAD 專屬的歸零項目
    	datax.mFno=msFno;
		datax.mHandno="+0";	//理論上是貨品明細"+5 -1"
		datax.mOrddate="";	//KEYIN
		datax.mFinedate="";	//KEYIN
 		datax.dOrdcash=0;	//KEYIN
		datax.dOrdcard=0;	//KEYIN
		datax.dCash=0;			//KEYIN
		datax.dCard=0;			//KEYIN
		datax.dAtot=0;  		//總件數	<--來自於ITEMS的統計累加 UNIT10 20 30 40 等１不同單據
		datax.dAsum=0; 		//應收		<--來自於ITEMS的統計累加 SUBPRICE
		datax.dBsum=0; 		//實收 		<--使用者的強制輸入
		datax.dCosts=0; 		//總成本 <--來自於ITEMS的統計累加 ACOST
		datax.dTuresum=0;	//換算匯率後的實際金額 edBsum*edRate
		datax.dDismoney=0;//折讓=應收-實收
		datax.dAtm=0;
		datax.dTrcash=0;
		datax.mhPs="";
		datax.mhPs1=Ps1Str[0];
		datax.mhPs2="";
		datax.dInc=0;
		datax.dMic=0;
		//維護畫面顯示資料
		iniMode();
		iniScreenData();
		ContentValues value = new ContentValues();
		upDBH(APos.this,NisEmpty,msFno,value,datax);  //0新增 1.更新 2.只要upDBH 不要存入
	
	}
	
	private void iniItems(){
 	//ITEM用
	data.mBatch=null;
	data.mSupply=null;
	data.mGoodsNo=null;
	data.mSourceNo=null;
	data.mGoodsNos=null;	
	data.mGoodsType=null;
	data.mGoodsName=null;
	data.mColors=null;//顏色名稱S
	data.mSizes=null; //SIZES
	data.dUnit=0; //	
	data.dUnit10=0;
	data.dUnit20=0;
	data.dUnit30=0;
	data.dUnit40=0;
	data.dUnitprice=0;
	data.dAcost=0;
	data.dRateprice=0;
	data.dRealsum=0;
	data.dsubprice=0;
	data.dP0=0;
	data.dP1=0;
	data.dP2=0;
	data.dP3=0;
	data.dP4=0;
	data.dP5=0;
	data.mColor=null;  //COLOR  單色編號
	data.mSize=null; //SIZE 單尺寸
	data.mPic=null;	
	data.nSeason=0;	
	data.mUnit1=null; //有分色尺寸的 單色名
	data.mUnit2=null;//多色的代碼
	data.mCountry=null;
	data.mYear=null;//年度
	data.mPS=null;  //PS
	}

	
	private LongClick mLongClickListener = new LongClick();

	class LongClick implements OnItemLongClickListener {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				final int position, long arg3) {
			
			
			return false;
		}
	}

	@SuppressWarnings("resource")
	private void chkKeyin(String aPut){
		if (aPut.length()>0 && mMode!=PItemMode.SEARCH ){  //表示有料且不為查詢的狀態
			edInput=aPut;
			int edserch=0;
			if (edInput.substring(0, 1).equalsIgnoreCase("+")){//結帳
				
				if (!datax.mIsconfirm.equalsIgnoreCase("O") && !datax.mIsconfirm.equalsIgnoreCase("R")){
					Intent intent = new Intent();
					intent.putExtra("pos_npart",nPart);
					intent.putExtra("pos_mode",mMode);
					intent.putExtra("pos_formno",msFno);
					intent.putExtra("pos_qkind",myKind);//int @@TR30 
					intent.putExtra("pos_where",PsaveWhere.Apos);
					intent.putExtra("pos_group",mGroup);
					
					intent.setClass(APos.this,QPosSave.class);
					startActivityForResult(intent, RESULT_QPOSAVE);
				}

			}else if (edInput.substring(0, 1).equalsIgnoreCase("$")){//會員
					edInput=edInput.substring(1); //忽略第一字元
					Intent intent = new Intent();
					intent.putExtra("qcustf_qkind", myKind);
						if (myKind!=10) {
							if (nPart==1 && myKind==20){
				    			Toast.makeText(APos.this,"無需調整門市代號!!", Toast.LENGTH_SHORT).show();				            		
							} else {
								if (mMode!=PItemMode.SEARCH){
								intent.putExtra("qcustf_mode", QCustfMode.SEARCHEDGOBACK); //查返
								}else {
									intent.putExtra("qcustf_mode", QCustfMode.SEARCH); //查
								}
								intent.putExtra("qcustf_key", edInput);					
								intent.putExtra("pos_dept", mDept);
								intent.setClass(APos.this, QCustff.class);
								startActivityForResult(intent, RESULT_QCUSTFF);
							}
						} else { //廠商
							intent.putExtra("qfact_key", edInput);					
							intent.putExtra("mode", EMode.GET);
							intent.putExtra("countryid", 0);  //表不分國別
							intent.setClass(APos.this, Qfactff.class);
							startActivityForResult(intent, RESULT_QFACT);
						}
//				pInput.setText("");

			} else if (edInput.substring(0, 1).equalsIgnoreCase("/")){//交易員
					edInput=edInput.substring(1); //忽略第一字元
					if (edInput.indexOf("999")>0) edInput=edInput.substring(0,edInput.indexOf("999"));
					Intent intent = new Intent();
					intent.putExtra("qcustf_qkind", 40); //這是櫃員基本檔是為了交易員
					if (mMode!=PItemMode.SEARCH){
					intent.putExtra("qcustf_mode", QCustfMode.SEARCHEDGOBACK); //查返
					}else {
						intent.putExtra("qcustf_mode", QCustfMode.SEARCH); //查
					}
					intent.putExtra("qcustf_key", edInput);					
					intent.putExtra("pos_dept", mDept);
					intent.setClass(APos.this, QCustff.class);
					
					startActivityForResult(intent, RESULT_QEMPFF);
					
//				pInput.setText("");
			} else if (edInput.substring(0, 1).equalsIgnoreCase(".")){//DOS的貨系編號
				//無法進行QDETAIL的判斷 
				edInput=edInput.substring(1); //忽略第一字元
				SQLiteDatabase db = Utilis.getDB(APos.this);
				Cursor cursor = null;					
				StringBuffer mySqlBuf = new StringBuffer();
				mySqlBuf.append("select distinct * from qitems");
				mySqlBuf.append(" where HANDNO ='" + edInput.trim()+"'");  //完全符合
				mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT 1");
				
				cursor = db.rawQuery(mySqlBuf.toString(), null);
						
				if (cursor.getCount()>0){ //找到唯一貨號後,檢查有否本單重覆的貨號
					if (nSingle==1) {  //是單量才可
						cursor.moveToFirst();
						edInput=cursor.getString(cursor.getColumnIndex("GOODSNOS"));
						int YN=IsExistItem(msFno,((Button)findViewById(R.id.btn_100)).getText().toString(),edInput,PlusMinus);  //如果本單存在,作累加OK
						long result=0;
						if (YN !=1){ //本單不存在該商品,需NEW_QITEMS
							ContentValues value = new ContentValues();
							int isYn=YN; if (YN==0) isYn=2;
							upDBH(APos.this,isYn,msFno,value,datax); //先製作單頭一致的PUT
							String stkAt=DBUtil.getStk(this, db, myKind, rDept, msCust, edInput,PlusMinus);
							value.put("FINEDATE",stkAt);
							data.mFinedate=stkAt;
							if (stkAt.indexOf("庫存不足")>0)
								Toast.makeText(this,stkAt , Toast.LENGTH_SHORT).show();
								
							upDBIN(APos.this,cursor,value,data,edInput,"","","",0); //製作一筆新ITEM的基礎PUT
							result = db.insert(TbName.QITEMS, null, value);
						}
						if (YN!=0 || (result>0)){ //需維護QHEAD(總?)及其畫面相關資訊(應收)(+件數)(-件數)
							reItems(APos.this, msFno);
							String Toot=recountHead(APos.this,msFno,""); //嘗試給GalleryViewP呼叫 但不用如下顯示段
							String[] arrayFieldH = Toot.toString().split(";");
							((Button)findViewById(R.id.btn_receive)).setText(arrayFieldH[0]);
							((Button)findViewById(R.id.btn_inc)).setText(arrayFieldH[1]);  //強制轉型	
							((Button)findViewById(R.id.btn_mic)).setText(arrayFieldH[2]); //強制轉型
						}
					}else { //有找到且唯一但是大宗
						cursor.moveToFirst();
						edInput=cursor.getString(cursor.getColumnIndex("GOODSNO"));
						if(mMode!=PItemMode.SEARCH) 
							runGVP(",2,"+deptStr[8]);
						else runGVP(",0,"+deptStr[8]);
						
					}
				}else{
					Toast.makeText(APos.this,edInput+"查無此貨號!!", Toast.LENGTH_SHORT).show();									
				}
				cursor.close();
				db.close();
			} else {//就是貨號  @input@需整合KEYIN捕捉事件
				//判斷商品存在否,優先QDETAIL
				SQLiteDatabase db = Utilis.getDB(APos.this);
				Cursor cursor = null;					
				StringBuffer mySqlBuf = new StringBuffer();

				if (edInput.indexOf("-")>0){//輸入了可能是完整的貨號,或條碼完整的貨號
					if (selectM!=0){	//優先判斷QDETAIL
							String DGOODS="";String DCOLORNO="";String DSIZES="";
						if (edInput.indexOf("-") !=edInput.lastIndexOf("-")){ 
							DGOODS=edInput.substring(0,edInput.indexOf("-"));
							DCOLORNO=edInput.substring(edInput.indexOf("-")+1,edInput.lastIndexOf("-"));
							DSIZES=edInput.substring(edInput.lastIndexOf("-")+1).trim();
						}else{
							DGOODS=edInput.substring(0,edInput.indexOf("-"));
							DCOLORNO=edInput.substring(edInput.indexOf("-")+1).trim();
							DSIZES="F";
						}
						mySqlBuf.delete(0, mySqlBuf.toString().length());
						mySqlBuf.append("select distinct * from qdetail");
						mySqlBuf.append(" where GOODSNO ='" + DGOODS+"' and COLORNO like '%"+DCOLORNO+"%' and SIZE like '%"+DSIZES+"%' ");  //完全符合
						mySqlBuf.append(" order by BATCH DESC LIMIT 1");
						cursor = db.rawQuery(mySqlBuf.toString(), null);
						if (cursor.getCount()>0){
							edserch=1;
							cursor.moveToFirst();
							//got it 再分為 單量大宗
							if (nSingle==1) {
								String [] Col=cursor.getString(cursor.getColumnIndexOrThrow("COLORNO")).split("，");
								String [] Siz=cursor.getString(cursor.getColumnIndexOrThrow("SIZE")).split(",");
								int chkC=0;int chkS=0;
								for (int x=0;x<Col.length;x++)
									if (DCOLORNO.equalsIgnoreCase(Col[x])){ chkC=1;DCOLORNO=Col[x];break;}
								
								for (int x=0;x<Siz.length;x++)
									if (DSIZES.equalsIgnoreCase(Siz[x])){ chkS=1;DSIZES=Siz[x];break;}
								
								if(chkC>0 && chkS>0){
									int YN=IsExistItem(msFno,((Button)findViewById(R.id.btn_100)).getText().toString(),edInput,PlusMinus);  //如果本單存在,作累加OK
									long result=0;
									if (YN !=1){ //本單不存在該商品,需NEW_QITEMS
										ContentValues value = new ContentValues();
										int isYn=YN; if (YN==0) isYn=2;
										//先製作單頭一致的PUT
										upDBH(APos.this,isYn,msFno,value,datax); 
										//製作一筆新ITEM的基礎PUT
										String stkAt=DBUtil.getStk(this, db, myKind, rDept, msCust, DGOODS+"-"+DCOLORNO+"-"+DSIZES,PlusMinus);
										if (stkAt.indexOf("庫存不足")>0)
											Toast.makeText(this,stkAt , Toast.LENGTH_SHORT).show();
										value.put("FINEDATE",stkAt);
										data.mFinedate=stkAt;
										upDBIN(APos.this,cursor,value,data,DGOODS+"-"+DCOLORNO+"-"+DSIZES,cursor.getString(cursor.getColumnIndex("COLOR")),cursor.getString(cursor.getColumnIndex("SIZE")),cursor.getString(cursor.getColumnIndex("COLORNO")),2); 
										result = db.insert(TbName.QITEMS, null, value);
									}
									if (YN !=0 || (result>0)){ //需維護QHEAD(總?)及其畫面相關資訊(應收)(+件數)(-件數)
										reItems(APos.this, msFno);
										String Toot=recountHead(APos.this,msFno,""); //嘗試給GalleryViewP呼叫 但不用如下顯示段
										String[] arrayFieldH = Toot.toString().split(";");
										((Button)findViewById(R.id.btn_receive)).setText(arrayFieldH[0]);
										((Button)findViewById(R.id.btn_inc)).setText(arrayFieldH[1]);	
										((Button)findViewById(R.id.btn_mic)).setText(arrayFieldH[2]);
									}
									
								}	
							}else{
								edInput=cursor.getString(cursor.getColumnIndex("GOODSNO"));
								if(mMode!=PItemMode.SEARCH) runGVP(",8,0");//qdetail_GOODSNO
							}
						}
					}
					if (edserch==0){
						mySqlBuf.delete(0, mySqlBuf.toString().length());
						mySqlBuf.append("select distinct * from qitems");
						mySqlBuf.append(" where GOODSNOS ='" + edInput.trim()+"'");  //完全符合
						mySqlBuf.append(" order by FORMDATE,CREATEDATETIME DESC LIMIT 1");
						cursor=null;
						cursor = db.rawQuery(mySqlBuf.toString(), null);
							
						if (cursor.getCount()>0){ //找到唯一貨號後,檢查有否本單重覆的貨號
							edserch=1;
							if (nSingle==1) {  //是單量才可
								cursor.moveToFirst();
								int YN=IsExistItem(msFno,((Button)findViewById(R.id.btn_100)).getText().toString(),edInput,PlusMinus);  //如果本單存在,作累加OK
								long result=0;
								if (YN !=1){ //本單不存在該商品,需NEW_QITEMS
									ContentValues value = new ContentValues();
									int isYn=YN; if (YN==0) isYn=2;
									upDBH(APos.this,isYn,msFno,value,datax); //先製作單頭一致的PUT
									String stkAt=DBUtil.getStk(this, db, myKind, rDept, msCust, edInput,PlusMinus);
									if (stkAt.indexOf("庫存不足")>0)
										Toast.makeText(this,stkAt , Toast.LENGTH_SHORT).show();
									value.put("FINEDATE",stkAt);
									data.mFinedate=stkAt;
									upDBIN(APos.this,cursor,value,data,edInput,"","","",0); //製作一筆新ITEM的基礎PUT
									result = db.insert(TbName.QITEMS, null, value);
								}
								if (YN !=0 || (result>0)){ //需維護QHEAD(總?)及其畫面相關資訊(應收)(+件數)(-件數)
									reItems(APos.this, msFno);
									String Toot=recountHead(APos.this,msFno,""); //嘗試給GalleryViewP呼叫 但不用如下顯示段
									String[] arrayFieldH = Toot.toString().split(";");
									((Button)findViewById(R.id.btn_receive)).setText(arrayFieldH[0]);
									((Button)findViewById(R.id.btn_inc)).setText(arrayFieldH[1]);  //強制轉型	
									((Button)findViewById(R.id.btn_mic)).setText(arrayFieldH[2]); //強制轉型
								}

							}else { //有找到且唯一但是大宗
								edInput=edInput.substring(0,edInput.indexOf("-"));
								if(mMode!=PItemMode.SEARCH) 
									runGVP(",2,"+deptStr[8]);
								else runGVP(",0,"+deptStr[8]);
							}
							
						}else Toast.makeText(APos.this,edInput+"顏色尺寸規格不符!!", Toast.LENGTH_SHORT).show();									
					}
				} else if (edInput.substring(0, 1).equalsIgnoreCase("*")){ //@@檢查如果關鍵字存在商品,即交給GALLERY
					edInput=edInput.substring(1); //忽略第一字元	
					mySqlBuf.delete(0, mySqlBuf.toString().length());
					
					if (selectM!=0){
						mySqlBuf.append("select * from qdetail");
						if (deptStr[8].equalsIgnoreCase("1"))  //預設來源反以主貨號搜尋
							mySqlBuf.append(" where GOODSNO like '%" + edInput.trim()+"%'");
						else //預設主貨號反以原始搜尋
							mySqlBuf.append(" where SOURCENO like '" + edInput.trim()+"%'");
						
						mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT 50");
						cursor=null;
						cursor = db.rawQuery(mySqlBuf.toString(), null);
						
						if (cursor.getCount()>0 && mMode!=PItemMode.SEARCH){
							//也要對調
							edserch=1;
							if (deptStr[8].equalsIgnoreCase("1")) runGVP(",5,0"); else runGVP(",5,1");
						}else{
							mySqlBuf.delete(0, mySqlBuf.toString().length());
							mySqlBuf.append("select * from qdetail");
							mySqlBuf.append(" where GOODSNAME like '%" + edInput.trim()+"%'");
							mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT 50");
							cursor = db.rawQuery(mySqlBuf.toString(), null);
							if (cursor.getCount()>0){
								edserch=1;
								if(mMode!=PItemMode.SEARCH) runGVP(",4,"+deptStr[8]);
							}else{							
							Toast.makeText(APos.this,edInput+"查無此貨號!!", Toast.LENGTH_SHORT).show();
							}
						}
					}else{	
						mySqlBuf.append("select distinct GOODSNO from qitems");
						if (deptStr[8].equalsIgnoreCase("1"))  //預設來源反以主貨號搜尋
							mySqlBuf.append(" where GOODSNO like '%" + edInput.trim()+"%'");
						else //預設主貨號反以原始搜尋
							mySqlBuf.append(" where SOURCENO like '" + edInput.trim()+"%'");
								
						mySqlBuf.append(" order by FORMDATE DESC LIMIT 300");
						
						cursor = db.rawQuery(mySqlBuf.toString(), null);
						
						if (cursor.getCount()>0){
							if (cursor.getCount()<=200){
								edserch=1;
								if(mMode!=PItemMode.SEARCH) {
									if (deptStr[8].equalsIgnoreCase("1")) runGVP(",1,"+deptStr[8]); else runGVP(",3,"+deptStr[8]); 
								}else {
									runGVP(",0,"+deptStr[8]);
								}
							}else{
								Toast.makeText(APos.this,"找到的商品(>300)太多了!!請縮小範圍!!", Toast.LENGTH_SHORT).show();
							}
						}else {  //以上都沒有找到,可以雜找品名
							mySqlBuf.delete(0, mySqlBuf.toString().length());
							if (cursor.getCount()<=0){
								mySqlBuf.delete(0, mySqlBuf.toString().length());
								mySqlBuf.append("select distinct GOODSNO from qitems");
								mySqlBuf.append(" where GOODSNAME like '%" + edInput+"%'")
								.append(" order by FORMDATE DESC LIMIT 100");
								cursor = db.rawQuery(mySqlBuf.toString(), null);
								if (cursor.getCount()>0 && cursor.getCount()<=200){ //以品名查商品 mMode7,locates=0
									edserch=1;
									if(mMode!=PItemMode.SEARCH) {
										runGVP(",7,"+deptStr[8]);
									}else {
										runGVP(",7,0");
									}
								}else{
									Toast.makeText(APos.this,edInput+"查無此貨號!!", Toast.LENGTH_SHORT).show();									
								}
							}						
						}
					}					
				} else { //@@檢查如果關鍵字存在商品,即交給GALLERY 
					//需要完整的 主貨號
					mySqlBuf.delete(0, mySqlBuf.toString().length());
					
					if (selectM!=0){//qdetail
						mySqlBuf.append("select * from qdetail");
						if (!deptStr[8].equalsIgnoreCase("1")){  //主貨號搜尋
							mySqlBuf.append(" where GOODSNO  like '%" + edInput.trim()+"%'");  //完全符合
							mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT 50");
						}else{//原廠編號搜尋
							mySqlBuf.append(" where SOURCENO  like '" + edInput.trim()+"%'");  //完全符合
							mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT 50");
						}	
							cursor = db.rawQuery(mySqlBuf.toString(), null);
						
						if ((cursor.getCount()==1 && nSingle==1) ){
							edserch=1;
							cursor.moveToFirst();
							if ((cursor.getString(cursor.getColumnIndex("SIZE")).split(",").length==1 && cursor.getString(cursor.getColumnIndex("COLOR")).split("，").length==1) || deptStr[8].equalsIgnoreCase("2"))
							//代表只有一個顏色尺寸 或 HONEY
							{	
								String DGOODS=cursor.getString(cursor.getColumnIndex("GOODSNO"));
								String DCOLORNO=cursor.getString(cursor.getColumnIndex("COLORNO")).split("，")[0];
								String DSIZES=cursor.getString(cursor.getColumnIndex("SIZE")).split(",")[0];
								edInput=DGOODS+"-"+DCOLORNO+"-"+DSIZES;
								int YN=IsExistItem(msFno,((Button)findViewById(R.id.btn_100)).getText().toString(),edInput,PlusMinus);  //如果本單存在,作累加OK
								long result=0;
								if (YN !=1){ //本單不存在該商品,需NEW_QITEMS
									ContentValues value = new ContentValues();
									int isYn=YN; if (YN==0) isYn=2;
									upDBH(APos.this,isYn,msFno,value,datax); //先製作單頭一致的PUT
									String stkAt=DBUtil.getStk(this, db, myKind, rDept, msCust, edInput,PlusMinus);
									if (stkAt.indexOf("庫存不足")>0)
										Toast.makeText(this,stkAt , Toast.LENGTH_SHORT).show();
									value.put("FINEDATE",stkAt);
									data.mFinedate=stkAt;
									upDBIN(APos.this,cursor,value,data,edInput,cursor.getString(cursor.getColumnIndex("COLOR")),cursor.getString(cursor.getColumnIndex("SIZE")),cursor.getString(cursor.getColumnIndex("COLORNO")),2); //製作一筆新ITEM的基礎PUT
									result = db.insert(TbName.QITEMS, null, value);
								}
								if (YN !=0 || (result>0)){ //需維護QHEAD(總?)及其畫面相關資訊(應收)(+件數)(-件數)
										reItems(APos.this, msFno);
										String Toot=recountHead(APos.this,msFno,""); //嘗試給GalleryViewP呼叫 但不用如下顯示段
										String[] arrayFieldH = Toot.toString().split(";");
										((Button)findViewById(R.id.btn_receive)).setText(arrayFieldH[0]);
										((Button)findViewById(R.id.btn_inc)).setText(arrayFieldH[1]);	
										((Button)findViewById(R.id.btn_mic)).setText(arrayFieldH[2]);
								}

							}else{
								if(mMode!=PItemMode.SEARCH) {
									if (!deptStr[8].equalsIgnoreCase("1"))
										edInput=cursor.getString(cursor.getColumnIndex("GOODSNO"));
									else 
										edInput=cursor.getString(cursor.getColumnIndex("SOURCENO"));
									
									runGVP(",8,"+deptStr[8]);
								}	
							}
						}else if (cursor.getCount()==1){
							edserch=1;
							if(mMode!=PItemMode.SEARCH) {
								cursor.moveToFirst();
								if (!deptStr[8].equalsIgnoreCase("1"))
									edInput=cursor.getString(cursor.getColumnIndex("GOODSNO"));
								else 
									edInput=cursor.getString(cursor.getColumnIndex("SOURCENO"));
								
								runGVP(",8,"+deptStr[8]);
							}
						}else if (cursor.getCount()>0){
							edserch=1;
							if(mMode!=PItemMode.SEARCH)	runGVP(",5,"+deptStr[8]); 
						}
					}
					if (edserch==0){
						//qitems
						mySqlBuf.delete(0, mySqlBuf.toString().length());
						mySqlBuf.append("select distinct GOODSNO,SOURCENO from qitems");
						if (!deptStr[8].equalsIgnoreCase("1"))  //原廠編號搜尋
							mySqlBuf.append(" where GOODSNO  like '%" + edInput.trim()+"%'");  //完全符合
						else//主貨號搜尋
							mySqlBuf.append(" where SOURCENO  like '" + edInput.trim()+"%'");  //完全符合

						mySqlBuf.append(" order by FORMDATE DESC LIMIT 20");
						cursor = db.rawQuery(mySqlBuf.toString(), null);
						
						if (cursor.getCount()==1 && nSingle==1){ //唯一且單量的主貨號
							edserch=1;
							cursor.moveToFirst();
							edInput=cursor.getString(cursor.getColumnIndex("GOODSNO"));
							mySqlBuf.delete(0, mySqlBuf.toString().length());
							mySqlBuf.append("select distinct GOODSNO,GOODSNOS from qitems");
							mySqlBuf.append(" where GOODSNO  ='" + edInput.trim()+"'");  //完全符合
							mySqlBuf.append(" order by FORMDATE ");
							//20141019//mySqlBuf.append(" order by FORMDATE,CREATEDATETIME DESC");
							cursor = db.rawQuery(mySqlBuf.toString(), null);
							if ((cursor.getCount()==1) || (deptStr[8].equalsIgnoreCase("2")  && cursor.getCount()>1)){
								//唯一色尺寸或隨意唯一
								cursor.moveToLast();
								edInput=cursor.getString(cursor.getColumnIndex("GOODSNOS"));
								mySqlBuf.delete(0, mySqlBuf.toString().length());
								mySqlBuf.append("select distinct * from qitems");
								mySqlBuf.append(" where GOODSNOS  ='" + edInput.trim()+"'");  //完全符合
								mySqlBuf.append(" order by FORMDATE DESC LIMIT 1");
								cursor = db.rawQuery(mySqlBuf.toString(), null);
								cursor.moveToFirst();
								int YN=IsExistItem(msFno,((Button)findViewById(R.id.btn_100)).getText().toString(),edInput,PlusMinus);  //如果本單存在,作累加OK
								long result=0;
								if (YN !=1){ //本單不存在該商品,需NEW_QITEMS
		//							Toast.makeText(APos.this,"YN=false_BEFORE_insert", Toast.LENGTH_SHORT).show();									
									ContentValues value = new ContentValues();
									int isYn=YN; if (YN==0) isYn=2;
									upDBH(APos.this,isYn,msFno,value,datax); //先製作單頭一致的PUT
									String stkAt=DBUtil.getStk(this, db, myKind, rDept, msCust, edInput,PlusMinus);
									if (stkAt.indexOf("庫存不足")>0)
										Toast.makeText(this,stkAt , Toast.LENGTH_SHORT).show();
									value.put("FINEDATE",stkAt);
									data.mFinedate=stkAt;
									upDBIN(APos.this,cursor,value,data,edInput,"","","",0); //製作一筆新ITEM的基礎PUT
		
									//應再發展 單價 件數UNIT?? 折DISCOUNT 小計SUBPRICE or RATEPRICE 成本ACOST
									//@@目前寫一起
									result = db.insert(TbName.QITEMS, null, value);
								}
								if (YN !=0 || (result>0)){ //需維護QHEAD(總?)及其畫面相關資訊(應收)(+件數)(-件數)
									reItems(APos.this, msFno);
									String Toot=recountHead(APos.this,msFno,""); //嘗試給GalleryViewP呼叫 但不用如下顯示段
									
									String[] arrayFieldH = Toot.toString().split(";");
									((Button)findViewById(R.id.btn_receive)).setText(arrayFieldH[0]);
									((Button)findViewById(R.id.btn_inc)).setText(arrayFieldH[1]);  //強制轉型	
									((Button)findViewById(R.id.btn_mic)).setText(arrayFieldH[2]); //強制轉型
									
								}
							}else{ // if (cursor.getCount()>1) 代表同款,有多色尺寸
								cursor.moveToFirst();
								if (!deptStr[8].equalsIgnoreCase("1"))
									edInput=cursor.getString(cursor.getColumnIndex("GOODSNO"));
								else 
									edInput=cursor.getString(cursor.getColumnIndex("SOURCENO"));
								
								runGVP(",8,"+deptStr[8]);
							}	
						}else if (cursor.getCount()>0){
							//含 單筆&大宗 多筆單量 多筆大宗
							//因來源編號 有可能 同來源編號卻有多款商品
							edserch=1;
							if (cursor.getCount()<=200){
								if(mMode!=PItemMode.SEARCH) {
									if (deptStr[8].equalsIgnoreCase("1")) runGVP(",3,"+deptStr[8]); else runGVP(",1,0"); 
									//runGVP(",1,999");
								}else {
									runGVP(",0,"+deptStr[8]);
								}
							}else{
								Toast.makeText(APos.this,"找到的商品(>200)太多了!!請縮小範圍!!", Toast.LENGTH_SHORT).show();
							}
							
						}else{  //QITEMS無,再進入Qdetail只找完全相符
						if (selectM==0){
							mySqlBuf.delete(0, mySqlBuf.toString().length());
							mySqlBuf.append("select distinct GOODSNO from qdetail");
							if (deptStr[8].equalsIgnoreCase("0") || deptStr[8].equalsIgnoreCase("2")){  //原始的主貨號搜尋
								mySqlBuf.append(" where GOODSNO  ='" + edInput.trim()+"'");  //完全符合
							}else{
								mySqlBuf.append(" where SOURCENO  ='" + edInput.trim()+"'");  //完全符合
							}
							cursor = db.rawQuery(mySqlBuf.toString(), null);
							if (cursor.getCount()>0){
								edserch=1;
									if(mMode!=PItemMode.SEARCH) runGVP(",8,"+deptStr[8]);
							//}else{
							//	Toast.makeText(APos.this,edInput+"查無此貨號!!", Toast.LENGTH_SHORT).show();									
							}
						}
						if (edserch==0){
							mySqlBuf.delete(0, mySqlBuf.toString().length());
							mySqlBuf.append("select distinct GOODSNO from qdetail");
							mySqlBuf.append(" where PS  like '%" + edInput.trim()+"%'");  // 備註搜尋
							cursor = db.rawQuery(mySqlBuf.toString(), null);
							if (cursor.getCount()>0){
								edserch=1;
									if(mMode!=PItemMode.SEARCH) runGVP(",9,"+deptStr[8]);
							}else{
								Toast.makeText(APos.this,edInput+"查無此貨號!!", Toast.LENGTH_SHORT).show();									
							}
							
						}
						}
					}
				}
				db.close();
				if (cursor!=null) cursor.close();
			}	
		}else { //不論該單有無DATA,一律前進

			if(mMode!=PItemMode.SEARCH) {
				runGVP(",0,"+deptStr[8]);
			}else {
				runGVP(",0,"+deptStr[8]);
			}
		}
		pInput.setText("");
		pInput.requestFocus();
		
	}
	
//@EVENT事件補捉中心	
class MainClick implements OnClickListener {
	@Override
	public void onClick(View v) {
		int id = v.getId();
		Utilis.runVibrate(APos.this);
		
		switch (id) {
			case R.id.btn_exit:  //返回
			{
	        	Intent intentS = new Intent();
	        	intentS.putExtra("POS_modify",1);
	        	APos.this.setResult(RESULT_OK,intentS);
				finish();
				break;
			}
			case R.id.btn_nsave:  //留貨
			{//如何開啟該會員的留貨資料
			//確認轉單後!如何重新開啟這張暫存單
			if ((myKind==30 || myKind==31) && mMode!=PItemMode.SEARCH){
				Toast.makeText(APos.this,"驗證是哪一個客戶的留貨單!!"+msCust, Toast.LENGTH_SHORT).show();				
				Intent intent = new Intent();
				intent.putExtra("GalleryUser",msCust);
				intent.putExtra("GalleryGoods","");
				intent.putExtra("GalleryDept", rDept);
				intent.putExtra("GalleryASK"," and USER='"+msCust+"' ");
				intent.putExtra("FormNo",msFno);
				//intent.putExtra("FormNo",PosUtilis.getFno(APos.this,msCust,""+myKind,0));
				intent.putExtra("GalleryQKIND",msKind);
				intent.putExtra("GalleryMode",2);//0mUser 1mGoods 2KeepaToSale
				intent.setClass(APos.this, GalleryViewO.class);
				startActivityForResult(intent, RESULT_GALLERYO);
			}				
				break;
			}
			
			case R.id.btn_dels: //棄單
			{
				//除非是尚未確認的單,才可以棄單
				if (mMode!=PItemMode.SEARCH) {	
	   			 String[] dlgMenu=  { "刪除" ,"保留"  };
		   	        new AlertDialog.Builder(APos.this)
		   	        .setTitle("是否刪除本單 ?")
		   	        .setItems(dlgMenu, mListener2)
		   	        .setPositiveButton(R.string.str_cancel,
		   	        new DialogInterface.OnClickListener()
		   	        {
		   	          public void onClick(DialogInterface dialog, int which)
		   	          {
		   	          }
		   	        }).show();	
				}else{ //show message
	    			Toast.makeText(APos.this,"只能放棄查詢的單據!!無法刪單!!", Toast.LENGTH_SHORT).show();				            		
				}
				break;
			}

			case R.id.btn_date:
				{	
				if (mMode!=PItemMode.SEARCH) {	
					mYear=Utilis.toInt(datax.mFormdate.substring(0, 4));
					mMonth=Utilis.toInt(datax.mFormdate.substring(5, 7));
					mDay=Utilis.toInt(datax.mFormdate.substring(8, 10));
					Calendar c = Calendar.getInstance();
						c.set(Calendar.YEAR, mYear);
						c.set(Calendar.MONTH, mMonth - 1);
						c.set(Calendar.DAY_OF_MONTH, mDay);
						
					DateUtil.showDateDialog(APos.this, "請輸入正確交易日期", c, new IDateDialog(){
						@Override
						public void onDateDialogFinish(String date, int year, int month, int day) {
							((Button)findViewById(R.id.btn_date)).setText(date);
		            		datax.mFormdate=date;
		                    if (mFD==1 && (myKind==30 || myKind==31)){
		                    	msFD=date;
			            		Utilis.putIni(APos.this, "SYS","DEV", msFD, 8);
		                    }
				    			Toast.makeText(APos.this,"單據日期已改為:"+datax.mFormdate, Toast.LENGTH_SHORT).show();				            		
								updateDBHI(APos.this, msCust, msFno, msKind, 3); //0.USER 1.EMPID 2.DEPTNO 3.FORMDATE 4.DISCOUNT
								((Button)findViewById(R.id.btn_date)).setText(datax.mFormdate);									
						}
					});
				}	
	            	break;
				}
			case R.id.btn_custp:
				{
					Intent intent = new Intent();
				if (myKind!=10){
					if (nPart==1 && myKind==20){
		    			Toast.makeText(APos.this,"無需調整門市代號!!", Toast.LENGTH_SHORT).show();				            		
					} else {
						intent.putExtra("qcustf_qkind", myKind);
						intent.putExtra("qcustf_mode", QCustfMode.NORMAL); 
						intent.putExtra("qcustf_key", "");
						intent.putExtra("pos_dept", mDept);
						intent.setClass(APos.this, QCustff.class);
						startActivityForResult(intent, RESULT_QCUSTFF);
					}
				}else { //廠商基本檔
					intent.setClass(APos.this, Qfactff.class);
					intent.putExtra("mode", EMode.EDIT);
					intent.putExtra("countryid", 0);  //表不分國別
					startActivityForResult(intent, RESULT_QFACT);
					
				}
					break;
				}
			case R.id.btn_emp:
				{	
					Intent intent = new Intent();
					intent.putExtra("qcustf_qkind", PItemKind.TR40); //這是櫃員基本檔是為了交易員
					intent.putExtra("qcustf_mode", QCustfMode.NORMAL);
					intent.putExtra("qcustf_key", "");					
					intent.putExtra("pos_dept",Utilis.getIni(APos.this,"SYS","DEPT",6));					
					intent.setClass(APos.this, QCustff.class);
					
					startActivityForResult(intent, RESULT_QEMPFF);
					break;
				}
			
			case R.id.btn_dis01 :  //單量/大宗
			{ 
				if (nSingle==1) { //單量=>大宗
					nSingle=0;
					((Button)findViewById(R.id.btn_dis01)).setText("大宗");
					Utilis.putIni(APos.this, "INIH", "SW_UNIT", "0", (myKind/10));
					Utilis.putIni(APos.this, "INIH", "DISBTN1", "大宗", (myKind/10));
				}else{//大宗=>單量
					nSingle=1;
					((Button)findViewById(R.id.btn_dis01)).setText("單量");
					Utilis.putIni(APos.this, "INIH", "SW_UNIT", "1", (myKind/10));
					Utilis.putIni(APos.this, "INIH", "DISBTN1", "單量", (myKind/10));
				}
				
				break;
			}
			
			case R.id.ibtn_fno:
			{
				//1.採購單交易時優先查訪採購單,也同時啟動了同步採購單的功能
				if (Utilis.haveInternet(APos.this) && selectM!=0)
					DBCloud.aa0_aa1_auto_qdetail_n(APos.this);
				if (Utilis.haveInternet(APos.this) && Utilis.toInt(Utilis.getIni(APos.this, "SYS", "SEASON", 4))>0){
					DBCloud.aa0_aa1_auto_HI(APos.this,myKind);
					Toast.makeText(APos.this, "下載雲端_背景_同步中,請稍候.......!!", Toast.LENGTH_SHORT).show();
				}else Toast.makeText(APos.this, "正在雲端_背景_同步中,請稍候.......!!", Toast.LENGTH_SHORT).show();
				break;
			}
			case R.id.btn_dis02 :  //交易紀錄
			{
				Intent intent = new Intent();
				intent.putExtra("QHis_kind", myKind);
				intent.putExtra("QHis_mode", 0);
				intent.putExtra("QHis_User",msCust );
				intent.putExtra("QHis_Goods","" );
				intent.setClass(APos.this, QHis.class);
				startActivity(intent);
				
			break;
			}
			
			case R.id.btn_dis03 :
			{ 
				if (nQhis==0) { //標準->歷史
					nQhis=1;
					((Button)findViewById(R.id.btn_dis03)).setText("歷史");
				}else{//歷史->標準
					nQhis=0;
					((Button)findViewById(R.id.btn_dis03)).setText("標準");
				}
				
				break;
			}
			case R.id.btn_receive:
			{
				if (((Button)findViewById(R.id.btn_100)).isShown())
				((Button)findViewById(R.id.btn_100)).setVisibility(View.INVISIBLE);
				else
					((Button)findViewById(R.id.btn_100)).setVisibility(View.VISIBLE);
				break;
			}
			case R.id.btn_chg: //切換+-
				if (PlusMinus==1){ //由正轉負
					PlusMinus=-1;
					((Button)findViewById(R.id.btn_chg)).setText(Utilis.getIni(APos.this,"INIH","DISBTN5M",(myKind/10)));					
				} else{
					PlusMinus=1;
					((Button)findViewById(R.id.btn_chg)).setText(Utilis.getIni(APos.this,"INIH","DISBTN5",(myKind/10)));					
				}
				break;
				
			case R.id.btn_save:   //結帳
				{
					//@@@如果是預購單又是為客戶的留貨總單,應該要產生一張新的暫存單
		        	mAdapter.getData(APos.this,msFno);
					if (!datax.mIsconfirm.equalsIgnoreCase("O") && !datax.mIsconfirm.equalsIgnoreCase("R")){
						Intent intent = new Intent();
						intent.putExtra("pos_npart",nPart);
						intent.putExtra("pos_mode",mMode);
						intent.putExtra("pos_formno",msFno);
						intent.putExtra("pos_qkind",myKind);//int @@TR30 
						intent.putExtra("pos_where",PsaveWhere.Apos);
						intent.putExtra("pos_group", mGroup);
						
						intent.setClass(APos.this,QPosSave.class);
						startActivityForResult(intent, RESULT_QPOSAVE);
					}else{
							recountHead(APos.this,msFno,"");
							if (Utilis.haveInternet(APos.this) && of_line==1  ) {
								DBCloud.aa1_aa0_update_HI(APos.this);
							}
				        	Intent intentS = new Intent();
				        	intentS.putExtra("POS_modify",1);
				        	APos.this.setResult(RESULT_OK,intentS);
							finish();
					}
					break;
				}
				
			case R.id.btn_100:
			{
				if (mMode!=PItemMode.SEARCH){ //非查詢狀態
					DialogUtilis.showComputer(APos.this, id);
					datax.dDiscount=Utilis.toDouble(((Button)findViewById(R.id.btn_100)).getText().toString());
				}
				if (nHintDisc==1) ((Button)findViewById(R.id.btn_100)).setVisibility(View.INVISIBLE);
				break;
			}

			case R.id.ibtn_input:
			{
				if (mMode!=PItemMode.SEARCH ) chkKeyin(pInput.getText().toString());
				break;
			}
			case R.id.btn_his:  //暫存
			{
				mMode = PItemMode.ADD;
	        	iniHead();  	//一張新的單據
	        	iniItems();	//一筆新的商品
	        	mAdapter.getData(APos.this,msFno);
	        	//mAdapter.notifyDataSetChanged();			        	
	        	Toast.makeText(APos.this, "已完成暫存!!並新增中.........", Toast.LENGTH_SHORT).show();

			break;
		}
			
		} //end_switch
		pInput.requestFocus();

	}
	
}

class MainLongClick implements OnLongClickListener { //所有長按的觸發事件,在此集中管理
	@Override
	public boolean onLongClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		Utilis.runVibrate(APos.this);
		switch (id) {
		case R.id.ibtn_input:  //搜尋各門市的庫存
		  {
			if (pInput.getText().toString().length()>0) { //總倉,且要輸入有值
				SQLiteDatabase db = Utilis.getDB(APos.this);
				StringBuffer mySqlBuf = new StringBuffer();
				mySqlBuf.append("select distinct * from qdetail");
				mySqlBuf.append(" where GOODSNO like '%" + pInput.getText().toString().trim()+"%'");  //
				mySqlBuf.append(" order by BATCH DESC LIMIT 300");
				Cursor cursor = db.rawQuery(mySqlBuf.toString(), null);
					if (cursor.getCount()>0){ //
						cursor.moveToFirst();
						String serch="'"+cursor.getString(cursor.getColumnIndex("GOODSNO"))+"'";
						cursor.moveToNext();
						for (int e=1;e<cursor.getCount();e++){
							serch=serch+",'"+cursor.getString(cursor.getColumnIndex("GOODSNO"))+"'";
							cursor.moveToNext();
						}
						
						Bundle bundle = new Bundle();
						Intent intent = new Intent();
						bundle = new Bundle();
						bundle.putString("GalleryChild",serch+";0;1");
						intent.setClass(APos.this, GalleryViewS.class);
						intent.putExtras(bundle);
						startActivity(intent);
					}
				db.close();
				cursor.close();
			}else{
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
				bundle = new Bundle();
				bundle.putString("GalleryChild","'pppppppppppppppppp'"+";0;1");
				intent.setClass(APos.this, GalleryViewS.class);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		  }	
		}
		return true;
	}
}

 private void runGVP(String mode){
	 
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		bundle = new Bundle();
		bundle.putString("GalleryChild",edInput+","+nQhis+","+((Button)findViewById(R.id.btn_100)).getText().toString()+","+msFno+","+msKind+mode+","+mDept+",0");
		intent.setClass(APos.this, GalleryViewP.class);
		intent.putExtras(bundle);
		startActivityForResult(intent, RESULT_GALLERY);
 }

	class PItemAdapter extends BaseAdapter{
		
		private LayoutInflater mInflater;
		
		LinkedList<PItemData> mPList = new LinkedList<PItemData>();	
		
		public PItemAdapter (Context context){
		      mInflater = LayoutInflater.from(context);
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mPList.size();
		}
		
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mPList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				//這是個展現ITEM的容器,可以制訂出幾種版面後,做引數供選擇
				convertView = mInflater.inflate(R.layout.list_pos, null);
				
				holder = new ViewHolder();
				holder.imageItem = (ImageView)convertView.findViewById(R.id.img_ppic);
				holder.textGoodsNos = (TextView) convertView.findViewById(R.id.text_pgoodsnos);
				holder.textSenter = (TextView) convertView.findViewById(R.id.text_psenter);
				holder.textImpo = (TextView) convertView.findViewById(R.id.text_pimpo);
				holder.textName = (TextView) convertView.findViewById(R.id.text_pname);
				holder.textMoney = (TextView) convertView.findViewById(R.id.text_pmoney);
				holder.textNumber = (TextView) convertView.findViewById(R.id.text_pnumber);
				holder.textCountry = (TextView) convertView.findViewById(R.id.text_pcountry);
				holder.textCompany = (TextView) convertView.findViewById(R.id.text_pcompany);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

	        if (QPosff.PSWD==1 && (myKind==10 || myKind==20 || myKind==21)){  //密碼不OK 
	        	holder.textMoney.setVisibility(View.INVISIBLE);
	        	holder.textCompany.setVisibility(View.INVISIBLE);
	        }			
//假想這是一個共用的容器,命名改為ADApter為主			
//			java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.0");
			PItemData datas = new PItemData();			
			datas = mPList.get(position);
//			holder.imageItem.setImageBitmap(Utilis.getSmallPic(datas.mPic));
			holder.imageItem.setImageBitmap(Utilis.getLimitBitmap(datas.mPic, 80, 80));
			
			holder.textGoodsNos.setText(datas.mGoodsNos+"("+datas.mUnit1+")");
			
			if (f123==0) holder.textMoney.setText("x單價:" + Math.round((datas.dUnitprice)));
			else holder.textMoney.setText("x單價:" + Utilis.dedb (datas.dUnitprice,2));
			if (f123==0) holder.textCompany.setText("=小計:" + Math.round((datas.dsubprice)));
			else holder.textCompany.setText("=小計:" + Utilis.dedb (datas.dsubprice,2));
			if (nHintDisc==0)
				holder.textNumber.setText( "x "+datas.dDiscount);  //discount
			else
				holder.textNumber.setText("");
			
			switch (myKind){
			case 10:	holder.textImpo.setText("進: " + Math.round(datas.dUnit10)+"件");	break;
			case 20:	holder.textImpo.setText("出: " + Math.round(datas.dUnit20)+"件");	break;
			case 21:	holder.textImpo.setText("出: " + Math.round(datas.dUnit20)+"件");	break;
			case 30:	holder.textImpo.setText("銷: " + Math.round(datas.dUnit30)+"件");	break;
			case 31:	holder.textImpo.setText("銷: " + Math.round(datas.dUnit30)+"件");	break;
			case 40:	holder.textImpo.setText("員購:" + Math.round(datas.dUnit40)+"件");	break;
			case 41:	holder.textImpo.setText("員購:" + Math.round(datas.dUnit40)+"件");	break;
			}
			
			holder.textName.setText(datas.mGoodsName);
			holder.textSenter.setText(datas.mFinedate);
			
			if (nHintDisc==0)
				holder.textCountry.setText(tradeStr[datas.nTrade]+"("+datas.mPS+")");
			else
				holder.textCountry.setText(tradeStr[datas.nTrade]);
			
			return convertView;
		}

		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textGoodsNos; 	//左上 原貨號-->明細貨號mGoodsNos
			TextView textSenter;  		//右上 總件數-->總件數 進unit10 出unit20 銷unit30 員購unit40
			TextView textImpo;  		//右上 總件數-->總件數 進unit10 出unit20 銷unit30 員購unit40
			TextView textName; 		//左中 品名稱-->品名mGoodsName
			TextView textMoney;		//右中 合計金-->dSubprice
			TextView textCountry;		//左下 產地		-->交易方式(追加)(退)
			TextView textNumber;	//中下 來原編-->折數
			TextView textCompany;	//右下 供應商-->小計
			
		}
		
		
//以下針對一張單,進行拜訪,並顯示在畫面,供(查詢)流覽(編輯)等
//讀取時有 10進貨單 20出貨單 30銷貨單 40員購單  60盤損單 70故障單
//isconfirm =null (暫存單)不認帳   "N"訂單-(30銷)時營業日報需計算訂金  "Y"已確認單

		public void getData(Context context, String formNo){

			SQLiteDatabase db = Utilis.getDB(context);
			int isHead=0;
			try{  //先從HEAD讀起 可能是進貨單10 出貨單20 銷貨單30
				StringBuffer mBuf = new StringBuffer();
				mBuf.append("select * from " + TbName.QHEAD).append(" where FORMNO='").append(formNo).append("'");
				mBuf.append(" and QKIND ='"+msKind+"'");
				//@@@@mBuf.append(" and QKIND =LIKE '").append(msKind.substring(0,1)).append("%'");
				
			Cursor cursorh = db.rawQuery(mBuf.toString(), null);
			if(cursorh != null){
				try{
					if(cursorh.getCount() > 0){  
						isHead=1; //表示單頭檔正常存在 ,否則需重建
						cursorh.moveToFirst();
				    	Toast.makeText(context, msFno+"資料載入中...請稍候!", Toast.LENGTH_SHORT).show();
						
						datax.mTR = cursorh.getString(cursorh.getColumnIndex("TR"));
						datax.nID = cursorh.getInt(cursorh.getColumnIndex("ID"));
//一定等於xKind						edKind = cursor.getString(cursor.getColumnIndex("QKIND"));
						datax.mHandno=cursorh.getString(cursorh.getColumnIndex("HANDNO"));
						datax.mFno = cursorh.getString(cursorh.getColumnIndex("FORMNO"));
						datax.mFormdate = cursorh.getString(cursorh.getColumnIndex("FORMDATE"));
						datax.mTime = cursorh.getString(cursorh.getColumnIndex("CREATEDATETIME"));
						datax.mIsconfirm = cursorh.getString(cursorh.getColumnIndex("ISCONFIRM"));
						datax.mIscheck = cursorh.getString(cursorh.getColumnIndex("ISCHECK"));
						datax.mEmpid = cursorh.getString(cursorh.getColumnIndex("EMPID"));
						datax.mEmpname = cursorh.getString(cursorh.getColumnIndex("EMPNAME"));
						datax.mUser = cursorh.getString(cursorh.getColumnIndex("USER"));
						msCust=datax.mUser;
						datax.mUsername = cursorh.getString(cursorh.getColumnIndex("USERNAME"));
						datax.nTrade = cursorh.getInt(cursorh.getColumnIndex("TRADETYPE"));
						msTrade=datax.nTrade;
						datax.mDeptno = cursorh.getString(cursorh.getColumnIndex("DEPTNO"));
						//這是防堵為何 DB 的 DEPTNO 為空字元
						if (datax.mDeptno == null || datax.mDeptno.length()<=0) datax.mDeptno=rDept; 
						datax.mOrddate = cursorh.getString(cursorh.getColumnIndex("ORDDATE"));
						datax.mFinedate = cursorh.getString(cursorh.getColumnIndex("FINEDATE"));
						//以上16欄位為共用
						
						datax.mIslist = cursorh.getString(cursorh.getColumnIndex("ISLIST"));
						datax.mBankno = cursorh.getString(cursorh.getColumnIndex("BANKNO"));
						datax.mBankname = cursorh.getString(cursorh.getColumnIndex("BANKNAME"));
						datax.dOrdcash = cursorh.getDouble(cursorh.getColumnIndex("ORDCASH"));
						datax.dOrdcard = cursorh.getDouble(cursorh.getColumnIndex("ORDCARD"));
						datax.dCash = cursorh.getDouble(cursorh.getColumnIndex("CASH"));
						datax.dCard = cursorh.getDouble(cursorh.getColumnIndex("CARD"));
						datax.dAtot = cursorh.getDouble(cursorh.getColumnIndex("ATOT"));
						datax.dAsum = cursorh.getDouble(cursorh.getColumnIndex("ASUM"));
						datax.dBsum = cursorh.getDouble(cursorh.getColumnIndex("BSUM"));
						datax.dCosts = cursorh.getDouble(cursorh.getColumnIndex("COSTS"));
						datax.dTuresum = cursorh.getDouble(cursorh.getColumnIndex("TURESUM"));
						datax.dDismoney = cursorh.getDouble(cursorh.getColumnIndex("DISMONEY"));
						datax.dAtm = cursorh.getDouble(cursorh.getColumnIndex("ATM"));
						datax.dTrcash = cursorh.getDouble(cursorh.getColumnIndex("TRCASH"));
						datax.mAtmdate = cursorh.getString(cursorh.getColumnIndex("ATMDATE"));
						datax.mhPs = cursorh.getString(cursorh.getColumnIndex("PS"));
						datax.mhPs1 = cursorh.getString(cursorh.getColumnIndex("PS1"));
						datax.mhPs2 = cursorh.getString(cursorh.getColumnIndex("PS2"));
						String mHandno=datax.mHandno;
						if (mHandno!=null && mHandno.length()>0){
							if (mHandno.indexOf("+")>=0 && mHandno.indexOf("-")>0){
								datax.dInc=Utilis.toInt(mHandno.substring(mHandno.indexOf("+")+1,mHandno.indexOf("-")));
								datax.dMic=Utilis.toInt(mHandno.substring(mHandno.indexOf("-")));
							}else if (mHandno.indexOf("+")>=0){
								datax.dInc=Utilis.toInt(mHandno.substring(mHandno.indexOf("+")+1));
								datax.dMic=0;
							}else{
								datax.dInc=0;datax.dMic=0;
							}
						}else{
							datax.dInc=0;datax.dMic=0;
						}
						BigDecimal bigAsum = new BigDecimal(datax.dAsum);
						((Button)findViewById(R.id.btn_receive)).setText(bigAsum.toString());
						((Button)findViewById(R.id.btn_inc)).setText(""+datax.dInc);	
						((Button)findViewById(R.id.btn_mic)).setText(""+datax.dMic);
						((Button)findViewById(R.id.edps1)).setText(""+datax.mhPs1);
						((Button)findViewById(R.id.edps)).setText(""+datax.mhPs);
						mBuf = mBuf.delete(0, mBuf.toString().length());
						if (!msKind.equalsIgnoreCase("10"))
							mBuf.append("select DISCOUNT,S2 from qcust where  CUSTNO='"+msCust+"' and TR= '"+msKind.substring(0, 1)+"0'" );
						else
							mBuf.append("select DISCOUNT,EMPID from qfact where  FACTNO='"+msCust+"'" );
						
						Cursor cs = db.rawQuery(mBuf.toString(), null);
						if (cs.getCount()>0){
							cs.moveToFirst();
								datax.dDiscount=cs.getDouble(0);
								fQhis=cs.getString(1);
								hisDiscount=datax.dDiscount;
								((Button)findViewById(R.id.btn_100)).setText(""+datax.dDiscount);
								if (datax.dDiscount<90 || nHintDisc==1)
									((Button)findViewById(R.id.btn_100)).setVisibility(View.INVISIBLE);
								else
									((Button)findViewById(R.id.btn_100)).setVisibility(View.VISIBLE);
								
						}		
						//為head專用 以下維護畫面顯示細節
						cs.close();
						if ( !fQhis.equalsIgnoreCase("1")){
							nQhis=1;  //歷史價
					       	((Button)findViewById(R.id.btn_dis03)).setText("歷史");
						}else {
							nQhis=0;  //標準價
				        	((Button)findViewById(R.id.btn_dis03)).setText("標準");
						}
						iniMode();
						iniScreenData();
						isHead=1;
						}
					}catch(Exception e){
						e.printStackTrace();
					}finally{
						cursorh.close();
						cursorh = null;
					}
				}
			
			}catch(Exception e){
				e.printStackTrace();
			}
			db.close();
			reItems(APos.this, formNo);
		}					
		
	}  //PItemAdapter ended
	
	//@@這是一個通用的QHEAD_欄位更新的呼叫
	//使用時機 會員櫃員日期的異動&QITEMS的連動異動&結帳功能
	public static void upDBH(Context context,int xMode,String Fno,ContentValues value,PItemData datax ){  //0新增 1.更新 2.只要upDBH 不要存入DB
		//value.put("TR", datax.mTR);
		value.put("TR", msKind);
		value.put("QKIND", msKind);
		value.put("FORMNO", Fno);
		
		if (msKind.substring(0, 1).equalsIgnoreCase("1") && xMode==2)
			value.put("HANDNO", datax.mBatch);
		else
			value.put("HANDNO", datax.mHandno);
		
		value.put("FORMDATE", datax.mFormdate);
		if (xMode==3)
			value.put("CREATEDATETIME",CTIME );
		else	
			value.put("CREATEDATETIME", DateUtil.getSystemTime().substring(2,14));
		//@@@
		value.put("ISCONFIRM", datax.mIsconfirm);
		value.put("ISCHECK", datax.mIscheck);

		value.put("EMPID", datax.mEmpid);
		value.put("EMPNAME", datax.mEmpname);
		value.put("USER", datax.mUser);
		value.put("USERNAME", datax.mUsername);
		value.put("TRADETYPE", datax.nTrade);
		value.put("DEPTNO", datax.mDeptno);
		
	if (xMode<2){	
		SQLiteDatabase db = Utilis.getDB(context);
		value.put("ID", "0"); // 
		value.put("ISLIST", "");
		value.put("ORDCASH", 0);
		value.put("ORDCARD", 0);
		value.put("CASH", 0);
		value.put("CARD", 0);
		value.put("ATOT", 0);
		value.put("ORDDATE", "");
		value.put("FINEDATE","");
		value.put("ASUM",0);
		value.put("BSUM",0);
		value.put("BILLRATE",0);
		value.put("TURESUM",0);
		value.put("DISMONEY",0);
		value.put("ATM",0);
		value.put("TRCASH",0);
		value.put("ATMDATE","");
		value.put("PS","");
		value.put("PS1","");
		value.put("PS2","");

		value.put("BANKNO",datax.mBankno);
		value.put("BANKNAME",datax.mBankname);
		
		if (xMode==0){
			long result = db.insert(TbName.QHEAD, null, value);
			db.close();
		} else {
			String[] args = {Fno};
			int success = db.update(TbName.QHEAD, value,"FORMNO=? ", args);
		}
		
		db.close();
	}
	}//end upbhH
	
	//QHIS 歷史價的重大功能
	public boolean Qhis(Context context,String user,String goodsno,String year,int season,int mode){
		//需取得 (單價)(折) mode=0原歷史價 mode=1對照表
		boolean YN=false;
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cs = null;					
		StringBuffer mySqlBuf = new StringBuffer();
		if (mode==0){
			mySqlBuf.append("select UNITPRICE,DISCOUNT,P0,GOODSNAME from qitems");
			mySqlBuf.append(" where GOODSNO = '" + goodsno+"'");
			
			if (user.indexOf("Z")==0 && myKind==31)//專櫃預設為實銷會員代號
				mySqlBuf.append(" and (USER= '"+user+"' or DEPTNO='"+user.substring(1)+"')");
			else
				mySqlBuf.append(" and USER= '"+user+"' and QKIND= '"+msKind+"'");
			
			mySqlBuf.append(" order by FORMDATE,CREATEDATETIME");  //取得最新一筆交易的歷史單價 折
			
			cs = db.rawQuery(mySqlBuf.toString(), null);
		
			if (cs.getCount()>0){ //找到唯一貨號後,檢查有否本單重覆的貨號
				cs.moveToLast();
				
				hisUnitprice=cs.getDouble(cs.getColumnIndex("UNITPRICE"));
					hisDiscount=cs.getDouble(cs.getColumnIndex("DISCOUNT"));
				hisP0=cs.getDouble(cs.getColumnIndex("P0"));
				YN=true;
				Toast.makeText(APos.this, "歷史價"+hisUnitprice, Toast.LENGTH_SHORT).show();							
			}
		}else{//對照表
			mySqlBuf.append("select APRI from qc_ppri where BPRI='"+goodsno+"' and YEAR='"+year+"' and SEASON='"+season+"'");
			Toast.makeText(APos.this, "歷史價/對照表"+goodsno+" YEAR="+year+" SEASON="+season, Toast.LENGTH_SHORT).show();							
			cs = db.rawQuery(mySqlBuf.toString(), null);
			
			if (cs.getCount()>0){ //找到唯一貨號後,檢查有否本單重覆的貨號
				cs.moveToFirst();
				hisUnitprice=cs.getDouble(0);
				hisDiscount=100;
				YN=true;
			}	
			
		}
		db.close();	
		cs.close();
		return YN;
		
	}
	
	//用途:新增一筆新的ITEM
	public void upDBIN(Context context,Cursor cursorx,ContentValues value,PItemData dataxx,String mInput,String Scols,String Ssizs,String Scoln,int modex){ 
		value.put("SUPPLY",cursorx.getString(cursorx.getColumnIndex("SUPPLY")));
		value.put("SOURCENO",cursorx.getString(cursorx.getColumnIndex("SOURCENO")));
		value.put("GOODSNO",cursorx.getString(cursorx.getColumnIndex("GOODSNO")));
		int nUnit=1;
		String qhisYear="";
		if (modex==0){
				value.put("ID",cursorx.getString(cursorx.getColumnIndex("ID")));
				value.put("GOODSNOS",cursorx.getString(cursorx.getColumnIndex("GOODSNOS")));
				value.put("COLOR",cursorx.getString(cursorx.getColumnIndex("COLOR")));
				value.put("SIZE",cursorx.getString(cursorx.getColumnIndex("SIZE")));
				value.put("UNIT1", cursorx.getString(cursorx.getColumnIndex("UNIT1")));
				value.put("UNIT2", cursorx.getString(cursorx.getColumnIndex("UNIT2")));
				value.put("COLORS",cursorx.getString(cursorx.getColumnIndex("COLORS")));
				value.put("SIZES",cursorx.getString(cursorx.getColumnIndex("SIZES")));
				value.put("GOODSTYPE",cursorx.getString(cursorx.getColumnIndex("GOODSTYPE")));
				value.put("ORDDATE",cursorx.getString(cursorx.getColumnIndex("ORDDATE")));
				qhisYear=cursorx.getString(cursorx.getColumnIndex("YEAR"));
				if (cursorx.getInt(cursorx.getColumnIndex("ORDDATE"))>1) nUnit=cursorx.getInt(cursorx.getColumnIndex("ORDDATE"));
				
		}else if (modex==1 || modex==2){//需組合顏色尺寸
			if (modex==1) value.put("ID",cursorx.getString(cursorx.getColumnIndex("ID"))); else value.put("ID",cursorx.getString(cursorx.getColumnIndex("STATE")));  
			String mcol=mInput.substring(mInput.indexOf("-")+1, mInput.indexOf("-")+3);
			String msiz="F";String mcols="混色";
			if (mInput.lastIndexOf("-")>mInput.indexOf("-")){
				mcol=mInput.substring(mInput.indexOf("-")+1, mInput.lastIndexOf("-"));
				msiz=mInput.substring(mInput.lastIndexOf("-")+1);
			}
			value.put("GOODSNOS",mInput);
			value.put("COLOR",mcol);
			value.put("SIZE",msiz);
			
			qhisYear=cursorx.getString(cursorx.getColumnIndex("UNIT2"));
			//如何取得色名?
			mcols=getAcolorName(Scols,Scoln,mcol);
			String [] mColorMore=mcols.split(";");
			if (Ssizs.indexOf(msiz)<0) Ssizs=Ssizs+","+msiz; 
			value.put("ORDDATE",cursorx.getString(cursorx.getColumnIndex("UNIT")));
			if (cursorx.getInt(cursorx.getColumnIndex("UNIT"))>1) nUnit=cursorx.getInt(cursorx.getColumnIndex("UNIT"));
			value.put("UNIT1",mColorMore[0]);
			value.put("UNIT2", mColorMore[2]);
			value.put("COLORS",mColorMore[1]);
			value.put("SIZES",Ssizs);
			 if (modex==1) //qitems with new Color or Size 
				 value.put("GOODSTYPE",cursorx.getString(cursorx.getColumnIndex("GOODSTYPE")));
			 else{ //qdetail change to TypeName
				 String qType=cursorx.getString(cursorx.getColumnIndex("GOODSTYPE"));
				 value.put("GOODSTYPE",getAtypeName(qType));
			 }
		}
		value.put("GOODSNAME",cursorx.getString(cursorx.getColumnIndex("GOODSNAME")));
		value.put("UNIT10",0);
		value.put("UNIT20",0);
		value.put("UNIT30",0);
		value.put("UNIT40",0);
		value.remove("UNIT"+msKind.substring(0, 1)+"0");
		
		value.put("UNIT"+msKind.substring(0, 1)+"0", PlusMinus*nUnit);
		if (datax.mIscheck.equalsIgnoreCase("Y")) value.put("UNIT", PlusMinus*nUnit); else value.put("UNIT", 0); 
		//How to Make UNIT when O R N
		value.put("RATEPRICE",0);
		value.put("REALSUM",0);
			double disc=Utilis.toDouble((((Button)findViewById(R.id.btn_100)).getText().toString()));
			double upri=cursorx.getDouble(cursorx.getColumnIndex("P"+msTrade));
			
			int checkP=0;
			hisUnitprice=upri;
			hisDiscount=disc;
			hisP0=cursorx.getDouble(cursorx.getColumnIndex("P0"));
			bQHIS=false;
			if (cursorx.getString(cursorx.getColumnIndex("GOODSNAME")).indexOf("*")==0)
				hisDiscount=100;
			else {
				if (((sQhis==4 && msTrade==3) || (sQhis==5 && msTrade==5))  && myKind==31){
					//@@@20190701
					//無論是標準價或歷史價 職 只要是 啟動 對照表 而且是 批發價 
					bQHIS=Qhis(this,datax.mUser,cursorx.getString(cursorx.getColumnIndex("P5")),qhisYear,cursorx.getInt(cursorx.getColumnIndex("SEASON")),1);
					if (bQHIS==true) checkP=1;
				}
				if (checkP==0){//當對照表不存在時 或 不是 對照表時 
					if (nQhis==1 )//當歷史價時
						bQHIS=Qhis(this,datax.mUser,cursorx.getString(cursorx.getColumnIndex("GOODSNO")),"",0,0);
				}
			}
		//if (hisDiscount<1) hisDiscount=100; //萬一維護不當時
		value.put("P0",hisP0);
		value.put("UNITPRICE",hisUnitprice);
		if (f123==0) value.put("SUBPRICE",Math.round(hisUnitprice*hisDiscount*PlusMinus*nUnit/100 ));
		else value.put("SUBPRICE",Utilis.dedb (hisUnitprice*hisDiscount*PlusMinus*nUnit/100,2 ));
		if (f123==0) value.put("ACOST", Math.round(cursorx.getDouble(cursorx.getColumnIndex("P1"))*PlusMinus*nUnit));
		else  value.put("ACOST", Utilis.dedb(cursorx.getDouble(cursorx.getColumnIndex("P1"))*PlusMinus*nUnit,3));
		value.put("DISCOUNT",hisDiscount );
		value.put("TRADETYPE",msTrade );
		String mPS="";
		if (bQHIS && PlusMinus>0 && checkP==0) mPS="追";
		else if (PlusMinus<0) mPS="退";
		if (hisDiscount<100) mPS=mPS+(int)hisDiscount;
		value.put("PS",mPS);
		
		value.put("P1",cursorx.getDouble(cursorx.getColumnIndex("P1")));
		value.put("P2",cursorx.getDouble(cursorx.getColumnIndex("P2")));
		value.put("P3",cursorx.getDouble(cursorx.getColumnIndex("P3")));
		value.put("P4",cursorx.getDouble(cursorx.getColumnIndex("P4")));
		value.put("P5",cursorx.getDouble(cursorx.getColumnIndex("P5")));
		 if (modex==2){
			 value.put("RATE",cursorx.getDouble(cursorx.getColumnIndex("BILLRATE")));
			 //@@@應換回中文國別
			 value.put("COUNTRY",getCountryName(cursorx.getString(cursorx.getColumnIndex("COUNTRY"))));
		 }else{
			 value.put("RATE",cursorx.getDouble(cursorx.getColumnIndex("RATE")));
			 value.put("COUNTRY",cursorx.getString(cursorx.getColumnIndex("COUNTRY")));
		 }
		value.put("YEAR",qhisYear);
		value.put("PIC",cursorx.getString(cursorx.getColumnIndex("PIC")));
		value.put("SEASON",cursorx.getString(cursorx.getColumnIndex("SEASON")));
		value.put("BATCH",cursorx.getString(cursorx.getColumnIndex("BATCH")));
		

	}	

	private String getCountryName(String countryNo){
		String returnName="";
		SQLiteDatabase db = Utilis.getDB(this);
		Cursor csC=db.rawQuery("select NAME from qc_country where _ID="+countryNo, null);
		if (csC.getCount()>0){
			csC.moveToFirst();
			returnName=csC.getString(0);
		}else{
			returnName=	countryNo;
		}
		csC.close();
		db.close();
		return returnName;
	}
	
	private String getAcolorName(String ColorNames,String ColorNos,String aColorNo){
		//如何取得色名?
		String aColorName="混色";
		String []mNos=ColorNos.split("，") ;
		String []mNames=ColorNames.split("，") ;
		int chkC=0;
		for (int i=0;i<mNos.length;i++){
			if (mNos[i].equalsIgnoreCase(aColorNo)){
				aColorName=mNames[i];
				chkC=1;break;
			}
		}
		if (chkC==0){
			SQLiteDatabase db = Utilis.getDB(this);
			Cursor csc = db.rawQuery("select * from qc_color where `NO` ='"+aColorNo+"'", null);
			if (csc.getCount()>0){
				csc.moveToFirst();
				ColorNos=ColorNos+"，"+csc.getString(csc.getColumnIndex("NO"));
				ColorNames=ColorNames+"，"+csc.getString(csc.getColumnIndex("TXT"));
				aColorName=csc.getString(csc.getColumnIndex("TXT"));
				chkC=1;
			}
		db.close();
		csc.close();
		}
		return aColorName+";"+ColorNames+";"+ColorNos; 
	}
	
	private String getAtypeName(String typeNo){
		String typeName=typeNo;
		SQLiteDatabase db = Utilis.getDB(this);
		Cursor csc = db.rawQuery("select * from qc_type where `_ID` ='"+typeNo+"'", null);
		if (csc.getCount()>0){
			csc.moveToFirst();
			typeName=csc.getString(csc.getColumnIndex("GOODTYPE"));
		}
		db.close();
		csc.close();
		return typeName;
	}
	
	private void iniKind(){ //單別不同的初始化參數設定B式搜尋法
			((Button)findViewById(R.id.btn_dis01)).setText(Utilis.getIni(this,"INIH","DISBTN1",(myKind/10)));
			((Button)findViewById(R.id.btn_dis02)).setText(Utilis.getIni(this,"INIH","DISBTN2",(myKind/10)));		
			((Button)findViewById(R.id.btn_dis03)).setText(Utilis.getIni(this,"INIH","DISBTN3",(myKind/10)));
			//((Button)findViewById(R.id.btn_dis04)).setText(Utilis.getIni(this,"INIH","DISBTN4",(myKind/10)));	
			((Button)findViewById(R.id.btn_chg)).setText(Utilis.getIni(this,"INIH","DISBTN5",(myKind/10)));
			((Button)findViewById(R.id.btn_100)).setText(Utilis.getIni(this,"INIH","DISBTN6",(myKind/10)));
			if (Utilis.toDouble(((Button)findViewById(R.id.btn_100)).getText().toString())<90 || nHintDisc==1)
				((Button)findViewById(R.id.btn_100)).setVisibility(View.INVISIBLE);
			else
				((Button)findViewById(R.id.btn_100)).setVisibility(View.VISIBLE);
	}

	private void iniScreenData(){
	   	 //必然的顯示   	 
			((Button)findViewById(R.id.btn_fno)).setText(msFno);
			((Button)findViewById(R.id.btn_date)).setText(datax.mFormdate);
			((Button)findViewById(R.id.btn_emp)).setText(datax.mEmpid+"/"+datax.mEmpname);
			((Button)findViewById(R.id.btn_custp)).setText(datax.mUser+"/"+datax.mUsername);
			((Button)findViewById(R.id.btn_dis04)).setText(tradeStr[datax.nTrade]);
			((Button)findViewById(R.id.btn_dept)).setText(datax.mDeptno);
			BigDecimal bigAsum = new BigDecimal(datax.dAsum);
			((Button)findViewById(R.id.btn_receive)).setText("$"+bigAsum.toString());
			((Button)findViewById(R.id.btn_inc)).setText("+"+datax.dInc);
			((Button)findViewById(R.id.btn_mic)).setText(""+datax.dMic);
			((Button)findViewById(R.id.edps1)).setText(datax.mhPs1);
			((Button)findViewById(R.id.edps)).setText(datax.mhPs);
	}
	
	private void iniMode(){
    	//  應該交給mMode 整合判斷
	   	String btns=null;
	   	String[] bttns;
   	 if(mMode == PItemMode.SEARCH){ //查詢將控制不可編輯的細節         	
		setTitle(getResources().getText(R.string.app_name).toString()+pKind[(myKind/10)-1]+"查詢中");
     	btns=Utilis.getIni(this,"INIH","BTN_SEARCH",9);  //參數設定A式搜尋法
	   		bttns = btns.split("!&!");
	   		
	   		//鎖住所有不可執行的按鈕
	        ((Button)findViewById(R.id.btn_emp)).setClickable(false);
	        ((Button)findViewById(R.id.btn_custp)).setClickable(false);
	        ((ImageButton)findViewById(R.id.ibtn_date)).setClickable(false);
	        ((Button)findViewById(R.id.btn_date)).setClickable(false);
	        ((ImageButton)findViewById(R.id.ibtn_input)).setClickable(false);  
	        pInput.setClickable(false);
	        ((Button)findViewById(R.id.btn_dis01)).setClickable(false);

	        ((Button)findViewById(R.id.btn_dis03)).setClickable(false);

	        ((Button)findViewById(R.id.btn_chg)).setClickable(false);
	        ((Button)findViewById(R.id.btn_100)).setClickable(false);
	        ((Button)findViewById(R.id.edps1)).setClickable(false);	   		
	        ((Button)findViewById(R.id.edps)).setClickable(false);	   		
   	 }else{ //包含 [新增][編輯],開放可以使用的BTN 
   		 	if (mMode == PItemMode.EDIT){
   		 		setTitle(getResources().getText(R.string.app_name).toString()+pKind[(myKind/10)-1]+"編輯中");
   		 		
   		 	}else {
   	     		setTitle(getResources().getText(R.string.app_name).toString()+pKind[(myKind/10)-1]+"新增中");   		 		
   		 	}
    	   	
 			((Button)findViewById(R.id.btn_emp)).setClickable(true);
	        ((Button)findViewById(R.id.btn_custp)).setClickable(true);
	      if(((backout[0].equalsIgnoreCase("0")) || QPosff.PSWD!=1 && backout[0].equalsIgnoreCase("1"))){
		        ((ImageButton)findViewById(R.id.ibtn_date)).setClickable(true);
		        ((Button)findViewById(R.id.btn_date)).setClickable(true);
	      }else{	
	        ((ImageButton)findViewById(R.id.ibtn_date)).setClickable(false);
	        ((Button)findViewById(R.id.btn_date)).setClickable(false);
	      } 
	        ((ImageButton)findViewById(R.id.ibtn_input)).setClickable(true);
	        pInput.setClickable(true);
	        ((Button)findViewById(R.id.btn_dis01)).setClickable(true);
	        //((Button)findViewById(R.id.btn_dis02)).setClickable(true);
	        ((Button)findViewById(R.id.btn_dis03)).setClickable(true);

	        ((Button)findViewById(R.id.btn_chg)).setClickable(true);
	        ((Button)findViewById(R.id.btn_100)).setClickable(true);
	        ((Button)findViewById(R.id.edps1)).setClickable(true);	   		
	        ((Button)findViewById(R.id.edps)).setClickable(true);	   		
    	   	
   	 }
   	 if (myKind!=30 && myKind!=31){
   		((Button)findViewById(R.id.btn_nsave)).setText("保留"); 	//暫存
   	 }
	}
	//@@@將直接轉入 暫存單 不再 指定 5,6 單別 或 統一放在一起了
	private void changeItems(int xx,int yy){
		 if ( of_line==0 || (Utilis.haveInternet(this) && of_line!=0)){
				int [] locas={0,1,2};//0預購 1留貨 2銷貨
				Toast.makeText(APos.this,msCust+"__"+msFno+"___"+data.mGoodsNos+"___"+msKind+"___"+data.mTime , Toast.LENGTH_SHORT).show();							

			 String returnStr=PosUtilis.changeItems(APos.this, rDept, msCust, msFno, data.mGoodsNos, msKind, data.mTime, locas, xx,yy, f123,1);
						
			    	  if (Utilis.haveInternet(this) && of_line!=0){
						
							StringBuffer bfstr = new StringBuffer();
							StringBuffer bfstrF = new StringBuffer();
							bfstr.append(Utilis.getIni(APos.this, "SYS", "IMPORT", 2)).append("!#%");
							bfstrF.append("UID").append("!#%");
							bfstr.append(mBankn).append("!#%");
							bfstrF.append("BANKNAME").append("!#%");
							bfstr.append(rDept).append("!#%");
							bfstrF.append("DEPTNO").append("!#%");
							bfstr.append(deptStr[5]).append("!#%");
							bfstrF.append("QPART").append("!#%");
							bfstr.append("0!#%");
							bfstrF.append("ALONE").append("!#%");
							//if (locas[yy]!=2) bfstr.append("!#%"); else bfstr.append("2!#%");
							bfstr.append("!#%");
							bfstrF.append("MODE").append("!#%");
							bfstr.append(returnStr.toString()).append("!#%");
							bfstrF.append("SERVERSTR").append("!#%");
							bfstr.append(Utilis.getIni(APos.this, "SYS", "AUPDATE", 3)).append("!#%");
							bfstrF.append("LUPDATET3").append("!#%");
							//目的是為了減少回傳的更新
							bfstr.append(Utilis.getIni(APos.this, "SYS", "AUPDATE", 4));
							bfstrF.append("LUPDATE");

							final String []fields=bfstr.toString().split("!#%");
							final String []fieldFs=bfstrF.toString().split("!#%");
							
							Log.i("DOWNLOAD_bufDtr", bfstr.toString()+"___"+bfstrF.toString());
								  
					     new Thread()
					      { 
						       public void run()
						       { 
						          try
						          { 
										String uriAPI="http://"+importStr[0]+File.separator+importStr[1]+File.separator+"aa1_aa0_gvor.php";
										HttpPost httpRequest = new HttpPost(uriAPI);
										
										List<NameValuePair> params = new ArrayList<NameValuePair>();
										for(int x=0;x<fields.length;x++){
											params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
										}
										try {
											httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
											HttpResponse httpResponse = new DefaultHttpClient()
													.execute(httpRequest);
											if (httpResponse.getStatusLine().getStatusCode() == 200)
											{
												String strResult = EntityUtils.toString(httpResponse	.getEntity());
												mHandlerGVOB.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
												
											}
										} catch (Exception e)
										{
											e.printStackTrace();
										}

						          }
						          catch (Exception e)
						          {
						        	  e.printStackTrace();
						          }
						       }
					      }.start(); /* 開始執行執行緒 */
			    	  }	
		
		 }else Toast.makeText(APos.this, "網路不正常,無法進行交易!!!!", Toast.LENGTH_SHORT).show();	        		        	
		 //網路不正常
		}
		
		Handler mHandlerGVOB = new Handler()
		{
			@Override
			public  void handleMessage(Message msg)
			{
				//傳回的//upup_1-30_系統時間
				String Hresult=null;
				switch (msg.what)
				{
				// 顯示網路上抓取的資料
				case REFRESH_DATA:
					if (msg.obj instanceof String) 
						Hresult = (String) msg.obj;
					if (Hresult != null ){
						if (Hresult.indexOf("aa1_aa0_gvo;")>0){
							String [] EchoStr=Hresult.split(";");
							Utilis.putIni(APos.this, "SYS", "AUPDATE",EchoStr[1] ,4 );//T4_ORNY
							SQLiteDatabase db = Utilis.getDB(APos.this);
							Cursor cs=db.rawQuery("select FORMNO from qitems where FORMNO='"+msFno+"'",null);
							if  (cs.getCount()>0)
								mAdapter.getData(APos.this,msFno);
							else{
								db.close();
								cs.close();
					        	Intent intentS = new Intent();
					        	intentS.putExtra("POS_modify",1);
					        	APos.this.setResult(RESULT_OK,intentS);
								finish();
							}
							db.close();
							cs.close();
						}
					}
				}
			}
		};
		
 	
	
	public int IsExistItem(String fNO,String fKind,String fKeyin,int fNumber){
		//檢查是否本單已存在該貨品,需判斷是否為qitems中的最後一筆資料GOODSNO主貨號
		//若為最後一筆,才可以累加
		int YN=0;
		SQLiteDatabase db = Utilis.getDB(APos.this);
		StringBuffer mySqlBuf = new StringBuffer();
		String sGood=fKeyin.substring(0,fKeyin.indexOf("-"));
		if (Firstgood.length()>0 && sGood.equalsIgnoreCase(Firstgood)){
			//最後一筆資料GOODSNO主貨號時 且折數同
			mySqlBuf.delete(0, mySqlBuf.toString().length());
			mySqlBuf.append("select UNIT,UNIT10,UNIT20,UNIT30,UNIT40,P0,P1,DISCOUNT,UNITPRICE,SUBPRICE,ACOST,ORDDATE,CREATEDATETIME");
			mySqlBuf.append(" from qitems where GOODSNOS = '" + fKeyin+"'")
			.append(" and CREATEDATETIME='"+CTIME+"' and  DISCOUNT = " +fKind +" and  FORMNO = '" + fNO+"' order by CREATEDATETIME desc LIMIT 1");
			
			Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
			
			if (cs.getCount()>0) {//本單存在同名細貨號 檢查累加自動? 單量
				cs.moveToFirst();
				ContentValues value = new ContentValues();
				hisDiscount=cs.getDouble(cs.getColumnIndex("DISCOUNT"));
				hisUnitprice=Math.round(cs.getDouble(cs.getColumnIndex("UNITPRICE")));
				hisP0=Math.round(cs.getDouble(cs.getColumnIndex("P0")));
				int nUnit=1;
				if (cs.getInt(cs.getColumnIndex("ORDDATE"))>1) nUnit=cs.getInt(cs.getColumnIndex("ORDDATE"));
				double toti=0;
				
				toti=Math.round(cs.getDouble(cs.getColumnIndex("UNIT"+msKind.substring(0, 1)+"0"))+fNumber*nUnit);
				value.put("UNIT"+msKind.substring(0, 1)+"0", toti);
				if (f123==0) value.put("SUBPRICE",Math.round(hisUnitprice*hisDiscount*toti/100 ));
				else value.put("SUBPRICE",Utilis.dedb(hisUnitprice*hisDiscount*toti/100,2 ));
				if (f123==0) value.put("ACOST", Math.round(cs.getDouble(cs.getColumnIndex("P1"))*toti));
				else value.put("ACOST", Utilis.dedb(cs.getDouble(cs.getColumnIndex("P1"))*toti,3));
				value.put("P0", cs.getDouble(cs.getColumnIndex("P0")));
				//延續 預購留貨
				if (cs.getInt(cs.getColumnIndex("UNIT"))!=0) value.put("UNIT", toti);
				CTIME=cs.getString(cs.getColumnIndex("CREATEDATETIME"));						
				Toast.makeText(APos.this, "最後一筆的CDT=="+CTIME, Toast.LENGTH_SHORT).show();							
				String[] args = {fNO,""+fKind,fKeyin,cs.getString(cs.getColumnIndex("CREATEDATETIME"))};
				int success = db.update(TbName.QITEMS, value,"FORMNO=? and DISCOUNT=? and GOODSNOS=? and CREATEDATETIME=?", args);
				if (success!=0) YN=1;
			}
			cs.close();
		}
		db.close();
		return YN;
	}
	
	//
	public String recountHead(Context context,String mKey,String mFmDate){
		String atoot=null;
		SQLiteDatabase db = Utilis.getDB(context);
		StringBuffer mySqlBuf = new StringBuffer();
//以上QHEAD完成維護,如下畫面 應收也要維護 ASUM 及 +件 -件				

			mySqlBuf.delete(0, mySqlBuf.toString().length());
			mySqlBuf.append("select sum(UNIT"+msKind.substring(0, 1)+"0) as UNITS");
			mySqlBuf.append(" from qitems where FORMNO ='" + mKey+"'")
			.append(" and QKIND ='"+msKind+"'");
			//先算出的
			String mySql=mySqlBuf.toString();
			mySqlBuf.append("and UNIT"+msKind.substring(0, 1)+"0 >=0 ");
			
			Cursor cursory = db.rawQuery(mySqlBuf.toString(), null);									
			if (cursory.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
				cursory.moveToFirst();
				datax.dInc=cursory.getInt(cursory.getColumnIndex("UNITS"));
			}else datax.dInc=0;
			
			cursory.close();
			
			mySqlBuf.delete(0, mySqlBuf.toString().length());
			mySqlBuf.append(mySql); //共用片段
			mySqlBuf.append("and UNIT"+msKind.substring(0, 1)+"0 <0 ");
			
			Cursor cursorz = db.rawQuery(mySqlBuf.toString(), null);									
			if (cursorz.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
				cursorz.moveToFirst();
				datax.dMic=cursorz.getInt(cursorz.getColumnIndex("UNITS"));				
			}else datax.dMic=0;
			
			cursorz.close();
			
			double SUBP=0;
			double SUBT=0;
			mySqlBuf.delete(0, mySqlBuf.toString().length());
			mySqlBuf.append("select FORMNO,sum(UNIT"+msKind.substring(0, 1)+"0) as UNITS,sum(SUBPRICE) as SUBPRIS,");
			mySqlBuf.append("sum(ACOST) as ACOSTS,sum(UNIT"+msKind.substring(0, 1)+"0 * P"+datax.nTrade+") as ATURESUM from qitems")
			.append(" where FORMNO ='" + mKey+"'")
			.append(" and QKIND ='"+msKind+"'");
			mySqlBuf.append(" group by FORMNO" );

			Cursor cursorx = db.rawQuery(mySqlBuf.toString(), null);
			
			if (cursorx.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
				ContentValues value = new ContentValues();
				cursorx.moveToFirst();
				double subP=cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS"));
				double pm=1;	if (subP<0) {pm=-1; subP=subP * pm; }
				int PERS=Utilis.toInt(Utilis.getIni(APos.this,"SYS", "SDB", 8));
				if (!msKind.equalsIgnoreCase("10")){
				if (PERS==5){
					SUBP=Math.round(subP/10)*10*pm;
				}else if (PERS==1){ //無條件捨去
					SUBP=Math.floor(subP/10)*10*pm;
				}else if (PERS==9){ //無條件進入
					SUBP=Math.ceil(subP/10)*10*pm;
				}else{ 
					SUBP=Math.round(subP*pm);
				}
				}else{
					SUBP=Math.round(subP*pm);
				}
				SUBT=Math.round(cursorx.getDouble(cursorx.getColumnIndex("ATURESUM")));
				BigDecimal bigSubP=new BigDecimal(SUBP); 
				BigDecimal bigSubT=new BigDecimal(SUBT); 
				
				//@@@何時不用 異動 TR
				//原先考量是因為 留貨內容異動預購內容異動
				if (SUBP!=datax.dAsum || datax.dAtot!= cursorx.getDouble(cursorx.getColumnIndex("UNITS")) || mFmDate.length()>0)
					datax.mTR=msKind;
				
				datax.dAsum=bigSubP.doubleValue();
				datax.dTuresum=bigSubT.doubleValue();
				datax.dAtot=cursorx.getDouble(cursorx.getColumnIndex("UNITS"));
				datax.dCosts=Math.round(cursorx.getDouble(cursorx.getColumnIndex("ACOSTS")));
				if (datax.dMic==0){
					datax.mHandno="+"+datax.dInc;
				}else {
					datax.mHandno="+"+datax.dInc+" "+datax.dMic;
				}
				if (mFmDate.length()>0) value.put("FORMDATE",mFmDate);
				value.put("TR",datax.mTR);
				value.put("ASUM",Math.round(datax.dAsum));
				value.put("BSUM",Math.round(datax.dAsum-datax.dDismoney+datax.dTrcash));
				value.put("ATOT",Math.round(datax.dAtot));
				value.put("COSTS",Math.round(datax.dCosts));
				value.put("HANDNO",datax.mHandno);
				value.put("BANKNAME", mBankn);
				//廠商進貨需再存入
				if (myKind==PItemKind.TR10){
					if (f123==0) value.put("TURESUM",Math.round(cursorx.getDouble(cursorx.getColumnIndex("ACOSTS"))));
					else value.put("TURESUM",Utilis.dedb(cursorx.getDouble(cursorx.getColumnIndex("ACOSTS")),2));
				}else{//銷貨原價金額
					if (f123==0) value.put("TURESUM",Math.round(bigSubT.doubleValue()));
					else value.put("TURESUM",Utilis.dedb(bigSubT.doubleValue(),2));
				}

				String[] args = {mKey,msKind,msCust};
				int success = db.update(TbName.QHEAD, value,"FORMNO=? and QKIND =? and USER=?", args);
				cursorx.close();			
		} else {  //讓單頭歸零,但是不離開
			Cursor csH = db.rawQuery("select * from qhead where FORMNO='" + mKey+"'", null);
			if (csH.getCount()>0){
				csH.moveToFirst();
				if (csH.getDouble(csH.getColumnIndex("ORDCASH"))!=0 || csH.getDouble(csH.getColumnIndex("ORDCARD"))!=0  || csH.getDouble(csH.getColumnIndex("CASH"))!=0  || csH.getDouble(csH.getColumnIndex("CARD"))!=0 || csH.getDouble(csH.getColumnIndex("TRCASH"))!=0 || csH.getDouble(csH.getColumnIndex("ATM"))!=0 || csH.getDouble(csH.getColumnIndex("DISMONEY"))!=0){
					//因為有訂金,所以不可以清除
					String SQL="update qhead set TR='Y1',HANDNO='+0',ISCONFIRM='Y',ISCHECK='N',ATOT='0',ASUM=0,BSUM=0,COSTS=0 where FORMNO='" + mKey+"'";
					db.execSQL(SQL);
				} else {
					db.execSQL("update qhead set TR='"+msKind+"',ASUM=0,ATOT=0,COSTS=0,HANDNO='+0',ISCONFIRM='N',ISCHECK='N',FINEDATE='',ORDDATE='' where FORMNO='"+mKey+"'");
				}
			}
			csH.close();
			//finish();
		}
		db.close();
		//傳回
		atoot="$:"+new BigDecimal(datax.dAsum).toString()+";+"+new BigDecimal(datax.dInc).toString()+";"+new BigDecimal(datax.dMic).toString();

		return atoot;
	}

	private android.content.DialogInterface.OnClickListener mListener1=new DialogInterface.OnClickListener()
	  {
	    @Override
	    public void onClick(DialogInterface dialog, int which)
	    {
	      // TODO Auto-generated method stub
	      switch(which)
	      {
	        case 0: //變更交易對象
	        	{
				Toast.makeText(APos.this, cust_no+"已進入updateDBHI程序!!", Toast.LENGTH_SHORT).show();
				updateDBHI(APos.this, cust_no, msFno, msKind, 0); //0.USER 1.EMPID 2.DEPTNO
				}
				break;
	        case 1: //放棄變更	        	
	      }
	    }
	  };

		private android.content.DialogInterface.OnClickListener mListener2=new DialogInterface.OnClickListener()
		  {
		    @Override
		    public void onClick(DialogInterface dialog, int which)
		    {
		      // TODO Auto-generated method stub
		      switch(which)
		      {
	   	        	  case 0:  //確認刪除
							SQLiteDatabase db = Utilis.getDB(APos.this);		   	        		  
							db.execSQL("delete from qitems where FORMNO='" + msFno+"'" );
							
							Cursor csH = db.rawQuery("select TR from qhead where FORMNO='" + msFno+"'", null);
							if (csH.getCount()>0){
								csH.moveToFirst();
							if ((of_line==0) ||  (csH.getString(0)!=null && !csH.getString(0).equalsIgnoreCase("Y0") && !csH.getString(0).equalsIgnoreCase("Y1")  && !csH.getString(0).equalsIgnoreCase("Y2"))) {
								db.execSQL("delete from qhead where FORMNO='" + msFno+"' and QKIND ='"+msKind+"'" );
								Toast.makeText(APos.this, "刪除資料成功", Toast.LENGTH_SHORT).show();
							} else {
								db.execSQL("update qhead set TR='Y2',ID='1008',QKIND='"+msKind.substring(0, 1)+"2', CREATEDATETIME='"+DateUtil.getSystemTime().substring(2, 14)+"',ISCONFIRM='N',ISCHECK='N',BANKNAME='"+mBankn+"' where FORMNO='" + msFno+"' and QKIND ='"+msKind+"'" );
								if (Utilis.haveInternet(APos.this) && of_line==1 ) {
									DBCloud.aa1_aa0_update_HI(APos.this);
								}
								Toast.makeText(APos.this, "刪除資料且製作Y2成功", Toast.LENGTH_SHORT).show();
								//@@cloud_update
							}
							}
							csH.close();
							db.close();
							
							mMode = PItemMode.ADD;
				        	iniHead();  	//一張新的單據
				        	iniItems();	//一筆新的商品
				        	mAdapter.getData(APos.this,msFno);
				        	//mAdapter.notifyDataSetChanged();			        	
				        	Toast.makeText(APos.this, "新增中.........", Toast.LENGTH_SHORT).show();	        	
							
	   	        		  	//finish();
		      }
		    }
		  };

	  
	  //使用時機 當cMode ==0 會員資料更新 ==1交易員 ==2門市 DEPTNO 更新時 檔案&畫面 都要更新
	  			//		updateDBHI(APos.this, cust_no, msFno, msKind, 3);	  
	  public void updateDBHI(Context context, String cKey, String cFno, String cKno, int cMode){
			  
				SQLiteDatabase db = Utilis.getDB(APos.this);

				String[] args = {cFno,msKind};				
				ContentValues value = new ContentValues();
			if (cMode==3){  //日期更新
				value.put("FORMDATE", datax.mFormdate);
				if (datax.mFinedate.length()>0 && !datax.mFormdate.equalsIgnoreCase(datax.mFinedate)){
					datax.mFinedate=datax.mFormdate;
					value.put("FINEDATE", datax.mFinedate);
				}//@@@結帳日期與開單日期不一致,使成一致
			}else if(cMode==4){ //廠商進貨單的廠商編號更新
				StringBuffer mySqlBuf = new StringBuffer();
				mySqlBuf.append("select FACTNO,FACTNAME,DISCOUNT,TRADETYPE,BANKNO,BANKNAME ,EMPID from qfact")
				.append(" where  FACTNO='"+cKey+"'" );
				Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
				if (cs.getCount()>0){
					cs.moveToFirst();
					datax.mUser=cs.getString(cs.getColumnIndex("FACTNO"));
					datax.mUsername=cs.getString(cs.getColumnIndex("FACTNAME"));
					datax.dDiscount=cs.getDouble(cs.getColumnIndex("DISCOUNT"));
					fQhis=cs.getString(cs.getColumnIndex("EMPID"));
					if (datax.dDiscount<10) datax.dDiscount=100;
					hisDiscount=datax.dDiscount;
					((Button)findViewById(R.id.btn_custp)).setText(datax.mUser+"/"+datax.mUsername);
					((Button)findViewById(R.id.btn_100)).setText(""+datax.dDiscount);
					if (datax.dDiscount<90)
						((Button)findViewById(R.id.btn_100)).setVisibility(View.INVISIBLE);
					else
						((Button)findViewById(R.id.btn_100)).setVisibility(View.VISIBLE);

						((Button)findViewById(R.id.btn_dis04)).setText(tradeStr[datax.nTrade]);
						value.put("USER", datax.mUser);
						value.put("USERNAME", datax.mUsername);
						value.put("TRADETYPE", mBankn);
						msCust=datax.mUser;
						msTrade=datax.nTrade;
						datax.nTrade=cs.getInt(cs.getColumnIndex("TRADETYPE"));
						datax.mBankno=cs.getString(cs.getColumnIndex("BANKNO"));
						datax.mBankname=mBankn;
						
						if ( !fQhis.equalsIgnoreCase("1")){
							nQhis=1;  //歷史價
					       	((Button)findViewById(R.id.btn_dis03)).setText("歷史");
						}else {
							nQhis=0;  //標準價
				        	((Button)findViewById(R.id.btn_dis03)).setText("標準");
						}
						
				}				
				cs.close();
			}else{	//更新/專櫃/會員/交易員 等交易對象		
				
				StringBuffer mySqlBuf = new StringBuffer();
				mySqlBuf.append("select CUSTNO,CUSTNAME,DISCOUNT,TRADETYPE,BANKNO,BANKNAME,S2 from qcust")
				.append(" where  CUSTNO='"+cKey+"'" )
				.append(" and TR= '"+cKno.substring(0, 1)+"0'");
				Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
				if (cs.getCount()>0){
					cs.moveToFirst();
				
					if (cMode==0){ 
						datax.mUser=cs.getString(cs.getColumnIndex("CUSTNO"));
						datax.mUsername=cs.getString(cs.getColumnIndex("CUSTNAME"));
						datax.dDiscount=cs.getDouble(cs.getColumnIndex("DISCOUNT"));
						hisDiscount=datax.dDiscount;
						datax.nTrade=cs.getInt(cs.getColumnIndex("TRADETYPE"));
						datax.mBankno=cs.getString(cs.getColumnIndex("BANKNO"));
						datax.mBankname=mBankn;
						fQhis=cs.getString(cs.getColumnIndex("S2"));
						if ( !fQhis.equalsIgnoreCase("1")){
							nQhis=1;  //歷史價
					       	((Button)findViewById(R.id.btn_dis03)).setText("歷史");
						}else {
							nQhis=0;  //標準價
				        	((Button)findViewById(R.id.btn_dis03)).setText("標準");
						}
						((Button)findViewById(R.id.btn_custp)).setText(datax.mUser+"/"+datax.mUsername);
						((Button)findViewById(R.id.btn_100)).setText(""+datax.dDiscount);
						if (datax.dDiscount<90 || nHintDisc==1 )
							((Button)findViewById(R.id.btn_100)).setVisibility(View.INVISIBLE);
						else
							((Button)findViewById(R.id.btn_100)).setVisibility(View.VISIBLE);
						
						((Button)findViewById(R.id.btn_dis04)).setText(tradeStr[datax.nTrade]);
							value.put("USER", datax.mUser);
							value.put("USERNAME", datax.mUsername);
							value.put("TRADETYPE", datax.nTrade);
							msCust=datax.mUser;
							msTrade=datax.nTrade;
					}else if (cMode==1){ //更新交易員
						datax.mEmpid=cs.getString(cs.getColumnIndex("CUSTNO"));
						datax.mEmpname=cs.getString(cs.getColumnIndex("CUSTNAME"));
						((Button)findViewById(R.id.btn_emp)).setText(datax.mEmpid+"/"+datax.mEmpname);
							value.put("EMPID", datax.mEmpid);
							value.put("EMPNAME", datax.mEmpname);
//					}else if (cMode==2){ //更新門市
//						datax.mDeptno=cs.getString(cs.getColumnIndex("CUSTNO"));
//						((Button)findViewById(R.id.btn_dept)).setText(datax.mDeptno);
//是否在總倉 且在 門市銷貨時 可以換門市代號,就不用 跳出APOS 再進來 但是同時也要QPOSFF同步換門市代號
					}
				}
				cs.close();			
			}
				if (value.size()>0 ){
					double success;
					value.put("DEPTNO", rDept);
					//cMode==5時,表示只更新單頭備註
					if (cMode!=5) success = db.update(TbName.QITEMS, value,"FORMNO=? and QKIND=?", args);
					if (cMode==0){ //會員要在QHEAD 增填入					
						value.put("BANKNO", datax.mBankno);
						value.put("BANKNAME", mBankn);
					}
					success = db.update(TbName.QHEAD, value,"FORMNO=? and QKIND=?", args);					
				}
				value.clear();
				db.close();
	  }

	  //在資料庫異動完後 重新將所有該單的Items 重新丟入顯示容器
	public void reItems(Context context, String formNo){
 			try{
				if(mAdapter.mPList != null)	mAdapter.mPList.clear();
					
				SQLiteDatabase db = Utilis.getDB(APos.this);				
				StringBuffer mBuf = new StringBuffer();
				mBuf.append("select * from " + TbName.QITEMS)
				.append(" where FORMNO='").append(formNo+"'");
				mBuf.append(" order by CREATEDATETIME desc");
				PItemData datas = new PItemData();
				Cursor cursor = db.rawQuery(mBuf.toString(), null);
				try{
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						for(int i = 0; i < cursor.getCount(); i++){
								datas=DBUtil.PItem.parseData(cursor);							
								mAdapter.mPList.add(datas);
								cursor.moveToNext();
						}
			        	mAdapter.notifyDataSetChanged();
						dataO = (PItemData) mAdapter.getItem(0);
						Firstgood=dataO.mGoodsNo;
						CTIME=dataO.mTime;
					}else Firstgood="";
					
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					db.close();
					cursor.close();
					cursor = null;
				}//@@@ db.close();
			}catch(Exception e){
				e.printStackTrace();
			}
 	  }

	 private void chkItems(){
			LayoutInflater factory = LayoutInflater.from(this);
			final View v1 = factory.inflate(R.layout.fcount, null);
			final EditText edtCount = (EditText) v1.findViewById(R.id.edcount);
			final EditText edtUprice = (EditText) v1.findViewById(R.id.eduprice);
			final EditText edtDiscount = (EditText) v1.findViewById(R.id.ediscount);
			final Button BD1= (Button) v1.findViewById(R.id.btn_disc1);
			BD1.setText(DISC[0]);
			final Button BD2= (Button) v1.findViewById(R.id.btn_disc2);
			BD2.setText(DISC[1]);
			final Button BD3= (Button) v1.findViewById(R.id.btn_disc3);
			BD3.setText(DISC[2]);
			final Button BD4= (Button) v1.findViewById(R.id.btn_disc4);
			BD4.setText(DISC[3]);
			final Button BD5= (Button) v1.findViewById(R.id.btn_disc5);
			BD5.setText(DISC[4]);
			final Button BD6= (Button) v1.findViewById(R.id.btn_disc6);
			BD6.setText(DISC[5]);
			final Button BD7= (Button) v1.findViewById(R.id.btn_disc7);
			BD7.setText(DISC[6]);
			final Button BD8= (Button) v1.findViewById(R.id.btn_disc8);
			BD8.setText(DISC[7]);
			final Button BD9= (Button) v1.findViewById(R.id.btn_disc9);
			BD9.setText(DISC[8]);
			
			final ImageView edtPic = (ImageView) v1.findViewById(R.id.imageV1);
			final TextView dUnit = (TextView) v1.findViewById(R.id.TextView02);
			nUnit=Utilis.toInt(data.mOrddate);
	        if (nUnit<=1) {nUnit=1;isUnit=0;} else isUnit=1;
	        
			Bitmap bm = Utilis.getLimitBitmap(data.mPic, 200,200);
			edtPic.setImageBitmap(bm);

			switch (myKind){
				case 10:{counts=data.dUnit10;break;}
				case 20:{counts=data.dUnit20;break;}
				case 21:{counts=data.dUnit20;break;}
				case 30:{counts=data.dUnit30;break;}
				case 31:{counts=data.dUnit30;break;}
				case 40:{counts=data.dUnit40;break;}
				case 41:{counts=data.dUnit40;break;}
			}
			if (isUnit==1 && nUnit>1 && (counts % nUnit)==0){
				counts=counts/nUnit;
				dUnit.setText(""+nUnit+"段");
			}else{
				isUnit=0;
				 dUnit.setText("件");
			}
			edtCount.setText(""+counts);  //件數
			edtUprice.setText(""+data.dUnitprice);
			edtDiscount.setText(""+data.dDiscount);
			
			if (QPosff.PSWD==1 && (backout[8].equalsIgnoreCase("2") || myKind==10 || myKind==20 || myKind==21 )){
				edtUprice.setVisibility(View.INVISIBLE);
				edtDiscount.setVisibility(View.INVISIBLE);
				BD1.setVisibility(View.INVISIBLE);
				BD2.setVisibility(View.INVISIBLE);
				BD3.setVisibility(View.INVISIBLE);
				BD4.setVisibility(View.INVISIBLE);
				BD5.setVisibility(View.INVISIBLE);
				BD6.setVisibility(View.INVISIBLE);
				BD7.setVisibility(View.INVISIBLE);
				BD8.setVisibility(View.INVISIBLE);
				BD9.setVisibility(View.INVISIBLE);
			}
			
			BD1.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utilis.runVibrate(APos.this);
					edtDiscount.setText(BD1.getText().toString());
				}
				});
			BD2.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utilis.runVibrate(APos.this);
					edtDiscount.setText(BD2.getText().toString());
				}
				});
			BD3.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utilis.runVibrate(APos.this);
					edtDiscount.setText(BD3.getText().toString());
				}
				});
			BD4.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utilis.runVibrate(APos.this);
					edtDiscount.setText(BD4.getText().toString());
				}
				});
			BD5.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utilis.runVibrate(APos.this);
					edtDiscount.setText(BD5.getText().toString());
				}
				});
			BD6.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utilis.runVibrate(APos.this);
					edtDiscount.setText(BD6.getText().toString());
				}
				});
			BD7.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utilis.runVibrate(APos.this);
					edtDiscount.setText(BD7.getText().toString());
				}
				});
			BD8.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utilis.runVibrate(APos.this);
					edtDiscount.setText(BD8.getText().toString());
				}
				});
			BD9.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utilis.runVibrate(APos.this);
					edtDiscount.setText(BD9.getText().toString());
				}
				});

			dUnit.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Utilis.runVibrate(APos.this);
					double lCount=Utilis.toDouble(edtCount.getText().toString());
					if (isUnit==0 && nUnit>1 && (lCount % nUnit)==0){
						lCount=lCount/nUnit;
						edtCount.setText(""+lCount);
						dUnit.setText(""+nUnit+"段");
						isUnit=1;
					}else if(isUnit==1){
						lCount=lCount*nUnit;
						edtCount.setText(""+lCount);
						isUnit=0;
						 dUnit.setText("件");
					}else{
						isUnit=0;
						 dUnit.setText("件");
					}
					
				}
				});
			
			edtUprice.requestFocus();
			//edtPic.setImageBitmap(reflactionBitmap);
			  new AlertDialog.Builder(this).setTitle(data.mGoodsNos+"/"+data.mGoodsName+"\n"+this.getString(R.string.detail_msg_fgalleryedu)).setView(v1).setNeutralButton("確認傳回", new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int which) {
			    	  double nDisC=Utilis.toDouble(edtDiscount.getText().toString());
			    	  double nCount=Utilis.toDouble(edtCount.getText().toString());
			    	  double nPri=Utilis.toDouble(edtUprice.getText().toString());

			    	  if (isUnit!=0) nCount=nCount*nUnit;
			    	  
			    	  if (nDisC!=data.dDiscount || counts!=nCount || nPri!=data.dUnitprice)
			    	  {//Update Db 
							SQLiteDatabase db = Utilis.getDB(APos.this);				
							ContentValues value = new ContentValues();
							value.put("DISCOUNT", nDisC);
							value.put("UNITPRICE", nPri);
							value.put("UNIT"+msKind.substring(0,1)+"0",nCount);
							if(f123==0) value.put("SUBPRICE", Math.round(nCount*nPri*nDisC/100));
							else value.put("SUBPRICE", Utilis.dedb(nCount*nPri*nDisC/100,2));  
							if (f123==0) value.put("ACOST",Math.round(nCount*data.dP1));
							else value.put("ACOST",Utilis.dedb(nCount*data.dP1,3));
							if (data.dUnit!=0) value.put("UNIT",nCount);
							String mPS="";
							if (nCount<0) mPS="退";
							if (nDisC<100 && nDisC>0) mPS=mPS+(int)nDisC;
							value.put("PS",mPS);

							String[] args = {msFno,msKind,data.mGoodsNos,data.mTime};				
							//String[] args = {msFno,msKind,data.mGoodsNos};
							int success =db.update(TbName.QITEMS, value,"FORMNO=? and QKIND= ? and GOODSNOS=? and CREATEDATETIME=?", args);
							db.close();
							String Toot=recountHead(APos.this,msFno,""); //嘗試給GalleryViewP呼叫 但不用如下顯示段
							
							String[] arrayFieldH = Toot.toString().split(";");
							((Button)findViewById(R.id.btn_receive)).setText(arrayFieldH[0]);
							((Button)findViewById(R.id.btn_inc)).setText(arrayFieldH[1]);  //強制轉型	
							((Button)findViewById(R.id.btn_mic)).setText(arrayFieldH[2]); //強制轉型
							
				        	mAdapter.getData(APos.this,msFno);					
							//mAdapter.notifyDataSetChanged();
							
			    	  }
			      }
			    }).setNegativeButton("放棄編輯", new DialogInterface.OnClickListener() {
				      public void onClick(DialogInterface dialog, int which) {
				      }
			    })
			    .show();
	 }
		
	
	}

	