package com.cwbuyer.lib;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
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 android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
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.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.cwbuyer.adapter.TableAdapter.TableCell;
import com.cwbuyer.adapter.TableAdapter.TableRow;
import com.cwbuyer.format.EMode;
import com.cwbuyer.format.IDateDialog;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.main.AccountList;
import com.cwbuyer.main.QCustff;
import com.pwbuyer.main.R;

	@SuppressLint({ "DefaultLocale", "HandlerLeak" })
	@SuppressWarnings("unused")
public class QpandnF extends Activity {
	
	ReportAdapter mAdapter = null;
	RepDataPan datas;	
	String goodO="";
	String goodOName="";
	String goodOPic="";
	private String[] deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");
	private String[] importStr =Utilis.getIni(this,"SYS", "IMPORT",9).split("!&!");
	String compStr[]=Utilis.getIni(QpandnF.this,"USER","COMPANY",9).split("!&!");
	int of_line=Utilis.toInt(importStr[2]);
	protected static final int REFRESH_DATA = 0x00000001;
	String clouds="http://"+importStr[0]+File.separator+importStr[1]+File.separator;
	String uriAPI1=clouds+"qpandngetdat.php";
	String uriAPI2=clouds+"qpandn_report.php";
   	String bankn=deptStr[0]+deptStr[1];
	StringBuffer sPrintB = new StringBuffer();
		
	String aExtWord="";
	private int mRestoreChoice = 0;
	String[] Pndnddlist;
	EditText pInput;
	int tabless=8;
	
	int nPart=0; //預設裝置為[0總倉][1門市][2業務裝置]理論上較像外部裝置,但是只可以盤點(不一定提供圖檔)
	int nDept=1; //預設門市盤點 0.總倉 1.門市 2.廠商  盤點
	int nSuccess=0; //如果nSuccess==0是應該不可以新增一個盤表,已存在未入帳的盤點清冊
	int nCompares=1;  //表示上盤日期比本盤日期還大,是不可以執行
	int nTradetype=5; //預設為零售價
	int nPandnK=0; //0詳式 1簡式 2盤價
	int nKind=1; //0暫盤表  1主盤表 1盤差表 2盤準表 3已盤表 4未盤表 5.增盤表(原盤表不存在的商品ID>80000 and ID<100000)
	//@@@關鍵點 暫存的ID>100000 在增盤表的商品 也+100000??
	//所以增盤表統計時,應判斷( ID>80000 and ID<100000 ) or (ID>180000 and ID<200000) 
	int locations=0;
	int nDiscount=100;
	int nID=0;
	int nCondition=0;  //控制頁面的判斷 1一樓選擇盤表  2二樓主盤表清冊 3三樓明細盤表清冊
	int nState=0;  //PNDNSTATE =0盤表 1暫盤 2歷史盤表
	String[] mState={"(尚未入帳)","","(已經過帳)"};
	int chkIn=0;
	int findP=0;
	int nPrice=0;
	int nAcost=0;
	int nAstk =0;
	int nAimn=0;
	int nAstn=0;
	int nAadn=0;
	int nLstk=0;
	int nAdefn=0;
	double nAdefm=0;
	int nPin=0;
	//nDept nTradetype  nDiscount nState
	int cLstkn=0;
	int cLstkm=0;
	int tLastStkn=0;
	double tLastStkm=0;
	//上次的盤存總件數&總金額
	ListView mListView = null;
	Button mBTain;
	Button mBTaim;
	Button mBTastn;
	Button mBTastm;
	Button mBTastkn;
	Button mBTastkm;
	Button mBTaadn;
	Button mBTaadm;
	
	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<Integer> mCountryIdList = new ArrayList<Integer>();
	private ArrayList<String> mTypeList = new ArrayList<String>();
	private ArrayList<Integer> mTypeIdList = new ArrayList<Integer>();
	LinkedList<String> mSizeLink = new LinkedList<String>();
	LinkedList<String> mColorLink = new LinkedList<String>();
	private LinearLayout lTableView = null;
  	private LinearLayout mLayoutRoot = null;
	HashMap<Integer,Integer> mCountRow = new HashMap<Integer,Integer>(); // 顏色行資料
	HashMap<Integer,String> mCountCell = new HashMap<Integer,String>();  // 尺寸欄資料
	private String[] eachItem;
	private String[] eachField;
	int Wheight;
	int Wwidth;
	int tableHeight=30;
	String mColor=null;  //單一顏色
	String mColorno=null;  //單一顏色
	String mySize=null; //單一尺寸
	private int mChoiceMode = ChoiceMode.PLUS;  //預設 盤進+
	String aInput=null;
	public ProgressDialog myDialog = null;


	
	String mDBPath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"cwbuyer/data/20123/qmtrio.sdb";		 
	String SD_PATH =android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
	String pathName="/CWBuyer/cualbun";	
	String myFilePath = SD_PATH+pathName+"/qpandnf_01.csv";

	String[] menu_E;
	String[] menu_LE;
//	String[] menu_E={ "進行盤點", "入帳","","匯出單一筆盤點清冊","分享","重新盤點","盤點量同在庫量","返回"};	
	String[] mKind={"總倉","門市","廠商"};
	String[] sKind={"盤點中","暫盤中","已過帳"};	
	boolean isNew=true;
	
	private int mYear = 0;
	private int mMonth = 0;
	private int mDay = 0;

	String Ldate="2012-03-14";
	String Ddate=null;
	
	String[] mTradeTypeStr={"外幣價","成本價","中盤價","批發價","網購價","零售價","歷史價"};
	String mWho=null;
	String mWhoName=null;
	String mItem=null;
	String mItemName=null;
	String mLocDD="A區";
	String mFormno="";
	
	private final int RESULT_QCUSTFF = 9999;		//會員檔回傳口令
	private final int RESULT_QFACT = 1020;		//廠商檔回傳口令
	
	public class RepDataPan{ 
		public String iPic;  
		public String iGoods; 
		public String iImpo; 
		public String iName; 
		public String iMoney;
		public String iCountry;
		public String iNumber;
		public String iCompany;
		public String iFormdate;
		public String iUnit2;
		public String iFormno;
		public int iSort;
		
	}

	public interface ChoiceMode{
		int  SERCH = 0; //查詢
		int  PLUS= +1; //盤進
		int MILUS = -1; //	盤退
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent dataR) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, dataR);
		switch (requestCode){
		case RESULT_QCUSTFF:  //返回(總倉)(專櫃)的各種可能性
			{
				if (resultCode == RESULT_OK) {
					int newone=1;
					String mW=dataR.getStringExtra("qcust_key");
					File fileQmtrio = new File(mDBPath);
			      	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
					Cursor csm = mdb.rawQuery("select PNDNADAY from qpandn where USER='"+mW+"' and PNDNFKIND="+nDept +" and PNDNSTATE<>2 and ID=3", null);
					if (csm.getCount()>0){
						newone=0;//表示不可重覆建立新的盤表
        				Toast.makeText(QpandnF.this, "不可以重複建立:"+mW+csm.getCount()+" 門市的盤點表!!", Toast.LENGTH_SHORT).show();
					}
					csm.close();
					mdb.close();
					if (newone==1){
						if ((nDept==1 || nPart==1) &&  (mW.equalsIgnoreCase(deptStr[5]))){
							//非總倉 選擇了總倉 NO 
	        				Toast.makeText(QpandnF.this, "所選的盤點對象不符規定", Toast.LENGTH_SHORT).show();
						}else if ((nDept==1 && nPart==1) && (!mW.equalsIgnoreCase(deptStr[0]))) {
							//非總倉 選擇了不是自己的門市時 NO
							Toast.makeText(QpandnF.this, "所選的盤點對象,不是自己門市", Toast.LENGTH_SHORT).show();
						}else{
							//
							SQLiteDatabase db = Utilis.getDB(QpandnF.this);
							Cursor cs = null;					
							StringBuffer mySqlBuf = new StringBuffer();
								mySqlBuf.append("select CUSTNO,CUSTNAME,TRADETYPE,DISCOUNT,S2 from qcust where CUSTNO='"+mW+"' and TR='20'");
								cs = db.rawQuery(mySqlBuf.toString(), null);
								if (cs.getCount()>0){
									cs.moveToFirst();
									//if (cs.getInt(4)==0)
									//nTradetype=6;//歷史價
									//else//指定價	
										nTradetype=cs.getInt(2);if (nTradetype<=0) nTradetype=1;
									
									mWho=cs.getString(0);
									mWhoName=cs.getString(1);
									((Button)findViewById(R.id.btn_pndnno)).setText(mWho);
									((Button)findViewById(R.id.btn_pndnname)).setText(mWhoName);
									((Spinner)findViewById(R.id.spinner_pri)).setSelection(nTradetype);

									if (cs.getString(3)!=null && cs.getString(3).length()>0 && cs.getInt(3)!=0)nDiscount=cs.getInt(3);
									else nDiscount=100;
									
									((Button)findViewById(R.id.btn_disc)).setText(""+nDiscount);
									getSuccess();
			        				nCondition=1;setCondition();
								}else{
									nSuccess=0;
								}
								db.close();
								cs.close();
						}
					}else{
						nCondition=2;setCondition();
					}
				}
				
				break;
			}
		case RESULT_QFACT:
			{
				if (resultCode == RESULT_OK) {
					int newone=1;
					String mW=dataR.getStringExtra("fact_id");
					File fileQmtrio = new File(mDBPath);
			      	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
					Cursor csm = mdb.rawQuery("select PNDNADAY from qpandn where USER='"+mW+"' and PNDNFKIND="+nDept +" and PNDNSTATE<>2 and ID=3", null);
					if (csm.getCount()>0) {
						newone=0;//表示不可重覆建立新的盤表
        				Toast.makeText(QpandnF.this, "不可以重複建立:"+mW+" 的盤點表!!", Toast.LENGTH_SHORT).show();
					}
					csm.close();
					mdb.close();
					if (newone==1){ 					
						SQLiteDatabase db = Utilis.getDB(QpandnF.this);
						Cursor cs = null;					
						StringBuffer mySqlBuf = new StringBuffer();
							mySqlBuf.append("select FACTNO,FACTNAME,TRADETYPE,DISCOUNT from qfact where FACTNO='"+mW+"' ");
							cs = db.rawQuery(mySqlBuf.toString(), null);
							if (cs.getCount()>0){
								cs.moveToFirst();
								nTradetype=cs.getInt(2);if (nTradetype<=0) nTradetype=1;
								mWho=cs.getString(0);
								mWhoName=cs.getString(1);
								((Button)findViewById(R.id.btn_pndnno)).setText(mWho);
								((Button)findViewById(R.id.btn_pndnname)).setText(mWhoName);
								((Spinner)findViewById(R.id.spinner_pri)).setSelection(nTradetype);
								
								if (cs.getString(3)!=null && cs.getString(3).length()>0 && cs.getInt(3)!=0)nDiscount=cs.getInt(3);
								else nDiscount=100;
								
								((Button)findViewById(R.id.btn_disc)).setText(""+nDiscount);
								getSuccess();
							}else{
								nSuccess=0;
							}
							db.close();
							cs.close();
					}else{
						nCondition=2;setCondition();
					}
				}
				break;				
			}
		}
	}
	
	public void onResume(){
		super.onResume();
		//意思是說 盤點前應該就緒
		String Tnow =DateUtil.getSystemTime().substring(2, 12);
		String T[]=Utilis.getIni(this, "SYS", "SEASON", 9).split("!&!");

		if (Utilis.haveInternet(QpandnF.this) && of_line!=0 && (Utilis.toDouble(Tnow)-Utilis.toDouble(T[1]))>6)  //逾6分鐘沒有同步
			DBCloud.aa0_aa1_auto_qdetail_n(QpandnF.this);
	}
	
    public void onDestroy(){
    	super.onDestroy();
    }
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
        setContentView(R.layout.pandnf);
        
        setTitle(getString(R.string.app_name_version));
        
        lTableView = (LinearLayout)findViewById(R.id.tableview);
    	mLayoutRoot = (LinearLayout)findViewById(R.id.root);
        

		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Wwidth = dm.widthPixels;
        Wheight = dm.heightPixels;
		tableHeight=(int) (Wheight/22);
		if (Wwidth<=800) tabless=(int) (Wwidth/80)+2; else  tabless=(int) (Wwidth/120)+1;

        if (!deptStr[0].equalsIgnoreCase(deptStr[5])) nPart=1;  //0門市版1總倉

        ArrayAdapter<CharSequence> adapterAccount = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, mTradeTypeStr);
        adapterAccount.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
		Spinner SpinPri = (Spinner)findViewById(R.id.spinner_pri);
		SpinPri.setAdapter(adapterAccount);
		SpinPri.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> adapterView, View view,
					int position, long id) {
				nTradetype = position;
				if (nTradetype<=0) nTradetype=1;
				reCountBG();
			}
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
        
		if( nPandnK==0 ){ //詳式盤點 預設
			((RadioGroup)findViewById(R.id.GroupP)).check(R.id.radioP0);
		}else if (nPandnK==1) { //簡式盤點
			((RadioGroup)findViewById(R.id.GroupP)).check(R.id.radioP1);
		}else{ //價格盤點
			((RadioGroup)findViewById(R.id.GroupP)).check(R.id.radioP2);
		}
		
		//GalleryView 11個欄位排列為
		//0代碼/1顏色/2尺寸/3暫盤/4已盤/5盤差/6應盤/7銷貨/8出貨/9進貨/10上存
        //nState 0主盤表 1暫盤表 2歷史表
		//nKind  0主盤表 1盤差表 2盤準表 3已盤表 4未盤表 5.增盤表(原盤表不存在的商品ID>8000 and ID<10000)
        
        //如果非總倉系統,一經點選 radio 可以為門市或廠商,就是不能為總倉,否則3種皆可
        //確認點選(門市)後,隨即拉開(門市通訊錄)供選後_確認傳回
        //並檢查,有否未入帳的(盤點清冊)若無:表首次盤點:上盤日期:2012-03-14,本盤日期:(today)
        //若有盤點清冊都已入帳,則取出最後一份盤清冊,並存入上盤日期
        //傳回該門市或廠商的代號,簡稱,價別,折數,盤點輸出的方式(詳式or簡式or盤價)
        //讀取上盤的REC1:(盤存)件數 盤存金額
        //--??--何時啟動上存的數據取出,然後建立本期的盤點清冊
        //本盤日期:預設為當月最後一天,如果>20天,則自動取上月最後一天
        //--??--價別&折數 可供修改
        //價別:歷史價成本價中盤價批發價網購價零售價 (spinner)
        //折數:可以喚出計算機版面
      
		//首頁的3+1大圖示功能 門市盤點 總倉盤點 廠商盤點 離開
		((LinearLayout)findViewById(R.id.layout_deptpndn)).setOnClickListener(new MainClick());
        ((LinearLayout)findViewById(R.id.layout_aapndn)).setOnClickListener(new MainClick());
        ((LinearLayout)findViewById(R.id.layout_factpndn)).setOnClickListener(new MainClick());
        ((LinearLayout)findViewById(R.id.layout_exitpndn)).setOnClickListener(new MainClick());
        
        //新增盤表的功能鍵
        ((Button)findViewById(R.id.btn_pndnno)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.btn_disc)).setOnClickListener(new MainClick());        
        ((Button)findViewById(R.id.btn_dpndn)).setOnClickListener(new MainClick());
        
        ((Button)findViewById(R.id.btn_cmd)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_pdd)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_add)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_save)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_savein)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_reset)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());

        ((ImageButton)findViewById(R.id.pbtn_input)).setOnClickListener(new MainClick());
        ((LinearLayout)findViewById(R.id.line_input)).setVisibility(View.GONE);
        pInput = (EditText)findViewById(R.id.pedIn);

        
    	mBTain=((Button)findViewById(R.id.btn_ainn));//本進
    	mBTaim=((Button)findViewById(R.id.btn_ainm));
    	mBTastn=((Button)findViewById(R.id.btn_astn));//本銷
    	mBTastm=((Button)findViewById(R.id.btn_astm));
    	mBTastkn=((Button)findViewById(R.id.btn_astkn));//本存
    	mBTastkm=((Button)findViewById(R.id.btn_astkm));

    	mBTaadn=((Button)findViewById(R.id.btn_aadn));//本進
    	mBTaadm=((Button)findViewById(R.id.btn_aadm));
    	//((Button)findViewById(R.id.btn_disc)).addTextChangedListener(watcherPrice);
    
        mListView = (ListView)findViewById(R.id.list_pditem);
        mAdapter = new ReportAdapter(this);
        mListView.setAdapter(mAdapter);
        mListView.setVisibility(View.GONE);
        
        getCountryData(this);
        getTypeData(this);
       
mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
			int arg2, long arg3) {
		// TODO Auto-generated method stub
		locations=arg2;
		datas = (RepDataPan) mAdapter.getItem(locations);
		mItem=datas.iFormdate;
		mItemName=datas.iGoods;
		mFormno=datas.iFormno;
		if (nCondition==2){ //二樓
			String [] mDdate=datas.iName.split("~");
			mWho=datas.iFormdate;  
			mWhoName=datas.iGoods;
			Ddate=mDdate[1];
			Ldate=mDdate[0];

			Utilis.runVibrate(QpandnF.this);
			DialogUtilis.showDialog(QpandnF.this, "請選擇以下功能", -1,
			menu_LE, new IDialog() {
			@Override
			public void onDialogFinish(int pos, String choice) {
				switch (pos) {
					case 0://二樓刪除盤表(含現行(如果為最後一筆,可以刪除)歷史(如果為最後一筆,不可刪除))
					{	
					//nState==2 歷史表 最後一筆決不可刪
					//唯有歷史表,才需要這個判斷
					//進階版 應需要檢查 本盤表是否已存在 外部的匯出檔案
						DialogUtilis.showDialog(QpandnF.this, "確定整張單刪除?", -1,
						new String[] { "取消刪除", datas.iGoods+"的盤點清冊  當真刪除!!" }, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
							  switch (pos) {
								case 0: {break;}
								case 1: // 確定刪除
								{
								//CloudVer && 已過帳
								if (of_line!=0 && nState==2){  
								  if (Utilis.haveInternet(QpandnF.this)){
									goCloud(8);
								  }else{
									//刪除失敗,請檢查網路品質  
										Toast.makeText(QpandnF.this, mWho+"/"+mWhoName+" 刪除失敗,請檢查網路品質!!! ", Toast.LENGTH_SHORT).show();
								  }
								}else{//Local 含過帳或現行 皆可以刪除
									File fileQmtrio = new File(mDBPath);
							      	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
							      	StringBuffer SQLb=new StringBuffer();
							      	SQLb.append("delete from qpandn where USER='"+mWho+"' and PNDNFKIND="+nDept );
							      	SQLb.append(" and PNDNADAY='"+Ddate+"'");
							      	mdb.execSQL(SQLb.toString());
							      	mdb.close();
									if (nState==2 && !mFormno.equalsIgnoreCase("FORMNO")) goDelQhead(mFormno);					
								}
								
								getGroupData(QpandnF.this, mWho, nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
								mAdapter.notifyDataSetChanged();        
								}
							  }
							}
						});
					break;
					}
					//case 1://匯出且移除盤表(現行/歷史(條件))
					case 1://重新校正上存數據(只限定,尚未過帳的現行盤表)
					{
						if (nState!=2){//非已過帳
							//qmtrs 歸零
							//qmtrs 存入上存實際數據 而非 上次盤表的紀錄
							if (!Ldate.equalsIgnoreCase("2012-03-14")){
								File fileQmtrio1 = new File(mDBPath);
						      	SQLiteDatabase pdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio1, null);

						    	String mDBPath1=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this,"SYS","YEAR",4);
						    	pdb.execSQL("attach database ? as cwdb", new String[]{mDBPath1});
						      	
								Cursor cs=pdb.rawQuery("select distinct ID from qmtrs", null);
								if (cs.getCount()>0){
									pdb.execSQL("delete from qmtrs");
								}
								cs.close();
						      	
								String SQL="insert into qmtrs (GOODSNO,ID)"+
										" select a.GOODSNOS,"+"sum(a.UNIT10)-sum(a.UNIT20)-sum(a.UNIT30)-sum(a.UNIT40)"+  
										" from cwdb.qitems as a";
									if (nDept==2)//廠商
										SQL+=" where a.SUPPLY='"+mWho+"' and a.QKIND<>'21' and a.ISCONFIRM='Y'";
									else if (nDept==1)//門市
										SQL+=" where a.DEPTNO='"+mWho+"' and a.ISCONFIRM='Y'";
									else  //總倉
										SQL+=" where a.DEPTNO='"+mWho+"' and a.QKIND<>'21' and a.ISCONFIRM='Y'";
								
								SQL+=" and a.FORMDATE<='"+Ldate+"' group by a.GOODSNOS ";
										pdb.execSQL(SQL);
										SystemClock.sleep(1000);
										
								if (nDept==1){//門市盤點 才需要執行	
										SQL="insert into qmtrs (GOODSNO,ID)"+
												" select a.GOODSNOS,sum(a.UNIT20) from cwdb.qitems as a"+
												" where a.USER ='"+mWho+"' and (a.QKIND='20' or a.QKIND='21')  and a.ISCONFIRM='Y'"+
												" and a.FORMDATE<='"+Ldate+"'"+
												" group by a.GOODSNOS";
												pdb.execSQL(SQL);
								}
								//備妥qmtrs 將盤表重新運算
								//校正上存,全面重新運算
								//從qpandn 一一讀取 找 qmtrs
									
								
								SQL="select USER,PNDNADAY,GOODSNO,DATA,ID,UNITPRICE from QPANDN where PNDNADAY='"+Ddate+"' and USER='"+mWho+"' order by GOODSNO";
								cs=pdb.rawQuery(SQL.toString(), null);
								int acLastStk=0;double acLastStkm=0; 
								int acAin=0;		double acAim=0;
								int acAadn=0;		double acAadm=0;
								int acAstn=0;		double acAstm=0;
								int acAstkn=0;		double acAstkm=0;
								int acApndefn=0;		double acApndefm=0;
								int acApan=0;		double acApam=0;
								int acAupn=0;
								
								if (cs.getCount()>0){
									while (cs.moveToNext()){
										String mUser=cs.getString(0);
										String mPndnadat=cs.getString(1);
										String mGoodsno=cs.getString(2);
										String mData=cs.getString(3);
										String mID=cs.getString(4);
										int mPri=cs.getInt(5);
										if (mData.indexOf("，")>0){
											String [] gData=mData.split("，");
											//重新校正 上存 每一筆
											int cLastStk=0;double cLastStkm=0; 
											int cAin=0;		double cAim=0;
											int cAadn=0;		double cAadm=0;
											int cAstn=0;		double cAstm=0;
											int cAstkn=0;		double cAstkm=0;
											int cApndefn=0;		double cApndefm=0;
											int cApan=0;		double cApam=0;
											int cAupn=0;		double cAupnm=0;
											String aaData="";
											
											for (int ii=0;ii<gData.length;ii++){
												if (gData[ii].indexOf(",")>0){
												  if (gData[ii].length()>10){
													String [] aData=gData[ii].split(",");

														String mGoodS=mGoodsno+"-"+aData[0]+"-"+aData[2];
														String SQLmtrs="select sum(ID) from qmtrs where GOODSNO='"+mGoodS+"' group by GOODSNO";
														Cursor CSmtr=pdb.rawQuery(SQLmtrs, null);
														if (CSmtr.getCount()>0){
															CSmtr.moveToFirst();
															int lastStk=CSmtr.getInt(0);
															//比較上存不一樣者 update之
															if (lastStk!=Utilis.toInt(aData[10])){
																aData[10]=""+lastStk;//修正上存
																aData[6]=""+(lastStk+Utilis.toInt(aData[9])-Utilis.toInt(aData[8])-Utilis.toInt(aData[7]));
																//算出應盤6= 10+9-8-7
															}
														}
														CSmtr.close();
													
													aData[5]=""+((Utilis.toInt(aData[6])-Utilis.toInt(aData[4]))*-1);
													//運算盤差5=6-4
													cLastStk+=Utilis.toInt(aData[10]);
													acLastStk+=Utilis.toInt(aData[10]);
													cLastStkm+=Utilis.toInt(aData[10])*mPri;
													acLastStkm+=Utilis.toInt(aData[10])*mPri;
													
													cAin+=Utilis.toInt(aData[9]);
													acAin+=Utilis.toInt(aData[9]);
													cAim+=Utilis.toDouble(aData[9])*mPri;
													acAim+=Utilis.toInt(aData[9])*mPri;
													
													cAadn+=Utilis.toInt(aData[8]);
													acAadn+=Utilis.toInt(aData[8]);
													cAadm+=Utilis.toDouble(aData[8])*mPri;
													acAadm+=Utilis.toInt(aData[8])*mPri;
													
													cAstn+=Utilis.toInt(aData[7]);
													acAstn+=Utilis.toInt(aData[7]);
													cAstm+=Utilis.toDouble(aData[7])*mPri;
													acAstm+=Utilis.toInt(aData[7])*mPri;
													
													cAstkn+=Utilis.toInt(aData[6]);
													acAstkn+=Utilis.toInt(aData[6]);
													cAstkm+=Utilis.toDouble(aData[6])*mPri;
													acAstkm+=Utilis.toInt(aData[6])*mPri;
													
													cApndefn+=Utilis.toInt(aData[5]);
													acApndefn+=Utilis.toInt(aData[5]);
													cApndefm+=Utilis.toDouble(aData[5])*mPri;
													acApndefm+=Utilis.toInt(aData[5])*mPri;
													
													cApan+=Utilis.toInt(aData[4]);
													acApan+=Utilis.toInt(aData[4]);
													cApam+=Utilis.toDouble(aData[4])*mPri;
													acApam+=Utilis.toInt(aData[4])*mPri;
													
													cAupn+=Utilis.toInt(aData[3]);
													acAupn+=Utilis.toInt(aData[3]);
													
													for (int x=0;x<10;x++){
														aaData+=aData[x]+",";
													}	
													aaData+=aData[10]+"，";
													//重新合成 DATA
												  }
												}
											}
											if (!mData.equalsIgnoreCase(aaData)){
												//update qpandn
												StringBuffer Bdata=new StringBuffer(); 
												Bdata.append("update qpandn set DATA='"+aaData+"',LASTSTKN='"+cLastStk+"',LASTSTKM='"+cLastStkm+"',ASTKN='"+cAstkn+"',ASTKM='"+cAstkm+"',ADEFN="+cApndefn+",ADEFM="+cApndefm);
												Bdata.append(" where  USER='"+mUser+"' and PNDNADAY='"+mPndnadat+"' and ID="+mID+" and GOODSNO='"+mGoodsno+"'");
												pdb.execSQL(Bdata.toString());
											}
										}
									}
								}
								
								cs.close();

								StringBuffer Udata=new StringBuffer(); 
								Udata.append("update qpandn set ");
								Udata.append("PNDNFKIND='"+nDept+"'");  //0AA 1A1 2SUPPLY
								Udata.append(",AINN='"+acAin+"'") ;
								Udata.append(",AINM='"+acAim+"'");
								Udata.append(",ASTN='"+acAstn+"'") ;
								Udata.append(",ASTM='"+acAstm+"'") ;
								Udata.append(",ASTKN='"+acAstkn+"'") ; //本存(應盤)
								Udata.append(",ASTKM='"+acAstkm+"'") ;  //這是個不對稱的欄位
								Udata.append(",APANN='"+acApan+"'") ; //本盤
								Udata.append(",APANM='"+acApam+"'") ;
								Udata.append(",ADEFN='"+acApndefn+"'") ;  //盤差量
								Udata.append(",ADEFM='"+acApndefm+"'") ;  //盤差金
								Udata.append(",CDT='"+DateUtil.getSystemTime().substring(2, 14)+"'") ;
								Udata.append(",APIN='"+acAupn+"'") ;  //暫盤
								Udata.append(",SDT='"+DateUtil.getSystemTime().substring(2, 14)+"'") ;
								Udata.append(",BANKNAME='"+bankn+"'") ;
								Udata.append(",TR='"+"Y1"+"'") ;
								Udata.append(" where PNDNADAY='"+Ddate+"' and USER='"+mWho+"' and ID=3") ;
								pdb.execSQL(Udata.toString());
								
								pdb.close();
								
								//		if (mAdapter.mList != null) {
								//			mAdapter.mList.clear();
								//		}
								 
								getGroupData(QpandnF.this, mWho, nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
								mAdapter.notifyDataSetChanged();
								
							}
						}
						break;
					}
					case 2://現行:重新盤點 歷史:取消過帳
					{
						if (nState!=2){ //現行:重新盤點
							DialogUtilis.showDialog(QpandnF.this, "確定已盤好的要歸零,再重新盤點?", -1,
									new String[] { "取消歸零", "當真歸零!起手無回大丈夫!" }, new IDialog() {
										@Override
										public void onDialogFinish(int pos, String choice) {
											switch (pos) {
											case 0: break;
											case 1: zeroPin("",1);  //1.盤點歸零 0.暫盤歸零 2
											}
										}
							});
						}else{//歷史:取消過帳
						  DialogUtilis.showDialog(QpandnF.this, "已過帳的歷史盤表,要取消過帳?", -1,
						  new String[] { "返回", "當真取消過帳!起手無回大丈夫!" }, new IDialog() {
							@Override
						   public void onDialogFinish(int pos, String choice) {
							switch (pos) {
							case 0: break;
							case 1:	//首先要 取得該盤點單的轉單單號
								if (of_line!=0 && nState==2){  
									  if (Utilis.haveInternet(QpandnF.this)){
										goCloud(10);
									  }else{
										//刪除失敗,請檢查網路品質  
											Toast.makeText(QpandnF.this, mWho+"/"+mWhoName+" 刪除失敗,請檢查網路品質!!! ", Toast.LENGTH_SHORT).show();
									  }
									}else{//Local 含過帳或現行 皆可以刪除
										File fileQmtrio = new File(mDBPath);
								      	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
								      	StringBuffer SQLb=new StringBuffer();
								      	SQLb.append("update qpandn set PNDNSTATE=0 where USER='"+mWho+"' and PNDNFKIND="+nDept );
								      	SQLb.append(" and PNDNADAY='"+Ddate+"' ");
								      	
								      	mdb.execSQL(SQLb.toString());
								      	mdb.close();
										if (nState==2 && !mFormno.equalsIgnoreCase("FORMNO")) goDelQhead(mFormno);					
									}
								nState=1;
								nCondition=2;	setCondition();								
								getGroupData(QpandnF.this, mWho, nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
								mAdapter.notifyDataSetChanged();        
							}
						   }
						  });
						}
						break;
					}
					case 3://現行:同在庫量 歷史:輸出
					{
						if (nState!=2){ 
							DialogUtilis.showDialog(QpandnF.this, "已盤同應盤量,先假設全部符合?", -1,
									new String[] { "返回", "當真讓已盤同應盤量!" }, new IDialog() {
										@Override
										public void onDialogFinish(int pos, String choice) {
											switch (pos) {
											case 1: zeroPin("",2);  //2.已盤同在庫量
											}
										}
							});
						}else{	//輸出(已過帳)就是專櫃請款單
							//前取得該已過帳的 盤點表資訊
							//mWho;mWhoName;Ddate;Ldate;

							Toast.makeText(QpandnF.this, mWho+"/"+mWhoName+" 對帳請款單建立中!!請稍後!!! ", Toast.LENGTH_SHORT).show();
				    		SQLiteDatabase dbc = Utilis.getDB(QpandnF.this);
				    		Cursor cus=dbc.rawQuery("select TRADETYPE from qcust where CUSTNO='"+mWho+"' and TR='20'", null);
				    		if (cus.getCount()>0) 
				    			{cus.moveToFirst();nTradetype=cus.getInt(0);} else nTradetype=3; 
				    		cus.close();
				    		dbc.close();
				    		
					    	if (Utilis.haveInternet(QpandnF.this) && of_line!=0 && nState==2){
					    		goCloud(7);	    		
					    	}else{//local read
					    		
								File fileQmtrio = new File(mDBPath);
						      	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
					    		SQLiteDatabase db = Utilis.getDB(QpandnF.this);
								StringBuffer mySqlBuf = new StringBuffer();
								StringBuffer myPanData = new StringBuffer();
								myPanData.append("_panok;SETPAGE\r\n");
								mySqlBuf.append("select PNDNADAY,PNDNBDAY,LASTSTKN,LASTSTKM,AINN,AINM,ASTKN,ASTKM,ASTN,ASTM,APANN,APANM,ADEFN,ADEFM from qpandn where USER='"+mWho+"'");
								mySqlBuf.append(" and PNDNADAY='"+Ddate+"' and PNDNBDAY='"+Ldate+"' and PNDNSTATE=2 and ID=3");
								//就是要之前盤表的表頭 數據
								Cursor csm = mdb.rawQuery(mySqlBuf.toString(), null);
								if (csm.getCount()>0){
									csm.moveToFirst();
									for (int x=0;x<=13;x++)
									myPanData.append(csm.getString(x)+";");
									myPanData.append("SETPAGE\r\n");
									
									//Part2 QHEAD_QAD 專櫃出貨單
									mySqlBuf.delete(0, mySqlBuf.toString().length());
									mySqlBuf.append("select FORMDATE,FORMNO,HANDNO,BSUM from qhead where USER='"+mWho+"' and FORMDATE>'"+Ldate+"' and FORMDATE<='"+Ddate+"' and ISCONFIRM='Y' and (QKIND='20' or QKIND='21') order by FORMDATE,FORMNO");
									Cursor cs=db.rawQuery(mySqlBuf.toString(), null);
									if (cs.getCount()>0){
										while (cs.moveToNext()){
											for (int x=0;x<=3;x++)
											myPanData.append(cs.getString(x)+";");	
											myPanData.append("HH20\r\n");
										}
									}
									cs.close();
									
									myPanData.append("SETPAGE\r\n");
									//Part3 QHEAD_QST 專櫃銷貨單
									mySqlBuf.delete(0, mySqlBuf.toString().length());
									mySqlBuf.append("select FORMDATE,FORMNO,HANDNO,BSUM from qhead where DEPTNO='"+mWho+"' and FORMDATE>'"+Ldate+"' and FORMDATE<='"+Ddate+"' and ISCONFIRM='Y' and (QKIND='30' or QKIND='31') order by FORMDATE,FORMNO");
									cs=db.rawQuery(mySqlBuf.toString(), null);
									if (cs.getCount()>0){
										while (cs.moveToNext()){
											//@@@尚未取得該專櫃的交易價別
											int sumDef=0;
											Cursor csi=db.rawQuery("select GOODSNO,sum(UNIT30),UNITPRICE,DISCOUNT,sum(SUBPRICE),sum((UNIT30*P"+nTradetype+")-SUBPRICE),P"+nTradetype+" from qitems "
											+ "where FORMNO='"+cs.getString(1)+"' and DEPTNO='"+mWho+"' and (QKIND='30' or QKIND='31') group by GOODSNO,UNITPRICE,DISCOUNT,P"+nTradetype+"", null);
											if (csi.getCount()>0){
												while (csi.moveToNext()){
													myPanData.append(csi.getString(0)+";");
													myPanData.append(csi.getString(1)+";");
													myPanData.append(csi.getString(2)+";");
													myPanData.append(csi.getString(3)+";");
													myPanData.append(csi.getString(4)+";");
													if (csi.getInt(3)!=100){
														myPanData.append(" ;");
														myPanData.append(" ;");
													}else{
														myPanData.append(csi.getString(5)+";");
														myPanData.append(csi.getString(6)+";");
														sumDef+=csi.getInt(4);
													}
													myPanData.append("II30\r\n");
												}
											}
											csi.close();
											for (int x=0;x<=3;x++)
											myPanData.append(cs.getString(x)+";");
											if (sumDef!=0) myPanData.append(""+sumDef+";");
											else myPanData.append(cs.getString(3)+";");
												
											myPanData.append("HH30\r\n");
										}
										
									}
									cs.close();
									myPanData.append("SETPAGE\r\n");
								}else{
									myPanData.append("_pan000\r\n");
								}
								mdb.close();
								csm.close();
								db.close();
								if (myPanData.toString().indexOf(";SETPAGE")>0)
									qadff(myPanData.toString(),0);
								//進行呼叫與goCloud 一樣的模組 對帳請款單
					    	}							
						}
						break;
					}
					case 4://現行:暫盤歸零 歷史:返回
					{	
						if (nState!=2){ 
							DialogUtilis.showDialog(QpandnF.this, "確定暫盤要歸零,再重新盤點?", -1,
									new String[] { "取消歸零", "當真歸零!起手無回大丈夫!" }, new IDialog() {
										@Override
										public void onDialogFinish(int pos, String choice) {
											switch (pos) {
											case 0: break;
											case 1: zeroPin("",0);  //暫盤歸零
											}
										}
							});
						}else{//已過帳盤表輸出A4
							reportPanDetail(QpandnF.this, mWho,2);
						}
						break;
					}
					case 5://現行:暫盤入帳 歷史:不執行
					{	
						if (nState!=2){ 
						zeroPin("",12); //所有暫盤入為已盤
						}
						break;
					}
					case 6://現行:盤點過帳 歷史:不執行
					{
						if (nState !=2 && nDept !=2 && datas.iMoney.indexOf("暫盤:")<0){  //有可能為門市 總倉 但廠商不可執行過帳動作
							DialogUtilis.showDialog(QpandnF.this, "請選擇盤點過帳的方式:", -1,
								new String[] { "盤差轉盤銷單", "盤差轉盤退單","返回" }, new IDialog() {
									@Override
									public void onDialogFinish(int pos, String choice) {
										switch (pos) {
										case 2: break;
										case 0: //盤差轉盤銷單 1確認為 總倉30 或門市31 (*-1)
											 if (nDept==1) SaveinQQ(datas,mWho,0); else SaveinQQ(datas,mWho,2);
											 break;
										case 1: //盤差轉盤退單 1確認為 總倉10 或門市20
											 if (nDept==1) SaveinQQ(datas,mWho,1); else SaveinQQ(datas,mWho,3);
											 break;
									}
								}
							});
						}else {
							Toast.makeText(QpandnF.this, mWho+" 盤點表,請檢查暫盤是否全部轉入已盤!! ", Toast.LENGTH_SHORT).show();
						}
						break;
					}
					case 7://現行:已盤量同在庫量,並直接點過帳  歷史:不執行
					{
						if (nState!=2){
							zeroPin("",11);	
						}
						break;
					}
					case 8://現行:返回 歷史:不執行
					{	
						break;
					}
				}
			}
			});
			return true;
		}else if (nCondition==3 && nState!=2){ //三樓
			Utilis.runVibrate(QpandnF.this);
			//[0]"單款(暫盤)歸零";[1]="單款(盤點)歸零";[2]="單款(盤準)零誤差";	[3]="補價";[4]="返回";
		
			DialogUtilis.showDialog(QpandnF.this, "請選擇以下功能", -1,
					menu_LE, new IDialog() {
					@Override
					public void onDialogFinish(int pos, String choice) {
						switch (pos) {
							case 0://三樓 單款暫盤歸零
							{
								zeroPin(datas.iFormdate,0);
								break;
							}
							case 1: //三樓 單款盤點歸零
							{	
								zeroPin(datas.iFormdate,1);
								break;
							}
							case 2: //單款盤準
							{
								zeroPin(datas.iFormdate,2);
								break;
							}
							case 3:  //補價 對話框 改為 追蹤(單款)
							{
								Intent intent = new Intent();
								intent.putExtra("QHis_kind", 20);
								intent.putExtra("QHis_mode", 1);
								intent.putExtra("QHis_User","" );
								intent.putExtra("QHis_Goods",datas.iFormdate );
								intent.setClass(QpandnF.this, QHis.class);
								startActivity(intent);
								
								
								break;
							}
							case 4:  //返回
							{
								break;
							}
						}
					}
			});
						
			return true;
		}
		
		return false;
	}
});
        
        //
        mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long ids) {
				// TODO Auto-generated method stub
				locations=position;
				datas = (RepDataPan) mAdapter.getItem(locations);
				Utilis.runVibrate(QpandnF.this);
			if (nCondition==3){//三樓  只有顯示該品TABLE
				if (nState!=2){
					goodO=datas.iFormdate;
					File fileQmtrio = new File(mDBPath);
				  	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
				  	StringBuffer mSQL = new StringBuffer();
					Cursor csm;
					//@@@ID>10<10000表示總盤表 10000以上為暫盤表
					//ID>8000<10000表示為補增資料 可以列式條件
					//是否納入 已盤清冊 未盤清冊 盤差清冊 等多元查詢
					mSQL.append("select * from qpandn where USER='"+mWho+"' and PNDNADAY='"+Ddate+"'")
					.append(" and PNDNFKIND="+nDept);
					mSQL.append(" and GOODSNO='"+goodO+"'");
					csm=mdb.rawQuery(mSQL.toString(), null);
						if(csm.getCount()>0 ){ //唯一性的,可以進行比對
							csm.moveToFirst();
							disPlayTable(csm.getString(csm.getColumnIndex("DATA")));
						}
					csm.close();
					mdb.close();
				}else{
				
					disPlayTable(datas.iUnit2);					
				}
			}else{  //二樓
				if (nState!=2){
					String [] mDdate=datas.iName.split("~");
					mWho=datas.iFormdate;  
					mWhoName=datas.iGoods;
					mFormno=datas.iFormno;
					Ddate=mDdate[1];
					Ldate=mDdate[0];
					DialogUtilis.showDialog(QpandnF.this, "請選擇以下功能", -1,
							menu_E, new IDialog() {
								@Override
								public void onDialogFinish(int pos, String choice) {
									switch (pos) {
										case 0:nKind=0;	break;//暫盤中,繼續盤點
										case 1:nKind=1;	break;//全部的盤點明細
										case 2:nKind=2;	break;//盤點且還有盤差的明細
										case 3:nKind=3;	break;//盤點而沒有盤差的明細
										case 4:nKind=4;	break;//已經有盤過的明細
										case 5:nKind=5;	break;//還沒有盤過的明細
										case 6:nKind=6;	break;//增盤明細(收負帳)
										case 7:nKind=7;	break;//本期沒有盤差的明細
										case 8:nKind=-2;break;//輸出報表
										case 9:nKind=-3;break;//輸出CSV
										case 10:nKind=-1;	break;//返回
									}
									if (nKind>=0){
										nCondition=3;	setCondition();  //
										aExtWord="";
										getDetailData(QpandnF.this, mWho);  //aState==1 有找到 暫盤表
										mAdapter.notifyDataSetChanged();
									}else if(nKind==-1) nKind=0;
									 else if (nKind==-2)//輸出報表
										reportPanDetail(QpandnF.this, mWho,0);
									 else if (nKind==-3){//輸出CSV
										 reportPanDetail(QpandnF.this, mWho,1);
									}
								}
					});
				}else{//之前盤表
					String [] mDdate=datas.iName.split("~");
					mWho=datas.iFormdate;  
					mWhoName=datas.iGoods;
					mFormno=datas.iFormno;
					Ddate=mDdate[1];
					Ldate=mDdate[0];
					nKind=1;
					getDetailData(QpandnF.this, mWho);  //aState==1 有找到 暫盤表
					mAdapter.notifyDataSetChanged();
    				//Toast.makeText(QpandnF.this, "已過帳盤點表,不提供進一步分析!!", Toast.LENGTH_SHORT).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){
        				String xx=pInput.getText().toString();
        				aInput=xx.toUpperCase();
        				catched();
        				return true;
        			}else if (keyCode == KeyEvent.KEYCODE_BACK) {
        	            new AlertDialog.Builder(QpandnF.this).setTitle(getString(R.string.str_msg)).setMessage("是否結束盤點作業").setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
        	              public void onClick(DialogInterface dialog, int which) {
        	  				finish();
        	  			}
        	              
        	            }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
        	              public void onClick(DialogInterface dialog, int which) {
        	              }
        	            }).show();
        	            return true;
        			}
        	}
        	return false;
        	}
        });
        	
        pInput.setOnFocusChangeListener(new View.OnFocusChangeListener(){
        	  public void onFocusChange(View view, boolean hasFocus){
        	    if(hasFocus){
        			pInput.getSelectionStart();
        	    }
        	  }
        	});
     
        mListView.setOnFocusChangeListener(new View.OnFocusChangeListener(){
      	  public void onFocusChange(View view, boolean hasFocus){
      	    if(hasFocus){
      			pInput.requestFocus();
      	    } else {
      	    }
      	  }
      	});

        
        
        nCondition=0;	setCondition();  //一樓
    } //END OF PROGRAM

/*
 	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
          new AlertDialog.Builder(QpandnF.this).setTitle(getString(R.string.str_msg)).setMessage("是否結束盤點作業").setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
				finish();
			}
            
          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
          }).show();
          return true;
    }
        return false;
 	}
*/
    
    private void catched(){
    	if(aInput.length()>0){
			pInput.setSelectAllOnFocus(true);
			int Echk=-1;
			int Schk=-1;
			int Chk=0;
			if (aInput.indexOf(".")==0){
	    		SQLiteDatabase db = Utilis.getDB(QpandnF.this);
				Cursor cs=db.rawQuery("select GOODSNOS from qitems where HANDNO='"+aInput.substring(1).trim()+"' order by FORMDATE LIMIT 1", null);
				if (cs.getCount()>0){
					cs.moveToFirst();
					aInput=cs.getString(0);
					goodO=aInput.substring(0,aInput.indexOf("-"));
					mColorno=aInput.substring(aInput.indexOf("-")+1,aInput.lastIndexOf("-"));
					mySize=aInput.substring(aInput.lastIndexOf("-")+1);
					Chk=1;
				}
				db.close();
				cs.close();
				
			}else if (aInput.indexOf("-")!=aInput.lastIndexOf("-")){//表示輸入了商品,顏色尺寸
				goodO=aInput.substring(0,aInput.indexOf("-"));
				mColorno=aInput.substring(aInput.indexOf("-")+1,aInput.lastIndexOf("-"));
				mySize=aInput.substring(aInput.lastIndexOf("-")+1);
				if (mySize.length()>0 && (mColorno.length()==2|| mColorno.length()==3) ){
					if (mySize.indexOf("X")==0 && mySize.length()==1)
						//@@@20200221表示尺寸取得不完整,自動補入XL
						mySize="XL";
					Chk=1;
				}
			}else if ((aInput.indexOf("-")==aInput.lastIndexOf("-") && aInput.indexOf("-")!=0)){//商品貨號不符合
				//貨號不完整
				Chk=0;
				
			}else if(aInput.indexOf("-")<0){
				//表示只有輸入該主貨號,例如其他轉檔強制植入"-00-F"
				//goodO=aInput;
				//mColorno="00";
				//mySize="F";
				//aInput=aInput+"-00-F";
				Chk=0;
			}
			if (Chk!=0){
				String Adata=searched(mChoiceMode);
				if (Adata.length()>0){
					Schk=1;
					for (int ii=0;ii<mAdapter.mList.size();ii++){
						datas = (RepDataPan) mAdapter.getItem(ii);
						if (datas.iFormdate.equalsIgnoreCase(goodO)){
							RepDataPan data = new RepDataPan();
							data.iPic=datas.iPic;
							data.iGoods=mLocDD;  //櫃位 
							data.iName=datas.iName;  
							data.iCountry=datas.iCountry;
							data.iNumber=datas.iNumber; //單價
							data.iImpo=datas.iImpo;  //應盤
							data.iUnit2=Adata;
							data.iMoney="暫盤:"+nPin+"/已盤:"+nAadn; //本盤
							data.iCompany="盤差:"+nAdefn+"/"+nAdefm;//盤差
							data.iFormdate=datas.iFormdate;  //盤點對象代號
							data.iFormno=datas.iFormno;
							mAdapter.mList.set(ii, data);
							mAdapter.notifyDataSetChanged();
							mListView.setSelection(ii);
							disPlayTable(Adata);
							Echk=1;
							break;
						}
					}
				}
				
			if (Schk==1 && Echk<0){//在Adapter增入這筆資料
				File fileQmtrio = new File(mDBPath);
			  	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
			  	StringBuffer mSQL = new StringBuffer();
				Cursor csm;
				mSQL.append("select * from qpandn where USER='"+mWho+"' and PNDNADAY='"+Ddate+"'")
				.append(" and PNDNFKIND="+nDept);
				mSQL.append(" and GOODSNO='"+goodO+"'");
				csm=mdb.rawQuery(mSQL.toString(), null);
				if(csm.getCount()==1 ){ //唯一性的,可以進行比對
					csm.moveToFirst();
				
					RepDataPan data = new RepDataPan();
					data.iPic=csm.getString(csm.getColumnIndex("PIC"));
					data.iGoods=csm.getString(csm.getColumnIndex("PNDNDD")); 
					data.iName=csm.getString(csm.getColumnIndex("GOODSNO"))+"/"+csm.getString(csm.getColumnIndex("GOODSNAME"));  
					data.iCountry="單價:"+csm.getString(csm.getColumnIndex("UNITPRICE"));
					data.iNumber="補價:"+csm.getString(csm.getColumnIndex("EXPRICE")); //單價
					data.iImpo="應盤"+csm.getString(csm.getColumnIndex("ASTKN"))+"/"+csm.getDouble(csm.getColumnIndex("ASTKM"));  //本存
					data.iMoney="暫盤:"+csm.getString(csm.getColumnIndex("APIN"))+"已盤:/"+csm.getString(csm.getColumnIndex("APANN")); //本盤
					data.iCompany="盤差:"+csm.getString(csm.getColumnIndex("ADEFN"))+"/"+csm.getDouble(csm.getColumnIndex("ADEFM"));//盤差
					data.iFormdate=csm.getString(csm.getColumnIndex("GOODSNO"));  //盤點對象代號
					data.iUnit2=csm.getString(csm.getColumnIndex("DATA"));
					data.iFormno=csm.getString(csm.getColumnIndex("DEPTSNO"));
					mAdapter.mList.add(data);
					mAdapter.notifyDataSetChanged();
					mListView.setSelection(mAdapter.mList.size()-1);
				}
				mdb.close();
				csm.close();
			}
			} else { //2019-04-19 ahow not found
				Toast.makeText(QpandnF.this, aInput+"__貨號輸入不完整!!請重新輸入貨號", Toast.LENGTH_SHORT).show();
			}
    	}
    }
    
    private void getCust(){
    	//關鍵值 總倉AA 可以所有對項 而門市是唯一 
 				Intent intent = new Intent();
 					if (nDept==0){//總倉盤點唯一 一定要在總倉
						intent.putExtra("qcustf_qkind", 20);
						intent.putExtra("qcustf_mode", 2); //查返
						intent.putExtra("qcustf_key", mWho);					
						intent.putExtra("pos_dept","AAP" );
						intent.setClass(QpandnF.this, QCustff.class);
						startActivityForResult(intent, RESULT_QCUSTFF);
    				}else if (nDept==1) {//@@@門市盤點 唯一( 只要在門是做盤點)
						intent.putExtra("qcustf_qkind", 20);
						intent.putExtra("pos_dept","" );
						if (nPart==1){
							intent.putExtra("qcustf_key", mWho);
							intent.putExtra("qcustf_mode", 0);
						}else{
							intent.putExtra("qcustf_key", "");					
							intent.putExtra("qcustf_mode", 0);
						}
						intent.setClass(QpandnF.this, QCustff.class);
						startActivityForResult(intent, RESULT_QCUSTFF);
					} else { //廠商
						intent.setClass(QpandnF.this, AccountList.class);
						intent.putExtra("mode", EMode.GET);
						intent.putExtra("countryid", 0);  //表不分國別
						startActivityForResult(intent, RESULT_QFACT);
					}
    }
    
    //來自於確認mDept盤點對象後探查有否上次盤點記錄
    //確認為 首次盤點 或 有上次盤點(順道取得上存總件數金額)
    //也擋掉 已經存在 盤點對象有現階段正在盤點的事實
    //@@@未來 有可能 主檔已卸除 最後盤點資訊,而需轉往歷史盤點檔去索取 上次盤點資訊
    private void getSuccess(){
    	int Success=0;
			nSuccess=0;
	//of_line==1 直接拜訪SERVER
	    	if (Utilis.haveInternet(QpandnF.this) && of_line!=0){
	    		goCloud(2);	    		
	    	}else{//local read 
					File fileQmtrio = new File(mDBPath);
			      	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
			      	//只讀取 ID=3 PNDNSTATE=2 指定已過帳的盤點且最後一筆   
			      	Cursor csm=mdb.rawQuery("select PNDNADAY,PNDNSTATE,sum(APANN),sum(APANM)  from qpandn where USER='"+mWho+"' and PNDNFKIND="+nDept+" and PNDNSTATE=2 and ID=3 group by PNDNADAY,PNDNSTATE order by PNDNADAY desc LIMIT 1", null);
			      	//讀取 存入帳? 最後盤點日 對於總倉盤點紀錄
			      	if (csm.getCount()>0){
			      		csm.moveToFirst();
		      			cLstkn=csm.getInt(2);tLastStkn=cLstkn;
		      			cLstkm=csm.getInt(3);tLastStkm=cLstkm;
		      			Success=1;  //表示可新增的盤點清冊
			      			
		      			Ldate=csm.getString(0);
		      			isNew=false;
			      	} else { //首次盤點
			      		Ldate="2012-03-14";
		      			cLstkn=0;tLastStkn=cLstkn;
		      			cLstkm=0;tLastStkm=cLstkm;
			      		Success=1;
			      		isNew=true;
			      	}
	      			((Button)findViewById(R.id.btn_lstkn)).setText(""+tLastStkn);	
	      			((Button)findViewById(R.id.btn_lstkm)).setText(""+tLastStkm);
			      	
		  			String day = Utilis.getMonthDate();
		  			day=day.replace("/", "-");
					String[] days = day.split("~");
		    		Ddate = days[1];
		    		DateUtil.addMonth(Ddate, -1);
		  			((Button)findViewById(R.id.btn_lpndn)).setText(Ldate);
		  			((Button)findViewById(R.id.btn_dpndn)).setText(Ddate);      			
			      	
		      		csm.close();
		      		mdb.close();
		      		nSuccess=Success;
		      		
		      		if (Success==0 && isNew==false){
		      			((TextView)findViewById(R.id.pndn_title)).setText(mKind[nDept]+"庫存盤點清冊[失敗]");
		      		}else{
		      			((TextView)findViewById(R.id.pndn_title)).setText(mKind[nDept]+"盤點清冊"+mState[nState]);
	    				reCountBG();
		      		}
		      		nSuccess=Success;
	    	}
    }
    
    private void setCondition(){
    	//btop  首頁
    	//ctop  新增盤表
    	//pditem 盤點清冊
    	//
    	switch (nCondition){
    	case 0:{ 	//一樓
    		//line_input
			((LinearLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.keypad_gray4);
			((ScrollView)findViewById(R.id.layout_cctop)).setVisibility(View.GONE);
			mLayoutRoot.setVisibility(View.GONE);
			((ScrollView)findViewById(R.id.layout_bbtop)).setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
	        ((LinearLayout)findViewById(R.id.layout_bottom)).setVisibility(View.GONE);
	        ((LinearLayout)findViewById(R.id.line_input)).setVisibility(View.GONE);
	    	((TextView)findViewById(R.id.pndn_title)).setText("請選擇盤點對象");
			((Button)findViewById(R.id.btn_cmd)).setVisibility(View.GONE);			
			((Button)findViewById(R.id.btn_pdd)).setVisibility(View.GONE);			
	    	break;
    	}
    	case 2:	//(二樓)盤表清冊 GroupData
    	{
    		((ScrollView)findViewById(R.id.layout_cctop)).setVisibility(View.GONE);
			((ScrollView)findViewById(R.id.layout_bbtop)).setVisibility(View.GONE);
			mLayoutRoot.setVisibility(View.GONE);
	        ((LinearLayout)findViewById(R.id.line_input)).setVisibility(View.GONE);
			((LinearLayout)findViewById(R.id.layout_bottom)).setVisibility(View.VISIBLE);
			((Button)findViewById(R.id.btn_save)).setVisibility(View.VISIBLE);			
	        ((Button)findViewById(R.id.btn_save)).setText("搜尋");
			((Button)findViewById(R.id.btn_reset)).setVisibility(View.VISIBLE);			
			((Button)findViewById(R.id.btn_reset)).setText("維護");
			mListView.setVisibility(View.VISIBLE);
			((Button)findViewById(R.id.btn_cmd)).setVisibility(View.GONE);			
			((Button)findViewById(R.id.btn_pdd)).setVisibility(View.GONE);			
			//PNDNFKIND==nDept0 總倉 1門市 2廠商
			if (nState!=2){
				//輕按
				menu_E=new String [11];menu_E[0]="暫盤中,繼續盤點";
				menu_E[1]="全部的盤點明細";menu_E[2]="盤點且還有盤差的明細";menu_E[3]="盤點而沒有盤差的明細";
				menu_E[4]="已經有盤過的明細";menu_E[5]="還沒有盤過的明細";menu_E[6]="增盤明細(收負帳)";
				menu_E[7]="本期沒有盤差的明細";menu_E[8]="輸出A4盤表表";menu_E[9]="輸出CSV分享";menu_E[10]="返回";
				//長按
				menu_LE=new String [9];menu_LE[0]="刪除盤表(須重新新增盤表)";
//				menu_LE[1]="匯出且移除盤表";menu_LE[2]="盤點表歸零,重新盤點";menu_LE[3]="盤點量同在庫量";
				menu_LE[1]="重新校正上存數據";menu_LE[2]="盤點表歸零,重新盤點";menu_LE[3]="盤點量同在庫量";
				menu_LE[4]="暫盤表歸零";menu_LE[5]="暫盤表入帳";menu_LE[6]="盤好後,盤點過帳";
				menu_LE[7]="直接將盤表直接過帳,不做盤銷!!";menu_LE[8]="返回";
				
		        ((Button)findViewById(R.id.btn_add)).setVisibility(View.VISIBLE);
		        ((Button)findViewById(R.id.btn_add)).setText("新增盤表");
				((Button)findViewById(R.id.btn_savein)).setVisibility(View.VISIBLE);        
				((Button)findViewById(R.id.btn_savein)).setText("以前盤表");        
				((TextView)findViewById(R.id.pndn_title)).setText(mKind[nDept]+"盤點清冊"+mState[nState]);
				if (nDept==0){ //總倉盤點 
					((LinearLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.keypad_gray5);
				}else if(nDept==1){//門市盤點
					((LinearLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.keypad_reds);
				}else if(nDept==2){//廠商盤點
					((LinearLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.keypad_blue2);
				}
			}else{
				//長按
				menu_LE=new String [6];menu_LE[0]="刪除盤表";
				menu_LE[1]="重新校正上存數據";menu_LE[2]="取消過帳,重新盤點";
				menu_LE[3]="專櫃請款單";menu_LE[4]="印製A4盤點清冊";menu_LE[5]="返回";
				((Button)findViewById(R.id.btn_add)).setVisibility(View.GONE);
				((Button)findViewById(R.id.btn_savein)).setText("現在盤表");        
				((TextView)findViewById(R.id.pndn_title)).setText(mKind[nDept]+"盤點清冊"+mState[nState]);
			}
			break;
    	}
    	
    	case 1:	//(二樓) 新增盤表
    	{
			mListView.setVisibility(View.GONE);
			((ScrollView)findViewById(R.id.layout_bbtop)).setVisibility(View.GONE);
    		((ScrollView)findViewById(R.id.layout_cctop)).setVisibility(View.VISIBLE);
			mLayoutRoot.setVisibility(View.GONE);
	        ((LinearLayout)findViewById(R.id.line_input)).setVisibility(View.GONE);
			((LinearLayout)findViewById(R.id.layout_bottom)).setVisibility(View.VISIBLE);
	        ((Button)findViewById(R.id.btn_add)).setVisibility(View.VISIBLE);
	        ((Button)findViewById(R.id.btn_add)).setText("建立盤點清冊");
	        ((Button)findViewById(R.id.btn_save)).setVisibility(View.GONE);
			((Button)findViewById(R.id.btn_reset)).setVisibility(View.GONE);
			((Button)findViewById(R.id.btn_savein)).setVisibility(View.GONE);
			((Button)findViewById(R.id.btn_cmd)).setVisibility(View.GONE);			
			((Button)findViewById(R.id.btn_pdd)).setVisibility(View.GONE);			
			if (nDept==0) //總倉盤點應多顯示 一個 出貨統計 
				((LinearLayout)findViewById(R.id.lay_ad)).setVisibility(View.VISIBLE);
			else
				((LinearLayout)findViewById(R.id.lay_ad)).setVisibility(View.GONE);
			break;
    	}
    	
        case 3:  //三樓 是在某一張盤單下  輕按: 直接顯示TABLE表 
        {
			mListView.setVisibility(View.VISIBLE);
			mLayoutRoot.setVisibility(View.VISIBLE);
			((Button)findViewById(R.id.btn_savein)).setVisibility(View.VISIBLE);
			((Button)findViewById(R.id.btn_savein)).setText("櫃位搜尋");
			if (nState!=2){//現行盤表
		        ((LinearLayout)findViewById(R.id.line_input)).setVisibility(View.VISIBLE);
				((Button)findViewById(R.id.btn_add)).setVisibility(View.VISIBLE);
				((Button)findViewById(R.id.btn_add)).setText("輸出");
				((Button)findViewById(R.id.btn_save)).setVisibility(View.VISIBLE);
				((Button)findViewById(R.id.btn_save)).setText("(暫盤)存入");
				((Button)findViewById(R.id.btn_reset)).setVisibility(View.VISIBLE);
				((Button)findViewById(R.id.btn_reset)).setText("(暫盤)歸零");
				((Button)findViewById(R.id.btn_cmd)).setVisibility(View.VISIBLE);
				((Button)findViewById(R.id.btn_pdd)).setVisibility(View.VISIBLE);
				//長按
				menu_LE=new String [5];
				menu_LE[0]="單款(暫盤)歸零";		menu_LE[1]="單款(盤點)歸零";
				menu_LE[2]="單款(盤準)零誤差";	menu_LE[3]="追蹤";menu_LE[4]="返回";
				if (nDept==0){ //總倉盤點 
				((LinearLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.keypad_gray);
				}else if(nDept==1){//門市盤點
					((LinearLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.keypad_orange);
				}else if(nDept==2){//廠商盤點
					((LinearLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.keypad_blue2);
				}
      			pInput.requestFocus();
			}else{//歷史盤表
		        ((LinearLayout)findViewById(R.id.line_input)).setVisibility(View.GONE);
				((Button)findViewById(R.id.btn_add)).setVisibility(View.GONE);
				((Button)findViewById(R.id.btn_save)).setVisibility(View.GONE);
				((Button)findViewById(R.id.btn_reset)).setVisibility(View.GONE);
				//長按
				menu_LE=new String [5];menu_LE[0]="返回";
			}
			((TextView)findViewById(R.id.pndn_title)).setText(mKind[nDept]+"盤點清冊"+mState[nState]);				
			break;
    	}
    	}
    	if (nCondition!=0)
    		((TextView)findViewById(R.id.pndn_end)).setText(mWhoName+"正在"+mKind[nDept]+nCondition+"樓 進行"+sKind[nState]);
    	else{
    		((TextView)findViewById(R.id.pndn_end)).setText("");
    		mWho="";		mWhoName="";
    	}
    }
    
	private void getGroupData(Context context, String aWho, int xState, String condition, String conditionValue ) {
		//只在二樓盤點頭
		
		if (mAdapter.mList != null) {
			mAdapter.mList.clear();
		}
		//@@@關鍵問題須強化nState的傳遞值 拜訪雲端是由於 之前盤表
    	if (Utilis.haveInternet(QpandnF.this) && of_line!=0 && xState==2){
    		goCloud(5);	    		
    	}else{//local read 
	      	StringBuffer mSQL = new StringBuffer();
			mSQL.append("select USER,USERNAME,PNDNADAY,PNDNBDAY,")
			.append("ASTKN,ASTKM,ASTN,ASTM,APANN,APANM,ADEFN,ADEFM,EXPRICE,APIN,DEPTSNO")
			.append(" from qpandn where  ID=3 and PNDNFKIND="+nDept+" and PNDNSTATE=" +xState); //只針對 盤表頭
			if (xState!=2){//未過帳盤表,永遠在LOCAL端 ID=3
				if (aWho.length()>0 && nState==0){//表示為單一對象
					mSQL.append(" and USER='"+mWho+"'");
				}
				mSQL.append(" order by USER,USERNAME,PNDNADAY,PNDNBDAY");
			}else{//已過帳的盤表
				mSQL.append(" and USER in (select distinct USER from `qpandn` group by USER having (PNDNADAY=MAX(PNDNADAY)))");
				mSQL.append(" order by USER,USERNAME,PNDNADAY,PNDNBDAY");
			}
    		File fileQmtrio = new File(mDBPath);
          	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
    		Cursor csm;
    		
    		SQLiteDatabase db = Utilis.getDB(QpandnF.this);
    		
    		csm=mdb.rawQuery(mSQL.toString(), null);

			Toast.makeText(QpandnF.this, mWho+"_State_"+xState+"_"+csm.getCount()+"盤點表_nDept"+nDept, Toast.LENGTH_SHORT).show();

			if(csm.getCount()>0){ //
				csm.moveToFirst();
				for(int xx=0;xx<csm.getCount();xx++){
					RepDataPan data = new RepDataPan();
					Cursor cs;
					data.iPic=SD_PATH+File.separator+"cwbuyer/para/04.jpg";
						if (nDept==2){
							cs=db.rawQuery("select PIC from qfact where FACTNO='"+csm.getString(0)+"'",null);
						} else {
							cs=db.rawQuery("select PIC from qcust where CUSTNO='"+csm.getString(0)+"'",null);
						}
						if (cs.getCount()>0){
							cs.moveToFirst();
							data.iPic=cs.getString(0);
						}
					cs.close();
					data.iGoods=csm.getString(0)+"/"+csm.getString(1);  //代號_名稱
					data.iName=csm.getString(3)+"~"+csm.getString(2); //上盤日期~本盤日期
					data.iNumber="補價:"+csm.getDouble(12); //補價
					data.iCountry="本銷:"+csm.getString(6)+"/"+csm.getDouble(7);  //本銷
					data.iImpo="應盤"+csm.getString(4)+"/"+csm.getDouble(5);  //本存

					if (csm.getInt(13)!=0)
						data.iMoney="暫盤:"+csm.getString(13)+"/已盤:"+csm.getString(8);  //本盤
					else
						data.iMoney="已盤:"+csm.getString(8)+"/"+csm.getDouble(9);  //本盤

					data.iCompany="盤差:"+csm.getString(10)+"/"+csm.getDouble(11);  //盤差
					data.iFormdate=csm.getString(0);  //盤點對象代號
					data.iFormno=csm.getString(14);

					mAdapter.mList.add(data);

					csm.moveToNext();
				}
			}
			db.close();
			mdb.close();
			csm.close();
    	}
	}    
    

private void reportPanDetail(Context context, String aWho,int mode) {
	//一定在 LOCAL端
	//單頭的資訊 代號門市 盤點日期 上期存貨件金 本期進退件金 本期已銷件金 本期應盤進金
	//商品明細 需解讀 DATA 只要是有盤差的 都要顯示印出
	//排列時 每個A4 排完左列 再 排右列 滿後 再另一頁
	//規格 [貨品編號][存][盤存][單價][%](100%不印)
	//記憶體沒有當下的ID=3 總清單 所以還要再 拜訪一次
	//再拜訪一次 ID!=3 清算
	
	File fileQmtrio = new File(mDBPath);
  	StringBuffer mSQL = new StringBuffer();
	int totItems=0;
	String qkindStr="";
	String BufTitle="";
	Cursor csm;
	mSQL.append("select USERNAME,LASTSTKN,LASTSTKM,AINN,AINM,ASTKN,ASTKM,ASTN,ASTM,ADEFN,ADEFM,APANN,APANM from qpandn where USER='"+mWho+"' and PNDNADAY='"+Ddate+"'")
	.append(" and PNDNFKIND="+nDept+" and ID=3");
	String SQLMAIN=mSQL.toString();
	
	mSQL.delete(0, mSQL.toString().length());
	mSQL.append("select GOODSNO,GOODSNAME,DATA,UNITPRICE,DISCOUNT from qpandn where USER='"+mWho+"' and PNDNADAY='"+Ddate+"'")
	.append(" and PNDNFKIND="+nDept+ " and ID<>3 order by GOODSNO");
	String SQLDETAIL=mSQL.toString();
		
	if (Utilis.haveInternet(QpandnF.this) && of_line!=0 && mode==2){
/*
$mWho=@$_REQUEST['USER'];  		//盤點對象
$DDATE=@$_REQUEST['PNDNADAY'];	//本盤日期
$nDept=@$_REQUEST['PNDNFKIND']; //盤表的種類
$SQLMAIN=@$_REQUEST['SQLMAIN']; //總盤數據
$SQLDETAIL=@$_REQUEST['SQLDETAIL']; //盤表明細
 */
	String theFile="/wamp/www/"+importStr[1]+"/IMPORT/20123/AA0_"+mWho+"_pandnfreport.csv";
	SQLDETAIL="SELECT `GOODSNO`,`GOODSNAME`,`DATA`,`UNITPRICE`,`DISCOUNT` "+  
	" into outfile '"+theFile+"' fields terminated by ';' lines terminated by '\r\n'"+
	" FROM `qpandn` where `USER`='"+mWho+"' and `PNDNADAY`='"+Ddate+"'  and `PNDNFKIND`="+nDept+ " and `ID`<>3 order by `GOODSNO`";
	StringBuffer bfstr = new StringBuffer();
	StringBuffer bfstrF = new StringBuffer();
	
	bfstr.append(importStr[1]).append("@#@");	//do it
	bfstrF.append("UID").append("@#@");
	bfstr.append(mWho).append("@#@");  //do it 
	bfstrF.append("USER").append("@#@"); 
	bfstr.append(Ddate).append("@#@"); 
	bfstrF.append("PNDNADAY").append("@#@"); 
	bfstr.append(nDept).append("@#@");	//do it 
	bfstrF.append("PNDNFKIND").append("@#@"); 
	bfstr.append(SQLMAIN).append("@#@"); 
	bfstrF.append("SQLMAIN").append("@#@"); 
	bfstr.append(SQLDETAIL); 
	bfstrF.append("SQLDETAIL"); 
	final String []fields=bfstr.toString().split("@#@");
	final String []fieldFs=bfstrF.toString().split("@#@");
	  
	  new Thread()
	  { 
	    public void run()
	    { 
	      try
	      { 
				HttpPost httpRequest = new HttpPost(uriAPI2);
				Log.i("DOWNLOAD_2", "取得上存的數據"+uriAPI2);
				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());
						mHandlerQpandnfReport.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
					}
				} catch (Exception e)
				{
					e.printStackTrace();
				}
	      }
	      catch (Exception e)
	      {
	        e.printStackTrace();
	      }
	      finally
	      {
	        // 卸載所建立的myDialog物件。
	  		//myDialog.dismiss();		
	      }
	    }
	  }.start();
	
	
	}else{//單機	
	  	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
		csm=mdb.rawQuery(SQLMAIN, null);
		if (csm.getCount()>0){
			String sepa=";SSSS\r\n";
			sPrintB = new StringBuffer();
			csm.moveToFirst();
			String aWhoName=csm.getString(csm.getColumnIndex("USERNAME"));
			int aLastStkN=csm.getInt(csm.getColumnIndex("LASTSTKN"));
			Double aLastStkM=csm.getDouble(csm.getColumnIndex("LASTSTKM"));
			int aAinN=csm.getInt(csm.getColumnIndex("AINN"));
			Double aAinM=csm.getDouble(csm.getColumnIndex("AINM"));
			int aAstkN=csm.getInt(csm.getColumnIndex("ASTKN"));
			Double aAstkM=csm.getDouble(csm.getColumnIndex("ASTKM"));
			int aAstN=csm.getInt(csm.getColumnIndex("ASTN"));
			Double aAstM=csm.getDouble(csm.getColumnIndex("ASTM"));
			int aAdefN=csm.getInt(csm.getColumnIndex("ADEFN"))*-1;
			Double aAdefM=csm.getDouble(csm.getColumnIndex("ADEFM"))*-1;
			int aApanN=csm.getInt(csm.getColumnIndex("APANN"));
			Double aApanM=csm.getDouble(csm.getColumnIndex("APANM"));
			//1,2,3,4,5,6,7應盤件數,8應盤金額
			qkindStr=mWho+"/"+aWhoName+"  自上期盤點:"+Ldate+"後 到"+Ddate+" 盤點清冊 ";
			BufTitle=aLastStkN+";"+aLastStkM+";"+aAinN+";"+aAinM+";"+aAstN+";"+aAstM+";"+aAstkN+";"+aAstkM;
			
			Cursor cs=mdb.rawQuery(SQLDETAIL, null);
			if (cs.getCount()>0){
				if (mode==0){//輸出報表
					while (cs.moveToNext()){
					String [] aData=cs.getString(cs.getColumnIndex("DATA")).split("，");
					//取得每個顏色尺寸的
						for (int ii=0;ii<aData.length;ii++){
						  if (aData[ii].length()>10){	
							String [] dataD=aData[ii].split(",");
							if (Utilis.toInt(dataD[6])!=0){
								//有盤點資料
								String Goodss=cs.getString(cs.getColumnIndex("GOODSNO"))+"-"+dataD[0]+"-"+dataD[2];
								totItems+=1;
								sPrintB.append("["+dataD[1]+"] "+Goodss+";").append(dataD[6]+";")
								.append(cs.getString(cs.getColumnIndex("UNITPRICE"))+";");
								//存放[貨品明細編號][應盤件數][單價][%]  製作報表的功能
								if (Utilis.toInt(cs.getString(cs.getColumnIndex("DISCOUNT")))==100)
									sPrintB.append(sepa);
								else	
									sPrintB.append(""+Utilis.toInt(cs.getString(cs.getColumnIndex("DISCOUNT")))+sepa);
							}
						  }	
						}
					}
				}else if (mode==1 || mode==2){
					sPrintB.append(mWho+"/"+aWhoName+",自上期盤點:"+Ldate+",後,,,,,到"+Ddate+",為止的盤點清冊,\r\n");					
					sPrintB.append("[顏色] 貨品編號,貨品名稱,應存,盤存,單價,折數,,[顏色] 貨品編號,貨品名稱,應存,盤存,單價,折數,\r\n");
					while (cs.moveToNext()){
					String [] aData=cs.getString(cs.getColumnIndex("DATA")).split("，");
					//取得每個顏色尺寸的
						for (int ii=0;ii<aData.length;ii++){
						  if (aData[ii].length()>10){	
							String [] dataD=aData[ii].split(",");
							if (Utilis.toInt(dataD[6])!=0){
								//有盤點資料
								String Goodss=cs.getString(cs.getColumnIndex("GOODSNO"))+"-"+dataD[0]+"-"+dataD[2];
								totItems+=1;
								sPrintB.append("["+dataD[1]+"] "+Goodss+",").append(cs.getString(cs.getColumnIndex("GOODSNAME"))+",").append(dataD[6]+",");
								if (mode==2) sPrintB.append(dataD[4]+","); else sPrintB.append(","); 
								sPrintB.append(cs.getString(cs.getColumnIndex("UNITPRICE"))+",");
								//存放[貨品明細編號][應盤件數][單價][%]  製作報表的功能
								sPrintB.append(""+Utilis.toInt(cs.getString(cs.getColumnIndex("DISCOUNT")))+",,");
								if ((totItems) %2==0)sPrintB.append("\r\n"); 
							}
						  }	
						}
					}
					sPrintB.append("\r\n");
					sPrintB.append("\r\n");
					sPrintB.append("\r\n");
					//數據表
					sPrintB.append("上期盤存量,"+aLastStkN+",,,,,,上期盤存小計,"+aLastStkM+",\r\n");
					sPrintB.append("本期進退量,"+aAinN+",,,,,,本期進退小計,"+aAinM+",\r\n");
					sPrintB.append("本期已銷量,"+aAstN+",,,,,,本期已銷小計,"+aAstM+",\r\n");
					sPrintB.append("本期應盤量,"+aAstkN+",,,,,,本期應盤小計,"+aAstkM+",\r\n");
					sPrintB.append("本期盤差量,"+aAdefN+",,,,,,本期盤差小計,"+aAdefM+",\r\n");
					sPrintB.append("本期盤存量,"+aApanN+",,,,,,本期盤存小計,"+aApanM+",\r\n");
					sPrintB.append("\r\n");
					sPrintB.append("本期結算量,"+(aAstN+aAdefN)+",,,,,,本期盤差小計,"+(aAstM+aAdefM)+",\r\n");
					
				}
			}
			cs.close();
		}
		csm.close();
		mdb.close();
	}
		if (totItems>0){ //表示有資料
			if (mode==0){
				Intent intent = new Intent();
				intent.putExtra("SERCH",compStr[0]);
				intent.putExtra("QKIND",qkindStr);
				intent.putExtra("MODE",13);
				intent.putExtra("DEPTNO",compStr[0]);
				intent.putExtra("BUFSTR",sPrintB.toString());
				intent.putExtra("BUFTITLE",BufTitle);
				intent.putExtra("STARTDAY",Ldate);
				intent.putExtra("ENDDAY",Ddate);
	
				intent.setClass(QpandnF.this, MkqrSt.class);
				startActivity(intent);
			}else{
        		try {
                    Writer out = new BufferedWriter(new OutputStreamWriter(
                    	    new FileOutputStream(myFilePath), "UTF-8"));
                    	try {
                    	    out.write(sPrintB.toString());
                    	} finally {
                    	    out.close();
                    	}                    
        		} catch (Exception e) {

        		}
        		
    			//進一步輸出,多媒體選擇
    	    	Intent send = new Intent(Intent.ACTION_SEND);
    	    	send.setType("image/jpeg");
    		    String uriText;
    		    Uri U=Uri.parse("file://"+myFilePath);  //重要的範例
    		    uriText = "https://www.google.com/cloudprint/addpublicprinter.html?printerid=bb160853-6274-0f65-eb1f-34ae2c9ed6e1&key=19901109";
    		    send.putExtra(Intent.ACTION_SENDTO,uriText);
    		    send.putExtra(Intent.EXTRA_STREAM,U);
    		    startActivity(Intent.createChooser(send, uriText));

			}
		}
	}
	
	private void getDetailData(Context context, String aWho) {
		//
		if (mAdapter.mList != null) {
			mAdapter.mList.clear();
		}
//如果有網路且已過帳 且唯讀時 直接拜訪伺服器
    	if (Utilis.haveInternet(QpandnF.this) && of_line!=0 && nState==2){
    		goCloud(6);	    		
    	}else{//local read___Qpandndetail.csv 
			File fileQmtrio = new File(mDBPath);
	      	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
	      	StringBuffer mSQL = new StringBuffer();
			Cursor csm;
			
			//ID>10<100000表示總盤表 100000以上為暫盤表
			//ID>50000 <80000表示為盤零表
			//ID>80000<100000表示為補增資料 可以列式條件
			//是否納入 已盤清冊 未盤清冊 盤差清冊 等多元查詢
			//nKind== 0.暫盤表 1總盤表 2盤差表 3盤準表 4已盤表 5未盤表 6.增盤表(原盤表不存在的商品ID>80000 and ID<100000)
	
				mSQL.append("select * from qpandn where USER='"+aWho+"' and PNDNADAY='"+Ddate+"'")
				.append(" and PNDNFKIND="+nDept+" and PNDNSTATE=" +nState);
				switch (nKind){
				case 0: //暫盤表
					mSQL.append(" and  ID>100000 and ID<200000 and APIN<>0");
					break;
				case 1:  //總盤表(包含:主盤,增盤,暫盤)
					//mSQL.append(" and  ((ID>10 and ID<60000)  or (ID>80000 and ID<100000)  or (ID>100000 and ID<150000)  or (ID>180000 and ID<200000)) ");
					mSQL.append(" and  ID>10");
					break;
				case 2:  //盤差表
					mSQL.append(" and  ID>10 and ID<200000");
					mSQL.append(" and  ADEFN<>0");
					//mSQL.append(" and  ADEFN<>0 and PNDNDD>''");
					break;
				case 3:  //盤準表
					mSQL.append(" and  ID>10 and ID<200000 ");
					mSQL.append(" and  ADEFN=0 and ((APANN+APIN)=ASTKN)");
					//mSQL.append(" and  ADEFN=0 and PNDNDD>'' and ((APANN+APIN)=ASTKN)");
					break;
				case 4:  //已盤表
					mSQL.append(" and  ID>10 and ID<200000");
					mSQL.append(" and  APANN<>0 and PNDNDD>''");
					break;
				case 5:  //未盤表
					mSQL.append(" and  ID>10 and ID<200000");
					mSQL.append(" and  APANN=0 and APIN=0 and PNDNDD=''");
					break;
				case 6:  //增盤表
					mSQL.append(" and  ((ID>80000 and ID<100000) or (ID>180000 and ID<200000)) ");
					break;
				case 7:  //盤零表
					mSQL.append(" and  ((ID>50000 and ID<80000) or (ID>150000 and ID<180000)) ");
					break;
				}
				//如果有額外的條件時
				if (aExtWord.length()>0)	mSQL.append(aExtWord);
				mSQL.append(" order by GOODSNO");
				csm=mdb.rawQuery(mSQL.toString(), null);
				
				if(csm.getCount()>0){ //
					csm.moveToFirst();
					for(int xx=0;xx<csm.getCount();xx++){
						RepDataPan data = new RepDataPan();
						data.iPic=csm.getString(csm.getColumnIndex("PIC"));
						data.iGoods=csm.getString(csm.getColumnIndex("PNDNDD"));  //櫃位 
						data.iName=csm.getString(csm.getColumnIndex("GOODSNO"))+"/"+csm.getString(csm.getColumnIndex("GOODSNAME"));  
						data.iCountry="單價:"+csm.getString(csm.getColumnIndex("UNITPRICE"));
						data.iNumber="補價:"+csm.getString(csm.getColumnIndex("EXPRICE")); //單價
						data.iImpo="應盤"+csm.getString(csm.getColumnIndex("ASTKN"))+"/"+csm.getString(csm.getColumnIndex("ASTKM"));  //本存
						data.iUnit2=csm.getString(csm.getColumnIndex("DATA"));
						if (csm.getInt(csm.getColumnIndex("ID"))>100000)
							data.iMoney="暫盤:"+csm.getInt(csm.getColumnIndex("APIN"))+"/已盤:"+csm.getString(csm.getColumnIndex("APANN"))+"/"+csm.getString(csm.getColumnIndex("APANM")); //本盤
						else
							data.iMoney="已盤:"+csm.getString(csm.getColumnIndex("APANN"))+"/"+csm.getDouble(csm.getColumnIndex("APANM")); //本盤
						data.iCompany="盤差:"+csm.getString(csm.getColumnIndex("ADEFN"))+"/"+csm.getDouble(csm.getColumnIndex("ADEFM"));//盤差
						data.iFormdate=csm.getString(csm.getColumnIndex("GOODSNO"));  //盤點對象代號
						data.iFormno=csm.getString(csm.getColumnIndex("DEPTSNO"));

						mAdapter.mList.add(data);
	
						csm.moveToNext();
					}
				}
				mdb.close();
				csm.close();
    	}
	}    
    
    private void reCountBG(){//這裡是 新增盤表的初步本進本銷
    	//@@@ 也要進一步拜訪 CLOUD
    	if (Utilis.haveInternet(QpandnF.this) && of_line!=0){
    		goCloud(0);	    		
    	}else{//local read 
    	
			int cAin=0;
			int cAim=0;
			int cAstn=0;
			int cAstm=0;
			int cAadn=0;
			int cAadm=0;
			int cAstkn=0;
			int cAstkm=0;
			int nDisc=nDiscount;  //可能為預設 或 歷史價
			
			nDiscount=Utilis.toInt(((Button)findViewById(R.id.btn_disc)).getText().toString());
			StringBuffer mySqlBuf = new StringBuffer();
			mySqlBuf.append("select sum(UNIT10),sum(UNIT20),sum(UNIT30),sum(UNIT40),max(P1),min(P2),min(P3),min(P4),min(P5),UNITPRICE,DISCOUNT from qitems ");
			mySqlBuf.append(" where FORMDATE>'"+Ldate+"' and FORMDATE<='"+Ddate+"' and ISCONFIRM='Y'");
			
			String SQLADD=mySqlBuf.toString();
			SQLiteDatabase db = Utilis.getDB(QpandnF.this);
			Cursor cs;
			if (nDept==0){  //總倉盤點
				//這裡不會讀取 KIND 21(門市轉貨單) 31 門市銷貨單 41員工自購 
					mySqlBuf.append(" and DEPTNO='"+mWho+"' group by GOODSNO");
					
				cs=db.rawQuery(mySqlBuf.toString(),null);
				

				if (cs.getCount()>0){
					cs.moveToFirst();
					for(int x=0;x<cs.getCount();x++){
						//if(nTradetype==6) nDisc=cs.getInt(10); 
						cAin=cAin+cs.getInt(0);
						cAim=cAim+cs.getInt(0)*cs.getInt((3+nTradetype))*nDisc/100;
						cAadn=cAadn+cs.getInt(1);
						cAadm=cAadm+cs.getInt(1)*cs.getInt((3+nTradetype))*nDisc/100;
						cAstn=cAstn+cs.getInt(2);
						cAstm=cAstm+cs.getInt(2)*cs.getInt((3+nTradetype))*nDisc/100;
						cAstkn=cAstkn+(cs.getInt(0)-(cs.getInt(1)+cs.getInt(2)+cs.getInt(3)));
						cAstkm=cAstkm+(cs.getInt(0)-(cs.getInt(1)+cs.getInt(2)+cs.getInt(3)))*cs.getInt((3+nTradetype))*nDisc/100;
						cs.moveToNext();
					}
				}
			}else if (nDept==1){//門市盤點本進銷存 @@@為何不用(DEPTNO='"+mWho or USER=mWho)
				//if(nTradetype==6)//歷史價
					//mySqlBuf.append(" and DEPTNO='"+mWho+"' group by GOODSNO,UNITPRICE,DISCOUNT");
				//else
					mySqlBuf.append(" and DEPTNO='"+mWho+"' group by GOODSNO");
				
				cs=db.rawQuery(mySqlBuf.toString(),null);
				if (cs.getCount()>0){
					cs.moveToFirst();
					for(int x=0;x<cs.getCount();x++){
						//if(nTradetype==6) nDisc=cs.getInt(10); 
						cAin=cAin-cs.getInt(1);
						cAim=cAim-(cs.getInt(1)*cs.getInt((3+nTradetype))*nDisc/100);
						cAstn=cAstn+cs.getInt(2)+cs.getInt(3);
						cAstm=cAstm+((cs.getInt(2)+cs.getInt(3))*cs.getInt((3+nTradetype))*nDisc/100);
						cAstkn=cAstkn-(cs.getInt(1)+(cs.getInt(2)+cs.getInt(3)));
						cAstkm=cAstkm-((cs.getInt(1)+(cs.getInt(2)+cs.getInt(3)))*cs.getInt((3+nTradetype))*nDisc/100);
						cs.moveToNext();
					}
				}
					//目的只找出門市到貨量
				mySqlBuf.delete(0, mySqlBuf.toString().length());
				mySqlBuf.append("select sum(UNIT20),max(P1),min(P2),min(P3),min(P4),min(P5),UNITPRICE,DISCOUNT from qitems ");
				mySqlBuf.append(" where FORMDATE>'"+Ldate+"' and FORMDATE<='"+Ddate+"' and ISCONFIRM='Y'");
				
				
				mySqlBuf.append(" and USER='"+mWho+"' and QKIND like '2%'");
				//if(nTradetype==6)//歷史價
					//mySqlBuf.append(" group by GOODSNO,UNITPRICE,DISCOUNT");
				//else
					mySqlBuf.append(" group by GOODSNO");
				
				cs=db.rawQuery(mySqlBuf.toString(),null);
				if (cs.getCount()>0){
					cs.moveToFirst();
					for(int x=0;x<cs.getCount();x++){
						//if(nTradetype==6) nDisc=cs.getInt(7); 
						cAin=cAin+cs.getInt(0);
						cAim=cAim+cs.getInt(0)*cs.getInt(nTradetype)*nDisc/100;
						cAstkn=cAstkn+cs.getInt(0);
						cAstkm=cAstkm+cs.getInt(0)*cs.getInt(nTradetype)*nDisc/100;
						cs.moveToNext();
					}
				}
			}else{//廠商進銷存
				//if(nTradetype==6)//歷史價
					//mySqlBuf.append(" and SUPPLY='"+mWho+"'  group by GOODSNO,UNITPRICE,DISCOUNT");
				//else
					mySqlBuf.append(" and SUPPLY='"+mWho+"'  group by GOODSNO");
				
				cs=db.rawQuery(mySqlBuf.toString(),null);
				if (cs.getCount()>0){
					cs.moveToFirst();
					for(int x=0;x<cs.getCount();x++){
						//if(nTradetype==6) nDisc=cs.getInt(10); 
						cAin=cAin+cs.getInt(0);
						cAim=cAim+cs.getInt(0)*cs.getInt(3+nTradetype)*nDisc/100;
						cAstn=cAstn+cs.getInt(2)+cs.getInt(3);
						cAstm=cAstm+(cs.getInt(2)+cs.getInt(3))*cs.getInt(3+nTradetype)*nDisc/100;
						cAstkn=cAstkn+(cs.getInt(0)-(cs.getInt(2)+cs.getInt(3)));
						cAstkm=cAstkm+(cs.getInt(0)-(cs.getInt(2)+cs.getInt(3)))*cs.getInt(3+nTradetype)*nDisc/100;
						cs.moveToNext();
					}
				}
			}
			
			mBTain.setText(""+cAin);
			mBTaim.setText(""+cAim);
			mBTastn.setText(""+cAstn);
			mBTastm.setText(""+cAstm);
			mBTastkn.setText(""+(cLstkn+cAstkn));
			mBTastkm.setText(""+(cLstkm+cAstkm));
	
			mBTaadn.setText(""+cAadn);
			mBTaadm.setText(""+cAadm);
			
			db.close();
			cs.close();
    	}    	
    }
    
	class MainClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			Utilis.runVibrate(QpandnF.this);
			int id = v.getId();
			switch (id) {
				case R.id.btn_add:  //(二)新增盤表 (三)繼續盤點
				{
    				Toast.makeText(QpandnF.this, "現在目前在第"+nCondition+" 樓!!", Toast.LENGTH_SHORT).show();
					int newone=0;
					if (nCondition==2 ){  //(二樓)新增盤表  主盤表清單
						if (nState!=2){ //現行盤點
						//不可執行新增的原因,是總倉現行盤表有資料時,不可新增
							if (nDept==0){//總倉盤點
								if (mAdapter.mList.size()<=0){newone=1; }
								else{
		            				Toast.makeText(QpandnF.this, "總倉盤表已存在,不可以新增盤表!!", Toast.LENGTH_SHORT).show();
								} ;
							}else{ //廠商 門市盤點 可以多門市 但不可重複 現行盤表
								newone=1;
							}
						}
						if (newone!=0){
							nCondition=1;setCondition();  //新增盤表的布置
					        getCust();
						}else {
							nCondition=2;setCondition(); 
						}
					}else if (nCondition==1 ){  //建立盤點清冊
						//@@@應先取得所有實際上存
						if (nSuccess>0 && nCompares<0){  //一切符合建立盤表的條件
							
						      //myDialog = ProgressDialog.show(QpandnF.this,"建立盤表清冊中.....","請稍候.............",true);//		setAutoRotationMode();
							      
				      			//tLastStkn=0;		      	tLastStkm=0;
		        				Toast.makeText(QpandnF.this, "開始建立盤點清冊中!! 請稍後!!", Toast.LENGTH_SHORT).show();
		        				//of_line
	        				if (Utilis.haveInternet(QpandnF.this) && of_line!=0){
		        		    		goCloud(3);	    		
	        				}else{//local read 
				      			String sepa=",";
				      			String sepaE="，";
	        				
								File fileQmtrio = new File(mDBPath);
						      	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
								StringBuffer mySqlBuf = new StringBuffer();
							      	
								if (isNew==false){ //若存在上次盤點清冊,且PNDNSTATE=2已完成盤點入帳 須先重置
							      	Cursor csm=mdb.rawQuery("select *  from qpandn where ID>10 and USER='"+mWho+"' and PNDNFKIND="+nDept+" and PNDNSTATE=2 and PNDNADAY='"+Ldate+"' and APANN<>0", null);
								      	nID=10;
								      	//這樣的條件會有同款庫存正負相抵為0時,就不再列出上存的疑點????
										//先將上次盤點清冊的(本盤)>0者,取出並作為本次盤點清冊的(上存)
										//不只主貨號的表檔,也要將明細的各筆(為零者,不再出列)
							      	if (csm.getCount()>0){
							      		csm.moveToFirst();
								      	mdb.beginTransaction();
								      	try{	
								      		for (int i=0;i<csm.getCount();i++){
								      			
												ContentValues valueI = new ContentValues();
													nID+=1;
													String buf=csm.getString(csm.getColumnIndex("DATA"));
				      								String [] fieldA=buf.split(sepaE); //各色尺寸
				      								buf="";
				      								
					      							for (int ij=0;ij<fieldA.length;ij++){//
					      								String [] fieldB=fieldA[ij].split(sepa); //各欄位
					      								fieldB[10]=fieldB[4]; //上存=本盤
					      								fieldB[6]=fieldB[4]; //本存
					      								fieldB[5]=""+(Utilis.toInt(fieldB[4])*-1);//即時放入盤差
					      								StringBuffer nBufB=new StringBuffer();
					      								for (int k=0;k<10;k++){
					      									if (k>2 && k!=5 && k!=6 ) fieldB[k]="0";
					      									nBufB.append(fieldB[k]+sepa);
					      								}
						      								nBufB.append(fieldB[10]);
						      								
						      								fieldA[ij]=nBufB.toString();
						      							buf=buf+fieldA[ij]+sepaE;	
				      								}
													valueI.put("PNDNFKIND",csm.getInt(csm.getColumnIndex("PNDNFKIND"))) ;
													valueI.put("PNDNPKIND",csm.getInt(csm.getColumnIndex("PNDNPKIND"))) ;
													valueI.put("PNDNCKIND",csm.getInt(csm.getColumnIndex("PNDNCKIND"))) ;
													valueI.put("PNDNSTATE",0) ;	//新的盤表
													valueI.put("ID",nID) ;
													valueI.put("USER",csm.getString(csm.getColumnIndex("USER"))) ;
													valueI.put("USERNAME",csm.getString(csm.getColumnIndex("USERNAME"))) ;
													valueI.put("PNDNBDAY",csm.getString(csm.getColumnIndex("PNDNADAY"))) ;
													valueI.put("PNDNADAY",Ddate) ;
													valueI.put("GOODSNO",csm.getString(csm.getColumnIndex("GOODSNO"))) ;
													valueI.put("GOODSNAME",csm.getString(csm.getColumnIndex("GOODSNAME"))) ;
													valueI.put("PIC",csm.getString(csm.getColumnIndex("PIC"))) ;
													valueI.put("UNITPRICE",csm.getInt(csm.getColumnIndex("UNITPRICE"))) ;
													valueI.put("DISCOUNT",csm.getDouble(csm.getColumnIndex("DISCOUNT"))) ;
													valueI.put("ACOST",csm.getDouble(csm.getColumnIndex("ACOST"))) ;
													valueI.put("EXPRICE",csm.getDouble(csm.getColumnIndex("EXPRICE"))) ;
													valueI.put("DATA",buf) ;
													valueI.put("DATA0","") ;
													valueI.put("PNDNDD","") ;
													valueI.put("DEPTSNO","FORMNO") ;
													valueI.put("PARTSNO","") ;
													valueI.put("LASTSTKN",csm.getInt(csm.getColumnIndex("APANN"))) ;
													valueI.put("LASTSTKM",csm.getDouble(csm.getColumnIndex("APANM"))) ;
													valueI.put("AINN",0) ;
													valueI.put("AINM",0) ;
													valueI.put("ASTN",0) ;
													valueI.put("ASTM",0) ;
													valueI.put("ASTKN",csm.getInt(csm.getColumnIndex("APANN")));
													
													//if(nDept!=1)  //正常為 上存金額
														valueI.put("ASTKM",csm.getDouble(csm.getColumnIndex("APANM")));
													//else  //留給本退用
													//	valueI.put("ASTKM",0);
													
													valueI.put("APANN",0) ;
													valueI.put("APANM",0) ;
													valueI.put("ADEFN",""+(csm.getInt(csm.getColumnIndex("APANN"))*-1)) ;
													valueI.put("ADEFM",""+(csm.getDouble(csm.getColumnIndex("APANM"))*-1)) ;
													valueI.put("CDT","") ;
													valueI.put("APIN",0) ;
													valueI.put("SDT","") ;
													valueI.put("BANKNAME",bankn) ;
													valueI.put("TR","Y0") ;
													mdb.insert("qpandn", null, valueI);
												csm.moveToNext();
									      	}  
								      		//將上盤表的盤點量轉存入本盤表(上存)
											mdb.setTransactionSuccessful();
								      	} finally {
								      		mdb.endTransaction();
								      	}
						      		}
							      	csm.close();
								}else nID=10;
								
								mdb.close();
					      		startIniDb(QpandnF.this);
					      		//startDB();
							}
						}						
					}else if (nCondition==3 ){  //輸出
/*
以銷貨單的商品列印模式
  //menu_E[nKind] 可以取得盤表的不同範圍名稱
						if (mAdapter.getCount()>0){ 
							for (int x=0; x<mAdapter.getCount();x++){
								datas = (RepData) mAdapter.getItem(x);
								String XX=datas.iCompany;
								
	
							}
								
						}
*/
					}
					
					break;
				}
				case R.id.btn_save:  //儲存 將盤點中的暫盤資料確實存入盤點清冊
				{
				if (nCondition==3){//ID>100000 視為暫盤 DATA 每一個色尺寸 都要分解 重算 打包 並算出TOT 維護
					zeroPin("",12);
				} else if (nCondition==2){//搜尋_已過帳盤表
					//Local端 直接拜訪PDB SERVER_PHP
					//MODE='5'
					if (nState==2){
			    		nCondition=2;	setCondition();
							getGroupData(QpandnF.this, mWho, nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
							mAdapter.notifyDataSetChanged();        
					}
				}
				
					break;
				}
				case R.id.btn_savein: //
				{
					//2樓_現在盤表/以前盤表	//3樓_櫃位搜尋
					if (nCondition==3 ){ 
						//拉出對話框 先整理出所有 櫃位清單,任選後 在搜尋之
					  	StringBuffer mLst = new StringBuffer();
					  	mLayoutRoot.removeAllViews();						
						File fileQmtrio = new File(mDBPath);
					  	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
					  	StringBuffer mSQL = new StringBuffer();
						Cursor csm;
						mSQL.append("select PNDNDD,sum(ASTKN),sum(APANN),sum(APIN),sum(ADEFN) from qpandn where USER='"+mWho+"' and PNDNADAY='"+Ddate+"'")
						.append(" and PNDNFKIND="+nDept +" and ID>10 group by PNDNDD ");
							csm=mdb.rawQuery(mSQL.toString(), null);
							if(csm.getCount()>0 ){ //唯一性的,可以進行比對
								csm.moveToFirst();
								for (int ii=0;ii<csm.getCount();ii++){
									String qPadndd=csm.getString(0)+"____________";
									String qStkn=csm.getString(1)+"______";
									String qPann=csm.getString(2)+"______";
									String qPin=csm.getString(3)+"______";
									String qDefn=csm.getString(4)+"______";
								mLst.append(qPadndd.substring(0, 12)+"   應盤:"+qStkn.substring(0,5)+"\r\n   已盤:"+qPann.substring(0,5)+" 暫盤:"+qPin.substring(0,5)+" 盤差:"+qDefn.substring(0,5)+"@@");
								csm.moveToNext();
								}
								Pndnddlist=mLst.toString().split("@@");
								String msgTitle="請選擇要顯示以下哪一個櫃位的盤點清冊";
								//資料格式 門市編號(批號)-實際檔路徑-12未匯入/已完成
								//所以先讀取download目錄,合法的一律rename to 目前目錄,再回到目前的路徑統一判斷
								if(Pndnddlist != null && Pndnddlist.length > 0){  //當找到檔案數量後
									AlertDialog.Builder sortDlg = new AlertDialog.Builder(QpandnF.this);
							        sortDlg.setTitle(msgTitle)
							        .setSingleChoiceItems(Pndnddlist, 0, new DialogInterface.OnClickListener() {
							            public void onClick(DialogInterface dialog, int item) {
							            	mRestoreChoice = item;
							            }
							        }) 
							        .setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
							            public void onClick(DialogInterface dialog, int which) { //確認
							            	mLocDD=Pndnddlist[mRestoreChoice].substring(0, Pndnddlist[mRestoreChoice].indexOf("__"));
							            	aExtWord=" and PNDNDD='"+mLocDD+"'";
								    		((Button)findViewById(R.id.btn_pdd)).setText(mLocDD);
											getDetailData(QpandnF.this, mWho);  //aState==1 有找到 暫盤表
											mAdapter.notifyDataSetChanged();
							            }
							          })
							        .setNegativeButton("還原", new DialogInterface.OnClickListener() {
							            public void onClick(DialogInterface dialog, int which) { //取消
							            	aExtWord="";
											getDetailData(QpandnF.this, mWho);  //aState==1 有找到 暫盤表
											mAdapter.notifyDataSetChanged();
							            }
							          }).show();
								}
							}
					}else if (nCondition==2 ){ 
						//2樓_現在盤表/以前盤表
						if (nState==2){ //從以前盤表->回到現在
							((Button)findViewById(R.id.btn_savein)).setText("以前盤表");
							nState=0;
						}else{	
							((Button)findViewById(R.id.btn_savein)).setText("回到現在");
							nState=2;
						}
						//((TextView)findViewById(R.id.pndn_title)).setText(mKind[nDept]+"盤點清冊"+mState[nState]);
			    		nCondition=2;	setCondition();
						getGroupData(QpandnF.this, mWho, nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
						mAdapter.notifyDataSetChanged();        
					}
					break;
				}
				case R.id.btn_reset: 
				{	
					if (nCondition==3 ){//三樓(暫存)歸零
						DialogUtilis.showDialog(QpandnF.this, "確定暫盤要歸零,再重新盤點?", -1,
								new String[] { "取消歸零", "當真歸零!起手無回大丈夫!" }, new IDialog() {
									@Override
									public void onDialogFinish(int pos, String choice) {
										switch (pos) {
										case 0: break;
										case 1: zeroPin("",0);  //如果有值,是針對單筆
										}
									}
						});			
					}
					break;
				}
				case R.id.btn_exit:  //離開盤點系統 回到主程式
				{
					if (nCondition==1 || nCondition==3 ){  //從三樓 或 從新增盤表 返回
						if (nDept!=0) mWho="";  //總倉唯一 (門市廠商盤點 對多 所以mWho="")
						nCondition=2; setCondition();

					}else if (nCondition==2){
						//nCondition=0; setCondition();
						finish();
					}
					getGroupData(QpandnF.this, mWho, nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
					mAdapter.notifyDataSetChanged();        
					break;
				}
				
				//----------/主畫面的6大功能\--下方的 buttom
				
				case R.id.layout_deptpndn: //門市盤點作業
				{
					nDept=1;nState=0;
					nCondition=2;	setCondition();  //
					mWho="";

					getGroupData(QpandnF.this, mWho, nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
					mAdapter.notifyDataSetChanged();        
					//預設為(未入帳)
					//如果有門市盤點清冊,直接顯示所有清冊
					//下半部視窗隨著輕觸(門市)顯示 的 上存/本/進/銷/存
					//如果沒有半個門市時,是否直接進入新增門市???
					//getCust(); //並非馬上新增
					//未入帳盤點清冊下鈕包含:__新增__匯入__返回__
					//輕觸ITEM_menu包含: 繼續盤點/入帳/直接刪除/匯出/輸出/重新盤點/盤點量同在庫量/返回

					//已入帳盤點清冊(如果沒有範圍)勢必會一大串(如果寄賣盤以100個專櫃而言,有可能全部超過數百)
					//所以(已入帳)顯示最後盤點清冊(所有專櫃),如果指定某一對象,應該顯示該對象所有盤點清冊(以夾鏈方式往右呈現)
					//下鈕包含:__返回
					//輕按MENU__取消入帳(一定要為最後一筆盤點清冊)才可為之__直接刪除__匯出(送回總倉進一步維護總倉庫存)__
					//__輸出(分享的概念)__明細清單__返回
					
					break;
				}
				case R.id.layout_aapndn: // 總倉盤點作業
				{
					if( nPart==0 ){ //總倉做總倉盤點
						nDept=0;nState=0;
						nCondition=2;	setCondition();  //
			        	mWho=deptStr[5];
						getGroupData(QpandnF.this, mWho, nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
						mAdapter.notifyDataSetChanged();
					}else{
						//
						Toast.makeText(QpandnF.this, "只有總倉,才可以進行總倉盤點", Toast.LENGTH_SHORT).show();
					}
					break;
				}
				case R.id.layout_factpndn: // 廠商盤點作業
				{
					nDept=2;;nState=0;
					nCondition=2;	setCondition();  //
					mWho="";
					getGroupData(QpandnF.this, mWho, nState,null,null);  //
					mAdapter.notifyDataSetChanged();        
					break;
				}
				case R.id.layout_exitpndn: // 結束盤點回庫存管理(MENU)
				{
					//取得總倉代號&名稱,並確認為總倉系統或門市系統&且預設總倉盤點
					finish();
					break;
				}
//--------------------/新增盤點清冊/-----------------------
				case R.id.btn_pndnno:  //[編號]當需要重新挑選對象時
				{
					nState=0;
					nCondition=1;	setCondition();  //
					getCust();
					break;
				}
				case R.id.btn_disc: // 
				{
					DialogUtilis.showComputer(QpandnF.this, id);
    				reCountBG();
					break;
				}
				case R.id.pbtn_input:
				{
   					aInput=pInput.getText().toString().toUpperCase();
					catched();
					break;
				}
				case R.id.btn_pdd://輸入櫃位
				{
					if (nCondition==3){  //對話窗
						LayoutInflater factory = LayoutInflater.from(QpandnF.this);
					    final View v1 = factory.inflate(R.layout.register, null);
					    final EditText edtReg = (EditText) v1.findViewById(R.id.edtReg);
					    ((TextView) v1.findViewById(R.id.TextView01)).setText("盤點時,系統為了資料安全起見,將正在盤點的商品放在(暫存區),並將商品的區域位置製作標簽,視為櫃位");
					    edtReg.setText(mLocDD);
					      new AlertDialog.Builder(QpandnF.this).setTitle("請輸入正在盤點的櫃位:").setView(v1).setNeutralButton("OK", new DialogInterface.OnClickListener() {
						      public void onClick(DialogInterface dialog, int which) {
							        mLocDD=edtReg.getText().toString();
						    		((Button)findViewById(R.id.btn_pdd)).setText(mLocDD);
						      }
					      }).show();
					}
					break;
				}
				case R.id.btn_cmd://輸入櫃位
				{
					if (mChoiceMode==ChoiceMode.SERCH){
						mChoiceMode=ChoiceMode.PLUS;
						((Button)findViewById(R.id.btn_cmd)).setText("盤進(+)");
					}else if (mChoiceMode==ChoiceMode.PLUS){
						mChoiceMode=ChoiceMode.MILUS;
						((Button)findViewById(R.id.btn_cmd)).setText("盤退(-)");
					}else if (mChoiceMode==ChoiceMode.MILUS){
						mChoiceMode=ChoiceMode.SERCH;
						((Button)findViewById(R.id.btn_cmd)).setText("僅查詢");
					} 
					break;
				}
				case R.id.btn_dpndn: // 本次盤點日
				{
					if (nSuccess>0){
						mYear=Utilis.toInt(Ddate.substring(0, 4));
						mMonth=Utilis.toInt(Ddate.substring(5, 7));
						mDay=Utilis.toInt(Ddate.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(QpandnF.this, "請輸入本次盤點日期", c, new IDateDialog(){
						@Override
						public void onDateDialogFinish(String date, int year, int month, int day) {
							((Button)findViewById(R.id.btn_dpndn)).setText(date);
		            		nCompares=DateUtil.compareTime(Ldate, date);
		            			if (nCompares>=0){  //表示本盤<=上盤,是無法盤點,需重返
		            				Toast.makeText(QpandnF.this, "本次盤點日須比上次盤點日還大", Toast.LENGTH_SHORT).show();
		            			}else{ //合法本盤日期
		            				Ddate=date;
		            				reCountBG();
								}
							}
						});
					 	
					}else{
						//資訊不完整,可以集中管理
						//尚未取得編號簡稱,或上次盤點日及價別及折數
						//是否警示:當價別折數與DATA上的設定不符時或與上次盤點不符時
						//@@@還是限定價別與折數需與DATA一致,不開放異動??
        				Toast.makeText(QpandnF.this, "請補正其他資訊!!", Toast.LENGTH_SHORT).show();
					}
					break;
				}
//				default:
//					break;
					
			}
		}
	}

	private TextWatcher watcherPrice = new TextWatcher(){  
        @Override  
        public void afterTextChanged(Editable s) {  
        }  
        @Override  
        public void beforeTextChanged(CharSequence s, int start, int count,  
                int after) {  
        }  
        @Override  
        public void onTextChanged(CharSequence s, int start, int before,  
                int count) {
        	  	reCountBG();
        }  
    };
	
	
	
	
private class ReportAdapter extends BaseAdapter{
		
		private LayoutInflater mInflater;
		
		public LinkedList<RepDataPan> mList = new LinkedList<RepDataPan>();
		
		public ReportAdapter (Context context ){
		      mInflater = LayoutInflater.from(context);
		}

		public RepDataPan getData(int Position){
			return mList.get(Position);
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mList.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;
			RepDataPan data = mList.get(position);
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_posh, null);
				holder = new ViewHolder();
				holder.imageItem = (ImageView)convertView.findViewById(R.id.img_ppic);
				if (data.iGoods.length()>0) ((TextView) convertView.findViewById(R.id.text_pgoodsno)).setBackgroundColor(Color.GREEN);
//				else ((TextView) convertView.findViewById(R.id.text_pgoodsno)).setBackgroundColor(Color.GREEN);
				holder.textGoodsNo = (TextView) convertView.findViewById(R.id.text_pgoodsno);
				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();
			}
			java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
			holder.imageItem.setImageBitmap(Utilis.getLimitBitmap(data.iPic, 80, 80));
			
			holder.textGoodsNo.setText(data.iGoods);
			
			holder.textName.setText(data.iName);
			holder.textCountry.setText(data.iCountry);
			holder.textCompany.setText(data.iCompany);
			holder.textMoney.setText(data.iMoney);
			holder.textNumber.setText(data.iNumber);
			holder.textImpo.setText(data.iImpo);			
			return convertView;
		}

		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textGoodsNo;
			TextView textImpo;
			TextView textName;
			TextView textMoney;
			TextView textCountry;
			TextView textNumber;
			TextView textCompany;
			
		}

	}


private void disPlayTable(String mData){  //到時候需區隔 0總倉 1門市 2廠商

	mLayoutRoot.removeAllViews();
	mSizeLink.clear();
	mCountRow.clear();	        		
	mCountCell.clear();

   	mSizeLink.add("代碼");mSizeLink.add("顏色");mSizeLink.add("尺寸");
	mSizeLink.add("暫盤");mSizeLink.add("已盤");mSizeLink.add("盤差");
	mSizeLink.add("應盤");mSizeLink.add("本銷");
	if (nDept==0)	mSizeLink.add("本出"); else if (nDept==1) mSizeLink.add("轉出"); else mSizeLink.add("保留"); 
	mSizeLink.add("本進");mSizeLink.add("上存");
	
	        	mCountRow.put(0, 0 * 100);
	        	for (int k=0;k<11;k++) mCountCell.put(k, mSizeLink.get(k));	        	
	        	
				//02,黑色,F,0,0,-16,16,0,0,16,0，11,灰色,F,0,0,-7,7,0,0,7,0，
				//分解 DATA
				//String mData=csm.getString(csm.getColumnIndex("DATA"));
				 
				eachItem = mData.split("，"); //取得各色號尺寸數據字串
	        	for (int i=0;i<eachItem.length;i++){
	        		mCountRow.put(i+1, (i +1)* 100);
	        		eachField=eachItem[i].split(",");
	        		for (int k=0;k<11;k++){
	        			mCountCell.put((i +1)* 100+k, eachField[k]);
	        		}
	        	}
	  		
	  		ArrayList<TableRow> table = new ArrayList<TableRow>();
        	table.removeAll(table);

        	for(int i = 0; i <= eachItem.length; i++){
        		TableCell[] titles = new TableCell[mSizeLink.size()];
//    			titles[k] = new TableCell((Wwidth/tabless)-8,tableHeight,TableCell.STRING);

        		for(int k = 0; k < titles.length; k++){
        			if (k<=2) titles[k] = new TableCell((Wwidth/tabless)-tabless,tableHeight,TableCell.STRING);
        			else titles[k] = new TableCell((Wwidth/(tabless-2))-tabless,tableHeight,TableCell.STRING);
        		}
        		table.add(new TableRow(titles));
        		
        	}
        	
        	TableRow tableRow = table.get(0);
        	for(int i = 0; i <=eachItem.length; i ++){
        		TableRowView row = new TableRowView(this, tableRow, i);
        		mLayoutRoot.addView(row);
        	}
}

public class TableRowView extends LinearLayout {  
    public TableRowView(Context context, TableRow tableRow, int position) {  
        super(context);  
        this.setOrientation(LinearLayout.HORIZONTAL);  
        for (int i = 0; i < tableRow.getSize(); i++) { 
            TableCell tableCell = tableRow.getCellValue(i);  
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(  
                    tableCell.width, tableCell.height);  
            layoutParams.setMargins(0, 0, 1, 1);  

            TextView textCell = new TextView(context);  
                textCell.setLines(1);  
                textCell.setGravity(Gravity.CENTER);
                textCell.setBackgroundColor(Color.WHITE);
                if(mCountRow.containsKey(position) == true){
                	int key = mCountRow.get(position);
                	if( mCountCell.containsKey(key + i)){
                		textCell.setText(String.valueOf(mCountCell.get(key + i)));
                	}else{
                		textCell.setText("X");
                	}
                }else{
                	textCell.setText("X");
                }
                textCell.setId(position * 100 + i);
                if (nState!=2){
                	textCell.setOnClickListener(new Clickable(position,i));
                	textCell.setOnLongClickListener(new ClickableLong(position,i));
                }
                textCell.setTextColor(Color.BLACK);
                if(position>0 && i>=2 ){
                	switch(i){
                		case 2:textCell.setBackgroundResource(R.drawable.keypad_orange);break;	//尺寸
                		case 3:textCell.setBackgroundColor(Color.WHITE);break;	//暫盤
                		case 4:textCell.setBackgroundResource(R.drawable.keypad_yellow);break;	//已盤
                		case 5:textCell.setBackgroundResource(R.drawable.keypad_green);break;	//盤差
                		case 6:textCell.setBackgroundResource(R.drawable.keypad_blue2);break;	//應盤
                		case 7:textCell.setBackgroundResource(R.drawable.keypad_orange);break;	//銷貨
                	}                    	
                }else  if(position>0 && i==0){  //
                	int getCol=Color.rgb(160, 160, 160);
                	if (!textCell.getText().toString().equalsIgnoreCase("01")) getCol=ColorGetnumber(QpandnF.this,textCell.getText().toString());
                	textCell.setBackgroundColor(getCol);
                } else {
                	textCell.setBackgroundColor(Color.rgb(208, 208, 208));
                }
                
                addView(textCell, layoutParams);
                
        }  
        this.setBackgroundColor(Color.BLACK);
}
}

class Clickable implements OnClickListener{
	private int mRow;
	private int mCell;
	Clickable(int row, int cell){
		mRow = row;
		mCell = cell;
	}
	@Override
	public void onClick(View v) {
		int id = v.getId();
		if(mRow>0 && mChoiceMode!= ChoiceMode.SERCH && nState!=2 ){
			//非查詢,又是已過帳盤表,不可再盤點
				int nCellKey = mCountRow.get(mRow);
				mColorno= mCountCell.get(nCellKey + 0);
				mySize= mCountCell.get(nCellKey + 2);
				aInput=goodO+"-"+mColorno+"-"+mySize;
				//未來應考慮 數字鍵盤呼叫
				//showComputer(id);
				String Adata=searched(mChoiceMode);
				Toast.makeText(QpandnF.this, "點選的:"+aInput+" 暫盤累進"+mChoiceMode, Toast.LENGTH_SHORT).show();
				RepDataPan data = new RepDataPan();
				data.iPic=datas.iPic;
				data.iGoods=mLocDD;  //櫃位 
				data.iName=datas.iName;  
				data.iCountry=datas.iCountry;
				data.iNumber=datas.iNumber; //單價
				data.iImpo=datas.iImpo;  //應盤
				data.iUnit2=Adata;
				data.iMoney="暫盤:"+nPin+"/已盤:"+nAadn; //本盤
				data.iCompany="盤差:"+nAdefn+"/"+nAdefm;//盤差
				data.iFormdate=datas.iFormdate;  //盤點對象代號
				data.iFormno=datas.iFormno;
				mAdapter.mList.set(locations, data);
				mAdapter.notifyDataSetChanged();
				mListView.setSelection(locations);
		}else{
			Toast.makeText(QpandnF.this, "[查詢]或[已過帳的盤表]不可盤點哦!!", Toast.LENGTH_SHORT).show();
		}
	}
}

//捕捉到了 但是也同時 啟動了 輕按 的 事件
class ClickableLong implements  OnLongClickListener{
	private int mRow;
	private int mCell;
	ClickableLong(int row, int cell){
		mRow = row;
		mCell = cell;
	}
	@Override
	public  boolean onLongClick(View v) {
		boolean returnS=true;
		int id = v.getId();
		if(mRow>0 && nState!=2 ){
			//請出一組 數字鍵盤
			//如果傳回不為0 就有意義 並乘以 mChoiceMode
				LayoutInflater factory = LayoutInflater.from(QpandnF.this);
	    final View v1 = factory.inflate(R.layout.fnumber, null);
	    final EditText edtReg = (EditText) v1.findViewById(R.id.edtsh);
	    edtReg.setText("");
	      new AlertDialog.Builder(QpandnF.this).setTitle("").setView(v1).setNeutralButton("開始加或減", new DialogInterface.OnClickListener() {
		      public void onClick(DialogInterface dialog, int which) {
		    	  if (edtReg.length()>0 && Utilis.toInt(edtReg.getText().toString())!=0){		

						int nCellKey = mCountRow.get(mRow);
						int moreorless=Utilis.toInt(edtReg.getText().toString());
						mColorno= mCountCell.get(nCellKey + 0);
						mySize= mCountCell.get(nCellKey + 2);
						aInput=goodO+"-"+mColorno+"-"+mySize;
						//未來應考慮 數字鍵盤呼叫
						//showComputer(id);
						String Adata=searched(moreorless);
						Toast.makeText(QpandnF.this, "點選的:"+aInput+" 暫盤累加減"+moreorless, Toast.LENGTH_SHORT).show();
						RepDataPan data = new RepDataPan();
						data.iPic=datas.iPic;
						data.iGoods=mLocDD;  //櫃位 
						data.iName=datas.iName;  
						data.iCountry=datas.iCountry;
						data.iNumber=datas.iNumber; //單價
						data.iImpo=datas.iImpo;  //應盤
						data.iUnit2=Adata;
						data.iMoney="暫盤:"+nPin+"/已盤:"+nAadn; //本盤
						data.iCompany="盤差:"+nAdefn+"/"+nAdefm;//盤差
						data.iFormdate=datas.iFormdate;  //盤點對象代號
						data.iFormno=datas.iFormno;
						mAdapter.mList.set(locations, data);
						mAdapter.notifyDataSetChanged();
						mListView.setSelection(locations);
		    		  
		    	  }
		     }
		    }).setNegativeButton("離開", new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int which) {
				      }
		    })
		    .show();
			
			
		}else{
			Toast.makeText(QpandnF.this, "[已過帳的盤表]不可盤點哦!!", Toast.LENGTH_SHORT).show();
		}
		return returnS;
	}
}

private void zeroPin(String aGood,int aMode){
	//aGood有值,表示單款歸零
	//aMode=0暫盤歸零 1已盤歸零_2,11,12 
	mLayoutRoot.removeAllViews();
	File fileQmtrio = new File(mDBPath);
  	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
  	StringBuffer mSQL = new StringBuffer();
	Cursor csm;
	mSQL.append("select * from qpandn where USER='"+mWho+"' and PNDNADAY='"+Ddate+"'")
	.append(" and PNDNFKIND="+nDept +""	);
	if (aMode>0 && aMode!=12) mSQL.append(" and ID>10"); else mSQL.append(" and ID>100000"); 
	if (aGood.length()>0) mSQL.append(" and GOODSNO='"+aGood+"'");
		csm=mdb.rawQuery(mSQL.toString(), null);
		if(csm.getCount()>0 ){ //唯一性的,可以進行比對
			
			csm.moveToFirst();
			for (int ii=0;ii<csm.getCount();ii++){
				int tApann=0;
				double tApanm=0;
				int tAdefn=0;
				double tAdefm=0;
				int tApin=0;
				StringBuffer Cdata=new StringBuffer();
				String Adata=csm.getString(csm.getColumnIndex("DATA"));
				String bGood=csm.getString(csm.getColumnIndex("GOODSNO"));
				int aID=csm.getInt(csm.getColumnIndex("ID"));
//[10]上存	[9]本進	[8]本出	[7]本銷	[6]應盤	[5]盤差	[4]已盤	[3]暫盤	[2]SIZE[1]COLOR_NAME[0]COLOR_NO
				String [] fieldA=Adata.split("，"); //各色尺寸
				String [] fieldB=fieldA[0].split(",");//首筆的欄位
				for (int ij=0;ij<fieldA.length;ij++){//檢查每一筆盤表存在這個顏色尺寸否
						fieldB=fieldA[ij].split(","); //各欄位
						if (aMode==0){
							fieldB[3]="0";  //暫盤歸零
							if (aID>100000) aID=aID-100000;
						}else if (aMode==1){
							fieldB[4]="0";  //已盤歸零
							if (aID>100000) aID=aID-100000;
						}else if (aMode==2){  //盤準 也只能計算給 暫盤 而不要直接轉入 已盤
							fieldB[3]=""+(Utilis.toInt(fieldB[3])-Utilis.toInt(fieldB[5]));
							if (aID<100000) aID=aID+100000;
						}else if (aMode==11){//所有轉入已盤
							//fieldB[4]=fieldB[6];//已盤=應盤
							//fieldB[5]="0";  //盤差歸零
							//fieldB[3]="0";  //暫盤歸零
						}else if (aMode==12){//暫盤 轉入已盤
							fieldB[4]=""+(Utilis.toInt(fieldB[4])+Utilis.toInt(fieldB[3]));
							fieldB[3]="0";  //暫盤歸零
							if (aID>100000) aID=aID-100000;
						}
						fieldB[5]=""+(Utilis.toInt(fieldB[4])+Utilis.toInt(fieldB[3])-Utilis.toInt(fieldB[6]));
						nAdefn=Utilis.toInt(fieldB[5]); //盤差
						nAdefm=nAdefn*(csm.getInt(csm.getColumnIndex("UNITPRICE"))*csm.getDouble(csm.getColumnIndex("DISCOUNT"))/100);
						tAdefn=tAdefn+nAdefn;
						tAdefm=tAdefm+nAdefm;
						tApann=tApann+Utilis.toInt(fieldB[4]);
						tApanm=tApanm+Utilis.toInt(fieldB[4])*(csm.getDouble(csm.getColumnIndex("UNITPRICE"))*csm.getDouble(csm.getColumnIndex("DISCOUNT"))/100);
						tApin=tApin+Utilis.toInt(fieldB[3]);
						for (int ik=0;ik<10;ik++)	Cdata.append(fieldB[ik]+",");
						Cdata.append(fieldB[10]+"，");
				}
				//副程式_要兜回DATA
				//也須維護 該商品的 盤差小計(金額) 已盤小計(金額)
				//存入PANDNF
				StringBuffer Bdata=new StringBuffer();
				Bdata.append("update qpandn set DATA='"+Cdata.toString()+"',APIN="+tApin+",APANN="+tApann+",APANM="+tApanm+",ADEFN="+tAdefn+",ADEFM="+tAdefm+",CDT='"+DateUtil.getSystemTime().substring(2, 14)+"',ID="+aID);
				if (aMode==2) Bdata.append(",PNDNDD='"+mLocDD+"'");
				Bdata.append(" where  USER='"+mWho+"' and PNDNADAY='"+Ddate+"' and PNDNFKIND="+nDept+" and GOODSNO='"+bGood+"'");
				mdb.execSQL(Bdata.toString());
				if (aGood.length()>0){  //應是唯一的商品
					RepDataPan data = new RepDataPan();
					data.iPic=datas.iPic;
					data.iGoods=mLocDD;  //櫃位 
					data.iName=datas.iName;  
					data.iCountry=datas.iCountry;
					data.iNumber=datas.iNumber;
					data.iImpo=datas.iImpo;
					data.iUnit2=Cdata.toString();
					data.iMoney="暫盤:"+tApin+"/已盤:"+tApann; //本盤
					data.iCompany="盤差:"+tAdefn+"/"+tAdefm;//盤差
					data.iFormdate=datas.iFormdate;  //盤點對象代號
					data.iFormno=datas.iFormno;
					mAdapter.mList.set(locations, data);
				}
				csm.moveToNext();
			}
			if (aGood.length()<=0) getDetailData(QpandnF.this, mWho);  //aState==1 有找到 暫盤表
			mAdapter.notifyDataSetChanged();
			
			//最後要維護 ID=3 盤表頭
			mSQL.delete(0, mSQL.toString().length());
			mSQL.append("select sum(APANN),sum(APANM),sum(ADEFN),sum(ADEFM),sum(APIN) from qpandn where USER='"+mWho+"' and PNDNADAY='"+Ddate+"'")
			.append(" and PNDNFKIND="+nDept +" and ID>10");
			csm=mdb.rawQuery(mSQL.toString(), null);
			if(csm.getCount()>0 ){ //唯一性的,可以進行比對
				csm.moveToFirst();
				int qApann=csm.getInt(0);	double qApanm=csm.getDouble(1);
				int qAdefn=csm.getInt(2);	double qAdefm=csm.getDouble(3);
				int qPin=csm.getInt(4); if (aMode==12) qPin=0;//強制暫盤在id=3 為0(20181220)表暫盤轉入已盤完畢
				mSQL.delete(0, mSQL.toString().length());
				mSQL.append("update qpandn set APIN="+qPin+",APANN="+qApann+",APANM="+qApanm+",ADEFN="+qAdefn+",ADEFM="+qAdefm+",CDT='"+DateUtil.getSystemTime().substring(2, 14)+"'");
				mSQL.append(" where  USER='"+mWho+"' and PNDNADAY='"+Ddate+"' and PNDNFKIND="+nDept+" and ID=3");
				mdb.execSQL(mSQL.toString());
				if (aMode==11){
					mSQL.delete(0, mSQL.toString().length());
					mdb.execSQL("update qpandn set PNDNSTATE='2',TR='Y1',DEPTSNO='"+mFormno+"',BANKNAME='"+bankn+"',CDT='"+DateUtil.getSystemTime().substring(2, 14)+"',SDT='"+DateUtil.getSystemTime().substring(2, 14)+"' where USER='"+mWho+"' and PNDNFKIND="+nDept+" and PNDNADAY='"+Ddate+"'");
					//盤表直接過帳,不再盤銷
					if (Utilis.haveInternet(QpandnF.this) && of_line==1) DBCloud.aa1_aa0_pan_update(QpandnF.this,mWho,Ddate,bankn,nDept);
					mWho="";
					getGroupData(QpandnF.this, mWho, nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
					mAdapter.notifyDataSetChanged();        
				}
			}							
		}
	csm.close();
	mdb.close();
	
}

private String searched(int addplus){
	//是否有2段式 先QPANDNF_及自家盤表 找不到 續找如果是自家門市,或總倉
	//尋找QITEMS 建立初始盤表 並讓上存=0
	//由table	//	aInput=goodO+"-"+mColorno+"-"+mySize;
	//@@@Keyin 時 ,有2個(-) 表示有輸入完整貨號,才會進入到 本程序
	String Adata="";
	File fileQmtrio = new File(mDBPath);
  	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
  	StringBuffer mSQL = new StringBuffer();
	Cursor csm;
	//@@@ID>10<10000表示總盤表 10000以上為暫盤表
	//ID>8000<10000表示為補增資料 可以列式條件
	//是否納入 已盤清冊 未盤清冊 盤差清冊 等多元查詢
	mSQL.append("select * from qpandn where USER='"+mWho+"' and PNDNADAY='"+Ddate+"'")
	.append(" and PNDNFKIND="+nDept);
	mSQL.append(" and GOODSNO='"+goodO+"'");
		csm=mdb.rawQuery(mSQL.toString(), null);
		if(csm.getCount()>0 ){ //唯一性的,可以進行比對
			csm.moveToFirst();
			int aID=csm.getInt(csm.getColumnIndex("ID"));
			if (aID<100000) aID=aID+100000;
			Adata=csm.getString(csm.getColumnIndex("DATA"));
					int Achk=-1;
//[10]上存	[9]本進	[8]本出	[7]本銷	[6]應盤	[5]盤差	[4]已盤	[3]暫盤	[2]SIZE[1]COLOR_NAME[0]COLOR_NO
					String [] fieldA=Adata.split("，"); //各色尺寸
					String [] fieldB=fieldA[0].split(",");//首筆的欄位
					for (int ij=0;ij<fieldA.length;ij++){//檢查每一筆盤表存在這個顏色尺寸否
							fieldB=fieldA[ij].split(","); //各欄位
							if(fieldB[0].equalsIgnoreCase(mColorno) && fieldB[2].equalsIgnoreCase(mySize)){
								Achk=ij;
								break;
						}
					}
					StringBuffer Bdata=new StringBuffer();
					if (Achk>=0){
						if (addplus!= ChoiceMode.SERCH){ 
							fieldB[3]=""+(Utilis.toInt(fieldB[3])+addplus);//暫盤
							fieldB[5]=""+(Utilis.toInt(fieldB[5])+addplus);	//盤差
							//重組單一色尺寸欄位
							Bdata.append(fieldB[0]);
							for (int ik=1;ik<11;ik++) Bdata.append(","+fieldB[ik]);
							fieldA[Achk]=Bdata.toString();
							//重組DATA
							Bdata.delete(0, Bdata.toString().length());
							//Bdata.append(fieldA[0]);
								for (int ij=0;ij<fieldA.length;ij++) Bdata.append(fieldA[ij]+"，");
							Adata=Bdata.toString();
							//運算 關鍵欄位 借用 nAstk nAadn nPin nAdefn nAdefm
							nAstk=csm.getInt(csm.getColumnIndex("ASTKN"));
							nAadn=csm.getInt(csm.getColumnIndex("APANN"));
							nPin=csm.getInt(csm.getColumnIndex("APIN"));
							nPin=nPin+addplus;
							nAdefn=nAstk-(nAadn+nPin);
							nAdefm=nAdefn*(csm.getDouble(csm.getColumnIndex("UNITPRICE"))*csm.getDouble(csm.getColumnIndex("DISCOUNT"))/100);
							Bdata.delete(0, Bdata.toString().length());
							Bdata.append("update qpandn set DATA='"+Adata+"',APIN="+nPin+",ADEFN="+nAdefn+",ADEFM="+nAdefm+",CDT='"+DateUtil.getSystemTime().substring(2, 14)+"',ID="+aID+",PNDNDD='"+mLocDD+"'")
							.append(" where  USER='"+mWho+"' and PNDNADAY='"+Ddate+"' and PNDNFKIND="+nDept+" and GOODSNO='"+goodO+"'");
							mdb.execSQL(Bdata.toString());
							//副程式_要兜回DATA
							//也須維護 該商品的 盤差小計(金額) 暫盤小計(金額) 已盤小計(金額)
							//存入PANDNF
						}
					}else{
						//應視為 此顏色尺寸不存在  要將Adata 再增設
						if (!mColorno.equalsIgnoreCase("00") && !mySize.equalsIgnoreCase("F") && mySize.length()>0){
						  Adata=Adata+mColorno+",";
						  Adata=Adata+ColorGetname(this,mColorno)+",";
						  Adata=Adata+mySize+",";
						  Adata=Adata+"1,0,1,0,0,0,0,0，";
						  nAstk=csm.getInt(csm.getColumnIndex("ASTKN"));
						  nAadn=csm.getInt(csm.getColumnIndex("APANN"));
						  nPin=csm.getInt(csm.getColumnIndex("APIN"));
						  nPin=nPin+addplus;
						  nAdefn=nAstk-(nAadn+nPin);
						  nAdefm=nAdefn*(csm.getDouble(csm.getColumnIndex("UNITPRICE"))*csm.getDouble(csm.getColumnIndex("DISCOUNT"))/100);
						  Bdata.delete(0, Bdata.toString().length());
						  Bdata.append("update qpandn set DATA='"+Adata+"',APIN="+nPin+",ADEFN="+nAdefn+",ADEFM="+nAdefm+",CDT='"+DateUtil.getSystemTime().substring(2, 14)+"',ID="+aID+",PNDNDD='"+mLocDD+"'")
						  .append(" where  USER='"+mWho+"' and PNDNADAY='"+Ddate+"' and PNDNFKIND="+nDept+" and GOODSNO='"+goodO+"'");
						  mdb.execSQL(Bdata.toString());
						}
						
					}
						disPlayTable(Adata);
		}else{
		//若盤表不存在,卻盤到了有意義的商品,有可能為,收負帳的商品
		//應增設該商品及結構到該盤表
			csm=mdb.rawQuery("select * from qpandn where USER='"+mWho+"' and PNDNADAY='"+Ddate+"' and PNDNFKIND='"+nDept+"' and ID<100000 order by ID desc limit 1", null);
			if (csm.getCount()>0){
				csm.moveToFirst();
				nID=csm.getInt(csm.getColumnIndex("ID"))+1;
				
				String SQL_qdetail="select * from qdetail where GOODSNO='"+goodO+"' order by BATCH desc limit 1";
				SQLiteDatabase db = Utilis.getDB(this);
				Cursor cs = db.rawQuery(SQL_qdetail,null);
				if (cs.getCount()>0){
					cs.moveToFirst();
					
					ContentValues valueI = new ContentValues();
					valueI.put("PNDNFKIND",csm.getString(csm.getColumnIndex("PNDNFKIND")));
					valueI.put("PNDNPKIND",csm.getString(csm.getColumnIndex("PNDNPKIND")));
					valueI.put("PNDNCKIND",csm.getString(csm.getColumnIndex("PNDNCKIND"))); 
					valueI.put("PNDNSTATE",0) ;	//新的盤表
					valueI.put("ID",(nID+100000)) ;
					valueI.put("USER",csm.getString(csm.getColumnIndex("USER"))) ;
					valueI.put("USERNAME",csm.getString(csm.getColumnIndex("USERNAME"))) ;
					valueI.put("PNDNBDAY",csm.getString(csm.getColumnIndex("PNDNBDAY"))) ;
					valueI.put("PNDNADAY",csm.getString(csm.getColumnIndex("PNDNADAY"))) ;
					
					valueI.put("GOODSNO",cs.getString(cs.getColumnIndex("GOODSNO"))) ;
					valueI.put("GOODSNAME",cs.getString(cs.getColumnIndex("GOODSNAME"))) ;
					valueI.put("PIC",cs.getString(cs.getColumnIndex("PIC"))) ;
					
					nPrice=cs.getInt(cs.getColumnIndex("P"+nTradetype)) ;
					valueI.put("UNITPRICE",""+nPrice) ;
					valueI.put("DISCOUNT",nDiscount) ;
					nAcost=cs.getInt(cs.getColumnIndex("P1")) ;
					valueI.put("ACOST",nAcost) ;
					
					String buf="";
					int having=0;
					String [] qColorNo=cs.getString(cs.getColumnIndex("COLORNO")).split("，");
					String [] qColor=cs.getString(cs.getColumnIndex("COLOR")).split("，");
					String [] qSize=cs.getString(cs.getColumnIndex("SIZE")).split(",");
					if (qColorNo.length>0){
						for (int x=0;x<qColorNo.length;x++){
							//13,藍色,F,0,1,0,1,0,0,1,0，
							for (int y=0;y<qSize.length;y++){
								buf=buf+qColorNo[x]+","+qColor[x]+","+qSize[y]+",";
								if(qColorNo[x].equalsIgnoreCase(mColorno) && qSize[y].equalsIgnoreCase(mySize)){
									buf=buf+"1,0,1,0,0,0,0,0，";
									having=1;
								}else buf=buf+"0,0,0,0,0,0,0,0，";
							}
						}
					}
					if (buf.length()>0 && having==1){
						valueI.put("DATA",buf) ;
						valueI.put("DATA0","") ;
						valueI.put("PNDNDD","A") ;
						valueI.put("DEPTSNO","FORMNO") ;
						valueI.put("PARTSNO","") ;
						valueI.put("LASTSTKN",0) ;
						valueI.put("LASTSTKM",0) ;
						valueI.put("AINN",0) ;
						valueI.put("AINM",0);				
						valueI.put("ASTN",0) ;
						valueI.put("ASTM",0);
						valueI.put("ASTKN",0) ; //本存
						
						valueI.put("ASTKM",0);
						valueI.put("APANN",0) ; //本盤
						valueI.put("APANM",0) ;
						valueI.put("ADEFN",1) ;  //盤差量
						valueI.put("ADEFM",(nPrice*nDiscount/100)) ;  //盤差金
						valueI.put("CDT",DateUtil.getSystemTime().substring(2, 14)) ;
						valueI.put("APIN",1) ;  //暫盤
						valueI.put("SDT",DateUtil.getSystemTime().substring(2, 14)) ;
						valueI.put("BANKNAME",bankn) ;
						valueI.put("TR","Y0") ;
						mdb.insert("qpandn", null, valueI);
						Adata=buf;
						disPlayTable(Adata);
					}				
				}else{
					myDialog = ProgressDialog.show(QpandnF.this,"查無此商品","請按任意鍵...繼續盤點",true);//		setAutoRotationMode();
					SystemClock.sleep(3000);
					myDialog.dismiss();
				}
				cs.close();
				db.close();
			}
		}
		mdb.close();
		csm.close();
		return Adata;
}


private String ColorGetname(Context context,String key){
	String Colname="多色";
	SQLiteDatabase db = Utilis.getDB(context);
	Cursor cs = null;					
	StringBuffer mySqlBuf = new StringBuffer();
		mySqlBuf.append("select distinct NO,TXT from qc_color where NO='"+key+"'");
		cs = db.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){
			cs.moveToFirst();
			Colname=cs.getString(1);
		}
		db.close();
		cs.close();
	return Colname;	
}

private int ColorGetnumber(Context context,String key){
	int number=0;
	SQLiteDatabase db = Utilis.getDB(context);
	Cursor cs = null;					
	StringBuffer mySqlBuf = new StringBuffer();
		mySqlBuf.append("select distinct NO,PIC from qc_color where NO='"+key+"'");
		cs = db.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){
			cs.moveToFirst();
			number=cs.getInt(1);
		}
		db.close();
		cs.close();
	return number;	
}

//wink 特例  雲端處理流程
//先製作雲端備份qhead qitems
//將已盤量,過帳,存入 總倉:廠商進貨單 門市:廠商進貨單及門市出貨單
//清除含盤點日以前所有(進貨出貨銷貨)資料
//依依存入


private double SaveinQQ(RepDataPan datas,String WHO,int pMode){
double result=-1;
	String [] LIMITD=datas.iName.split("~");
	String pKind="30";
	switch (pMode){
		case 0:pKind="31";break;	//門市轉銷貨
		case 1:pKind="20";break;	//門市轉出退
		case 2:pKind="30";break;	//總倉轉銷貨
		case 3:pKind="10";break;	//總倉轉進退
//		case 4:pKind="20";break;	//門市轉出貨
//		case 5:pKind="10";break;	//總倉轉入庫
	}		
	SQLiteDatabase db = Utilis.getDB(QpandnF.this);
	//需事先檢查 是否有 qitems 存在 應該是錯誤而殘留的資料
	String SQLDEL="delete from qitems where FORMDATE='"+LIMITD[1]+"' and EMPID='PAN' and QKIND='"+pKind+"'";
	if (pMode==1) //20門市盤點 盤退
		db.execSQL(SQLDEL=SQLDEL+" and USER='"+WHO+"'" );
	else if (pMode==0) //31門市盤點 盤銷
		db.execSQL(SQLDEL=SQLDEL+" and DEPTNO='"+WHO+"'" );
	else if (pMode==2) //30總倉盤點 盤銷888
		db.execSQL(SQLDEL=SQLDEL+" and DEPTNO='"+WHO+"'" );
	else if (pMode==3) //10總倉盤點 盤退廠商
		db.execSQL(SQLDEL=SQLDEL+" and DEPTNO='"+WHO+"'" );

	//Cursor cs=null;
	StringBuffer SQLb=new StringBuffer();
	Cursor cursorx=null;
File fileQmtrio = new File(mDBPath);
	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);

	SQLb.append("select GOODSNO,UNITPRICE,DISCOUNT,EXPRICE,DATA,CDT,ID from qpandn where USER='"+WHO+"' and PNDNFKIND="+nDept );
	SQLb.append(" and PNDNADAY='"+LIMITD[1]+"' and ID>10");
	cursorx=mdb.rawQuery(SQLb.toString(),null);
	
Toast.makeText(QpandnF.this, WHO+" TOOT_REC!! ="+cursorx.getCount(), Toast.LENGTH_SHORT).show();
myDialog = ProgressDialog.show(QpandnF.this,"盤好過帳中.....","請稍候.............",true);//		setAutoRotationMode();

	if (cursorx.getCount()>0){
		cursorx.moveToFirst();
		int insertQitems=0;
		double tMoney=0;
		double tCost=0;
		double tExtPrice=0;
		int tTot=0;
		int tTotm=0;
		int tTotp=0;
		
		
		String msFno=deptStr[0]+deptStr[1]+pKind.substring(0,1)+DateUtil.getCurrentYearFormat1().substring(0, 2);
		String mFormno= getNFormno(msFno);
		
		String CDT=DateUtil.getSystemTime().substring(2,14);

		for (int ii=0;ii<cursorx.getCount();ii++){
			double uPrice=cursorx.getDouble(1);
			double uDisc=cursorx.getDouble(2);
			//專櫃盤銷 專櫃盤退 才用到 出貨歷史價
			if (pMode<2){//@@@如何拉出 出貨歷史價 出貨日期<=本盤日意義深
				Cursor csi= db.rawQuery("select UNITPRICE,DISCOUNT from qitems where GOODSNO='"+cursorx.getString(0)+"' and QKIND='20' and USER='"+WHO+"' and ISCONFIRM='Y' and FORMDATE<='"+LIMITD[1]+"' order by FORMDATE desc LIMIT 1",null);
				if (csi.getCount()>0){
					csi.moveToFirst();
					 uPrice=csi.getDouble(0);
					 uDisc=csi.getDouble(1);
				} csi.close();
			}
			
		StringBuffer mySqlBuf = new StringBuffer();
		mySqlBuf.append("select * from qdetail ");
		mySqlBuf.append(" where GOODSNO='"+cursorx.getString(0)+"'order by BATCH desc LIMIT 1");
		
		Cursor cs=db.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){
			cs.moveToFirst();
			String iSTATE=cs.getString(cs.getColumnIndex("STATE"));
			String iSUPPLY=cs.getString(cs.getColumnIndex("SUPPLY"));
			String iSOURCENO=cs.getString(cs.getColumnIndex("SOURCENO"));
			String iGOODSNO=cursorx.getString(0);
			String iGOODSNAME=cs.getString(cs.getColumnIndex("GOODSNAME"));
			String iCOLORNO=cs.getString(cs.getColumnIndex("COLORNO"));
			String iUNIT=cs.getString(cs.getColumnIndex("UNIT"));
			String iCOLOR=cs.getString(cs.getColumnIndex("COLOR"));
			String iSIZE=cs.getString(cs.getColumnIndex("SIZE"));
			String iPIC=cs.getString(cs.getColumnIndex("PIC"));
			String iSEASON=cs.getString(cs.getColumnIndex("SEASON"));
			String iBATCH=cs.getString(cs.getColumnIndex("BATCH"));
			String iYEAR=cs.getString(cs.getColumnIndex("UNIT2"));
			double iP0=cs.getDouble(cs.getColumnIndex("P0"));
			double iP1=cs.getDouble(cs.getColumnIndex("P1"));
			double iP2=cs.getDouble(cs.getColumnIndex("P2"));
			double iP3=cs.getDouble(cs.getColumnIndex("P3"));
			double iP4=cs.getDouble(cs.getColumnIndex("P4"));
			double iP5=cs.getDouble(cs.getColumnIndex("P5"));
			double iBILLRATE=cs.getDouble(cs.getColumnIndex("BILLRATE"));
			String iTYPE="";
			int gtype = cs.getInt(cs.getColumnIndex("GOODSTYPE"));  //代號需轉換為文字
        	int index = mTypeIdList.indexOf(gtype);
        	if(index >= 0) iTYPE=mTypeList.get(index);	
        	else iTYPE=cs.getString(cs.getColumnIndex("GOODSTYPE"));
        	
			String iCOUNTRY="";
        	int gcountry= cs.getInt(cs.getColumnIndex("COUNTRY"));   //代號需轉換為文字
			int cindex = mCountryIdList.indexOf(gcountry);
			if(cindex>=0)iCOUNTRY=mCountryList.get(cindex);
			else iCOUNTRY=cs.getString(cs.getColumnIndex("COUNTRY"));
			
			
			String FIELDA []=cursorx.getString(4).split("，");
			for (int ij=0;ij<FIELDA.length;ij++){
				String FIELDB []=FIELDA[ij].split(",");
				if ((Utilis.toInt(FIELDB[5])!=0 && pMode<=3) || (Utilis.toInt(FIELDB[4])!=0 && pMode>3) ){  //盤差<>0時
						ContentValues value = new ContentValues();
						value.put("TR",pKind);
						value.put("QKIND",pKind);
						value.put("ID",iSTATE);  //0正品 1實收價
						if (pMode==1 || pMode==3){
							value.put("DEPTNO",deptStr[5]);
							value.put("USER",WHO);
						}else if(pMode==0 || pMode==2){
							value.put("DEPTNO",WHO);
							value.put("USER","Z"+WHO);
//						}else if(pMode==4 || pMode==5){
//							value.put("DEPTNO",deptStr[5]);
//							value.put("USER",WHO);
						}
						value.put("USERNAME",mWhoName);
						value.put("SUPPLY",iSUPPLY);
						value.put("FORMDATE",LIMITD[1]);
						value.put("FORMNO",mFormno);
						value.put("CREATEDATETIME",CDT);
						value.put("ISCONFIRM","Y");
						value.put("ISCHECK","N");
						value.put("EMPID","PAN");																					
						value.put("EMPNAME","盤");
						value.put("TRADETYPE",""+nTradetype);
						value.put("SOURCENO",iSOURCENO);
						value.put("GOODSNO",iGOODSNO);
						value.put("GOODSTYPE",iTYPE);
						value.put("GOODSNAME",iGOODSNAME);
						value.put("UNIT2",iCOLORNO);
						double aCost=0;
						double aMoney=0;
						int UnitS=0;
						if (pMode==0 || pMode==2) UnitS=Utilis.toInt(FIELDB[5])*-1; 
						else if (pMode>=4) UnitS=Utilis.toInt(FIELDB[4]);
						else UnitS=Utilis.toInt(FIELDB[5]);
						
						if (UnitS<0) tTotp=tTotp-UnitS; else tTotm=tTotm-UnitS; 
						aMoney=Math.round(uPrice*uDisc*UnitS/100);
						aCost=UnitS*iP1;
						tMoney=tMoney+aMoney;
						tCost=tCost+aCost;
						
						value.put("UNITPRICE",uPrice);
						value.put("DISCOUNT",uDisc);
						value.put("ACOST",aCost );
						value.put("SUBPRICE", aMoney);
						
						switch (pMode){
						case 0:
							value.put("UNIT30",UnitS);
							value.put("UNIT10",0);
							value.put("UNIT20",0);
							break;
						case 1:
							value.put("UNIT20",UnitS);
							value.put("UNIT10",0);
							value.put("UNIT30",0);

							break;
						case 2:
							value.put("UNIT30",UnitS);
							value.put("UNIT10",0);
							value.put("UNIT20",0);

							break;
						case 3:
							value.put("UNIT10",UnitS);
							value.put("UNIT20",0);
							value.put("UNIT30",0);

							break;
						case 4:
							value.put("UNIT20",UnitS);
							value.put("UNIT10",0);
							value.put("UNIT30",0);

							break;
						case 5:
							value.put("UNIT10",Utilis.toInt(FIELDB[4]));
							value.put("UNIT20",0);
							value.put("UNIT30",0);

						}
						value.put("HANDNO","+1");
						value.put("UNIT",0);
						value.put("UNIT40",0);
						value.put("P0",iP0);
						value.put("P1",iP1);
						value.put("P2",iP2);
						value.put("P3",iP3);
						value.put("P4",iP4);
						value.put("P5",iP5);
						value.put("ORDDATE",iUNIT);
						value.put("FINEDATE","");
						value.put("RATE",iBILLRATE);		
						value.put("COLORS",iCOLOR);
						value.put("SIZES",iSIZE);
						value.put("PIC",iPIC);
						value.put("SEASON",iSEASON);
						value.put("BATCH",iBATCH);
						
						value.put("COUNTRY",iCOUNTRY);
						
						value.put("YEAR",iYEAR);
						//補價
						tExtPrice=tExtPrice+cursorx.getDouble(3);
						value.put("GOODSNOS",cursorx.getString(0)+"-"+FIELDB[0]+"-"+FIELDB[2]);
						value.put("COLOR",FIELDB[0]);
						value.put("SIZE",FIELDB[2]);
						value.put("UNIT1", FIELDB[1]);
						value.put("RATEPRICE",0);
						value.put("REALSUM",0);
						
						result = db.insert(TbName.QITEMS, null, value);
						insertQitems=1;
				}		
			}
		}
		cs.close();
		cursorx.moveToNext();
		}
		
		if ((tMoney!=0 || tCost!=0 || tTot!=0) && result>=0 && insertQitems==1){
		ContentValues value = new ContentValues();
		value.put("TR",pKind);
		value.put("QKIND",pKind);
		value.put("ID",pKind); 
		if (pMode==1 || pMode==3){
			value.put("DEPTNO",deptStr[5]);
			value.put("USER",WHO);
		}else if(pMode==0 || pMode==2){
			value.put("DEPTNO",WHO);
			value.put("USER","Z"+WHO);
//		}else if(pMode==4 || pMode==5){
//			value.put("DEPTNO",deptStr[5]);
//			value.put("USER",WHO);
		}
		value.put("USERNAME",mWhoName);
		value.put("FORMDATE",LIMITD[1]);
		value.put("FORMNO",mFormno);
		if (tTotm==0)
			value.put("HANDNO","+"+tTotp);
		else
			value.put("HANDNO","+"+tTotp+" "+tTotm);
			
		value.put("CREATEDATETIME",CDT);
		value.put("ISCONFIRM","Y");
		value.put("ISCHECK","N");
		value.put("EMPID","PAN");																					
		value.put("EMPNAME","盤");
		value.put("TRADETYPE",""+nTradetype);
		value.put("ATOT",(tTotp+tTotm));
		value.put("ASUM",tMoney);
		value.put("BSUM",tMoney);
		value.put("COSTS",tCost);
		value.put("CASH",0);
		value.put("CARD",0);
		value.put("ORDCASH",0);
		value.put("ORDCARD",0);
		value.put("TURESUM",0);
		value.put("DISMONEY",tExtPrice);
		value.put("BANKNO","1");
		value.put("BANKNAME",bankn);
		value.put("ATMDATE","");
		value.put("ATM",0);
		value.put("TRCASH",0);
		value.put("PS","");
		value.put("PS1","");
		value.put("PS2","");
		value.put("FINEDATE","");
		value.put("ORDDATE","");
		value.put("ISLIST","");
		value.put("BILLRATE",0);
		
		result = db.insert(TbName.QHEAD, null, value);
			Toast.makeText(QpandnF.this, WHO+" 盤點表已成功過帳!! ", Toast.LENGTH_SHORT).show();
		}else{//避免在已過帳盤表,存入一個空單號碼
			mFormno="";
		}

		//重新運算 ID=3 的各欄位
		int tSTKN=0;double tSTKM=0;
		int tPANN=0;double tPANM=0;
		int tDEFN=0;double tDEFM=0;
		Cursor csm=mdb.rawQuery(" select sum(ASTKN),sum(ASTKM),sum(APANN),sum(APANM),sum(ADEFN),sum(ADEFM) from qpandn where USER='"+WHO+"' and PNDNFKIND="+nDept+" and PNDNADAY='"+LIMITD[1]+"' and ID<>3 ",null);
		if (csm.getCount()>0){
			csm.moveToFirst();
			tSTKN=csm.getInt(0);
			tSTKM=csm.getDouble(1);
			tPANN=csm.getInt(2);
			tPANM=csm.getDouble(3);
			tDEFN=csm.getInt(2)-csm.getInt(0);
			tDEFM=csm.getDouble(3)-csm.getDouble(1);
		}
		csm.close();
		
		Toast.makeText(QpandnF.this, WHO+" 盤點表已成功過帳!! ", Toast.LENGTH_SHORT).show();
		mdb.execSQL("update qpandn set PNDNSTATE='2',TR='Y1',DEPTSNO='"+mFormno+"',BANKNAME='"+bankn+"',CDT='"+DateUtil.getSystemTime().substring(2, 14)+"',SDT='"+DateUtil.getSystemTime().substring(2, 14)+"' where USER='"+WHO+"' and PNDNFKIND="+nDept+" and PNDNADAY='"+LIMITD[1]+"'");
		SystemClock.sleep(2000);
		mdb.execSQL("update qpandn set ASTKN="+tSTKN+",ASTKM="+tSTKM+",APANN="+tPANN+",APANM="+tPANM+",ADEFN="+tDEFN+",ADEFM="+tDEFM+" where USER='"+WHO+"' and PNDNFKIND="+nDept+" and PNDNADAY='"+LIMITD[1]+"' and ID=3");
		

		//@@@保留雲端的傳送,予以手動傳送
		if (Utilis.haveInternet(QpandnF.this) && of_line==1) DBCloud.aa1_aa0_pan_update(QpandnF.this,WHO,LIMITD[1],bankn,nDept);
		if (Utilis.haveInternet(QpandnF.this) && of_line==1) DBCloud.aa1_aa0_update_HI(QpandnF.this);
		
	}
myDialog.dismiss();		
db.close();
mdb.close();
cursorx.close();

return result;
}

private String getNFormno(String formf){
	int flowNumber = 0;
	SQLiteDatabase db = Utilis.getDB(this);
	try{
		Cursor cursor = db.rawQuery("select FORMNO from " + TbName.QHEAD + " where FORMNO like '"+formf+"%' order by FORMNO DESC limit 1", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					flowNumber = Utilis.toInt(cursor.getString(cursor.getColumnIndex("FORMNO")).substring(formf.length()))+1;
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			cursor.close();
		}else{ //新的開始單號
			flowNumber=1;
		}
	}catch(Exception e){
		e.printStackTrace();
	}
	if(db != null){
		db.close();
	}
	return formf+Utilis.formatFlow(flowNumber);
}

//事先整理出產地國別	
	public void getCountryData(Context context){
		if(mCountryIdList != null){
			mCountryIdList.clear();
		}
		if(mCountryList != null){
			mCountryList.clear();
		}
		SQLiteDatabase dbs = Utilis.getDB(context);
		Cursor cursor = dbs.rawQuery("select NAME,_ID from qc_country order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));						
						String name = cursor.getString(cursor.getColumnIndex("NAME"));
						mCountryIdList.add(id);
						mCountryList.add(name);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		dbs.close();
		dbs = null;
	}
	
	// 取得類別資料
	public void getTypeData(Context context){
		if(mTypeList != null){
			mTypeList.clear();
		}
		if(mTypeIdList != null){
			mTypeIdList.clear();
		}
		SQLiteDatabase dbs = Utilis.getDB(context);
		Cursor cursor = dbs.rawQuery("select GOODTYPE,_ID from qc_type order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						String name = cursor.getString(cursor.getColumnIndex("GOODTYPE"));
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						mTypeList.add(name);
						mTypeIdList.add(id);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		dbs.close();
		dbs = null;
	}

	private void startIniDb(Context context){
		
		File fileQmtrio = new File(mDBPath);
      	SQLiteDatabase db_chk = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
		int exist_db=0;
		//第一段 無論如何 建立	TABLE  
		String SQL_INI="	CREATE TABLE  IF NOT EXISTS zpandn ("+ 
				"	    XID        int,"+
				"	    GOODSNO        VARCHAR( 20 ),"+
				"	    GOODSNAME      VARCHAR( 20 ),"+
				"	    P1             DOUBLE,"+
				"	    P2             DOUBLE,"+
				"	    P3             DOUBLE,"+
				"	    P4             DOUBLE,"+
				"	    P5             DOUBLE,"+
				"	    PIC            TEXT( 128 ),"+
				"	    COLORNO   VARCHAR( 8 ),"+
				"	    COLOR          VARCHAR( 8 ),"+
				"	    SIZE               VARCHAR( 6 ),"+
				"	    UNIT10         DOUBLE,"+
				"	    UNIT20         DOUBLE,"+
				"	    UNIT21         DOUBLE,"+
				"	    UNIT34         DOUBLE	); ";
		
		db_chk.execSQL(SQL_INI);

		SQL_INI="create index IF NOT EXISTS qmtrsG on qmtrs (GOODSNO)";
		db_chk.execSQL(SQL_INI);
		
		Cursor cs;
		cs=db_chk.rawQuery("select distinct XID from zpandn", null);
		if (cs.getCount()>0){
			db_chk.execSQL("delete from zpandn");
		}
		cs=db_chk.rawQuery("select distinct ID from qmtrs", null);
		if (cs.getCount()>0){
			db_chk.execSQL("delete from qmtrs");
		}
		cs.close();
		db_chk.close();
//	}
	
	//@@@改寫startIniDb 和 startDB 合併
	
//private void startDB(){
	if (Utilis.haveInternet(QpandnF.this) && of_line!=0){
		//基本條件mWho Ldate Ddate nDept QYEARS
		//門市盤點 則會帶回兩個 File 總倉 廠商 一個
		//再依著 mDept 判斷
		//Server
		//一樣的讀取 如下的結構
		//進一步以FTP檔案帶回,aa0_aa1_Qpandn_0.csv,aa0_aa1_Qpandn_1.csv 一一存入 zpandn
		//進一步以FTP檔案帶回,aa0_aa1_Qpandn_2.csv,aa0_aa1_Qpandn_31.csv 一一存入 qmtrs
		goCloud(1);	    		
	}else{//local read 
		File fileQmtrio1 = new File(mDBPath);
      	SQLiteDatabase pdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio1, null);
      	
    	String mDBPath1=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this,"SYS","YEAR",4);
    	pdb.execSQL("attach database ? as cwdb", new String[]{mDBPath1});
    	
		String SQL="insert into zpandn (XID,GOODSNO,"+
				"GOODSNAME,P1,P2,P3,P4,P5,"+
				"PIC,COLORNO,COLOR,SIZE,"+
				"UNIT10,UNIT20,UNIT21,UNIT34)"+
				" select 0,a.GOODSNO,"+
				"max(a.GOODSNAME),max(a.P1),max(a.P2),min(a.P3),max(a.P4),min(a.P5),"+
				"max(a.PIC),a.COLOR,a.UNIT1,a.SIZE,"+
				"sum(a.UNIT10),sum(a.UNIT20),0,sum(a.UNIT30+a.UNIT40)"+  
				" from cwdb.qitems as a";
			if (nDept==2)//廠商盤點@@@總倉與門市 運算不一樣
				SQL+=" where a.SUPPLY='"+mWho+"' and a.QKIND<>'21' and a.ISCONFIRM='Y'";
			else if (nDept==1)//門市盤點
				SQL+=" where a.DEPTNO='"+mWho+"' and a.QKIND<>'20'   and a.ISCONFIRM='Y'";
			else  //總倉
				SQL+=" where a.DEPTNO='"+mWho+"' and a.QKIND<>'21' and a.ISCONFIRM='Y'";
		
		SQL+=" and a.FORMDATE>'"+Ldate+"' and a.FORMDATE<='"+Ddate+"'"+
				" group by a.GOODSNO,a.COLOR,a.UNIT1,a.SIZE ";
				pdb.execSQL(SQL);
				SystemClock.sleep(1000);
				
		if (nDept==1){//門市盤點 才需要執行	
				SQL="insert into zpandn (XID,GOODSNO,GOODSNAME,P1,P2,P3,P4,P5,"+
						"PIC,COLORNO,COLOR,SIZE,UNIT10,UNIT20,UNIT21,UNIT34)"+
						" select 0,a.GOODSNO,"+
						"max(a.GOODSNAME),max(a.P1),max(a.P2),min(a.P3),max(a.P4),min(a.P5)" +
						",max(a.PIC),a.COLOR,a.UNIT1,a.SIZE,"+
						"0,0,sum(a.UNIT20),0 from cwdb.qitems as a"+
						" where a.USER ='"+mWho+"' and (a.QKIND='20' or a.QKIND='21')  and a.ISCONFIRM='Y'"+
						" and a.FORMDATE>'"+Ldate+"' and a.FORMDATE<='"+Ddate+"'"+
						" group by a.GOODSNO,a.COLOR,a.UNIT1,a.SIZE";
						pdb.execSQL(SQL);
		}
		//qmtrs 存入上存實際數據 而非 上次盤表的紀錄
		if (!Ldate.equalsIgnoreCase("2012-03-14")){
		
			SQL="insert into qmtrs (GOODSNO,ID)"+
					" select a.GOODSNOS,"+"sum(a.UNIT10)-sum(a.UNIT20)-sum(a.UNIT30)-sum(a.UNIT40)"+  
					" from cwdb.qitems as a";
				if (nDept==2)//廠商
					SQL+=" where a.SUPPLY='"+mWho+"' and a.QKIND<>'21' and a.ISCONFIRM='Y'";
				else if (nDept==1)//門市
					SQL+=" where a.DEPTNO='"+mWho+"' and a.ISCONFIRM='Y'";
				else  //總倉
					SQL+=" where a.DEPTNO='"+mWho+"' and a.QKIND<>'21' and a.ISCONFIRM='Y'";
			
			SQL+=" and a.FORMDATE<='"+Ldate+"' group by a.GOODSNOS ";
					pdb.execSQL(SQL);
					SystemClock.sleep(1000);
					
			if (nDept==1){//門市盤點 才需要執行	
					SQL="insert into qmtrs (GOODSNO,ID)"+
							" select a.GOODSNOS,sum(a.UNIT20) from cwdb.qitems as a"+
							" where a.USER ='"+mWho+"' and (a.QKIND='20' or a.QKIND='21')  and a.ISCONFIRM='Y'"+
							" and a.FORMDATE<='"+Ldate+"'"+
							" group by a.GOODSNOS";
							pdb.execSQL(SQL);
			}
		}
		
		pdb.close();
		getStart();
	}
}

private void goDelQhead(String Formno){
	SQLiteDatabase db = Utilis.getDB(QpandnF.this);		   	        		  
	db.execSQL("delete from qitems where FORMNO='" + Formno+"' and EMPID='PAN'" );
	String delKind="10";
	Cursor csH = db.rawQuery("select TR,QKIND from qhead where FORMNO='" + Formno+"' and EMPID='PAN'", null);
	if (csH.getCount()>0){
		csH.moveToFirst();
		delKind=csH.getString(1);
		if (of_line==0) {
			db.execSQL("delete from qhead where FORMNO='" + Formno+"' and EMPID='PAN'" );
			Toast.makeText(QpandnF.this, "刪除資料成功", Toast.LENGTH_SHORT).show();
		} else {
			db.execSQL("update qhead set TR='Y2',ID='1008',QKIND='"+delKind.substring(0, 1)+"2', CREATEDATETIME='"+DateUtil.getSystemTime().substring(2, 14)+"',ISCONFIRM='N',ISCHECK='N',BANKNAME='"+bankn+"' where FORMNO='" + Formno+"' and EMPID='PAN'" );
			if (Utilis.haveInternet(QpandnF.this) && of_line==1 ) {
				DBCloud.aa1_aa0_update_HI(QpandnF.this);
			}
			Toast.makeText(QpandnF.this, "刪除資料且製作Y2成功", Toast.LENGTH_SHORT).show();
			//@@cloud_update
		}
	}
	csH.close();
	db.close();
}

private void goCloud(int nMode){
	//0	1	2	345
StringBuffer bfstr = new StringBuffer();
StringBuffer bfstrF = new StringBuffer();
//myDialog = new ProgressDialog(this);
//myDialog.setCancelable(true);
//myDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//myDialog.setMessage(nMode+"__"+"資料處理中...請稍候...");			
//myDialog.show();
//myDialog = ProgressDialog.show(QpandnF.this,nMode+"__"+"資料處理中...","請稍候...",true);

		bfstr.append(importStr[1]).append(";");	//do it
		bfstrF.append("UID").append(";");
		bfstr.append(mWho).append(";");  //do it 
		bfstrF.append("WHO").append(";"); 
		bfstr.append(bankn).append(";"); 
		bfstrF.append("MDEPT").append(";"); 
		bfstr.append(nDept).append(";");	//do it 
		bfstrF.append("NDEPT").append(";"); 
		bfstr.append(Ldate).append(";"); 
		bfstrF.append("LDATE").append(";"); 
		bfstr.append(Ddate).append(";"); 
		bfstrF.append("DDATE").append(";"); 
		bfstr.append(nMode).append(";");	//取得上存盤點日件數
		bfstrF.append("MODE").append(";"); 
		bfstr.append(nTradetype).append(";"); 
		bfstrF.append("TRADETYPE").append(";"); 
		bfstr.append(nDiscount).append(";"); 
		bfstrF.append("DISCOUNT").append(";"); 
		bfstr.append(Utilis.getIni(QpandnF.this, "SYS", "YEAR", 1)+Utilis.getIni(QpandnF.this, "SYS", "YEAR", 2));
		bfstrF.append("QYEARS");	//do it
		final String []fields=bfstr.toString().split(";");
		final String []fieldFs=bfstrF.toString().split(";");
		  
      new Thread()
      { 
        public void run()
        { 
          try
          { 
				HttpPost httpRequest = new HttpPost(uriAPI1);
				Log.i("DOWNLOAD_2", "取得上存的數據"+uriAPI1);
				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());
						mHandlerQpandnf.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
					}
				} catch (Exception e)
				{
					e.printStackTrace();
				}
          }
          catch (Exception e)
          {
            e.printStackTrace();
          }
          finally
          {
            // 卸載所建立的myDialog物件。
      		//myDialog.dismiss();		
          }
        }
      }.start();
      

}

Handler mHandlerQpandnfReport = new Handler()
{
	@Override
	public  void handleMessage(Message msg)
	{
		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_gpandn")>2){
					Log.i("DOWNLOAD_5_mHandlerQC===", ""+Hresult);						
					String rData[]=Hresult.split("SSSS\r\n");
					String  FileH=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this, "SYS", "YEAR",7)+File.separator+"AA0_"+mWho+"_pandnfreport.csv";
					final File localFileH = new File(FileH);
					final String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		        	boolean success=false;
					try {
						success=DBCloud.ftpDownloadAndSaveFile(QpandnF.this,importStr[0], 21,importStr[3], importStr[4], serverFileH, localFileH);												
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			          finally
			        {
				     try{
			        	  if (success){ //表示已存入LOCAL端
			        		  if (localFileH.exists()){  //檔案存在
		        				sPrintB = new StringBuffer();
		        				String theData[]=rData[1].split(";");
		        				String aWhoName=theData[0];
		        				int aLastStkN=Utilis.toInt(theData[1]);
		        				Double aLastStkM=Utilis.toDouble(theData[2]);
		        				int aAinN=Utilis.toInt(theData[3]);
		        				Double aAinM=Utilis.toDouble(theData[4]);
		        				int aAstkN=Utilis.toInt(theData[5]);
		        				Double aAstkM=Utilis.toDouble(theData[6]);
		        				int aAstN=Utilis.toInt(theData[7]);
		        				Double aAstM=Utilis.toDouble(theData[8]);
		        				int aAdefN=Utilis.toInt(theData[9])*-1;
		        				Double aAdefM=Utilis.toDouble(theData[10])*-1;
		        				//1,2,3,4,5,6,7應盤件數,8應盤金額
		    					sPrintB.append(mWho+"/"+aWhoName+",自上期盤點:"+Ldate+",後,,,,,到"+Ddate+",為止的盤點清冊,\r\n");					
		    					sPrintB.append("[顏色] 貨品編號,貨品名稱,應存,盤存,單價,折數,,[顏色] 貨品編號,貨品名稱,應存,盤存,單價,折數,\r\n");

		        				int totItems=0;
		      					String encodout = "UTF8";
								StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
								FileInputStream fis = new FileInputStream(localFileH);
								InputStreamReader isr = new InputStreamReader(fis, encodout);
								Reader in = new BufferedReader(isr);
								int ch;
								while ((ch = in.read()) > -1) {
									buffers.append((char)ch);
									if(buffers.toString().indexOf("\r\n")>0){
										String fields=buffers.toString().substring(0,buffers.toString().length()-2);

										String[] arrayField = fields.split(";");
										//已經分解到每一筆的每個欄位
										String[] aData=arrayField[2].split("，");
										
										for (int ii=0;ii<aData.length;ii++){
										  if (aData[ii].length()>10){	
											String [] dataD=aData[ii].split(",");
											if (Utilis.toInt(dataD[6])!=0){
												//有盤點資料
												String Goodss=arrayField[0]+"-"+dataD[0]+"-"+dataD[2];
												totItems+=1;
												sPrintB.append("["+dataD[1]+"] "+Goodss+",").append(arrayField[1]+",").append(dataD[6]+",");
												sPrintB.append(dataD[4]+","); 
												sPrintB.append(arrayField[3]+",");
												//存放[貨品明細編號][應盤件數][單價][%]  製作報表的功能
												sPrintB.append(""+Utilis.toInt(arrayField[4])+",,");
												if ((totItems) %2==0)sPrintB.append("\r\n"); 
											}
										  }	
										}
										buffers.delete(0, buffers.toString().length()	);	
									}
								}
								in.close();  //
								sPrintB.append("\r\n");
								sPrintB.append("\r\n");
								sPrintB.append("\r\n");
								//數據表
								sPrintB.append("上期盤存量,"+aLastStkN+",,,,,,上期盤存小計,"+aLastStkM+",\r\n");
								sPrintB.append("本期進退量,"+aAinN+",,,,,,本期進退小計,"+aAinM+",\r\n");
								sPrintB.append("本期已銷量,"+aAstN+",,,,,,本期已銷小計,"+aAstM+",\r\n");
								sPrintB.append("本期應盤量,"+aAstkN+",,,,,,本期應盤小計,"+aAstkM+",\r\n");
								
				        		try {
				                    Writer out = new BufferedWriter(new OutputStreamWriter(
				                    	    new FileOutputStream(myFilePath), "UTF-8"));
				                    	try {
				                    	    out.write(sPrintB.toString());
				                    	} finally {
				                    	    out.close();
				                    	}                    
				        		} catch (Exception e) {

				        		}
				        		
				    			//進一步輸出,多媒體選擇
				    	    	Intent send = new Intent(Intent.ACTION_SEND);
				    	    	send.setType("image/jpeg");
				    		    String uriText;
				    		    Uri U=Uri.parse("file://"+myFilePath);  //重要的範例
				    		    uriText = "https://www.google.com/cloudprint/addpublicprinter.html?printerid=bb160853-6274-0f65-eb1f-34ae2c9ed6e1&key=19901109";
				    		    send.putExtra(Intent.ACTION_SENDTO,uriText);
				    		    send.putExtra(Intent.EXTRA_STREAM,U);
				    		    startActivity(Intent.createChooser(send, uriText));
			        		  }
			        	  }
			        	} catch (Exception e) {
			        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
			        		success=false;
			        	}
			        }
				}
			}
		}
	}
};

Handler mHandlerQpandnf = new Handler()
{
	@SuppressWarnings("resource")
	@Override
	public  void handleMessage(Message msg)
	{
		String Hresult=null;
		switch (msg.what)
		{
		// 顯示網路上抓取的資料
		case REFRESH_DATA:
			if (msg.obj instanceof String) 
				Hresult = (String) msg.obj;

			if (Hresult != null ){
				if (Hresult.indexOf("_okok")>2){
					//mode==1
					if (mAdapter.mList != null) {
						mAdapter.mList.clear();
					}
					//開始以FTP 接收 csv
					Log.i("DOWNLOAD_5", "取得本期的zpndnf交易資料"+Hresult);
					String  FileH=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this, "SYS", "YEAR",7)+File.separator+"AA0_"+bankn+"_Qpandn_0.csv";
					
					final File localFileH = new File(FileH);
					final String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		        	boolean success=false;
					try {
						success=DBCloud.ftpDownloadAndSaveFile(QpandnF.this,importStr[0], 21,importStr[3], importStr[4], serverFileH, localFileH);												
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			          finally
			        {
				     try{
			        	  if (success){ //表示已存入LOCAL端

			        		  if (localFileH.exists()){  //檔案存在
									String puts[]={"XID","GOODSNO","GOODSNAME","P1","P2","P3","P4","P5","PIC","COLORNO","COLOR","SIZE","UNIT10","UNIT20","UNIT21","UNIT34"};
									File fileQmtrio = new File(mDBPath);
							      	SQLiteDatabase pdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
							      	
			      					String encodout = "UTF8";
									StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
									FileInputStream fis = new FileInputStream(localFileH);
									InputStreamReader isr = new InputStreamReader(fis, encodout);
									Reader in = new BufferedReader(isr);
									int ch;
									pdb.beginTransaction();
							      	try{	
							      	
										while ((ch = in.read()) > -1) {
												buffers.append((char)ch);
											if(buffers.toString().indexOf("SSSS\r\n")>0){
												String fields=buffers.toString().substring(0,buffers.toString().length()-2);
												String[] arrayField = fields.toString().split(";");
												//insert into zpandn
												ContentValues value = new ContentValues();
												for (int ii=0;ii<puts.length;ii++)	value.put(puts[ii], arrayField[ii]);
												pdb.insert("zpandn", null, value);
												
												buffers.delete(0, buffers.toString().length());
											}
											
									}
									in.close();  //
									pdb.setTransactionSuccessful();
							      	} finally {
							      		pdb.endTransaction();
							      		pdb.close();
							      	}
									
			        		  }
			        	  }
			        	} catch (Exception e) {
			        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
			        		success=false;
			        	}
			        }
					
				if (nDept==1) {//門市版才需要跑這一趟	
					 String FileH1=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this, "SYS", "YEAR",7)+File.separator+"AA0_"+bankn+"_Qpandn_1.csv";
					
					File localFileH1 = new File(FileH1);
					String serverFileH1 =FileH1.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		        	success=false;
					try {
						success=DBCloud.ftpDownloadAndSaveFile(QpandnF.this,importStr[0], 21,importStr[3], importStr[4], serverFileH1, localFileH1);												
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			          finally
			        {
				     try{
			        	  if (success){ //表示已存入LOCAL端

			        		  if (localFileH1.exists()){  //檔案存在
									String puts[]={"XID","GOODSNO","GOODSNAME","P1","P2","P3","P4","P5","PIC","COLORNO","COLOR","SIZE","UNIT10","UNIT20","UNIT21","UNIT34"};
									File fileQmtrio = new File(mDBPath);
							      	SQLiteDatabase pdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
							      	
			      					String encodout = "UTF8";
									StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
									FileInputStream fis = new FileInputStream(localFileH1);
									InputStreamReader isr = new InputStreamReader(fis, encodout);
									Reader in = new BufferedReader(isr);
									int ch;
									pdb.beginTransaction();
							      	try{	
							      	
										while ((ch = in.read()) > -1) {
												buffers.append((char)ch);
											if(buffers.toString().indexOf("SSSS\r\n")>0){
												String fields=buffers.toString().substring(0,buffers.toString().length()-2);
												String[] arrayField = fields.toString().split(";");
												//insert into zpandn
												ContentValues value = new ContentValues();
												for (int ii=0;ii<puts.length;ii++)	value.put(puts[ii], arrayField[ii]);
												pdb.insert("zpandn", null, value);
												
												buffers.delete(0, buffers.toString().length());
											}
										}
									in.close();  //
									pdb.setTransactionSuccessful();
							      	} finally {
							      		pdb.endTransaction();
							      		pdb.close();
							      	}
									
			        		  }
			        	  }
			        	} catch (Exception e) {
			        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
			        		success=false;
			        	}
			        }
				}

			if (!Ldate.equalsIgnoreCase("2012-03-14")){
				
				//開始以FTP 接收 第二組csv 
				Log.i("DOWNLOAD_5", "取得本期的zpndnf上存"+Hresult);
				 String FileHm=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this, "SYS", "YEAR",7)+File.separator+"AA0_"+bankn+"_Qpandn_2.csv";
				
				final File localFile = new File(FileHm);
				final String serverFile =FileHm.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
	        	success=false;
				try {
					success=DBCloud.ftpDownloadAndSaveFile(QpandnF.this,importStr[0], 21,importStr[3], importStr[4], serverFile, localFile);												
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		          finally
		        {
			     try{
		        	  if (success){ //表示已存入LOCAL端

		        		  if (localFile.exists()){  //檔案存在
								String puts[]={"GOODSNO","ID"};
								File fileQmtrio = new File(mDBPath);
						      	SQLiteDatabase pdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
						      	
		      					String encodout = "UTF8";
								StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
								FileInputStream fis = new FileInputStream(localFile);
								InputStreamReader isr = new InputStreamReader(fis, encodout);
								Reader in = new BufferedReader(isr);
								int ch;
								pdb.beginTransaction();
						      	try{	
						      	
									while ((ch = in.read()) > -1) {
											buffers.append((char)ch);
										if(buffers.toString().indexOf("SSSS\r\n")>0){
											String fields=buffers.toString().substring(0,buffers.toString().length()-2);
											String[] arrayField = fields.toString().split(";");
											//insert into qmtrs
											ContentValues value = new ContentValues();
											for (int ii=0;ii<puts.length;ii++)	value.put(puts[ii], arrayField[ii]);
											pdb.insert("qmtrs", null, value);
											
											buffers.delete(0, buffers.toString().length());
										}
										
								}
								in.close();  //
								pdb.setTransactionSuccessful();
						      	} finally {
						      		pdb.endTransaction();
						      		pdb.close();
						      	}
								
		        		  }
		        	  }
		        	} catch (Exception e) {
		        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
		        		success=false;
		        	}
		        }
				
			if (nDept==1) {//門市版才需要跑這一趟	
				 String FileHm1=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this, "SYS", "YEAR",7)+File.separator+"AA0_"+bankn+"_Qpandn_3.csv";
				
				File localFileH1 = new File(FileHm1);
				String serverFileH1 =FileHm1.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
	        	success=false;
				try {
					success=DBCloud.ftpDownloadAndSaveFile(QpandnF.this,importStr[0], 21,importStr[3], importStr[4], serverFileH1, localFileH1);												
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		          finally
		        {
			     try{
		        	  if (success){ //表示已存入LOCAL端

		        		  if (localFileH1.exists()){  //檔案存在
								String puts[]={"GOODSNO","ID"};
								File fileQmtrio = new File(mDBPath);
						      	SQLiteDatabase pdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
						      	
		      					String encodout = "UTF8";
								StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
								FileInputStream fis = new FileInputStream(localFileH1);
								InputStreamReader isr = new InputStreamReader(fis, encodout);
								Reader in = new BufferedReader(isr);
								int ch;
								pdb.beginTransaction();
						      	try{	
						      	
									while ((ch = in.read()) > -1) {
											buffers.append((char)ch);
										if(buffers.toString().indexOf("SSSS\r\n")>0){
											String fields=buffers.toString().substring(0,buffers.toString().length()-2);
											String[] arrayField = fields.toString().split(";");
											//insert into qmtrs
											ContentValues value = new ContentValues();
											for (int ii=0;ii<puts.length;ii++)	value.put(puts[ii], arrayField[ii]);
											pdb.insert("qmtrs", null, value);
											
											buffers.delete(0, buffers.toString().length());
										}
									}
								in.close();  //
								pdb.setTransactionSuccessful();
						      	} finally {
						      		pdb.endTransaction();
						      		pdb.close();
						      	}
								
		        		  }
		        	  }
		        	} catch (Exception e) {
		        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
		        		success=false;
		        	}
		        }
			}
			}//end of reset laststk with qmtrs, Because First Pandn. 	
				getStart();
				}else if (Hresult.indexOf("oktitle;")>0){
					//mode==0
					Log.i("DOWNLOAD_5", "取得上存的盤點日期及件數金額"+Hresult);
					String Lines [] = Hresult.split(";");
					mBTain.setText(Lines [1]);
					mBTaim.setText(Lines [2]);
					mBTastn.setText(Lines [5]);
					mBTastm.setText(Lines [6]);
					mBTastkn.setText(""+(cLstkn+Utilis.toInt(Lines [7])));
					mBTastkm.setText(""+(cLstkm+Utilis.toInt(Lines [8])));

					mBTaadn.setText(Lines [3]);
					mBTaadm.setText(Lines [4]);
				}else if (Hresult.indexOf("oklastvalue")>0){
					//mode==2
					Log.i("DOWNLOAD_5", "本期的盤點各數據,顯示在一樓_再加上存_"+Hresult);
					if (Hresult.indexOf("oklastvalue1;")>0){
						String Lines [] = Hresult.split(";");
		      			cLstkn=Utilis.toInt(Lines[2]);tLastStkn=cLstkn;
		      			cLstkm=Utilis.toInt(Lines[3]);tLastStkm=cLstkm;
		      			nSuccess=1;  //表示可新增的盤點清冊
		      			Ldate=Lines[1];
		      			isNew=false;
					}else if (Hresult.indexOf("oklastvalue0;")>0){
		      			isNew=true;
			      		Ldate="2012-03-14";
		      			nSuccess=1;
		      			cLstkn=0;tLastStkn=cLstkn;
		      			cLstkm=0;tLastStkm=cLstkm;
		      			Toast.makeText(QpandnF.this, "新增盤表:", Toast.LENGTH_SHORT).show();
					}
	      			((Button)findViewById(R.id.btn_lstkn)).setText(""+tLastStkn);	
	      			((Button)findViewById(R.id.btn_lstkm)).setText(""+tLastStkm);
					
		  			String day = Utilis.getMonthDate();
		  			day=day.replace("/", "-");
					String[] days = day.split("~");
		    		Ddate = days[1];
		    		DateUtil.addMonth(Ddate, -1);
		  			((Button)findViewById(R.id.btn_lpndn)).setText(Ldate);
		  			((Button)findViewById(R.id.btn_dpndn)).setText(Ddate);      			
		      		if (nSuccess==0 && isNew==false){
		      			((TextView)findViewById(R.id.pndn_title)).setText(mKind[nDept]+"庫存盤點清冊[失敗]");
		      		}else{
		      			((TextView)findViewById(R.id.pndn_title)).setText(mKind[nDept]+"盤點清冊"+mState[nState]);      			
		      		}
    				reCountBG();
				}else if (Hresult.indexOf("getvalue")>0){
					//mode==3
					Log.i("DOWNLOAD_5", "取得上期末轉入本期"+Hresult);
      			  	nID=10;
					String FileH1=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this, "SYS", "YEAR",7)+File.separator+"AA0_"+bankn+"_Qpandn.csv";
					File localFileH1 = new File(FileH1);
					String serverFileH1 =FileH1.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		        	boolean success=false;
					try {
						success=DBCloud.ftpDownloadAndSaveFile(QpandnF.this,importStr[0], 21,importStr[3], importStr[4], serverFileH1, localFileH1);												
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			          finally
			        {
	        			  nID=10;
		        		  if (localFileH1.exists()){  //檔案存在
		        			  putData(localFileH1);	        			  
		        		  }else{
					      		startIniDb(QpandnF.this);
					      		//startDB();
		        		  }
			        }
				}else if (Hresult.indexOf("geteachmax")>0){
					Log.i("DOWNLOAD_5", "取得已過帳盤點清單頭"+Hresult);
					//mode==5
					String FileH1=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this, "SYS", "YEAR",7)+File.separator+"AA0_"+bankn+"_Qpandneach.csv";
					File localFileH1 = new File(FileH1);
					String serverFileH1 =FileH1.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		        	boolean success=false;
					try {
						success=DBCloud.ftpDownloadAndSaveFile(QpandnF.this,importStr[0], 21,importStr[3], importStr[4], serverFileH1, localFileH1);												
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			          finally
			        {
			  			String encodout = "UTF8";
						StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
						FileInputStream fis;
						try {
						fis = new FileInputStream(localFileH1);
						InputStreamReader isr;
							try {
				    		SQLiteDatabase db = Utilis.getDB(QpandnF.this);
							isr = new InputStreamReader(fis, encodout);
							Reader in = new BufferedReader(isr);
							int ch;
								while ((ch = in.read()) > -1) {
								buffers.append((char)ch);
									if(buffers.toString().indexOf("SSSS\r\n")>0){
										String fields=buffers.toString().substring(0,buffers.toString().length()-2);
										String[] arrayField = fields.toString().split(";");
										
										RepDataPan data = new RepDataPan();
										Cursor cs;
										data.iPic=SD_PATH+File.separator+"cwbuyer/para/04.jpg";
											if (nDept==2){
												cs=db.rawQuery("select PIC from qfact where FACTNO='"+arrayField[0]+"'",null);
											} else {
												cs=db.rawQuery("select PIC from qcust where CUSTNO='"+arrayField[0]+"'",null);
											}
											if (cs.getCount()>0){
												cs.moveToFirst();
												data.iPic=cs.getString(0);
											}
										cs.close();
										data.iGoods=arrayField[0]+"/"+arrayField[1];  //代號_名稱
										data.iName=arrayField[3]+"~"+arrayField[2]; //上盤日期~本盤日期
										data.iNumber="補價:"+arrayField[12]; //補價
										data.iCountry="本銷:"+arrayField[6]+"/"+arrayField[7];  //本銷
										data.iImpo="應盤"+arrayField[4]+"/"+arrayField[5];  //本存
										data.iMoney="已盤:"+arrayField[8]+"/"+arrayField[9];  //本盤
										data.iCompany="盤差:"+arrayField[10]+"/"+arrayField[11];  //盤差
										data.iFormdate=arrayField[0];  //盤點對象代號
										data.iFormno=arrayField[14]; //已過帳的Qhead單號
										mAdapter.mList.add(data);
										buffers.delete(0, buffers.toString().length());
									}
								}
								db.close();
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							}
						} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						} finally{
							nCondition=2;	setCondition();  //
							nState=2;
							mAdapter.notifyDataSetChanged();        
						}
			        }					
				}else if (Hresult.indexOf("getdetail")>0){
					Log.i("DOWNLOAD_6", "取得已過帳盤點明細"+Hresult);
					//mode==6  Qpandndetail.csv
					if (mAdapter.mList != null) mAdapter.mList.clear();
					String FileH1=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this, "SYS", "YEAR",7)+File.separator+"AA0_"+bankn+"_Qpandndetail.csv";
					File localFileH1 = new File(FileH1);
					String serverFileH1 =FileH1.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		        	boolean success=false;
					try {
						success=DBCloud.ftpDownloadAndSaveFile(QpandnF.this,importStr[0], 21,importStr[3], importStr[4], serverFileH1, localFileH1);												
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			          finally
			        {
			  			String encodout = "UTF8";
						StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
						FileInputStream fis;
						try {
						fis = new FileInputStream(localFileH1);
						InputStreamReader isr;
							try {
				    		//SQLiteDatabase db = Utilis.getDB(QpandnF.this);
							isr = new InputStreamReader(fis, encodout);
							Reader in = new BufferedReader(isr);
							int ch;
								while ((ch = in.read()) > -1) {
								buffers.append((char)ch);
								if(buffers.toString().indexOf("SSSS\r\n")>0){
									String fields=buffers.toString().substring(0,buffers.toString().length()-2);
									String[] arrayField = fields.toString().split(";");
									RepDataPan data = new RepDataPan();
									//@@@引導真正的圖檔路徑
									data.iPic=arrayField[11];
									data.iGoods=arrayField[18];  //櫃位 
									data.iName=arrayField[9]+"/"+arrayField[10];  
									data.iCountry="單價:"+arrayField[12];
									data.iNumber="補價:"+arrayField[15];
									data.iImpo="應盤"+arrayField[27]+"/"+arrayField[28];  //本存
									data.iMoney="已盤:"+arrayField[29]+"/"+arrayField[30]; //本盤
									data.iCompany="盤差:"+arrayField[31]+"/"+arrayField[32];//盤差
									data.iFormdate=arrayField[9];  //盤點對象代號
									data.iFormno=arrayField[19];
									data.iUnit2=arrayField[16];	//DATA
									mAdapter.mList.add(data);
									buffers.delete(0, buffers.toString().length());
								}
								}
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							}
					} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					} finally{
						nCondition=3;	setCondition();  //
						mAdapter.notifyDataSetChanged();        
					}
			        }
				}else if (Hresult.indexOf(";SETPAGE")>0){
				//mode=7 專櫃請款單
					Log.i("DOWNLOAD_7", "取得本期的請款"+Hresult);
					qadff(Hresult,0);
				}else if (Hresult.indexOf("pandel_ok")>0){
					//mode=8 已過帳的盤表,刪除後 應將該 已過帳的單據 刪除
					if (!mFormno.equalsIgnoreCase("FORMNO")) goDelQhead(mFormno);					
				}else if (Hresult.indexOf("getpanedok")>0){
					//mode=10 取消過帳SERVER 的程序
					//表示SERVER已做好_Qpandndetail.csv
					//需取回
					Log.i("DOWNLOAD_5", "取得SERVER一份已過帳qpndnf資料,轉存入LOCAL"+Hresult);
					String  FileH=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QpandnF.this, "SYS", "YEAR",7)+File.separator+"AA0_"+bankn+"_Qpandndetail.csv";
					
					final File localFileH = new File(FileH);
					final String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		        	boolean success=false;
					try {
						success=DBCloud.ftpDownloadAndSaveFile(QpandnF.this,importStr[0], 21,importStr[3], importStr[4], serverFileH, localFileH);												
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			          finally
			        {
				     try{
			        	  if (success){ //表示已存入LOCAL端

			        		  if (localFileH.exists()){  //檔案存在
									String puts[]={"PNDNFKIND","PNDNPKIND","PNDNCKIND","PNDNSTATE","ID","USER","USERNAME","PNDNADAY","PNDNBDAY","GOODSNO",
								    "GOODSNAME","PIC","UNITPRICE","DISCOUNT","ACOST","EXPRICE","DATA","DATA0","PNDNDD","DEPTSNO",
									"PARTSNO","LASTSTKN","LASTSTKM","AINN","AINM","ASTN","ASTM","ASTKN","ASTKM","APANN",
									"APANM","ADEFN","ADEFM","CDT","APIN","SDT","BANKNAME","TR"};
									File fileQmtrio = new File(mDBPath);
							      	SQLiteDatabase pdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
							      	
			      					String encodout = "UTF8";
									StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
									FileInputStream fis = new FileInputStream(localFileH);
									InputStreamReader isr = new InputStreamReader(fis, encodout);
									Reader in = new BufferedReader(isr);
									int ch;
									pdb.beginTransaction();
							      	try{	
							      	
										while ((ch = in.read()) > -1) {
												buffers.append((char)ch);
											if(buffers.toString().indexOf("SSSS\r\n")>0){
												String fields=buffers.toString().substring(0,buffers.toString().length()-2);
												String[] arrayField = fields.toString().split(";");
												//@@@[11]PIC
												if (arrayField[11].indexOf("/cwbuyer/")>0){
													String chg=arrayField[11].replace(arrayField[11].substring(0, arrayField[11].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
													arrayField[11]=chg;
												}
												arrayField[3]="0";//將已過帳改為未過帳

												ContentValues value = new ContentValues();
												for (int ii=0;ii<puts.length;ii++)	value.put(puts[ii], arrayField[ii]);
												pdb.insert("qpandn", null, value);
												//從SERVER存入LOCAL
												
												buffers.delete(0, buffers.toString().length());
											}
											
									}
									in.close();  //
									pdb.setTransactionSuccessful();
							      	} finally {
							      		pdb.endTransaction();
							      		pdb.close();
										if (!mFormno.equalsIgnoreCase("FORMNO")) goDelQhead(mFormno);					
										SystemClock.sleep(3000);
										
										goCloud(8);
										
										nState=1;
										nCondition=2;	setCondition();								
										getGroupData(QpandnF.this, "", nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
										mAdapter.notifyDataSetChanged();        
							      	}
									
			        		  }
			        	  }
			        	} catch (Exception e) {
			        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
			        		success=false;
			        	}
			        }
					
				}
			}
		}
//  		myDialog.dismiss();		
	}
};

	private void putData(File localFileH1){
			String sepa=",";
			String sepaE="，";
			nID=10;
		String puts[]={"PNDNFKIND","PNDNPKIND","PNDNCKIND","PNDNSTATE","ID","USER","USERNAME","PNDNADAY","PNDNBDAY","GOODSNO",
				    "GOODSNAME","PIC","UNITPRICE","DISCOUNT","ACOST","EXPRICE","DATA","DATA0","PNDNDD","DEPTSNO",
						"PARTSNO","LASTSTKN","LASTSTKM","AINN","AINM","ASTN","ASTM","ASTKN","ASTKM","APANN",
						"APANM","ADEFN","ADEFM","CDT","APIN","SDT","BANKNAME","TR" 
		};
			File fileQmtrio = new File(mDBPath);
			SQLiteDatabase pdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
			
			String encodout = "UTF8";
			StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
			FileInputStream fis;
			try {
			fis = new FileInputStream(localFileH1);
			InputStreamReader isr;
				try {
				isr = new InputStreamReader(fis, encodout);
				Reader in = new BufferedReader(isr);
				int ch;
					while ((ch = in.read()) > -1) {
					buffers.append((char)ch);
						if(buffers.toString().indexOf("SSSS\r\n")>0){
							String fields=buffers.toString().substring(0,buffers.toString().length()-2);
							String[] arrayField = fields.toString().split(";");
							ContentValues valueI = new ContentValues();
							nID+=1;
							String buf=arrayField[16];
							String [] fieldA=buf.split(sepaE); //各色尺寸
							buf="";
							
							for (int ij=0;ij<fieldA.length;ij++){//
							String [] fieldB=fieldA[ij].split(sepa); //各欄位
							fieldB[10]=fieldB[4]; //上存=本盤
							fieldB[6]=fieldB[4]; //本存
							fieldB[5]=""+(Utilis.toInt(fieldB[4])*-1);//即時放入盤差
							StringBuffer nBufB=new StringBuffer();
							for (int k=0;k<10;k++){
							if (k>2 && k!=5 && k!=6 ) fieldB[k]="0";
							nBufB.append(fieldB[k]+sepa);
							}
							nBufB.append(fieldB[10]);
							
							fieldA[ij]=nBufB.toString();
							buf=buf+fieldA[ij]+sepaE;	
							}
							arrayField[16]=buf;
							
							arrayField[3]="0";
							arrayField[4]=""+nID;
							arrayField[7]=Ddate;
							arrayField[8]=Ldate;
							//@@@PIC圖的路徑 轉換[11]
							if (arrayField[11].indexOf("/cwbuyer/")>0){
								String chg=arrayField[11].replace(arrayField[11].substring(0, arrayField[11].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
								arrayField[11]=chg;
							}
							arrayField[21]=arrayField[29];
							arrayField[22]=arrayField[30];
							arrayField[17]="";
							arrayField[18]="";
							arrayField[19]="";
							arrayField[20]="";
							arrayField[23]="0";
							arrayField[24]="0";
							arrayField[25]="0";
							arrayField[26]="0";
							arrayField[27]=arrayField[29];
							//if(nDept!=1)  //正常為 上存金額
							arrayField[28]=arrayField[30];
							//else  //留給本退用
							//arrayField[28]="0";
							
							arrayField[31]=""+Utilis.toInt(arrayField[29])*-1;
							arrayField[32]=""+Utilis.toInt(arrayField[30])*-1;
							arrayField[29]="0";
							arrayField[30]="0";
							arrayField[33]="";
							arrayField[34]="0";
							arrayField[35]="";
							arrayField[36]=bankn;
							arrayField[37]="Y1";
							
							for (int ii=0;ii<puts.length;ii++)	valueI.put(puts[ii], arrayField[ii]);
							pdb.insert("qpandn", null, valueI);
							
							buffers.delete(0, buffers.toString().length());
						}
					}
					in.close();  //
					pdb.close();
				} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			} finally{
	      		startIniDb(QpandnF.this);
	      		//startDB();
			}
	}
	private void getStart(){//一律由建立盤點清冊呼叫
		//這樣可以有效率的 分為 已存在盤表 XID=1 update XID=0 insert
		File fileQmtrio = new File(mDBPath);
	  	SQLiteDatabase pdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
		String SQL="update zpandn set XID=1 where GOODSNO in (select distinct GOODSNO from qpandn where PNDNADAY='"+Ddate+"' and USER='"+mWho+"')";
		pdb.execSQL(SQL);
		StringBuffer mySqlBuf=new StringBuffer(); 			
		if (mySqlBuf.toString().length()>0) mySqlBuf.delete(0, mySqlBuf.toString().length());
		mySqlBuf.append("select GOODSNO,COLORNO,COLOR,SIZE,P1,P2,P3,P4,P5,sum(UNIT10),sum(UNIT20),sum(UNIT21),sum(UNIT34),GOODSNAME,PIC from zpandn ");
		mySqlBuf.append(" where XID=1");  
		//
		mySqlBuf.append(" group by GOODSNO,COLORNO,COLOR,SIZE,P1,P2,P3,P4,P5,GOODSNAME,PIC");
		mySqlBuf.append(" order by GOODSNO,COLORNO,COLOR,SIZE");
		//0.NO 1.COLORNO 2.COLOR 3.SIZE   4.P1 5.P2 6.P3,7.P4 8.P5
		//9.UNT10 10.UNIT20 11.UNIT21 12.UNIT34  
		//13.GOODSNAME 14.PIC
		Cursor csp=null;
		Cursor cs= pdb.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){ //本期有交易
			String buf="";
			nLstk=0;
			cs.moveToFirst();
			csp=pdb.rawQuery("select DATA,LASTSTKN from qpandn where GOODSNO='"+cs.getString(0)+"' and PNDNADAY='"+Ddate+"' and USER='"+mWho+"'", null);
			if (csp.getCount()>0) {
				csp.moveToFirst();
				buf=csp.getString(0);
				nLstk=csp.getInt(1); //從盤表取得上存 
			}
			goodO=cs.getString(0);  //初始goodO
			goodOName=cs.getString(13); 
			goodOPic=cs.getString(14);
			findP=1;
			nPrice=cs.getInt(nTradetype+3);
			nAcost=cs.getInt(4);
			nAstk =0;
			nAimn=0;
			nAstn=0;
			nAadn=0;
			for (int ii=0;ii<cs.getCount();ii++){  //現行DB每筆交易明細讀取
				if (cs.getString(0).equalsIgnoreCase(goodO)){ //是同一個貨號時
					buf=bufAdd(cs,buf);
				}else{  //不同的貨號時,應將DATA再度存入
				//一定有存在的DATA需要存入
					if (buf.length()>0){
						//nID+=1;	//原先盤表不存在需insert
						bufSave(QpandnF.this,pdb,buf,findP);						      								
					}
	  				buf="";
					csp=pdb.rawQuery("select DATA,LASTSTKN from qpandn where GOODSNO='"+cs.getString(0)+"' and PNDNADAY='"+Ddate+"' and USER='"+mWho+"'", null);
					if (csp.getCount()>0) {
						csp.moveToFirst();
						buf=csp.getString(0);
						nLstk=csp.getInt(1);
					}
					goodO=cs.getString(0);
	  				goodOName=cs.getString(13); 
	  				goodOPic=cs.getString(14);
	  				findP=1;
					nPrice=cs.getInt(nTradetype+3);
					nAcost=cs.getInt(4);
					nAstk =0;
					nAimn=0;
					nAstn=0;
					nAadn=0;
					buf=bufAdd(cs,buf);
				}//不同貨號END  
				
				if (ii==(cs.getCount()-1)){
						if (buf.length()>0){
							//nID+=1;	//原先盤表不存在需insert
						bufSave(QpandnF.this,pdb,buf,findP);						      								
					}
				}
				cs.moveToNext();
			}//for_end
			csp.close();
			cs.close();
		}
		//@@@還要讀取 XID=1 表示盤表已存在
		if (mySqlBuf.toString().length()>0) mySqlBuf.delete(0, mySqlBuf.toString().length());
		mySqlBuf.append("select GOODSNO,COLORNO,COLOR,SIZE,P1,P2,P3,P4,P5,sum(UNIT10),sum(UNIT20),sum(UNIT21),sum(UNIT34),GOODSNAME,PIC from zpandn ");
		mySqlBuf.append(" where XID=0");  
		//一律新增盤表(沒有)
		mySqlBuf.append(" group by GOODSNO,COLORNO,COLOR,SIZE,P1,P2,P3,P4,P5,GOODSNAME,PIC");
		mySqlBuf.append(" order by GOODSNO,COLORNO,COLOR,SIZE");
		//0.NO 1.COLORNO 2.COLOR 3.SIZE   4.P1 5.P2 6.P3,7.P4 8.P5
		//9.UNT10 10.UNIT20 11.UNIT21 12.UNIT34  
		//13.GOODSNAME 14.PIC
		cs= pdb.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){ //本期沒有交易
			cs.moveToFirst();
			goodO=cs.getString(0);  //初始goodO
			goodOName=cs.getString(13); 
			goodOPic=cs.getString(14);
			String buf="";
			findP=0;
			nPrice=cs.getInt(nTradetype+3);
			nAcost=cs.getInt(4);
			nAstk =0;
			nAimn=0;
			nAstn=0;
			nAadn=0;
			nLstk=0;
			for (int ii=0;ii<cs.getCount();ii++){  //現行DB每筆交易明細讀取
				if (cs.getString(0).equalsIgnoreCase(goodO)){ //是同一個貨號時
					buf=bufAdd(cs,buf);
				}else{  //不同的貨號時,應將DATA再度存入
				//一定有存在的DATA需要存入
					if (buf.length()>0){
						nID+=1;	//原先盤表不存在需insert
						bufSave(QpandnF.this,pdb,buf,findP);						      								
					}
					goodO=cs.getString(0);
	  				goodOName=cs.getString(13); 
	  				goodOPic=cs.getString(14);
	  				buf="";
	  				findP=0;
					nPrice=cs.getInt(nTradetype+3);
					nAcost=cs.getInt(4);
					nAstk =0;
					nAimn=0;
					nAstn=0;
					nAadn=0;
					nLstk=0;
					buf=bufAdd(cs,buf);
				}//不同貨號END  
				
				if (ii==(cs.getCount()-1)){
						if (buf.length()>0){
							nID+=1;	//原先盤表不存在需insert
						bufSave(QpandnF.this,pdb,buf,findP);						      								
					}
				}
				cs.moveToNext();
			}//for_end
			
		}

		//如何知道是首次盤點 2012-03-14 不執行這一段
		//校正上存,全面重新運算
		//從qpandn 一一讀取 找 qmtrs
			
		
		SQL="select USER,PNDNADAY,GOODSNO,DATA,ID,UNITPRICE from QPANDN where PNDNADAY='"+Ddate+"' and USER='"+mWho+"' order by GOODSNO";
		cs=pdb.rawQuery(SQL.toString(), null);
		int acLastStk=0;double acLastStkm=0; 
		int acAin=0;		double acAim=0;
		int acAadn=0;		double acAadm=0;
		int acAstn=0;		double acAstm=0;
		int acAstkn=0;		double acAstkm=0;
		int acApndefn=0;		double acApndefm=0;
		int acApan=0;		double acApam=0;
		int acAupn=0;
		
		if (cs.getCount()>0){
			while (cs.moveToNext()){
				String mUser=cs.getString(0);
				String mPndnadat=cs.getString(1);
				String mGoodsno=cs.getString(2);
				String mData=cs.getString(3);
				String mID=cs.getString(4);
				int mPri=cs.getInt(5);
				if (mData.indexOf("，")>0){
					String [] gData=mData.split("，");
					//重新校正 上存 每一筆
					int cLastStk=0;double cLastStkm=0; 
					int cAin=0;		double cAim=0;
					int cAadn=0;		double cAadm=0;
					int cAstn=0;		double cAstm=0;
					int cAstkn=0;		double cAstkm=0;
					int cApndefn=0;		double cApndefm=0;
					int cApan=0;		double cApam=0;
					int cAupn=0;		double cAupnm=0;
					String aaData="";
					
					for (int ii=0;ii<gData.length;ii++){
						if (gData[ii].indexOf(",")>0){
						  if (gData[ii].length()>10){
							String [] aData=gData[ii].split(",");
							if (!Ldate.contentEquals("2012-03-02")){
								String mGoodS=mGoodsno+"-"+aData[0]+"-"+aData[2];
								String SQLmtrs="select sum(ID) from qmtrs where GOODSNO='"+mGoodS+"' group by GOODSNO";
								Cursor CSmtr=pdb.rawQuery(SQLmtrs, null);
								if (CSmtr.getCount()>0){
									CSmtr.moveToFirst();
									int lastStk=CSmtr.getInt(0);
									//比較上存不一樣者 update之
									if (lastStk!=Utilis.toInt(aData[10])){
										aData[10]=""+lastStk;//修正上存
										aData[6]=""+(lastStk+Utilis.toInt(aData[9])-Utilis.toInt(aData[8])-Utilis.toInt(aData[7]));
										//算出應盤6= 10+9-8-7
									}
								}
								CSmtr.close();
							}
							aData[5]=""+((Utilis.toInt(aData[6])-Utilis.toInt(aData[4]))*-1);
							//運算盤差5=6-4
							cLastStk+=Utilis.toInt(aData[10]);
							acLastStk+=Utilis.toInt(aData[10]);
							cLastStkm+=Utilis.toInt(aData[10])*mPri;
							acLastStkm+=Utilis.toInt(aData[10])*mPri;
							
							cAin+=Utilis.toInt(aData[9]);
							acAin+=Utilis.toInt(aData[9]);
							cAim+=Utilis.toDouble(aData[9])*mPri;
							acAim+=Utilis.toInt(aData[9])*mPri;
							
							cAadn+=Utilis.toInt(aData[8]);
							acAadn+=Utilis.toInt(aData[8]);
							cAadm+=Utilis.toDouble(aData[8])*mPri;
							acAadm+=Utilis.toInt(aData[8])*mPri;
							
							cAstn+=Utilis.toInt(aData[7]);
							acAstn+=Utilis.toInt(aData[7]);
							cAstm+=Utilis.toDouble(aData[7])*mPri;
							acAstm+=Utilis.toInt(aData[7])*mPri;
							
							cAstkn+=Utilis.toInt(aData[6]);
							acAstkn+=Utilis.toInt(aData[6]);
							cAstkm+=Utilis.toDouble(aData[6])*mPri;
							acAstkm+=Utilis.toInt(aData[6])*mPri;
							
							cApndefn+=Utilis.toInt(aData[5]);
							acApndefn+=Utilis.toInt(aData[5]);
							cApndefm+=Utilis.toDouble(aData[5])*mPri;
							acApndefm+=Utilis.toInt(aData[5])*mPri;
							
							cApan+=Utilis.toInt(aData[4]);
							acApan+=Utilis.toInt(aData[4]);
							cApam+=Utilis.toDouble(aData[4])*mPri;
							acApam+=Utilis.toInt(aData[4])*mPri;
							
							cAupn+=Utilis.toInt(aData[3]);
							acAupn+=Utilis.toInt(aData[3]);
							
							for (int x=0;x<10;x++){
								aaData+=aData[x]+",";
							}	
							aaData+=aData[10]+"，";
							//重新合成 DATA
						  }
						}
					}
					if (!mData.equalsIgnoreCase(aaData)){
						//update qpandn
						StringBuffer Bdata=new StringBuffer(); 
						Bdata.append("update qpandn set DATA='"+aaData+"',LASTSTKN='"+cLastStk+"',LASTSTKM='"+cLastStkm+"',ASTKN='"+cAstkn+"',ASTKM='"+cAstkm+"',ADEFN="+cApndefn+",ADEFM="+cApndefm);
						Bdata.append(" where  USER='"+mUser+"' and PNDNADAY='"+mPndnadat+"' and ID="+mID+" and GOODSNO='"+mGoodsno+"'");
						pdb.execSQL(Bdata.toString());
					}
				}
			}
		}
		
		cs.close();
		
			ContentValues valueI = new ContentValues();
				valueI.put("PNDNFKIND",""+nDept);  //0AA 1A1 2SUPPLY
				valueI.put("PNDNPKIND",""+nTradetype); //priceType P1-P5
				valueI.put("PNDNCKIND",""+nPandnK) ;  //GOODSNOS GOODNO PRICE 
				nState=0;valueI.put("PNDNSTATE",nState) ;	//新的盤表
				valueI.put("ID",3) ;
				valueI.put("USER",mWho) ;
				valueI.put("USERNAME",((Button)findViewById(R.id.btn_pndnname)).getText().toString()) ;
				valueI.put("PNDNBDAY",Ldate) ;
				valueI.put("PNDNADAY",Ddate) ;
				valueI.put("GOODSNO","") ;
				valueI.put("GOODSNAME","") ;
				valueI.put("PIC","") ;//Picture of USER
				valueI.put("UNITPRICE",0) ;
				valueI.put("DISCOUNT",nDiscount) ;
				valueI.put("ACOST",0) ;
				valueI.put("DATA","") ;
				valueI.put("DATA0","") ;
				valueI.put("PNDNDD","") ;
				valueI.put("DEPTSNO","FORMNO") ;
				valueI.put("PARTSNO","") ;
				valueI.put("LASTSTKN",tLastStkn) ;
				valueI.put("LASTSTKM",tLastStkm) ;
				valueI.put("AINN",acAin) ;
				valueI.put("AINM",acAim);
				valueI.put("ASTN",acAstn) ;
				valueI.put("ASTM",acAstm);
				valueI.put("ASTKN",acAstkn); //本存(應盤)
				valueI.put("ASTKM",acAstkm);  //這是個不對稱的欄位
				valueI.put("APANN",acApan) ; //本盤
				valueI.put("APANM",acApam) ;
				valueI.put("ADEFN",acApndefn) ;  //盤差量
				valueI.put("ADEFM",acApndefm) ;  //盤差金
				valueI.put("CDT",DateUtil.getSystemTime().substring(2, 14)) ;
				valueI.put("APIN",acAupn) ;  //暫盤
				valueI.put("SDT",DateUtil.getSystemTime().substring(2, 14)) ;
				valueI.put("BANKNAME",bankn) ;
				valueI.put("TR","Y0") ;
				pdb.insert("qpandn", null, valueI);
		
		pdb.close();
		
		//myDialog.dismiss();
		nCondition=2;	setCondition();  //回盤點清冊
		if (nDept!=0) mWho="";
		getGroupData(QpandnF.this, mWho, nState,null,null);  //2表示PNDNSTATE!=2 未入帳的盤表
		mAdapter.notifyDataSetChanged();
	}

	private void qadff(String buff,int mode){
	//專櫃請款單 進一步 解析資料後 呼叫mkqrst
		if (buff.indexOf(";SETPAGE")>0){
			String qkindStr=mWhoName+"  自:"+Ldate+" 到: "+Ddate+" 對帳請款單 ";
			Toast.makeText(QpandnF.this, mWhoName+" 對帳請款單建立中!!請稍後!!! ", Toast.LENGTH_SHORT).show();
			if (mode==0){
				Intent intent = new Intent();
				intent.putExtra("SERCH",compStr[0]+" VS "+mWhoName);
				intent.putExtra("QKIND",qkindStr);
				intent.putExtra("MODE",14);
				intent.putExtra("DEPTNO",mWho);
				intent.putExtra("BUFSTR",buff);
				intent.putExtra("BUFTITLE","1;2;3");
				intent.putExtra("STARTDAY",Ldate);
				intent.putExtra("ENDDAY",Ddate);
	
				intent.setClass(QpandnF.this, MkqrSt.class);
				startActivity(intent);
			}else{
        		try {
                    Writer out = new BufferedWriter(new OutputStreamWriter(
                    	    new FileOutputStream(myFilePath), "UTF-8"));
                    	try {
                    	    out.write(sPrintB.toString());
                    	} finally {
                    	    out.close();
                    	}                    
        		} catch (Exception e) {

        		}
        		
    			//進一步輸出,多媒體選擇
    	    	Intent send = new Intent(Intent.ACTION_SEND);
    	    	send.setType("image/jpeg");
    		    String uriText;
    		    Uri U=Uri.parse("file://"+myFilePath);  //重要的範例
    		    uriText = "https://www.google.com/cloudprint/addpublicprinter.html?printerid=bb160853-6274-0f65-eb1f-34ae2c9ed6e1&key=19901109";
    		    send.putExtra(Intent.ACTION_SENDTO,uriText);
    		    send.putExtra(Intent.EXTRA_STREAM,U);
    		    startActivity(Intent.createChooser(send, uriText));

			}
			
			
		}
		
	}
	
	private String bufAdd(Cursor cs,String buf){  //到時候需區隔 0總倉 1門市 2廠商
		StringBuffer nBufB=new StringBuffer();		
		String sepaE="，";
		String sepa=",";
		int Aimn=cs.getInt(10);  //取至(UNIT20) 當門市盤點時(混淆的是 門市的轉入轉出都合計了)
		int Astsn=cs.getInt(12);//本銷
		int Aadn=cs.getInt(11);//門市進
		int Aimn10=cs.getInt(9);//總倉廠商進
		nAstn+=Astsn;//本銷UNIT30UNIT40
		chkIn=0;
		if (nDept==0){//總倉(本進-本出-本銷)
			nAstk+=(Aimn10-Aimn-Astsn);//總存
			nAadn+=Aimn;//總出
			nAimn+=Aimn10;//總進
		}else if (nDept==2){  //廠商較像門市(本進-本銷)
			nAstk+=(Aimn10-Astsn);
			nAimn+=Aimn10;
			nAadn=0;
		}else if (nDept==1){//門市
			nAadn+=Aimn; //本退
			nAimn+=Aadn;  //本進
			nAstk+=(Aadn-Aimn-Astsn);//本存
		}
		nAcost=cs.getInt(4);//成本P1
		//總應盤 總盤差 
		if(buf.length()>0){
			String [] fieldA=buf.split(sepaE); //各色尺寸
			for (int ij=0;ij<fieldA.length;ij++){//檢查每一筆盤表存在這個顏色尺寸否
				String [] fieldB=fieldA[ij].split(sepa); //各欄位
				if (cs.getString(1).equalsIgnoreCase(fieldB[0]) && cs.getString(3).equalsIgnoreCase(fieldB[2])){
					//表示同一顏色尺寸,需累加運算到DATA內
					//[9]上存[8]本進[7]本出[6]本銷[5]本存[4]盤差[3]本盤
					//[10]上存	[9]本進	[8]本出	[7]本銷	[6]本存	[5]盤差	[4]本盤	[3]暫盤	
					//[1]COLOR_NO,[2]COLOR_NAME,[3]SIZE
					int f9=Utilis.toInt(fieldB[9]);int f10=Utilis.toInt(fieldB[10]);
					int f7=Utilis.toInt(fieldB[7]);int f8=Utilis.toInt(fieldB[8]);
					if(nDept==0){  //總倉盤表
						fieldB[9]=""+(Aimn10+f9);  //UNIT10
						fieldB[8]=""+(Aimn+f8);  //UNIT20
					}else if(nDept==1){  //門市盤表
						fieldB[9]=""+(Aadn+f9);  //UNIT21 本進 
						fieldB[8]=""+(Aimn+f8);  //UNIT20 本退
					}else if(nDept==2){  //廠商盤表與門市盤表
						fieldB[9]=""+(Aimn10+f9);  //UNIT10
						fieldB[8]="0";
					}
					fieldB[7]=""+(Astsn+f7);  //UNIT3040
					fieldB[6]=""+(Utilis.toInt(fieldB[10])+Utilis.toInt(fieldB[9])-Utilis.toInt(fieldB[8])-Utilis.toInt(fieldB[7]));
					fieldB[5]=""+(Utilis.toInt(fieldB[6])*-1); //盤差(期初建表)
					for (int k=0;k<10;k++){  //重組
						nBufB.append(fieldB[k]+sepa);
					}
					//@@@ 如何也填入最新 上存 qmtrs.GOODSNO,ID
					nBufB.append(fieldB[10]);

					fieldA[ij]=nBufB.toString();
					chkIn=1;
					break;
				} //表示有找到盤表,並做data運算
			}
				if (chkIn>0){ //在盤表中存在,重組buf_data字串
					buf=""; for (int ij=0;ij<fieldA.length;ij++){buf=buf+fieldA[ij]+sepaE;}
				}	
		}	
		//0.NO 1.COLORNO 2.COLOR.SIZE   4.P1 5.P2 6.P3,7.P4 8.P5
		//9.UNT10 10.UNIT20 11.UNIT21 12.UNIT34 
		//13.GOODSNAME 14.PIC
				if (chkIn<1){ //在盤表不存在,重建buf_data字串
					StringBuffer buff=new StringBuffer();
					buff.append(cs.getString(1)+sepa)
					.append(cs.getString(2)+sepa)
					.append(cs.getString(3)+sepa)
					.append("0"+sepa)  //暫盤歸零
					.append("0"+sepa);  //本盤歸零
					if(nDept==0){
						buff.append(""+((Aimn10-Aimn-Astsn)*-1)+sepa)  //盤差=本存*-1 為負正關係
						.append(""+(Aimn10-Aimn-Astsn)+sepa)  //本存
						.append(""+Astsn+sepa)  //本銷會員+員購
						.append(""+Aimn+sepa)  //本出
						.append(""+Aimn10+sepa);  //本進
					}else if(nDept==1 ){  //門市 
						buff.append(""+((Aadn-Aimn-Astsn)*-1)+sepa)  //盤差=本存*-1 為負正關係
						.append(""+(Aadn-Aimn-Astsn)+sepa)  //本存
						.append(""+Astsn+sepa)  //本銷會員+員購
						.append(""+Aimn+sepa)  //本轉貨
						.append(""+Aadn+sepa);  //本進
					}else if(nDept==2 ){  //廠商
						buff.append(""+((Aimn10-Astsn)*-1)+sepa)  //盤差=本存*-1 為負正關係
						.append(""+(Aimn10-Astsn)+sepa)  //本存
						.append(""+Astsn+sepa)  //本銷會員+員購
						.append("0"+sepa)  //本出
						.append(""+Aimn10+sepa);  //本進
					}
					//@@@ 如何也填入最新 上存 qmtrs.GOODSNO,ID
					buff.append("0"+sepaE);  //上存
					buf+=buff.toString();
					chkIn=1;
				}
		return buf;
	}

	//存入的時機,也是第一階段製作盤表
	//盤表會不存在,是因為本期的新品(沒有上存)
	private void bufSave(Context context,SQLiteDatabase mdb,String buf,int nfindF){  //到時候需區隔 0總倉 1門市 2廠商
		//mdb.beginTransaction();
		ContentValues valueI = new ContentValues();
		if (nfindF==0){  //盤表不存在,而需要新增時
			valueI.put("PNDNFKIND",""+nDept);  //0AA 1A1 2SUPPLY
			valueI.put("PNDNPKIND",""+nTradetype); //priceType P1-P5
			valueI.put("PNDNCKIND",""+nPandnK) ;  //GOODSNOS GOODNO PRICE 
			valueI.put("PNDNSTATE",0) ;	//新的盤表
			if (nAstk>0){  //有盤差
				valueI.put("ID",nID) ;
			}else{	//沒有盤差 50000-80000
				int nnID=nID+50000;
				valueI.put("ID",nnID) ;
			}
			valueI.put("USER",mWho) ;
			valueI.put("USERNAME",((Button)findViewById(R.id.btn_pndnname)).getText().toString()) ;
			valueI.put("PNDNBDAY",Ldate) ;
			valueI.put("PNDNADAY",Ddate) ;
			valueI.put("GOODSNO",goodO) ;
			valueI.put("GOODSNAME",goodOName) ;
			valueI.put("PIC",goodOPic) ;
			valueI.put("UNITPRICE",nPrice) ;
			valueI.put("DISCOUNT",nDiscount) ;
			valueI.put("ACOST",nAcost) ;
	
			valueI.put("DATA",buf) ;
			valueI.put("DATA0","") ;
			valueI.put("PNDNDD","") ;
			valueI.put("DEPTSNO","FORMNO") ;
			valueI.put("PARTSNO","") ;
			valueI.put("LASTSTKN",0) ;
			valueI.put("LASTSTKM",0) ;
			if (nDept==1){
				valueI.put("AINN",nAimn-nAadn) ;
				valueI.put("AINM",(nAimn-nAadn)*nPrice*nDiscount/100);				
			}else{
				valueI.put("AINN",nAimn) ;
				valueI.put("AINM",nAimn*nPrice*nDiscount/100);				
			}
			valueI.put("ASTN",nAstn) ;
			valueI.put("ASTM",(nAstn*nPrice*nDiscount/100));
			valueI.put("ASTKN",nAstk) ; //本存
			valueI.put("ASTKM",(int)(nAstk*nPrice*nDiscount/100));
			valueI.put("APANN",0) ; //本盤
			valueI.put("APANM",0) ;
			valueI.put("ADEFN",(nAstk*-1)) ;  //盤差量
			valueI.put("ADEFM",((nAstk*-1)*nPrice*nDiscount/100)) ;  //盤差金
			valueI.put("APIN",0) ;  //暫盤
			valueI.put("SDT","") ;
			valueI.put("BANKNAME",bankn) ;
			valueI.put("TR","Y0") ;
			mdb.insert("qpandn", null, valueI);
		} else {  //update 應該不是只有DATA欄位更新,而是如上欄位也要更新
			StringBuffer SQLTXT=new StringBuffer();
			SQLTXT.append("update qpandn set DATA='"+buf+"',");
					if(nDept==1)	{
						SQLTXT.append("AINN="+(nAimn-nAadn)+",");
						SQLTXT.append("AINM="+((nAimn-nAadn)*nPrice*nDiscount/100)+",");
					}else{  //本存金額
						SQLTXT.append("AINN="+nAimn+",");
						SQLTXT.append("AINM="+(nAimn*nPrice*nDiscount/100)+",");
					}
					SQLTXT.append("ASTN="+nAstn+",")
					.append("ASTM="+(nAstn*nPrice*nDiscount/100)+",")
					.append("ASTKN="+(nAstk+nLstk)+",");  //還要加上存
					SQLTXT.append("ASTKM="+((nAstk+nLstk)*nPrice*nDiscount/100)+",");
					SQLTXT.append("ADEFN="+((nAstk+nLstk)*-1)+",")  
					.append("ADEFM="+(((nAstk+nLstk)*-1)*nPrice*nDiscount/100)+",")  //盤差量 盤差金
					.append("APIN=0")
					.append(" where ID>10 and USER='"+mWho+"' and PNDNADAY='"+Ddate+"' and GOODSNO='"+goodO+"'");
					mdb.execSQL(SQLTXT.toString());
		}
	}
}
