package com.cwbuyer.main;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import 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.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.format.IDateDialog;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.KeySet;
import com.cwbuyer.lib.AsyncImageFileLoader;
import com.cwbuyer.lib.QMacc;
import com.cwbuyer.lib.QPosSave.PsaveWhere;
import com.cwbuyer.lib.AppUtil;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DateUtil;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.GalleryViewO;
import com.cwbuyer.lib.GalleryViewP;
import com.cwbuyer.lib.GalleryViewS;
import com.cwbuyer.lib.GalleryViewVP;
import com.cwbuyer.lib.MakeTransDetail;
import com.cwbuyer.lib.MkqrSt;
import com.cwbuyer.lib.PosUtilis;
import com.cwbuyer.lib.PrefKey;
import com.cwbuyer.lib.QHis;
import com.cwbuyer.lib.QPosSave;
import com.cwbuyer.lib.QRep_01;
import com.cwbuyer.lib.QRep_02;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.main.APos.PItemKind;
import com.cwbuyer.main.APos.PItemMode;
import com.cwbuyer.main.APos.PItemWhere;
import com.pwbuyer.main.R;

//銷售王的核心2層式ADAPTER,複製自 MANAGEITEM採購王
@SuppressLint({ "InflateParams", "HandlerLeak" })
@SuppressWarnings("unused")
public class QPosff extends Activity{
	
	ItemAdapter mAdapter = null;
	ExpandItemAdapter mExpandAdapter = null;
	
	private LinkedList<PxData> mList = new LinkedList<PxData>();
	//private ArrayList<Integer> mCountryIdList = new ArrayList<Integer>();	
	//private ArrayList<String> mCountryList = new ArrayList<String>();
	//private ArrayList<String> mCountryIcon = new ArrayList<String>();
	//private ArrayList<String> mTypeList = new ArrayList<String>();
	//private ArrayList<Integer> mTypeIdList = new ArrayList<Integer>();
	
	TextView mTextDuration = null;

//ACTION 預設模式 POS定義為 銷貨單;預購單;暫存單;單頭+單身	
	
	int mMode = KeySet.SearchMode.ACTION;
	int abMode=0;  // 預設 0單頭+單身  1.日結+單頭
	private int nPart=0; //0總店 1分店
	public static int PSWD=0; //0OK 1密碼不符
	private String[] deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");
	private String[] importStr =Utilis.getIni(this,"SYS", "IMPORT",9).split("!&!");
	private String[] DeptSend=Utilis.getIni(this,"SYS","DEPT_SEND",9).split("!&!");
	//4隱藏折數 5業績不計6
	private String whoDel="";
	public static int isOnkey=0;
	private String mDept="SOS";  //若有值時,所有搜尋都以單一門市做考量
	private final int RESULT_APOS=3333; 		//GALLERY
	private final int RESULT_GALLERY=6666; 		//GALLERY
	private final int RESULT_GALLERYO=5566; 		//GALLERY
	private final int RESULT_QPOSAVE=5555;
	private final int RESULT_REP_02=6602; 		//REP_02
	public static String mBankn="";//門市代號+機號		
	int of_line=Utilis.toInt(importStr[2]);
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);	
	final String myCSVPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",6);	
	int mGroupMode = GroupMode.COMPANY;
	private LinkedList<GroupData> mGroupList = new LinkedList<GroupData>();
	
	/** State :  true 正式 , false 樣品*/
	String mEndDay = null;
	String mStartDay = null;
	String mLimitDay = null;//WeiLa七天限制
	String mKey = null;
	String mUser ="";
	String mGoods="";
	String mTime="";
	double  mDiscount=0;
	double mUnitprice=0;
	String mFD="";
	int WeiLa=0; //0不限制 1限七天

	//PItemData dataH;	
	String[] pKind=Utilis.getIni(this,"SYS","PKIND",9).split("!&!");
	
	String[] menu_X={ "大圖瀏覽","明細清冊", "結帳","各門市庫存分析","追蹤","補印條碼","保留","保留","保留","返回" };

	//日結單
	String [] A123={"預購","留貨","銷貨"};
	String [] C123={"_立刻轉預購","_立刻轉留貨","_立刻轉銷貨"};
	String [] Lmenu1={"印製日結單","印製日結明細單","印製日結A4單","印製日結A4明細單","返回"};
	String [] Lmenu0={"確認結帳","變更交易","整張單刪除","整張單轉預購","整張單轉留貨","預購留貨清單","留貨轉銷貨清單","輸出","補印單據","返回"};
	String [] Lmenu3={"確認結帳","變更交易","整張單刪除","輸出","補印單據","","返回","",""};
	
	String [] Lmenu2= {"轉留貨","轉預購","預購留貨清單","商品追蹤","返回"};
	//只針對QHEAD時 整張單轉(預購)(留貨)(銷貨)
	//QITEMS商品 輕按 { "大圖瀏覽(編輯)","明細清冊(編輯)", "庫存分析表","補印條碼","返回" };
	//QITEMS商品 長按 {  "轉留貨","轉預購","預購清單","留貨清單","返回" };

	String mKind=null; //單別 102030405060
	int nKind=0;
	int isPass=0;
	int f123=0;
	DecimalFormat df = new DecimalFormat();
	String style = "###,###.###";
	DatePicker dp1;
	DatePicker dp2;
	
	String[] listdept;
   	String btns=null;
   	String[] bttns;
   	String USER=null;
   	double Disc=0;
   	
   	String QUA=null;
   	String ANS=null;
	
	private int mYear1 = 0;
	private int mYear2 = 0;
	private int mMonth1 = 0;
	private int mMonth2 = 0;
	private int mDay1 = 0;
	private int mDay2 = 0;
	private int mYear = 0;
	private int mMonth = 0;
	private int mDay = 0;

	public static ProgressDialog myDialog = null;
	protected static final int REFRESH_DATA = 0x00000001;
	static String uriAPI=null;
//	static int work=0;
	static String ServerT;
	
	ListView mListView = null;
	ExpandableListView mExpandListView = null;
	
	class GroupData{ //第一層版面
		public String strPic;  // 左
		public String strTextG1;  // 上左
		public String strText1; // 中左 會員編號/名稱 USER/USERNAME
		public String strTextG2;  // 下左		
		public String strMoney; // 中右 		CASH/CARD
		public String strTime;  // 上中
		public String strText2; // 上右  		ASUM/BSUM
		public String strOriMoney;  //右下ORDCASH/ORDCARD
		public String SEARCH;  // 唯查
	}
	
	class PxData{ //第二層版面
		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 iCreatetime;
		
	}
	
//@@日後需補充用ITEM檢測HEAD是否漏掉的清單,並自動修補	
	public interface GroupMode{//EVERYDAY/WEEK/MONTH 以FORMDATE
		int NUMBER = 0;  //銷貨單(1單頭2單身)isConfirm=="Y";isList<>"Y";
		//第一層:1.圖略 2.單號 3.本單應收 4.
		int CATEGORY = 1; //預購單(1單頭2單身)isConfirm=="Y";isList=="Y"
		int COMPANY = 2; //暫存單(1單頭2單身) isConfirm<>"Y"
		int KEEPA =3;		  //假想		日結單                (1.結算單2單頭)
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent dataR) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, dataR);
		
		switch(requestCode){
		
		case 1001:
			{
				if (resultCode == RESULT_OK) {
				}else{
					finish();
				}
				break;
			}
		case RESULT_QPOSAVE:
		{
			if (resultCode == RESULT_OK) {
				if ((of_line==1 ) ) {
					SystemClock.sleep(500);
					DBCloud.aa1_aa0_update_HI(QPosff.this);
				}
		    	getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
				mExpandAdapter.notifyDataSetChanged();
				
			}
			break;
		}
		case RESULT_GALLERY:
			{
				//如何重新運算單頭的重頭戲
			  if (resultCode == RESULT_OK) {
				//如果傳回代表需要
				//if(dataR.getIntExtra("GVP_modify",0)==1 && mGroupMode != GroupMode.NUMBER)
				if( mGroupMode != GroupMode.NUMBER)
					PosUtilis.reCountHead(QPosff.this,mKey,"",mKind,f123);
				getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
			  }
			break;				
			}
		case RESULT_APOS:
		{
			  if (resultCode == RESULT_OK) 
				  getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
			break;
		}
		case RESULT_GALLERYO:
			{
				  if (resultCode == RESULT_OK) 
					  getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
				break;
			}
		}	
    }

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qposff_00);
        
		 df = new DecimalFormat(style);
        mTextDuration = (TextView)findViewById(R.id.text_duration);
        //@@應增加營業時間的判斷而視為當日或前一天
        mStartDay =DateUtil.getCurrentDate();  //2012/10/15 將 batch 視為當日的關鍵"/"
        if (Utilis.getIni(this,"SYS","SDB",7).equalsIgnoreCase("1")) f123=1; //需要小數位
        mMode = getIntent().getIntExtra("search_mode", KeySet.SearchMode.ACTION);
        mDept = getIntent().getStringExtra("search_dept");//空白表示全部顯示,一如原始設計,否則只有在總公司才有的判斷
        checkABMode(mMode);
        nKind =getIntent().getIntExtra("QPosff", PItemKind.TR10); //預設為進貨單
        mKind=""+nKind;
		isPass=AppUtil.isRegSucceed(this,1);
        //isPass=0;
		PSWD=Utilis.toInt(deptStr[4]);
		isOnkey=Utilis.toInt(deptStr[7]);		
		mBankn=deptStr[0]+deptStr[1];		
        if (!deptStr[0].equalsIgnoreCase(deptStr[5])) nPart=1;  //門市版
		//@@	   	if (){} //如果沒找到時,2種選擇,
    	//顯示最後一天交易
    	//滿滿收獲的一天,表示空白等待交易,甚至進入銷貨畫面等候開單
//@@另類思考:以容許使用者約30天的鑑賞查詢範圍,否則需更高階的密碼,才可以放行
//回QPOSFF後,又是重新判斷,如APos中按了[預購][暫存][結帳]時,帶回不同的場景
//如[預購]則只顯示所有預購項目,如果沒有任何預購未完成交易者,回到預設標準模式
//如[暫存]則只顯示所有暫存項目,如果沒有任何預購未完成交易者,回到預設標準模式
//如[結帳]則顯示標準模式	        	
//##參數設定為交易完成後,是否返回APos否則可以進行下一筆交易##
    	
//製作畫面初始狀態 ACTION為交易模式 
//單頭+單身,可以上下一日,或受限7日的資料範圍
        
    	if (PSWD!=0 && DeptSend[1].equalsIgnoreCase("1")) WeiLa=1;
    	//沒有權限又啟動薇菈7日
    	mLimitDay = DateUtil.addDate(mStartDay, -7);
		//2021/01/01
        ((Button)findViewById(R.id.btn_new)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_account)).setOnClickListener(new MainClick());  //對帳        
        ((Button)findViewById(R.id.btn_qmacc)).setOnClickListener(new MainClick());  //收支        
        ((Button)findViewById(R.id.btn_sort_number)).setOnClickListener(new MainClick()); //已結帳單
        ((Button)findViewById(R.id.btn_sort_company)).setOnClickListener(new MainClick()); //暫存
    if (nKind==30 || nKind==31 || nKind==40 || nKind==41){
        ((Button)findViewById(R.id.btn_sort_cate)).setOnClickListener(new MainClick()); //預購單
        if (nKind==40 || nKind==41)        
        ((Button)findViewById(R.id.btn_sort_keepa)).setVisibility(View.GONE); //留貨
        else
            ((Button)findViewById(R.id.btn_sort_keepa)).setOnClickListener(new MainClick()); //預購單
    } else {
    	((Button)findViewById(R.id.btn_sort_cate)).setVisibility(View.GONE);
    	((Button)findViewById(R.id.btn_sort_keepa)).setVisibility(View.GONE);
    }
        ((Button)findViewById(R.id.btn_sort_pic)).setOnClickListener(new MainClick()); //日結單
        ((Button)findViewById(R.id.btn_prev_date)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_next_date)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_state)).setOnClickListener(new MainClick());  //統計
        if (WeiLa==1) ((Button)findViewById(R.id.btn_state)).setVisibility(View.INVISIBLE);
        ((Button)findViewById(R.id.btn_fbatch)).setOnClickListener(new MainClick());
        ((TextView)findViewById(R.id.text_duration)).setOnClickListener(new MainClick());
        
        ((Button)findViewById(R.id.btn_sort_number)).setText(pKind[nKind/10-1]);
        mExpandListView = (ExpandableListView)findViewById(R.id.list_item_expand);

        mExpandAdapter = new ExpandItemAdapter(this);
        
        mExpandListView.setAdapter(mExpandAdapter);
        mExpandListView.setOnChildClickListener(mChildClcik);
        
        mListView = (ListView)findViewById(R.id.list_item);
        mAdapter = new ItemAdapter(this);
        mListView.setAdapter(mAdapter);
        
        mExpandListView.setOnItemLongClickListener(mLongClickListener);
        ((Button)findViewById(R.id.btn_sort_pic)).setOnLongClickListener(new MainLongClick());
        
        switch(mMode){ //剛進入主程式的狀態
	    	case KeySet.SearchMode.ACTION: 
	    	{
	    		int mDefaultCtime=05;  //##預設營業打烊時間為 隔日清晨05點
	    		mStartDay = DateUtil.getCurrentDate(); //2012/10/17 
    			int Ttime=Utilis.toInt(DateUtil.getSystemTime().substring(8, 10));  //取得目前幾點
   				if (Ttime<=mDefaultCtime)  mStartDay = DateUtil.addDate(mStartDay, -1);
   				//表示要回到昨天
				mEndDay = mStartDay;
	        	mKey = "";
	            String SWH=Utilis.getIni(this,"SYS","DEV",7);
	            if (SWH !=null && SWH.equalsIgnoreCase("1") && (nKind==30 || nKind==31)){
	            	//啟動樺穎的 詢問日期
	            	mFD=Utilis.getIni(this,"SYS","DEV",8);
	            	
 					mYear=Utilis.toInt(mFD.substring(0, 4));
					mMonth=Utilis.toInt(mFD.substring(5, 7));
					mDay=Utilis.toInt(mFD.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(QPosff.this, "請輸入正確交易日期", c, new IDateDialog(){
						@Override
						public void onDateDialogFinish(String date, int year, int month, int day) {
							if (WeiLa==0)
		            		mFD=date;
							else{
								if (DateUtil.compareTime(DateUtil.toDBDate(date), mLimitDay)<0)
									mFD=mLimitDay.replace("/", "-");
								else
									mFD=date;
							}
							//@@@2020-11-26
		            		Utilis.putIni(QPosff.this, "SYS","DEV", mFD, 8);
			    			Toast.makeText(QPosff.this,"開單日期已改為:"+mFD, Toast.LENGTH_SHORT).show();				            		
						}
					});
	            }
	        	
	            resetButton(R.id.btn_sort_company);
	    		mGroupMode = GroupMode.COMPANY;
	    		abMode=0;
	    		btns=Utilis.getIni(this,"INIH","M_COMPANY",9);
	    		bttns = btns.split("!&!");  	for(int i=0;i<9;i++)	menu_X[i] = bttns[i];
	        	getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
	        	
	        	((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_date)).setText("下一日");
	    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_date)).setText("上一日");
	    		break;
	    	}
	    	case KeySet.SearchMode.DAY:
	    	{
	    		mStartDay = Utilis.getRecentPDate(this);
				mEndDay = mStartDay;
				
				resetButton(R.id.btn_sort_pic);
				mGroupMode = GroupMode.NUMBER;
				abMode=1;
				
		    	getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
			   	
	    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_date)).setText("下一日");
	    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_date)).setText("上一日");
	    		break;
	    	}
	    	case KeySet.SearchMode.WEEK:
	    	{
	    		String day = Utilis.getWeekDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
		        resetButton(R.id.btn_sort_pic);
				mGroupMode = GroupMode.NUMBER;
				abMode=1;
		    	getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
		    	
	    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_date)).setText("下一週");
	    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_date)).setText("上一週");
	    		break;
	    	}
	    	case KeySet.SearchMode.MONTH:
	    	{
	    		String day = Utilis.getMonthDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
		        resetButton(R.id.btn_sort_pic);
				mGroupMode = GroupMode.NUMBER;
				abMode=1;
		    	getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
		    	
	    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_date)).setText("下個月");
	    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_date)).setText("上個月");
	    		break;
	    	}
	    	case KeySet.SearchMode.ACCOUNT:  //外部帳戶進場
	    	{
	    		final int nAccountId = getIntent().getIntExtra("accountid", 0);
	    		new AlertDialog.Builder(QPosff.this).setTitle("搜尋(起始、結束日期)")
				.setView(makeDateDialog())
				.setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            	String startDay = "" + mYear1 + "/" + Utilis.formatDate(mMonth1) + "/" + Utilis.formatDate(mDay1);
		            	String endDay = "" + mYear2 + "/" + Utilis.formatDate(mMonth2) + "/" + Utilis.formatDate(mDay2);
		            	
		            	mStartDay = startDay;
		            	mEndDay = endDay;
		            	mKey = null;
		            	mTextDuration.setText( mStartDay + "~" + mEndDay);		            	
		            	//帳戶@@只能(第一層_日+第二層_單頭)
				        resetButton(R.id.btn_sort_pic);
						mGroupMode = GroupMode.NUMBER;
						abMode=1;
		            	getGroupData(QPosff.this, mStartDay, mEndDay, "BANKNO", String.valueOf(nAccountId));
		            }
		          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            }
		          }).show();
	    		break;
	    	}

        }
        
        setCondition();
    	checkABMode(mMode);        
        

		mListView.setVisibility(View.GONE);
		mExpandListView.setVisibility(View.VISIBLE);
    	
		mExpandListView.setOnChildClickListener(mChildClcik);
		
	String isQyear=DeptSend[6];
	if (isQyear.equalsIgnoreCase("1")){ //執行年度謄檔
		
		SQLiteDatabase db = Utilis.getDB(this);
		int numRows = db.rawQuery("SELECT FORMNO FROM QHEAD", null).getCount();
		numRows += db.rawQuery("SELECT FORMNO FROM QITEMS", null).getCount();
		Calendar c = Calendar.getInstance();
		Integer mMonth = c.get(Calendar.MONTH)+1;
		//建議年度謄檔 每月檢查一次,提醒一次為限 且 現行檔存在兩個年度或以上時
		Cursor cs = db.rawQuery("select distinct substr(FORMDATE,1,4) from qhead order by FORMDATE desc",null);
		if(cs.getCount()>2){ //3個年度以上的資料
			if (numRows>1500000 && mMonth>9){
			      myDialog = ProgressDialog.show(this,"建議您執行 年度謄檔!!","資料庫筆數已超過"+numRows+"筆",true);//		setAutoRotationMode();			  
			      new Thread()
			      { 
			        public void run()
			        { 
			          try
			          { 
			        	  SystemClock.sleep(2000);
			          }
			          catch (Exception e)
			          {
			        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());					          }
			          finally
			          {
			            // 卸載所建立的myDialog物件。
			            myDialog.dismiss();
			          }
			        }
			      }.start();
			}
		}
		cs.close();
		db.close();
	}
	 
   }//end of main program
	
	
	public void onResume(){
		super.onResume();
		
		//表示非外來程式 
		if(mMode != KeySet.SearchMode.WIDGET && mMode != KeySet.SearchMode.ACCOUNT){
			getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
				DBCloud.aa0_aa1_auto_HI(QPosff.this,nKind);
    			SystemClock.sleep(500);
				DBCloud.aa0_aa1_auto_qdetail_n(QPosff.this);
		}
	}
	
	private void setCondition(){
		
		//台頭:CWBuyer銷售王+[進貨]
		//(APos.java)[新增][查詢][編輯] 帶過去的引數
		//現階段可分為:[交易中][統計中]
		
    	switch(mMode){ //可否判斷為A式B式
    	
    		case KeySet.SearchMode.ACTION:
    		{
    			mTextDuration.setText("  日期 : " +mStartDay);
	    	break;
    		}
			case KeySet.SearchMode.DAY:
			{
	    		mTextDuration.setText("  日期 : " + mStartDay);
				break;
			}
			case KeySet.SearchMode.WEEK:
			{
//				mTextDuration.setText(getString(R.string.str_duration) + " : " + mStartDay + "~" + mEndDay);
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);				
				break;
			}
			case KeySet.SearchMode.MONTH:
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
				break;
			}
			default:
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
		    	abMode=0;
				break;
			}
    	}
    	String sameStep="";
    	if (of_line!=0 && Utilis.toDouble(Utilis.getIni(QPosff.this, "SYS", "SEASON", 4))==0) sameStep=Utilis.getIni(QPosff.this, "SYS", "SEASON", 3)+"_雲端同步中";
    	else sameStep=Utilis.getIni(QPosff.this, "SYS", "SEASON", 4)+"_已雲端同步完成";
    		
   		setTitle(getString(R.string.app_name)+":["+pKind[nKind/10-1]+"]"+sameStep);
	}
	
	// 特別處理 日結單 GROUPS第一層 是以(日/週/月)為統計結算 childs第二層 才是單頭
	//如何分開 日結+單頭  及 單頭+單身 的製作就是關鍵
	public void getGroupData(Context context, String startDay, String endDay, String condition, String conditionValue) {
		
		if(startDay != null && startDay.length() > 0 && startDay.indexOf("/")>0){
			startDay = startDay.replace("/", "-");
		}
		if(endDay != null && endDay.length() > 0 && endDay.indexOf("/")>0){
			endDay = endDay.replace("/", "-");
		}
		
		if (abMode==1) { //日+單頭
				getGroupBatchData(context, startDay, endDay, condition, conditionValue);
				QUA=null;
				ANS=null;
				return;
		}
		
//		int nState = mbState == true ? 0 : 1; // 0 正式 1 樣品
		//先換成 DB資料庫的格式
		LinkedList<GroupData> groups = new LinkedList<GroupData>();
		LinkedList<List<PxData>> childs = new LinkedList<List<PxData>>();
		if (mGroupList != null) {
			mGroupList.clear();
		}
		SQLiteDatabase db = Utilis.getDB(context);
		try {
			Cursor cursorGroup = null;
			//Cursor cursor = null;
			StringBuffer bufCategory = new StringBuffer();
			
				bufCategory.append("select FORMNO,FORMDATE,USER,USERNAME,ATOT,ASUM,BSUM,CASH,CARD,")
				.append("ORDCASH,ORDCARD,HANDNO,BILLRATE,COSTS,EMPID,EMPNAME,CREATEDATETIME,TRCASH,ATM") 
				.append(" from qhead ");
				
    		if (!mDept.equalsIgnoreCase("SOS")) {
    			bufCategory.append(" where QKIND ='"+mKind).append("' and DEPTNO='"+mDept+"'");
    		}else {
    			bufCategory.append(" where QKIND ='"+mKind).append("'");
    		}
			
			if (condition!=null && condition.length()>0 && conditionValue!=null && conditionValue.length()>0)
				bufCategory.append(" and ").append(condition).append(conditionValue);
			
			
			if(mGroupMode == GroupMode.NUMBER){  //銷貨單_每個單號一筆記錄
				bufCategory.append(" and ISCONFIRM ='Y'")
				.append(" and FORMDATE >= '").append(startDay).append("'")
				.append(" and FORMDATE <= '").append(endDay).append("'"); 
				
			}else if(mGroupMode == GroupMode.CATEGORY){ //預購單
				//bufCategory.append(" and ((ISCONFIRM ='O' and ISCHECK='Y') or (ISCONFIRM ='N' and ISCHECK='Y') )")
				bufCategory.append(" and ISCHECK='Y' and ISCONFIRM <>'R'")
				.append(" and FORMDATE >= '").append(startDay).append("'")
				.append(" and FORMDATE <= '").append(endDay).append("'"); 
				//只要預購 
			}else if(mGroupMode == GroupMode.KEEPA){ // 留貨區
				bufCategory.append(" and ISCONFIRM ='R'")
				.append(" and ISCHECK ='Y'")
				.append(" and FORMDATE >= '").append(startDay).append("'")
				.append(" and FORMDATE <= '").append(endDay).append("'"); 
			}else if(mGroupMode == GroupMode.COMPANY){ // 暫存單@@沒有日期限制
				bufCategory.append(" and ISCONFIRM <>'Y'")
				.append(" and ISCHECK <>'Y'");
			}
			
			bufCategory.append(" order by FORMNO DESC");

			cursorGroup = db.rawQuery(bufCategory.toString(), null);
			
		       //Toast.makeText(QPosff.this,bufCategory.toString() , Toast.LENGTH_SHORT).show(); 				

//			mTextDuration.setText(bufCategory.toString());
			if (cursorGroup != null) {
				if (cursorGroup.getCount() > 0) {
					cursorGroup.moveToFirst();
					for (int i = 0; i < cursorGroup.getCount(); i++) {
						GroupData data = new GroupData();
						data.SEARCH = cursorGroup.getString(0);
						//求證存在ITEMS否?
						int chkinc=0;
						int chkmic=0;
						if (cursorGroup.getString(11).length()>0) {
							String[] arrayW = cursorGroup.getString(11).split("-");
							if (arrayW.length>0 && arrayW[0].indexOf("+-")<0) chkinc=Utilis.toInt(arrayW[0].substring(1, 2));
							if (arrayW.length>1) chkmic=Utilis.toInt(arrayW[1].substring(0,1));
						if (chkinc !=0 || chkmic !=0)	{  //有ITEM存在,才能進一步
							//廠商進貨與出貨與銷貨都有其欄位顯示需求
							data.strTime = "("+cursorGroup.getString(16).substring(5)+")";  //進貨時間
							if (nKind==PItemKind.TR10){ //進貨主單
								data.strPic="";
								Cursor csCust=db.rawQuery("select pic from qfact where FACTNO='"+cursorGroup.getString(2)+"'", null);
								if (csCust.getCount()>0) {
									csCust.moveToFirst();
									data.strPic=csCust.getString(0);
								}
								
								data.strTextG1 = cursorGroup.getString(2)+"/"+cursorGroup.getString(3); //供應商
								data.strText1 = cursorGroup.getString(0);  //單號
								data.strText2 = "小計:"+cursorGroup.getString(11)+"件";
								if (PSWD==1){//受限
									data.strMoney ="";
									data.strOriMoney="";
								}else {
									data.strMoney ="外幣"+Utilis.dedb(cursorGroup.getDouble(5),2)+"匯:"+cursorGroup.getDouble(12);
									data.strOriMoney="合計"+Utilis.dedb(cursorGroup.getDouble(13),2); //台幣
								}
								data.strTextG2 = cursorGroup.getString(1);  //進貨日期
								csCust.close();
							}else if (nKind==PItemKind.TR30 || nKind==PItemKind.TR40 || nKind==PItemKind.TR31 || nKind==PItemKind.TR41){ //銷貨員購主單
									data.strPic="";
									Cursor csCust=db.rawQuery("select pic from qcust where CUSTNO='"+cursorGroup.getString(2)+"'", null);
									if (csCust.getCount()>0) {
										csCust.moveToFirst();
										data.strPic=csCust.getString(0);
									}
									data.strTextG1 = cursorGroup.getString(2)+"/"+cursorGroup.getString(3); //客戶								
									data.strText1 = cursorGroup.getString(1).substring(3)+":"+cursorGroup.getString(0).substring(cursorGroup.getString(0).length()-3);  //單號
									data.strTextG2 = "(件:"+cursorGroup.getString(11)+") "+cursorGroup.getString(14)+"/"+cursorGroup.getString(15);
									data.strText2 = "應:"+Utilis.dedb(cursorGroup.getDouble(6),2)+" 收:"+Utilis.dedb(cursorGroup.getDouble(7)+cursorGroup.getDouble(8)+cursorGroup.getDouble(9)+cursorGroup.getDouble(10)+cursorGroup.getDouble(18),2);
									data.strOriMoney=	"現:"+Utilis.dedb(cursorGroup.getDouble(7),2)+" 票:"+Utilis.dedb(cursorGroup.getDouble(8),2)+" 匯:"+Utilis.dedb(cursorGroup.getDouble(18),2);
									data.strMoney=	"訂:"+(cursorGroup.getString(9))+" 票:"+(cursorGroup.getString(10))+" 墊:"+(cursorGroup.getString(17));
									csCust.close();
							}else if (nKind==PItemKind.TR20 || nKind==PItemKind.TR21){ //@@出貨主單未來再論功能修正
									data.strPic="";
									Cursor csCust=db.rawQuery("select pic from qcust where CUSTNO='"+cursorGroup.getString(2)+"'", null);
									if (csCust.getCount()>0) {
										csCust.moveToFirst();
										data.strPic=csCust.getString(0);
									}
									csCust.close();
									data.strTextG1 = cursorGroup.getString(2)+"/"+cursorGroup.getString(3); //客戶								
									data.strText1 = cursorGroup.getString(1).substring(3)+":"+cursorGroup.getString(0).substring(cursorGroup.getString(0).length()-3);  //單號
									data.strTextG2 = "(件:"+cursorGroup.getString(11)+") "+cursorGroup.getString(14)+"/"+cursorGroup.getString(15);
									if (PSWD==1){//受限
										data.strText2 ="";
										data.strMoney ="";
										data.strOriMoney="";
									}else{	
										data.strText2 ="應:"+Utilis.dedb(cursorGroup.getDouble(6),2)+" 收:"+Utilis.dedb(cursorGroup.getInt(7)+cursorGroup.getInt(8)+cursorGroup.getInt(9)+cursorGroup.getInt(10)+cursorGroup.getInt(18),2);
										data.strOriMoney=	"現:"+Utilis.dedb(cursorGroup.getDouble(7),2)+" 票:"+Utilis.dedb(cursorGroup.getDouble(8),2)+" 匯:"+Utilis.dedb(cursorGroup.getDouble(18),2);
										data.strMoney=		"訂:"+(cursorGroup.getString(9))+" 票:"+(cursorGroup.getString(10))+" 墊:"+(cursorGroup.getString(17));
									}
							}
							groups.add(data);							
						}	
						}	
//							data.strPic = cursorGroup.getString(12);							

//							Toast.makeText(QPosff.this, "拜訪:"+data.strMoney+data.strOriMoney, Toast.LENGTH_SHORT).show();
							
							cursorGroup.moveToNext();
					}
				}
				
				if (groups.size() > 0) {  //製作第二層因為進10出20銷30櫃40 件數 金額 預購 
					StringBuffer bufList = new StringBuffer();
					for (int i = 0; i < groups.size(); i++) {
						if(bufList.length() > 0){
							bufList.delete(0, bufList.length());
						}
						bufList.append("select GOODSNO,GOODSNAME,UNITPRICE,PIC,RATE,P0,P1,DISCOUNT,COLORS,SIZES,PS,")
						.append(" sum(UNIT"+mKind.substring(0, 1)+"0) as SUM"+mKind.substring(0, 1)+"0,")
						.append(" sum(UNIT) as SUMORD,sum(SUBPRICE) as SUMSUB,")
						.append(" sum(RATEPRICE) as SUMRATE")
						.append(",CREATEDATETIME   from qitems WHERE FORMNO='").append(groups.get(i).SEARCH+"'");
							if (!mDept.equalsIgnoreCase("SOS")){
								bufList.append(" and QKIND='"+mKind+"' and DEPTNO='"+mDept+"'");
							}else{
								bufList.append(" and QKIND='"+mKind+"'");
							}
							bufList.append(" group by GOODSNO,GOODSNAME,UNITPRICE,PIC,RATE,P0,P1,DISCOUNT,COLORS,SIZES,PS,CREATEDATETIME order by CREATEDATETIME desc");

							Cursor cursor = db.rawQuery(bufList.toString(), null);
							List<PxData> listData = new ArrayList<PxData>();							
						if (cursor != null) {
							if (cursor.getCount() > 0) {
								cursor.moveToFirst();
								for (int k = 0; k < cursor.getCount(); k++) {
									
									PxData data=new PxData();
									data.iFormdate = groups.get(i).SEARCH;
									data.iGoods = cursor.getString(cursor.getColumnIndex("GOODSNO"));
									data.iCreatetime=cursor.getString(cursor.getColumnIndex("CREATEDATETIME"));
									if (Utilis.toInt(DeptSend[4])==0)
										data.iName = cursor.getString(cursor.getColumnIndex("GOODSNAME"))+"("+cursor.getString(cursor.getColumnIndex("PS"))+")";
									else
										data.iName = cursor.getString(cursor.getColumnIndex("GOODSNAME"));
									
									data.iPic=cursor.getString(cursor.getColumnIndex("PIC"));
									data.iCompany ="=$:"+ Utilis.dedb(cursor.getDouble(cursor.getColumnIndex("SUMSUB")),2);									
									
									if (nKind==PItemKind.TR10){ //採購進貨
										data.iImpo = "共:"+Utilis.dedb(cursor.getDouble(cursor.getColumnIndex("SUM10")),2)+"件";
										if (PSWD==1){//受限
											data.iCountry = "";
											data.iNumber = "";
											data.iMoney = "";
											data.iCompany ="";
										}else{
											data.iCountry = "成本:"+Utilis.dedb(cursor.getDouble(cursor.getColumnIndex("P1")),2);
											data.iNumber = ""+df.format(cursor.getDouble(cursor.getColumnIndex("RATE")));
											data.iMoney = "x 外幣:"+Utilis.dedb(cursor.getDouble(cursor.getColumnIndex("UNITPRICE")),2);
										}
									}else if (nKind==PItemKind.TR20 || nKind==PItemKind.TR21){
										data.iCountry = cursor.getString(cursor.getColumnIndex("COLORS"));
										data.iNumber = cursor.getString(cursor.getColumnIndex("SIZES"));
										data.iImpo = "共:"+Utilis.dedb(cursor.getDouble(cursor.getColumnIndex("SUM"+mKind.substring(0, 1)+"0")),2)+"件";
										if (PSWD==1){ data.iMoney = "";data.iCompany ="";}
										else data.iMoney = "單價:"+cursor.getString(cursor.getColumnIndex("UNITPRICE"));
									}else{
										data.iCountry = cursor.getString(cursor.getColumnIndex("COLORS"));
										data.iNumber = cursor.getString(cursor.getColumnIndex("SIZES"));
										data.iMoney = "單價:"+cursor.getString(cursor.getColumnIndex("UNITPRICE"));
										data.iImpo = "共:"+Utilis.dedb(cursor.getDouble(cursor.getColumnIndex("SUM"+mKind.substring(0, 1)+"0")),2)+"件";

									}	
									listData.add(data);
									cursor.moveToNext();
								}
								childs.add(listData);
								//可以將group的不存在作移除
								//@@@20140107 增設else 做測試
							}else groups.remove(i);
						} else groups.remove(i);
						cursor.close();
					}
				}

			}
			cursorGroup.close();
/*			
			if(groups != null && groups.size() > 0 && childs != null && childs.size() > 0){
				mExpandAdapter.setData(groups, childs);
    			mExpandAdapter.notifyDataSetChanged();
			}
*/			
		} catch (Exception e) {
			e.printStackTrace();
		}
//		if(groups != null && childs != null && groups.size() <= 0 && childs.size() <=0){
			mExpandAdapter.setData(groups, childs);
//			int count =  mExpandAdapter.getGroupCount(); 
//			for (int i = 0; i <count ; i++) mExpandListView.collapseGroup(i); 
			mExpandAdapter.notifyDataSetChanged();
//		}
		db.close();
		db = null;
		QUA=null;
		ANS=null;
	}
	
	
	// 可能需要再加上 Account 參數! 日結單(日期->單頭) 日結單(單頭->單身) 預購單(單頭->單身) 暫存單(單頭->單身)
	//日結單(日期->單頭)
		public void getGroupBatchData(Context context, String startDay, String endDay, String condition, String conditionValue) {
			
			//0 預購留貨不計入應收 1要計2全不計

			LinkedList<GroupData> groups = new LinkedList<GroupData>();
			LinkedList<List<PxData>> childs = new LinkedList<List<PxData>>();
			if (mGroupList != null) {
				mGroupList.clear();
			}
			
			SQLiteDatabase db = Utilis.getDB(context);
			try {
				Cursor cursorGroup = null;
				//第三層 日結,除了暫存未確認單以外,全數運算
				StringBuffer bufCategory = new StringBuffer();
				String Day1=startDay.substring(0, 4)+startDay.substring(5, 7)+startDay.substring(8, 10);
				String Day2=endDay.substring(0, 4)+endDay.substring(5, 7)+endDay.substring(8, 10);
				int defDay=DateUtil.computerDiffDate(DateUtil.getDateTime(Day2),DateUtil.getDateTime(Day1));
				if(startDay != null && startDay.length() > 0 && startDay.indexOf("/")>0) startDay = startDay.replace("/", "-");
				if(endDay != null && endDay.length() > 0 && endDay.indexOf("/")>0) endDay = endDay.replace("/", "-");
			
				StringBuffer theDay = new StringBuffer();
				theDay.append("9999999999");
				double deday[][] = new double[defDay+10][11];
				int fnd=0;
				int found=0;

				bufCategory=bufCategory.delete(0, bufCategory.toString().length());
				bufCategory.append("select FORMDATE,") //每個單日的總件數,總實應收,總成本
				.append("sum(ASUM) ,sum(BSUM) ,sum(ATOT) ,sum(COSTS),sum(DISMONEY),sum(TRCASH),sum(ATM)")
				.append(" from qhead")
				.append(" where FORMDATE >= '").append(startDay).append("'")
				.append(" and FORMDATE <= '").append(endDay).append("'");
				if (!mDept.equalsIgnoreCase("SOS")){
					bufCategory.append(" and QKIND ='").append(mKind).append("' and DEPTNO='"+mDept+"'");
				}else {
					bufCategory.append(" and QKIND ='").append(mKind).append("'");
				}
				int ORS=Utilis.toInt(DeptSend[5]);
				if (ORS!=2) //含預購帳 
					bufCategory.append(" and (ISCONFIRM='Y' or (ISCHECK='Y' and ISCONFIRM='N'))");
				else
					bufCategory.append(" and ISCONFIRM='Y' and ISCHECK='N'");

				if (condition!=null && condition.length()>0 && conditionValue!=null && conditionValue.length()>0)
					bufCategory.append(" and ").append(condition).append(conditionValue);
					
				bufCategory.append(" group by FORMDATE ");
 				cursorGroup = db.rawQuery(bufCategory.toString(), null);
			       
				if (cursorGroup != null) {
					if (cursorGroup.getCount() > 0) {
						cursorGroup.moveToFirst();
						for (int i = 0; i < cursorGroup.getCount(); i++) {
							String chkDay= cursorGroup.getString(0);
							found=theDay.toString().indexOf(chkDay);
							if (found>=0){
								fnd=found/10; //
							} else{
								fnd=0;
								for (int x=1;x<(theDay.toString().length()/10);x++){
									if (DateUtil.compare_Date(chkDay, theDay.toString().substring(x*10,(x+1)*10))==false){
										//新插入的日期較小時,將字串往後移,也要將陣列同步往後移
										theDay.insert(x*10, chkDay);
										for(int y=(theDay.toString().length()/10) ; y>x; y--){
											for (int z=0;z<11;z++) deday[y][z]=deday[y-1][z];
										}
										fnd=x;
										break;
									}
								}
								if (fnd==0){
									theDay.append(chkDay);
									fnd=(theDay.toString().length()/10)-1;
								}
							}
							
							if (nKind==PItemKind.TR10){ 
								
								if (PSWD==1){
									deday[fnd][1]=0;
									deday[fnd][0]=0;
								}else{
									deday[fnd][1]=deday[fnd][1]+cursorGroup.getDouble(4);
									deday[fnd][0]=deday[fnd][0]+(cursorGroup.getDouble(2));
								}
								deday[fnd][2]=deday[fnd][2]+cursorGroup.getDouble(3);
							}else if (nKind==PItemKind.TR20 || nKind==PItemKind.TR21){
								if (PSWD==1){
									deday[fnd][0]=0;
									deday[fnd][2]=deday[fnd][2]+cursorGroup.getDouble(3);
									deday[fnd][7]=0;
								}else{
									deday[fnd][0]=deday[fnd][0]+(cursorGroup.getDouble(2));
									deday[fnd][2]=deday[fnd][2]+cursorGroup.getDouble(3);
									deday[fnd][7]=deday[fnd][7]+cursorGroup.getDouble(5);
								}
							} else {
								deday[fnd][0]=deday[fnd][0]+(cursorGroup.getDouble(2));
								deday[fnd][2]=deday[fnd][2]+cursorGroup.getDouble(3);
								deday[fnd][7]=deday[fnd][7]+cursorGroup.getDouble(5);
							}
							cursorGroup.moveToNext();							
 						}
 					}	
 				}		
				cursorGroup.close();

				bufCategory=bufCategory.delete(0, bufCategory.toString().length());
				bufCategory.append("select FINEDATE,") //每個單日的總現金,總卡
				.append("sum(CASH) as CASHS,sum(CARD) as CARDS,sum(TRCASH),sum(ATM)")
				.append(" from qhead")
				.append(" where FINEDATE >= '").append(startDay).append("'")
				.append(" and FINEDATE <= '").append(endDay).append("'");
				if (!mDept.equalsIgnoreCase("SOS")){
					bufCategory.append(" and QKIND ='").append(mKind).append("' and DEPTNO='"+mDept+"'");
				}else {
					bufCategory.append(" and QKIND ='").append(mKind).append("'");
				}

				if (ORS!=2) //含預購帳 
					bufCategory.append(" and (ISCONFIRM='Y' or (ISCHECK='Y' and ISCONFIRM='N'))");
				else
					bufCategory.append(" and ISCONFIRM='Y' and ISCHECK='N'");
				
				if (condition!=null && condition.length()>0 && conditionValue!=null && conditionValue.length()>0)
					bufCategory.append(" and ").append(condition).append(conditionValue);
				
				bufCategory.append(" group by FINEDATE ");
				bufCategory.append(" HAVING sum(CASH)<>0 or sum(CARD)<>0 or sum(TRCASH)<>0 or sum(ATM)<>0" );
 				cursorGroup = db.rawQuery(bufCategory.toString(), null);
 				
				if (cursorGroup.getCount() > 0) {
					cursorGroup.moveToFirst();
					for (int j = 0; j < cursorGroup.getCount(); j++) {
						String chkDay= cursorGroup.getString(0);
						found=theDay.toString().indexOf(chkDay);
						if (found>=0){
							fnd=found/10; //
						} else{
							fnd=0;
							for (int x=1;x<(theDay.toString().length()/10);x++){
								if (DateUtil.compare_Date(chkDay, theDay.toString().substring(x*10,(x+1)*10))==false){
									//新插入的日期較小時,將字串往後移,也要將陣列同步往後移
									theDay.insert(x*10, chkDay);
									for(int y=(theDay.toString().length()/10) ; y>x; y--){
										for (int z=0;z<11;z++) deday[y][z]=deday[y-1][z];
									}
									fnd=x;
									break;
								}
							}
							if (fnd==0){
								theDay.append(chkDay);
								fnd=(theDay.toString().length()/10)-1;
							}
						}
						deday[fnd][3]=deday[fnd][3]+cursorGroup.getDouble(1);
						deday[fnd][4]=deday[fnd][4]+cursorGroup.getDouble(2);

						deday[fnd][8]=deday[fnd][8]+cursorGroup.getDouble(3);
						deday[fnd][9]=deday[fnd][9]+cursorGroup.getDouble(4);
						
						cursorGroup.moveToNext();
						}
					}
				cursorGroup.close();				

				bufCategory=bufCategory.delete(0, bufCategory.toString().length());
				bufCategory.append("select ORDDATE,") //每個單日的總現金,總卡
				.append("sum(ORDCASH) as CASHS,sum(ORDCARD) as CARDS")
				.append(" from qhead")
				.append(" where ORDDATE >= '").append(startDay).append("'")
				.append(" and ORDDATE <= '").append(endDay).append("'");
				if (!mDept.equalsIgnoreCase("SOS")){
					bufCategory.append(" and QKIND ='").append(mKind).append("' and DEPTNO='"+mDept+"'");
				}else {
					bufCategory.append(" and QKIND ='").append(mKind).append("'");
				}
				if (ORS!=2) //含預購帳 
					bufCategory.append(" and (ISCONFIRM='Y' or (ISCHECK='Y' and ISCONFIRM='N'))");
				else
					bufCategory.append(" and ISCONFIRM='Y' and ISCHECK='N'");

				if (condition!=null && condition.length()>0 && conditionValue!=null && conditionValue.length()>0)
					bufCategory.append(" and ").append(condition).append(conditionValue);

				bufCategory.append(" group by ORDDATE ");
				bufCategory.append(" HAVING sum(ORDCASH)<>0 or sum(ORDCARD)<>0 " );
				
 				cursorGroup = db.rawQuery(bufCategory.toString(), null);
					if (cursorGroup.getCount() > 0) {
						cursorGroup.moveToFirst();
						for (int j = 0; j < cursorGroup.getCount(); j++) {
							String chkDay= cursorGroup.getString(0);
							found=theDay.toString().indexOf(chkDay);
							if (found>=0){
								fnd=found/10; //
							} else{
								fnd=0;
								for (int x=1;x<(theDay.toString().length()/10);x++){
									if (DateUtil.compare_Date(chkDay, theDay.toString().substring(x*10,(x+1)*10))==false){
										//新插入的日期較小時,將字串往後移,也要將陣列同步往後移
										theDay.insert(x*10, chkDay);
										for(int y=(theDay.toString().length()/10) ; y>x; y--){
											for (int z=0;z<11;z++) deday[y][z]=deday[y-1][z];
										}
										fnd=x;
										break;
									}
								}
								if (fnd==0){
									theDay.append(chkDay);
									fnd=(theDay.toString().length()/10)-1;
								}
							}
							deday[fnd][5]=deday[fnd][5]+cursorGroup.getDouble(1);
							deday[fnd][6]=deday[fnd][6]+cursorGroup.getDouble(2);
							
							cursorGroup.moveToNext();							
							}
						}
					cursorGroup.close();
					
					bufCategory=bufCategory.delete(0, bufCategory.toString().length());
					bufCategory.append("select FORMDATE,sum(BSUM) from qhead")
					.append(" where FORMDATE >= '").append(startDay).append("'")
					.append(" and FORMDATE <= '").append(endDay).append("'");
					if (!mDept.equalsIgnoreCase("SOS")){
						bufCategory.append(" and QKIND ='").append(mKind).append("' and DEPTNO='"+mDept+"'");
					}else {
						bufCategory.append(" and QKIND ='").append(mKind).append("'");
					}
					if (ORS!=2) //含預購帳 
						bufCategory.append(" and (ISCONFIRM='Y' or (ISCHECK='Y' and ISCONFIRM='N'))");
					else
						bufCategory.append(" and ISCONFIRM='Y' and ISCHECK='N'");
					//指算出該日賒帳的金額
					bufCategory.append(" and (FINEDATE<=' ' or (CASH=0 and CARD=0 and ORDCASH=0 and ORDCARD=0 and ATM=0 ))"); 
					if (condition!=null && condition.length()>0 && conditionValue!=null && conditionValue.length()>0)
						bufCategory.append(" and ").append(condition).append(conditionValue);

					bufCategory.append(" group by FORMDATE ");
					
	 				cursorGroup = db.rawQuery(bufCategory.toString(), null);
						if (cursorGroup.getCount() > 0) {
							cursorGroup.moveToFirst();
							for (int j = 0; j < cursorGroup.getCount(); j++) {
								String chkDay= cursorGroup.getString(0);
								found=theDay.toString().indexOf(chkDay);
								if (found>=0){
									fnd=found/10; //
								} else{
									fnd=0;
									for (int x=1;x<(theDay.toString().length()/10);x++){
										if (DateUtil.compare_Date(chkDay, theDay.toString().substring(x*10,(x+1)*10))==false){
											//新插入的日期較小時,將字串往後移,也要將陣列同步往後移
											theDay.insert(x*10, chkDay);
											for(int y=(theDay.toString().length()/10) ; y>x; y--){
												for (int z=0;z<11;z++) deday[y][z]=deday[y-1][z];
											}
											fnd=x;
											break;
										}
									}
									if (fnd==0){
										theDay.append(chkDay);
										fnd=(theDay.toString().length()/10)-1;
									}
								}
								deday[fnd][10]=deday[fnd][10]+cursorGroup.getDouble(1);
								
								cursorGroup.moveToNext();							
								}
							}
						cursorGroup.close();
						
					for (int i=1;i<(theDay.toString().length()/10);i++){
						GroupData data = new GroupData();
							data.strPic="";
						if (nKind==PItemKind.TR10){ //進貨
							data.SEARCH = ""+theDay.toString().substring(i*10, i*10+10);
							data.strTextG1=""+theDay.toString().substring(i*10, i*10+10); //日期
							data.strTextG2="總:"+Utilis.dedb(deday[i][2],2)+"件"; //
							data.strText1 = pKind[nKind/10-1];
							if (PSWD!=1){
							data.strText2 ="外幣:"+Utilis.dedb(deday[i][0],2)+"/賒:"+Utilis.dedb(deday[i][10],2);
							data.strMoney ="合計:"+Utilis.dedb(deday[i][1],2);
							data.strOriMoney="實付:"+Utilis.dedb(deday[i][3]+deday[i][4]+deday[i][5]+deday[i][6]+deday[i][9],2);
							}else{
								data.strText2 ="";
								data.strMoney ="";
								data.strOriMoney="";
							}
						} else {
							data.SEARCH = ""+theDay.toString().substring(i*10, i*10+10);
							data.strTextG1=""+theDay.toString().substring(i*10, i*10+10); //日期
							data.strTextG2="總計:"+Utilis.dedb(deday[i][2],2)+"件 折讓:"+deday[i][7]; //								
							data.strText1 = pKind[nKind/10-1];
							if ((nKind==PItemKind.TR20 || nKind==PItemKind.TR21) && PSWD==1){
								data.strText2 ="";
								data.strOriMoney="";
								data.strMoney ="";
							}else{
								data.strText2 ="應收:"+Utilis.dedb(deday[i][0],2)+" /實:"+Utilis.dedb(deday[i][3]+deday[i][4]+deday[i][5]+deday[i][6]+deday[i][9],2)+"/賒:"+Utilis.dedb(deday[i][10],2);
								data.strOriMoney="";
								if (deday[i][3]!=0 ) data.strOriMoney="現金:"+Utilis.dedb(deday[i][3],2);
								if (deday[i][4]!=0 ) data.strOriMoney=data.strOriMoney+" /票:"+Utilis.dedb(deday[i][4],2);
								if (deday[i][9]!=0 ) data.strOriMoney=data.strOriMoney+" /匯:"+Utilis.dedb(deday[i][9],2);
								data.strMoney ="";
								if (deday[i][5]!=0 ) data.strMoney="訂金:"+Utilis.dedb(deday[i][5],2);
								if (deday[i][6]!=0 ) data.strMoney=data.strMoney+" /票:"+Utilis.dedb(deday[i][6],2);
								if (deday[i][8]!=0 ) data.strMoney=data.strMoney+" /墊:"+Utilis.dedb(deday[i][8],2);
							}
						}	
							groups.add(data);
					}
					
			//第四層各單單頭		
					if (groups.size() > 0) {
						StringBuffer bufList = new StringBuffer();
						for (int i = 0; i < groups.size(); i++) {
							if(bufList.length() > 0){
								bufList.delete(0, bufList.length());
							}
							
								bufList.append("select FORMNO,FORMDATE,USER,USERNAME,ATOT,ASUM,BSUM,")
								.append("CASH,CARD,ORDCASH,ORDCARD,HANDNO,COSTS,FINEDATE,ORDDATE,EMPID,EMPNAME,DISMONEY,TRCASH,ATM,CREATEDATETIME from qhead ");
								
								bufList.append("  where (( FORMDATE = '").append(groups.get(i).SEARCH).append("' and ISCONFIRM = 'Y')");
								bufList.append(" or ( FINEDATE = '").append(groups.get(i).SEARCH).append("' and ISCONFIRM = 'Y')")
								.append(" or (ORDDATE = '").append(groups.get(i).SEARCH).append("' and (ISCONFIRM = 'Y' or (ISCHECK='Y' and ISCONFIRM='N')))");

								if (!mDept.equalsIgnoreCase("SOS")){
									bufList.append(") and QKIND ='").append(mKind).append("' and DEPTNO='"+mDept+"'");
								}else {
									bufList.append(") and QKIND ='").append(mKind).append("'");
								}
								
								if (condition!=null && condition.length()>0 && conditionValue!=null && conditionValue.length()>0)
									bufList.append(" and ").append(condition).append(conditionValue);
							       //Toast.makeText(QPosff.this,bufList.toString() , Toast.LENGTH_SHORT).show();
								bufList.append(" order by FORMNO");							       
									Cursor cursor = db.rawQuery(bufList.toString(), null);
									List<PxData> listData = new ArrayList<PxData>();
									if (cursor != null) {
										if (cursor.getCount() > 0) {
											cursor.moveToFirst();
											for (int k = 0; k < cursor.getCount(); k++) {
												PxData data=new PxData();
												
												data.iFormdate = cursor.getString(0);
												data.iGoods = cursor.getString(2)+"/"+cursor.getString(3);
												data.iName = cursor.getString(20);
												data.iPic="";
												
												if (nKind==PItemKind.TR10){ //進貨
													Cursor csCust=db.rawQuery("select pic from qfact where FACTNO='"+cursor.getString(2)+"'", null);
													if (csCust.getCount()>0) {
														csCust.moveToFirst();
														data.iPic=csCust.getString(0);
													}
													if (PSWD==1){													
													data.iImpo = ""; 
													data.iMoney =  "";
													}else{
														data.iImpo = "成本合計"+Utilis.dedb(cursor.getDouble(6)+cursor.getDouble(18),2); 
														data.iMoney =  "外幣合計"+Utilis.dedb(cursor.getDouble(12),2);
													}
													data.iNumber ="("+Utilis.dedb(cursor.getDouble(11),2)+"件)(折:"+cursor.getString(17)+")";
												} else {   //(14FINEDATE)(15ORDDATE)
													data.iCountry =cursor.getString(4);
													Cursor csCust=db.rawQuery("select pic from qcust where CUSTNO='"+cursor.getString(2)+"'", null);
													if (csCust.getCount()>0) {
														csCust.moveToFirst();
														data.iPic=csCust.getString(0);
													}
													
													if ((nKind==PItemKind.TR20 || nKind==PItemKind.TR21) && PSWD==1){
														data.iCountry =cursor.getString(15)+"/"+cursor.getString(16);
														data.iImpo ="";
														data.iMoney ="現:";
														data.iCompany = "訂:";
													}else{
														data.iCountry =cursor.getString(15)+"/"+cursor.getString(16);
														data.iImpo = "應:"+Utilis.dedb(cursor.getInt(6),2)+"收"+Utilis.dedb(Math.round(cursor.getDouble(7)+cursor.getDouble(8)+cursor.getDouble(9)+cursor.getDouble(10)+cursor.getDouble(19)),2);
														data.iMoney ="現:";
														if (Utilis.toInt(cursor.getString(7))!=0)	data.iMoney =data.iMoney + Utilis.dedb(cursor.getDouble(7),2);
														if (Utilis.toInt(cursor.getString(8))!=0)	data.iMoney =data.iMoney +" 票:"+Utilis.dedb(cursor.getDouble(8),2);
														if (Utilis.toInt(cursor.getString(19))!=0)	data.iMoney =data.iMoney +" 匯:"+Utilis.dedb(cursor.getDouble(19),2);
														data.iCompany = "訂:";
														if (Utilis.toInt(cursor.getString(9))!=0)	data.iCompany =data.iCompany + Utilis.dedb(cursor.getDouble(9),2);
														if (Utilis.toInt(cursor.getString(10))!=0)	data.iCompany =data.iCompany +" 票:"+Utilis.dedb(cursor.getDouble(10),2);
														if (Utilis.toInt(cursor.getString(18))!=0)	data.iCompany =data.iCompany +" 墊:"+cursor.getString(18);
													}
														if (Utilis.toInt(cursor.getString(17))!=0)
															data.iNumber ="("+cursor.getString(11)+"件)(折:"+cursor.getString(17)+")";
														else
															data.iNumber ="("+cursor.getString(11)+"件)";
												}
												listData.add(data);
												
												cursor.moveToNext();
											}
											childs.add(listData);
										}
									}
									cursor.close();
						}
					}
/*				
				if(groups != null && groups.size() > 0 && childs != null && childs.size() > 0){
					mExpandAdapter.setData(groups, childs);
					mExpandAdapter.notifyDataSetChanged();
				}
*/				
			} catch (Exception e) {
				e.printStackTrace();
			}
//			if(groups != null && childs != null && groups.size() <= 0 && childs.size() <=0){
				mExpandAdapter.setData(groups, childs);
				mExpandAdapter.notifyDataSetChanged();
//			}
			db.close();
			db = null;
			
		}

		//日總結
	class MainLongClick implements OnLongClickListener {
		@Override
		public boolean onLongClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QPosff.this);
			if (mStartDay.equalsIgnoreCase(mEndDay) && nPart==0){
				//只能在單一天的情況,且在總倉做日總結時,作用
				switch (id) {
					case R.id.btn_sort_pic:
						DialogUtilis.showDialog(QPosff.this, "是否開始印製 出貨銷貨總結", -1,
								new String[] { "放棄印製", "開始印製","A4預覽","匯入電商銷貨檔(CSV)" }, new IDialog() {
									@Override
									public void onDialogFinish(int pos, String choice) {
										switch (pos) {
										case 0: {break;}
										case 1: //開始印製
											String theDay=mStartDay.replace("/", "-");
											PosUtilis.printDayOf20213031(QPosff.this,theDay,0);
											break;
										case 2:
											theDay=mStartDay.replace("/", "-");
											PosUtilis.printDayOf20213031(QPosff.this,theDay,1);
										case 3:
											//選擇匯入銷貨.CSV
											//明細貨號 件數 單價
											
										}
									}
						});
				}
			} else Toast.makeText(QPosff.this,"只能以日為單位,進行[日總結]" , Toast.LENGTH_SHORT).show();
			
			return false;
		}
	}
		

		private LongClick mLongClickListener = new LongClick();
		private int [] locas={0,1,2};//0預購 1留貨 2銷貨
		private String [] locS={"O","R","N"};
		private int isGroup=0;
		
		class LongClick implements OnItemLongClickListener {
			@SuppressWarnings("static-access")
			@Override
			 public boolean onItemLongClick(AdapterView<?> parent, View childView,int flatPos, long id) {  			
	                long packedPos = ((ExpandableListView) parent).getExpandableListPosition(flatPos);  
	                final int groupPosition = mExpandListView.getPackedPositionGroup(packedPos);
	                final int childPosition = ExpandableListView.getPackedPositionChild(id);
	                //預設在 暫存單 長按
	    			String [] Lmenu={"結帳","變更交易","整張單刪除","整張單轉預購","整張單轉留貨","預購留貨清單","留貨轉銷貨清單","輸出","補印單據","返回"};
	                if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
	                	//GROUP
	                	isGroup=1;
	                	GroupData datag =mExpandAdapter.groups.get(groupPosition);
    	    			if (abMode==0) {//非日結 先確立 單號 會員
    	    				mKey=datag.SEARCH;
    	    				mUser=datag.strTextG1.substring(0, datag.strTextG1.indexOf("/"));
    	    				
    	    				if (mGroupMode==GroupMode.NUMBER){//確認的交易單
        	    				Lmenu=Lmenu3;
        	    				//"0確認結帳","1變更交易","2整張單刪除","3輸出","4補印單據","5","6返回","7","8"
        	    				if (nKind==10){ Lmenu[5]="選擇匯入門市出貨單";Lmenu[6]="進貨商品拜訪預購留貨";Lmenu[7]="進貨商品拜訪預購配貨";Lmenu[8]="返回";}
        	    				if (nKind==20 || nKind==21) { Lmenu[5]="";Lmenu[6]="出貨商品拜訪預購留貨";Lmenu[7]="匯出csv文件";Lmenu[8]="返回"; }
    	    					locas[0]=0;locas[1]=1;locas[2]=2;
    	    					Lmenu[0]="重返結帳";
    	    				}else if (mGroupMode==GroupMode.CATEGORY){//預購
        	    				Lmenu=Lmenu0;
        	    				//"0確認結帳","0變更交易","1整張單刪除","2整張單轉預購","3整張單轉留貨","4預購留貨清單","5留貨轉銷貨清單","6輸出","7補印單據","8返回"
    	    					locas[0]=1;locas[1]=2;locas[2]=0;
    	    					Lmenu[0]="立刻確認儲存";Lmenu[1]="保留";
    	    					if (nKind==30 || nKind==31) {Lmenu[3]= datag.SEARCH+A123[locas[2]]+ C123[locas[0]];Lmenu[4]= datag.SEARCH+A123[locas[2]]+ C123[locas[1]];}
    	    					else{Lmenu[3]="輸出";Lmenu[4]="補印單據";}
    	    					
        	    				if (nKind==10) { Lmenu[5]="不可_匯入門市出貨單";Lmenu[6]="進貨商品拜訪預購留貨";}  
        	    				if (nKind==20 || nKind==21) { Lmenu[5]="保留";Lmenu[6]="出貨商品拜訪預購留貨"; }
        	    				if (nKind==30 || nKind==31) { Lmenu[5]="會員:"+datag.strTextG1+"_的預購留貨清單";Lmenu[6]="會員:"+datag.strTextG1+"_的留貨轉銷貨清單";	}
        	    				
    	    				}else if (mGroupMode==GroupMode.COMPANY){//暫存銷貨
        	    				Lmenu=Lmenu0;
    	    					locas[0]=0;locas[1]=1;locas[2]=2;
    	    					Lmenu[0]="確認結帳";
    	    					if (nKind==30 || nKind==31) {Lmenu[3]= datag.SEARCH+A123[locas[2]]+ C123[locas[0]];Lmenu[4]= datag.SEARCH+A123[locas[2]]+ C123[locas[1]];}
    	    					else{Lmenu[3]="輸出";Lmenu[4]="補印單據";}
    	    					
        	    				if (nKind==10){ Lmenu[5]="不可_匯入門市出貨單";Lmenu[6]="進貨商品拜訪預購留貨";Lmenu[7]="進貨商品拜訪預購配貨";Lmenu[8]="";}  else if (nKind==20 || nKind==21) { Lmenu[5]="保留";Lmenu[6]="出貨商品拜訪預購留貨";Lmenu[7]="返回";Lmenu[8]=""; }
        	    				else{
            	    				Lmenu[5]="會員:"+datag.strTextG1+"_的預購留貨清單";
            	    				Lmenu[6]="會員:"+datag.strTextG1+"_的留貨轉銷貨清單";
        	    				}
    	    				}else if (mGroupMode==GroupMode.KEEPA){//留貨
        	    				Lmenu=Lmenu0;
    	    					locas[0]=0;locas[1]=2;locas[2]=1;
    	    					Lmenu[0]="立刻確認儲存";Lmenu[1]="保留";
    	    					if (nKind==30 || nKind==31) {Lmenu[3]= datag.SEARCH+A123[locas[2]]+ C123[locas[0]];Lmenu[4]= datag.SEARCH+A123[locas[2]]+ C123[locas[1]];}
    	    					else{Lmenu[3]="輸出";Lmenu[4]="補印單據";}
    	    					
        	    				if (nKind==10){ Lmenu[5]="不可_匯入門市出貨單";Lmenu[6]="進貨商品拜訪預購留貨";}  else if (nKind==20 || nKind==21) { Lmenu[5]="保留";Lmenu[6]="出貨商品拜訪預購留貨"; }
        	    				else{
            	    				Lmenu[5]="會員:"+datag.strTextG1+"_的預購留貨清單";
            	    				Lmenu[6]="會員:"+datag.strTextG1+"_的留貨轉銷貨清單";
        	    				}
    	    				}
    	    			}else{//日結單頭
    	    				Lmenu=Lmenu1;
    	    				mKey=datag.SEARCH;
    	    				//PxData dataa = mExpandAdapter.getData(groupPosition, childPosition);
    	    				//mKey=dataa.iFormdate;
    	    			}
	                }else{//CHILD
	                	isGroup=0;
    	    			if (abMode==1) {//日結單
    	    				//QHEAD
							PxData dataa = mExpandAdapter.getData(groupPosition, childPosition);
    	    				Lmenu=Lmenu3;
    	    				//if (nKind!=10){ Lmenu[5]="返回";Lmenu[6]="";} else { Lmenu[5]="匯入門市出貨單";Lmenu[6]="返回";}
    	    				//if (nKind==10){ Lmenu[5]="匯入門市出貨單";Lmenu[6]="進貨商品拜訪預購留貨";}  else if (nKind==20 || nKind==21) { Lmenu[5]="保留";Lmenu[6]="進貨商品拜訪預購留貨"; } else {Lmenu[5]="返回";Lmenu[6]="";} 

    	    				if (mGroupMode==GroupMode.NUMBER){
    	    					locas[0]=0;locas[1]=1;locas[2]=2;Lmenu[0]="重返結帳";
    	    				}else if (mGroupMode==GroupMode.CATEGORY){//預購
    	    					locas[0]=1;locas[1]=2;locas[2]=0;Lmenu[0]="確認儲存";
    	    				}else if (mGroupMode==GroupMode.COMPANY){//暫存銷貨
    	    					locas[0]=0;locas[1]=1;locas[2]=2;Lmenu[0]="結帳";
    	    				}else if (mGroupMode==GroupMode.KEEPA){//留貨
    	    					locas[0]=0;locas[1]=2;locas[2]=1;Lmenu[0]="確認儲存";
    	    				}
    	    				mUser=dataa.iGoods.substring(0, dataa.iGoods.indexOf("/"));
    	    				mKey=dataa.iFormdate;
    	    			}else{//非日結單
    	    				//QITEMS商品 長按 {  "轉留貨","轉預購","預購清單","留貨清單","返回" };
							PxData dataa = mExpandAdapter.getData(groupPosition, childPosition);
    	    				Lmenu=Lmenu2;
    	    				//"0轉留貨","1轉預購","2預購留貨清單","3商品追蹤","4返回"
    	    				if (mGroupMode==GroupMode.NUMBER){
    	    					locas[0]=0;locas[1]=1;locas[2]=2;
    	    				}else if (mGroupMode==GroupMode.CATEGORY){//預購
    	    					locas[0]=1;locas[1]=2;locas[2]=0;
    	    				}else if (mGroupMode==GroupMode.COMPANY){//暫存銷貨
    	    					locas[0]=0;locas[1]=1;locas[2]=2;
    	    				}else if (mGroupMode==GroupMode.KEEPA){//留貨
    	    					locas[0]=0;locas[1]=2;locas[2]=1;
    	    				}
    	    				mGoods=dataa.iGoods;
    	    				mTime=dataa.iCreatetime;
    	    				if ((nKind==30 || nKind==31) && mGroupMode != GroupMode.NUMBER){
    	    					Lmenu[0]=dataa.iGoods+A123[locas[2]]+C123[locas[0]];Lmenu[1]= dataa.iGoods+A123[locas[2]]+C123[locas[1]];
    	    				}else{
    	    					Lmenu[0]="功能保留";Lmenu[1]="功能保留";
    	    				}
	    					GroupData datag =mExpandAdapter.groups.get(groupPosition);
	    					mUser=datag.strTextG1.substring(0, datag.strTextG1.indexOf("/"));
	    					mKey=datag.SEARCH;
    	    				Lmenu[2]="商品:"+mGoods+"_的預購留貨清單";
    	    				Lmenu[3]="商品:"+mGoods+"_追蹤";
    	    			}
	                	
	                }
	    			Utilis.runVibrate(QPosff.this);
	    			
	    			//@@@日結單只能有,印製日結單的功能
	    			DialogUtilis.showDialog(QPosff.this, "請選擇以下功能", -1,
	    					Lmenu, new IDialog() {
	    						@Override
	    						public void onDialogFinish(int pos, String choice) {
	    							switch (pos) {
	    								case 0: //重返結帳作業
	    								{
    									if (abMode==0 && isGroup==1 || abMode==1 && isGroup==0){
											int canDo=0;
	    									if (isPass<6 && isPass!=3 && isPass!=4) { 
												SQLiteDatabase db = Utilis.getDB(QPosff.this);
	    											if (mGroupMode!=GroupMode.KEEPA){ //非留貨區
	    												if (mGroupMode==GroupMode.CATEGORY){//預購有2種
	    													Cursor cs=db.rawQuery("select ISCONFIRM from qhead where FORMNO='"+mKey+"'", null);
	    													if (cs.getCount()>0){
	    														cs.moveToFirst();
	    														if (!cs.getString(0).equalsIgnoreCase("O"))	canDo=1;
	    														else {
	    															canDo=2;
	    														}
	    													}
	    													cs.close();
	    												}else  canDo=1;

	    												if (canDo==1){
		    												Intent intent = new Intent();
		    												if (mGroupMode==GroupMode.NUMBER){
		    													intent.putExtra("pos_mode",PItemMode.SEARCH);
		    												}else {  //總部單及分店單分治
		    														intent.putExtra("pos_mode",PItemMode.EDIT);
		    												} 
		    												intent.putExtra("pos_npart",nPart);
			    											intent.putExtra("pos_formno",mKey);
			    											intent.putExtra("pos_qkind",nKind);// @@TR30為預設(暫時廠進貨單)
			    											intent.putExtra("pos_where",PsaveWhere.Qposf);
			    											intent.putExtra("pos_group",mGroupMode);
			    											intent.setClass(QPosff.this,QPosSave.class);
			    											startActivityForResult(intent, RESULT_QPOSAVE);
	    												}
	    											}else{//留貨
	    												canDo=2;
	    											}
		    					    			if (canDo==2){//預購或留貨
		    										String[] args = {mKey,mKind};
		    										ContentValues value = new ContentValues();
		    										value.put("TR","Y1");
		    										int success = db.update(TbName.QHEAD, value,"FORMNO=? and QKIND=?", args);
    												Toast.makeText(QPosff.this, mKey+" 留貨預購已儲存完畢!!", Toast.LENGTH_SHORT).show();
    												if (of_line!=0 && Utilis.haveInternet(QPosff.this)) {
    													DBCloud.aa1_aa0_update_HI(QPosff.this);
    												}
		    					    			}
		    					    			db.close();
    										}else {
	    											ProgressDialog mProgress = null;
	    						        		    mProgress = new ProgressDialog(QPosff.this);
	    						        			mProgress.setCancelable(true);
	    						        			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    						        			mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
	    						        			mProgress.show();
	    										}
    									}else if (abMode==1 && isGroup==1){ //印製日結單
    										rep_today(groupPosition, 0);
    									}else if (abMode==0 && isGroup==0 && mGroupMode != GroupMode.NUMBER && (nKind==30 || nKind==31)){ //qitems
    										changeItems(1,0);//銷貨轉預購 類
    									}else{
											 Toast.makeText(QPosff.this, "非銷貨單!! 不可執行喔!! ", Toast.LENGTH_LONG).show();
    									}
  										break;
	    							}
    								case 1://變更交易
    								{
    									if ((abMode==1 && isGroup==0)){
    										//@@@如果是入金單,不可變更交易 只能重返帳 或 正張單刪除
    										PxData dataa = mExpandAdapter.getData(groupPosition, childPosition);
    										if (dataa.iNumber.indexOf("+0")<0 || dataa.iNumber.indexOf("-")>0){
		    										if (PSWD==0) modifyF(0);	else askPSWD(0);
    										}else{
    											Toast.makeText(QPosff.this, "入金單 不能變更交易!! 只能重返結帳 或 整張單刪除 ", Toast.LENGTH_SHORT).show();
    										}
    									}else if ((abMode==0 && isGroup==1 && mGroupMode == GroupMode.NUMBER)){
    										if (PSWD==0) modifyF(0);	else askPSWD(0);
    									}else if (abMode==0 && isGroup==0 && mGroupMode != GroupMode.NUMBER && (nKind==30 || nKind==31)){
    										changeItems(1,1);//銷貨轉留貨 類
    									}else if (abMode==1 && isGroup==1){ //印製日結單
    										rep_today(groupPosition, 1);
    									}else if (mGroupMode == GroupMode.COMPANY){
    										Intent intent = new Intent();										
											intent.putExtra("pos_mode",PItemMode.EDIT);
    										//PxData data = mExpandAdapter.getData(groupPosition, childPosition);
											intent.putExtra("pos_formno",mKey);
											intent.putExtra("pos_qkind",nKind);// @@TR30為預設(暫時廠進貨單) 
											intent.putExtra("pos_dept",mDept);//理論上為"SOS" 或 門市代號
											intent.putExtra("pos_where",PItemWhere.Qposf);
											intent.putExtra("pos_group",mGroupMode);
    										intent.setClass(QPosff.this,APos.class);									
    										startActivityForResult(intent,RESULT_APOS);
    									}
    									break;
    								}
    								case 2://整張單刪除
    								{
    									if (abMode==0 && isGroup==1 || abMode==1 && isGroup==0){
	    										if (PSWD==0) modifyF(1);	else askPSWD(1);
    									}else if (abMode==0 && isGroup==0){//預購留貨清單_依商品 所有會員
    										Intent intent = new Intent();
    					    				intent.putExtra("GalleryUser","");
    					    				intent.putExtra("GalleryGoods",mGoods);
    										String Dept=mDept;if (mDept.equalsIgnoreCase("SOS")) Dept=deptStr[0]; 
    					    				intent.putExtra("GalleryDept", Dept);
    					    				intent.putExtra("GalleryASK"," and GOODSNO='"+mGoods+"' ");
    					    				intent.putExtra("FormNo","");
    					    				intent.putExtra("GalleryQKIND",mKind);
    					    				intent.putExtra("GalleryMode",1);//0mUser 1mGoods 2KeepaToSale
    										intent.setClass(QPosff.this, GalleryViewO.class);
											startActivityForResult(intent, RESULT_GALLERYO);
    									}else if (abMode==1 && isGroup==1){ //印製A4日結單
    						    			GroupData datag =mExpandAdapter.groups.get(groupPosition);
    										String Dept=mDept;if (mDept.equalsIgnoreCase("SOS")) Dept=deptStr[0]; 
    										Intent intent = new Intent();
    										intent.putExtra("SERCH",datag.strTextG1);
    										intent.putExtra("QKIND",mKind);
    										intent.putExtra("MODE",1);
    										intent.putExtra("DEPTNO",Dept);
    										intent.putExtra("BUFSTR","");
    										intent.putExtra("BUFTITLE","1;2;3");
    										intent.putExtra("STARTDAY",datag.strTextG1);
    										intent.putExtra("ENDDAY",datag.strTextG1);
    										
    										intent.setClass(QPosff.this, MkqrSt.class);
    										startActivity(intent);
    										
    									}
    									break;
    								}
    								case 3://商品追蹤
    								{
    									if (abMode==0 && isGroup==1 && mGroupMode!=GroupMode.NUMBER && (nKind==30 || nKind==31)){
    										changeItems(0,0);//整張單轉預購 類
    									}else if (abMode==0 && isGroup==0){//qitems
											Intent intent = new Intent();
											intent.putExtra("QHis_kind", nKind);
											if (mGroupMode==GroupMode.KEEPA) intent.putExtra("QHis_mode", 6); else if (mGroupMode==GroupMode.CATEGORY) intent.putExtra("QHis_mode", 5); else intent.putExtra("QHis_mode", 1); 
											intent.putExtra("QHis_User","" );
											intent.putExtra("QHis_Goods",mGoods );
											intent.setClass(QPosff.this, QHis.class);
											startActivity(intent);
    									}else if (abMode==1 && isGroup==1){ //輸出A4日結明細單
    						    			GroupData datag =mExpandAdapter.groups.get(groupPosition);
    										String Dept=mDept;if (mDept.equalsIgnoreCase("SOS")) Dept=deptStr[0]; 
    										Intent intent = new Intent();
    										intent.putExtra("SERCH",datag.strTextG1);
    										intent.putExtra("QKIND",mKind);
    										intent.putExtra("MODE",2);
    										intent.putExtra("DEPTNO",Dept);
    										intent.putExtra("BUFSTR","");
    										intent.putExtra("BUFTITLE","1;2;3");
    										intent.putExtra("STARTDAY",datag.strTextG1);
    										intent.putExtra("ENDDAY",datag.strTextG1);
    										
    										intent.setClass(QPosff.this, MkqrSt.class);
    										startActivity(intent);
    									}else if(abMode==1 && isGroup==0 || abMode==0 && isGroup==1){//qhead
        									Intent intent = new Intent();
        									intent.setClass(QPosff.this,MakeTransDetail.class);
											intent.putExtra("make_batch",mKey);
											intent.putExtra("make_mode",1);
											intent.putExtra("make_kind",nKind);
											intent.putExtra("make_user","");
											intent.putExtra("make_01",0);
        									startActivity(intent);
    									}
    									break;
    								}
    								case 4://整張單轉單
    								{
    									if (abMode==0 && isGroup==1 && mGroupMode!=GroupMode.NUMBER && (nKind==30 || nKind==31)){
    										changeItems(0,1);//整張單轉留貨 類
       									}else if ( abMode==1 && isGroup==0 || abMode==0 && isGroup==1){//補印單據
	    									Intent intent = new Intent();
	    									intent.putExtra("pos_npart",nPart);
	    									intent.putExtra("pos_mode",PItemMode.SEARCH);
	    									intent.putExtra("pos_formno",mKey);
	    									intent.putExtra("pos_qkind",nKind);//int @@TR30 
	    									intent.putExtra("pos_where",PsaveWhere.Repeat);
	    									intent.putExtra("pos_group",mGroupMode);
	    									intent.setClass(QPosff.this,QPosSave.class);
    									startActivity(intent);

    									}
    									break;
    								}
    								case 5://預購留貨清單&&選擇匯入門市出貨單
    								{
    								if (abMode==0 && isGroup==1 && mGroupMode!=GroupMode.NUMBER && (nKind==30 || nKind==31)){
										Intent intent = new Intent();
					    				intent.putExtra("GalleryUser",mUser);
					    				intent.putExtra("GalleryGoods","");
										String Dept=mDept;if (mDept.equalsIgnoreCase("SOS")) Dept=deptStr[0]; 
					    				intent.putExtra("GalleryDept", Dept);
					    				intent.putExtra("GalleryASK"," and USER='"+mUser+"' ");
					    				intent.putExtra("FormNo","");
					    				intent.putExtra("GalleryQKIND",mKind);
					    				intent.putExtra("GalleryMode",0);//0mUser 1mGoods 2KeepaToSale
										intent.setClass(QPosff.this, GalleryViewO.class);
										startActivityForResult(intent, RESULT_GALLERYO);
    								}else if (nKind==10 && (abMode==1 && isGroup==0) || (abMode==0 && isGroup==1 && mGroupMode==GroupMode.NUMBER)){ 
    									if (nKind==10){//選擇匯入門市出貨單
    										//且為 廠商進貨單時選擇匯入門市
											//廠商進貨單 可以開出門市代號清單 選擇確認轉入 門市出貨單
											//註記在 EMPNAME存入了 轉貨單號 也需再轉單時,檢查該單是否存在
											//如果存在,應先刪除該單QITEMS,再INSERT
											//showImportDialog(final Context context,final String mKey,int nPart,int tmode)
    										PosUtilis.showImportDialog(QPosff.this,mKey,nPart,1);    										
    									}
    								}
    									break;
    								}
    									
    								case 6://留貨轉銷貨清單
    								{
    									if (abMode==0 && isGroup==1 && mGroupMode!=GroupMode.NUMBER && (nKind==30 || nKind==31)){
											Toast.makeText(QPosff.this, "留貨轉銷貨 USER= "+mUser+"  QKIND="+""+nKind, Toast.LENGTH_SHORT).show();
    										Intent intent = new Intent();
						    				intent.putExtra("GalleryUser",mUser);
						    				intent.putExtra("GalleryGoods","");
											String Dept=mDept;if (mDept.equalsIgnoreCase("SOS")) Dept=deptStr[0]; 
						    				intent.putExtra("GalleryDept", Dept);
						    				intent.putExtra("GalleryASK"," and USER='"+mUser+"' ");
    					    				intent.putExtra("FormNo",PosUtilis.getFno(QPosff.this,mUser,""+nKind,0));
    					    				intent.putExtra("GalleryQKIND",mKind);
						    				intent.putExtra("GalleryMode",2);//0mUser 1mGoods 2KeepaToSale
											intent.setClass(QPosff.this, GalleryViewO.class);
											startActivityForResult(intent, RESULT_GALLERYO);
											
           								}else if ((nKind==10 || nKind==20 || nKind==21) && (abMode==0 && isGroup==1)){ 
											//以廠商進貨商品內容拜訪預購留貨清單
							    			int count =  mExpandAdapter.getChildrenCount(groupPosition);
							    			if (count>0){  //一一加入GOODSNO,
        										String ASK=" and GOODSNO IN (";
								    			for (int i = 0; i <count ; i++){
								    				PxData data =mExpandAdapter.getData(groupPosition, i);
								    				ASK=ASK+"'"+data.iGoods+"'";
								    				if (i<(count-1)) ASK=ASK+","; 
								    			}
								    			ASK=ASK+")";
		   										//Toast.makeText(QPosff.this, "檢測_ASK="+ASK, Toast.LENGTH_SHORT).show();
    											Intent intent = new Intent();
        					    				intent.putExtra("GalleryUser","");
        					    				intent.putExtra("GalleryGoods","");
        										String Dept=mDept;if (mDept.equalsIgnoreCase("SOS")) Dept=deptStr[0]; 
        					    				intent.putExtra("GalleryDept", Dept);
        					    				intent.putExtra("GalleryASK",ASK);
        					    				intent.putExtra("FormNo","");
        					    				intent.putExtra("GalleryQKIND",mKind);
        					    				intent.putExtra("GalleryMode",3);//0mUser 1mGoods 2KeepaToSale
        										intent.setClass(QPosff.this, GalleryViewO.class);
        										startActivity(intent);					
							    			}
            							}
    									break;
    								}
    									
    								case 7: //廠商進貨單拜訪(配貨)
    								{
    									 if (nKind==10 && (abMode==0 && isGroup==1)){ 
 											//以廠商進貨商品內容拜訪預購留貨清單
						    				PxData data =mExpandAdapter.getData(groupPosition, 0);
 								    			
 												Bundle bundle = new Bundle();
 												Intent intent = new Intent();
 												bundle = new Bundle();
 												bundle.putString("GalleryChild",mKey+";0;0");
 												intent.setClass(QPosff.this, GalleryViewVP.class);
 												intent.putExtras(bundle);
 												startActivity(intent);
    									 } else	 if ((nKind==20 || nKind==21) && (abMode==0 && isGroup==1)){
    										 //以單號拜訪qitems
    										 //出貨轉貨單匯出CSV
    										 //檔案名稱 E_D_D1221000001_2021-03-20.csv
    										 //欄位結構
    										 //主貨號|明細貨號|品名規格|進貨數量|進貨單價|品名規格|顏色|尺寸|倉儲|廠商|倉庫|明細貨號|0|進貨數量|0|0|明細貨號|進貨單價|進貨小計
												SQLiteDatabase db = Utilis.getDB(QPosff.this);
												Cursor cs=db.rawQuery("select GOODSNO,GOODSNOS,GOODSNAME,UNIT20,UNITPRICE,GOODSNAME, UNIT1,SIZE,DEPTNO,USER,FORMDATE,FORMNO from qitems where FORMNO='"+mKey+"'", null);
												if (cs.getCount()>0){
													StringBuffer Bufstr=new StringBuffer();
													String FromW="";
													char Ttab=(char)9;
													//Bufstr.append("主貨號,明細貨號,品名規格,進貨數量,進貨單價,品名格,顏色,尺寸,倉儲,廠商,倉庫,明細貨號,0,進貨數量,0,0,明細貨號,進貨單價,進貨小計\r\n");
													Bufstr.append("商品編號"+Ttab+"品項條碼"+Ttab+"品名規格"+Ttab+"進貨數量"+Ttab+"進貨單價"+Ttab+"品名格"+Ttab+"顏色"+Ttab+"尺寸"+Ttab+"倉儲"+Ttab+"廠商\r\n");
													while(cs.moveToNext()){
														FromW=myCSVPath+"/"+cs.getString(10)+"_"+cs.getString(11)+""+"_"+cs.getString(8)+""+"_"+cs.getString(9)+".csv";
														for (int x=0;x<=7;x++)
														Bufstr.append(cs.getString(x)+Ttab);
														
														Bufstr.append(Ttab);//倉儲
														Bufstr.append(cs.getString(8)+Ttab);
														Bufstr.append("\r\n");//換行
													}
													outPut_bufStr(Bufstr.toString(),FromW);
												}

    										 
     									}else if(abMode==1 && isGroup==0 || abMode==0 && isGroup==1){//qhead
        									Intent intent = new Intent();
        									intent.setClass(QPosff.this,MakeTransDetail.class);
											intent.putExtra("make_batch",mKey);
											intent.putExtra("make_mode",1);
											intent.putExtra("make_kind",nKind);
											intent.putExtra("make_user","");
											intent.putExtra("make_01",0);
        									startActivity(intent);
             								
             							}
    									break;
    								}
    								case 8://補印單據
    								{
    									//if ((nKind!=10 && abMode==0 && isGroup==1) || abMode==1 && isGroup==0){
    									if (nKind!=10 && abMode==0 && isGroup==1 && mGroupMode!=GroupMode.NUMBER){
    										//GroupData datag =mExpandAdapter.groups.get(groupPosition);
	    									Intent intent = new Intent();
	    									intent.putExtra("pos_npart",nPart);
	    									intent.putExtra("pos_mode",PItemMode.SEARCH);
	    									intent.putExtra("pos_formno",mKey);
	    									intent.putExtra("pos_qkind",nKind);//int @@TR30 
	    									intent.putExtra("pos_where",PsaveWhere.Repeat);
	    									intent.putExtra("pos_group",mGroupMode);
	    									intent.setClass(QPosff.this,QPosSave.class);
    									startActivity(intent);
    									}
    									break;
    								}
    								case 9://返回
    								{
    									
    									break;
    								}
	    						}
	    					}
					});
	    			
					return true;

			}
		}
			
		
	ExpandChildClick mChildClcik = new ExpandChildClick();
	
	class ExpandChildClick implements OnChildClickListener{
		@Override
		public boolean onChildClick(ExpandableListView parent, View v,
				final int groupPosition,final int childPosition, long id) {
			Utilis.runVibrate(QPosff.this);
			//輕按第二層商品清冊
			if (abMode!=1){
				if(mGroupMode == GroupMode.COMPANY)
		    		btns=Utilis.getIni(QPosff.this,"INIH","M_COMPANY",9);
				else if (mGroupMode == GroupMode.CATEGORY)
					btns=Utilis.getIni(QPosff.this,"INIH","M_CATEGORY",9);
				else if (mGroupMode == GroupMode.NUMBER)
					btns=Utilis.getIni(QPosff.this,"INIH","M_NUMBER",9);
				else
					btns=Utilis.getIni(QPosff.this,"INIH","M_NUMBER",9);
			}else{
				btns=Utilis.getIni(QPosff.this,"INIH","M_PIC",9);
			}
	    		bttns = btns.split("!&!");  	for(int i=0;i<9;i++)	menu_X[i] = bttns[i];
				//if (mGroupMode == GroupMode.NUMBER && nKind==10) menu_X[5]="轉入門市出貨單";
				
			      // Toast.makeText(QPosff.this," groupPosition="+groupPosition+"_childPosition="+childPosition , Toast.LENGTH_SHORT).show();										
				
			
			DialogUtilis.showDialog(QPosff.this, "請選擇以下功能", -1,
					menu_X, new IDialog() {
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch (pos) {
								case 0: //商品流覽編輯(或唯讀)
								{
									int nQhis=Utilis.toInt(Utilis.getIni(QPosff.this,"INIH","QHIS",(nKind/10)));									
									Intent intent = new Intent();
				                	GroupData datag =mExpandAdapter.groups.get(groupPosition);
									PxData data = mExpandAdapter.getData(groupPosition, childPosition);
									mKey=data.iFormdate;
									Bundle bundle = new Bundle();
									if (abMode==1 || mGroupMode==GroupMode.NUMBER){//查詢唯讀
										Toast.makeText(QPosff.this,"此處不可以進入商品流覽!!" , Toast.LENGTH_SHORT).show();										
									}else{
										//找出qfact qcust
										StringBuffer mySqlBuf = new StringBuffer();
										if (nKind!=10)
											mySqlBuf.append("select DISCOUNT,S2 from qcust where  CUSTNO='"+datag.strTextG1.substring(0, datag.strTextG1.indexOf("/"))+"'" );
										else
											mySqlBuf.append("select DISCOUNT,EMPID from qfact where  FACTNO='"+datag.strTextG1.substring(0, datag.strTextG1.indexOf("/"))+"'" );
											
										mySqlBuf.append(" and TR= '"+mKind.substring(0, 1)+"0'");
										SQLiteDatabase db = Utilis.getDB(QPosff.this);
										Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
										if (cs.getCount()>0){
											cs.moveToFirst();
											if (!cs.getString(1).equalsIgnoreCase("1"))
												nQhis=1;
											else
												nQhis=0;
											mDiscount=cs.getDouble(0);
										}
										cs.close();
										db.close();
										bundle.putString("GalleryChild",data.iGoods+","+nQhis+","+mDiscount+","+mKey+","+mKind+",0,"+deptStr[8]+","+mDept+",0");
										intent.setClass(QPosff.this, GalleryViewP.class);
										intent.putExtras(bundle);
										startActivityForResult(intent, RESULT_GALLERY);
									}
									break;
								}
								
								case 1: // 編輯呼叫APos主程式
								{//明細清冊
								if (isPass<6 && isPass!=3 && isPass!=4) { //常態才可編輯
										Intent intent = new Intent();										
										if (abMode==1 || mGroupMode==GroupMode.NUMBER){
											intent.putExtra("pos_mode",PItemMode.SEARCH);
										}else {
											intent.putExtra("pos_mode",PItemMode.EDIT);
										} 
										PxData data = mExpandAdapter.getData(groupPosition, childPosition);
										intent.putExtra("pos_formno",data.iFormdate);
										intent.putExtra("pos_qkind",nKind);// @@TR30為預設(暫時廠進貨單) 
										intent.putExtra("pos_dept",mDept);//理論上為"SOS" 或 門市代號
										intent.putExtra("pos_where",PItemWhere.Qposf);
										intent.putExtra("pos_group",mGroupMode);
										intent.setClass(QPosff.this,APos.class);									
										startActivityForResult(intent,RESULT_APOS);
									
								}else {
									ProgressDialog mProgress = null;
				        		    mProgress = new ProgressDialog(QPosff.this);
				        			mProgress.setCancelable(true);
				        			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//				        			mProgress.setMessage(ErrorMsg[isError]);
				        			mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
				        			mProgress.show();

								}
									break;
								}
								
								case 2: //結帳功能 僅限
								{
								PxData data = mExpandAdapter.getData(groupPosition, childPosition);
								mKey=data.iFormdate;
								int canDo=0;
								if (isPass<6 && isPass!=3 && isPass!=4) { 
									if (abMode==0){
										SQLiteDatabase db = Utilis.getDB(QPosff.this);
										if (mGroupMode==GroupMode.NUMBER || mGroupMode==GroupMode.COMPANY){
												Intent intent = new Intent();
												if (mGroupMode==GroupMode.NUMBER ){//重返結帳作業
												intent.putExtra("pos_mode",PItemMode.SEARCH);
												}else {  //結帳
													intent.putExtra("pos_mode",PItemMode.EDIT);
												} 
											intent.putExtra("pos_npart",nPart);
											intent.putExtra("pos_formno",mKey);
											intent.putExtra("pos_qkind",nKind);// @@TR30為預設(暫時廠進貨單)
											intent.putExtra("pos_dept",mDept);//理論上為"SOS" 或 門市代號
											intent.putExtra("pos_where",PsaveWhere.Qposf);
											intent.putExtra("pos_group",mGroupMode);
											intent.setClass(QPosff.this,QPosSave.class);
											startActivityForResult(intent, RESULT_QPOSAVE);
										}else if (mGroupMode==GroupMode.CATEGORY){//
											
											Cursor cs=db.rawQuery("select ISCONFIRM,ISCHECK from qhead where FORMNO='"+mKey+"'", null);
											if (cs.getCount()>0){
												cs.moveToFirst();
												if (!cs.getString(0).equalsIgnoreCase("O") && !cs.getString(0).equalsIgnoreCase("R")){//收尾款結帳
													canDo=1;
												}else{
													canDo=2;
												}
											}
											cs.close();
											if (canDo!=0){
												Intent intent = new Intent();
												intent.putExtra("pos_mode",PItemMode.EDIT);
												intent.putExtra("pos_npart",nPart);
												intent.putExtra("pos_formno",mKey);
												intent.putExtra("pos_qkind",nKind);// @@TR30為預設(暫時廠進貨單)
												intent.putExtra("pos_dept",mDept);//理論上為"SOS" 或 門市代號
												intent.putExtra("pos_where",PsaveWhere.Qposf);
												intent.putExtra("pos_group",mGroupMode);
												intent.setClass(QPosff.this,QPosSave.class);
												startActivityForResult(intent, RESULT_QPOSAVE);
											}
										}else{
											canDo=2;
										}
    					    			if (canDo==2){
    										String[] args = {mKey,mKind};
    										ContentValues value = new ContentValues();
    										value.put("TR","Y1");
    										int success = db.update(TbName.QHEAD, value,"FORMNO=? and QKIND=?", args);
											Toast.makeText(QPosff.this, mKey+" 留貨預購已儲存完畢!!", Toast.LENGTH_SHORT).show();
											if (of_line!=0 && Utilis.haveInternet(QPosff.this)) {
												SystemClock.sleep(500);
												DBCloud.aa1_aa0_update_HI(QPosff.this);
											}
    					    			}
										db.close();
									}
								}
								break;
								}
								case 3:  //改為新功能_各門市庫存分析表
								{
								PxData dataa = mExpandAdapter.getData(groupPosition, childPosition);
								mGoods=dataa.iGoods;
								if (abMode==0 ){									
									try{
										Bundle bundle = new Bundle();
										Intent intent = new Intent();
										bundle = new Bundle();
										bundle.putString("GalleryChild","'"+mGoods+"';0;1");
										intent.setClass(QPosff.this, GalleryViewS.class);
										intent.putExtras(bundle);
										startActivity(intent);
									}catch(Exception e){
										e.printStackTrace();
									}finally{
									}
								}
								break;	
								}
								case 4:
									PxData dataa = mExpandAdapter.getData(groupPosition, childPosition);
									mGoods=dataa.iGoods;
									if (abMode==0 ){									
										try{
											Intent intent = new Intent();
											intent.putExtra("QHis_kind", nKind);
											if (mGroupMode==GroupMode.KEEPA) intent.putExtra("QHis_mode", 6); else if (mGroupMode==GroupMode.CATEGORY) intent.putExtra("QHis_mode", 5); else intent.putExtra("QHis_mode", 1); 
											intent.putExtra("QHis_User","" );
											intent.putExtra("QHis_Goods",mGoods );
											intent.setClass(QPosff.this, QHis.class);
											startActivity(intent);
										}catch(Exception e){
											e.printStackTrace();
										}finally{
										}
									}
									break;
								
								case 5:  //商品轉入留貨區(COMPANY) 其餘只能對單一商品DISPLAY
								{
									if (abMode!=1){
										Intent intent = new Intent();
										PxData data = mExpandAdapter.getData(groupPosition, childPosition);
										SQLiteDatabase db = Utilis.getDB(QPosff.this);
										
	//									Cursor cs=db.rawQuery("select * from qitems where GOODSNO='"+data.iGoods+"' and FORMNO='"+data.iFormdate+"'", null);
										StringBuffer mySqlBuf = new StringBuffer();
										mySqlBuf.append("select GOODSNO,GOODSNAME,COLOR,SIZE,UNIT1,UNIT2,COLORS,SIZES,ORDDATE,");
										mySqlBuf.append("sum(UNIT"+mKind.substring(0, 1)+"0) as SUMS");
										mySqlBuf.append(" from qitems  where GOODSNO='" + data.iGoods+"' and FORMNO='"+data.iFormdate+"'");
										mySqlBuf.append(" group by GOODSNO,GOODSNAME,COLOR,SIZE,UNIT1,UNIT2,COLORS,SIZES,ORDDATE");
										Cursor cs=db.rawQuery(mySqlBuf.toString(), null);
										if (cs.getCount()>0){
											cs.moveToFirst();
											intent.putExtra("batch", cs.getString(cs.getColumnIndex("GOODSNO")));									
											intent.putExtra("mid", 0);
											intent.putExtra("item_mode", 4); // 僅唯讀查詢
					 						intent.putExtra("mkind", mKind);
					 						intent.putExtra("cong", 0);
					 						intent.putExtra("unit", cs.getInt(cs.getColumnIndex("ORDDATE")));
					 						
											intent.putExtra("size", cs.getString(cs.getColumnIndex("SIZES")));
											intent.putExtra("color", cs.getString(cs.getColumnIndex("COLORS")));
											intent.putExtra("colorno", cs.getString(cs.getColumnIndex("UNIT2")));
											
											String mSplitColorNo=cs.getString(cs.getColumnIndex("UNIT2"));
											//String mSplitColor=cs.getString(cs.getColumnIndex("COLORS"));
											String mSplitSizes=cs.getString(cs.getColumnIndex("SIZES"));
											
								        	String [] anumber = mSplitColorNo.split("，"); //取得各色號字串
								        	//String [] anames = mSplitColor.split("，");
								        	String [] asizes = mSplitSizes.split(",");
								        	
								        	int [] ttot=new int[asizes.length*anumber.length];
											for (int i=0;i<cs.getCount();i++){  //從第一筆--最後一筆讀取
												String acol=cs.getString(cs.getColumnIndex("COLOR"));
												String asiz=cs.getString(cs.getColumnIndex("SIZE"));
												
											for (int j=0;j<anumber.length;j++){
												if (acol.equalsIgnoreCase(anumber[j]))  { //顏色相符
							  						for (int k=0;k<asizes.length;k++){
								  						if (asiz.equalsIgnoreCase(asizes[k]))  { //尺寸相符  置入進銷存
							  								ttot[(j*asizes.length)+k]=Math.round(cs.getInt(cs.getColumnIndex("SUMS")));
								  						}
							  						}
												}
											}
											cs.moveToNext();
										}
								  			StringBuffer mInCountList= new StringBuffer(); //所有件數表 5,5，3,3
								  			
								  			for (int i=0;i<anumber.length;i++){
								  				for (int j=0;j<asizes.length;j++){
								  					mInCountList.append(""+Math.round(ttot[((i*asizes.length)+j)]));
							  			  		if  ( j<(asizes.length-1)) {
							  			  			mInCountList.append(",");
							  			  			}
							  					}
								  				if (i<(anumber.length-1)){	
								  					mInCountList.append("，");
								  					}
								  			}
											//需取得本單本款原有的各色尺寸的件數 製作countlist
								  			//Toast.makeText(QPosff.this,mInCountList.toString(), Toast.LENGTH_LONG).show();										
											intent.putExtra("countlist", mInCountList.toString());
											if (isOnkey==1)
												intent.setClass(QPosff.this, AIncomePc.class);
											else
												intent.setClass(QPosff.this, AIncome.class);
											startActivity(intent);
										}	
										db.close();
										cs.close();
									}
									break;									
								}
								case 6: //會員留貨商品清單
								{
									Toast.makeText(QPosff.this, " 請改為長按單頭,繼續執行!!", Toast.LENGTH_SHORT).show();									
									break;									
								}
								case 7: //輸出
									Toast.makeText(QPosff.this, " 請改為長按單頭,繼續執行!!", Toast.LENGTH_SHORT).show();									
									break;									
								
								case 8: //補印條碼
								{
									break;									
								}
								case 9: //補印單據
									Toast.makeText(QPosff.this, " 請改為長按單頭,繼續執行!!", Toast.LENGTH_SHORT).show();									
									break;									
							}
						}
			});
			
			return false;
		}
	}

	class ExpandItemAdapter extends BaseExpandableListAdapter{
		private Context context;

		LinkedList<GroupData> groups = new LinkedList<GroupData>();
		LinkedList<List<PxData>> childs = new LinkedList<List<PxData>>();
		private AsyncImageFileLoader asyncImageFileLoader;
		/*
		* 構造函數:
		* 參數1:context物件
		* 參數2:一級清單資料來源
		* 參數3:二級清單資料來源
		*/
		
		public ExpandItemAdapter(Context context)
		{
//			this.groups = groups;
//			this.childs = childs;
			this.context = context;
			asyncImageFileLoader = new AsyncImageFileLoader();
		}
		
		public void setData(LinkedList<GroupData> groups, LinkedList<List<PxData>> childs){
			if(this.groups != null){
				this.groups.clear();
			}
			if(this.childs != null){
				this.childs.clear();
			}
			this.groups = groups;
			this.childs = childs;
		}
		
//@@
		public PxData getData(int groupPosition, int childPosition){
			return childs.get(groupPosition).get(childPosition);
		}

		public Object getChild(int groupPosition, int childPosition)
		{
			return childs.get(groupPosition).get(childPosition);
		}

		public long getChildId(int groupPosition, int childPosition)
		{
		return childPosition;
		}

		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textName;
			TextView textMoney;
			TextView textCountry;
			TextView textNumber;
			TextView textCompany;
			TextView textGoodsNo;
			TextView textImpo;
			TextView textItime;
		}
		
		/* class GroupViewHolder */
		private class GroupViewHolder {
			ImageView imageIcon;
			TextView text1;
			TextView text2;
			TextView textMoney;
			TextView textOriMoney;
			TextView textG1;
			TextView textG2;
			TextView tTime;
			
		}

		//獲取二級清單的View物件
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
		ViewGroup parent)
		{
		PxData data = childs.get(groupPosition).get(childPosition);
		//
		LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			ViewHolder holder;
			if (convertView == null) {
				convertView = layoutInflater.inflate(R.layout.list_posh, null);
				holder = new ViewHolder();
				holder.imageItem = (ImageView)convertView.findViewById(R.id.img_ppic);
				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.textNumber = (TextView) convertView.findViewById(R.id.text_pnumber);
				holder.textMoney = (TextView) convertView.findViewById(R.id.text_pmoney);
				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");
				try{
					if(data.iPic != null && data.iPic.length() > 0){
						holder.imageItem.setImageDrawable(Utilis.getResourceImage(QPosff.this, data.iPic));
					}else{
						holder.imageItem.setImageResource(R.drawable.icon_store);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			if (abMode==1) holder.textName.setText(data.iFormdate); else holder.textName.setText(data.iName);
			holder.textGoodsNo.setText(data.iGoods);
			holder.textImpo.setText(data.iImpo);			
			holder.textMoney.setText(data.iMoney);
			holder.textCountry.setText(data.iCountry);
			holder.textCompany.setText(data.iCompany);
			holder.textNumber.setText(data.iNumber);
			
//	        if (PSWD==1){  //密碼不OK
//	        	holder.textMoney.setVisibility(View.INVISIBLE);
//	        	holder.textCompany.setVisibility(View.INVISIBLE);
//	        	holder.textCountry.setVisibility(View.INVISIBLE);
//	        }
			return convertView;
		}

		public int getChildrenCount(int groupPosition)
		{
		return childs.get(groupPosition).size();
		}

		public Object getGroup(int groupPosition)
		{
		return groups.get(groupPosition);
		}

		public int getGroupCount()
		{
		return groups.size();
		}

		public long getGroupId(int groupPosition)
		{
		return groupPosition;
		}

		//獲取一級清單View物件
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
		{
//			String text = groups.get(groupPosition).get("group");
			GroupData data = groups.get(groupPosition);
			
			LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			GroupViewHolder holder;
			if (convertView == null) {
				convertView = layoutInflater.inflate(R.layout.plist_group, null);
				holder = new GroupViewHolder();
				holder.imageIcon = (ImageView)convertView.findViewById(R.id.img_icon);
				holder.text1 = (TextView) convertView.findViewById(R.id.text1);
				holder.text2 = (TextView) convertView.findViewById(R.id.text2);
				holder.textMoney = (TextView)convertView.findViewById(R.id.textMoney);
				holder.textOriMoney = (TextView)convertView.findViewById(R.id.textOriMoney);
				holder.textG1 = (TextView) convertView.findViewById(R.id.textg1);
				holder.textG2 = (TextView) convertView.findViewById(R.id.textg2);
				holder.tTime = (TextView) convertView.findViewById(R.id.text_ttime);
				convertView.setTag(holder);
				
			} else {
				holder = (GroupViewHolder) convertView.getTag();
			}
			//@@應該區隔進貨單mKind=10 或日結單abMode==1 與不是進貨單
			if(abMode==1){ //不顯示第一層的圖檔
				holder.imageIcon.setVisibility(View.GONE);
			} else {
				holder.imageIcon.setVisibility(View.VISIBLE);
				try{
					if(data.strPic != null && data.strPic.length() > 0){
						holder.imageIcon.setImageDrawable(Utilis.getResourceImage(QPosff.this, data.strPic));
					}else{
						holder.imageIcon.setImageResource(R.drawable.icon_store);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}				
			holder.text1.setText(data.strText1);
			holder.text2.setText(data.strText2);
			holder.textOriMoney.setText(data.strOriMoney);
			holder.textMoney.setText(data.strMoney);
			holder.textG1.setText(data.strTextG1);
			holder.textG2.setText(data.strTextG2);
			holder.tTime.setText(data.strTime);			
			
//	        if (PSWD==1){  //密碼不OK
//	        	holder.textMoney.setVisibility(View.INVISIBLE);
//	        	holder.textOriMoney.setVisibility(View.INVISIBLE);
//	        	holder.text2.setVisibility(View.INVISIBLE);
//	        }			
			return convertView;
		}

		public boolean hasStableIds()
		{
		return false;
		}

		public boolean isChildSelectable(int groupPosition, int childPosition)
		{
		return true;
		}
	}
	
	
	class ItemAdapter extends BaseAdapter{
		
		private LayoutInflater mInflater;
		
		public ItemAdapter (Context context){
		      mInflater = LayoutInflater.from(context);
		}

		public PxData getData(int Position){
			return null;
//			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);
			return null;			
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_posh, null);
				holder = new ViewHolder();
				holder.imageItem = (ImageView)convertView.findViewById(R.id.img_ppic);
				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");
			PxData data = mList.get(position);
			holder.imageItem.setImageBitmap(Utilis.getScaleBitmap(data.iPic, 80, 80));
			
			holder.textGoodsNo.setText(data.iGoods);
//			holder.textImpo.setText("總件數 " + data.nTotalCount);
			
			holder.textName.setText(data.iName);
			//@@@@是否思考 abMode==1 or not
//			holder.textMoney.setText(" $ " + myformat.format((data.nTotalCount * data.dP1)));
			holder.textCountry.setText(data.iCountry);
			holder.textCompany.setText(data.iCompany);
			holder.textNumber.setText(data.iNumber);
			return convertView;
		}

		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textGoodsNo;
			TextView textImpo;
			TextView textName;
			TextView textMoney;
			TextView textCountry;
			TextView textNumber;
			TextView textCompany;
			TextView textItime;
			
		}
	    
	}
	
	class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QPosff.this);
			switch (id) {
				case R.id.btn_exit:
				{
					finish();
					break;
				}
				case R.id.btn_new:  //新增 指向暫存模式
				{
				if (isPass<6 && isPass!=3  && isPass!=4) { //只有在單頭+單身,才可以新增	
					Utilis.runVibrate(QPosff.this);
					Intent intent = new Intent();
					//需帶入正確的值					
					//intent.putExtra("item_mode", AItem.ItemMode.ADD);
					mGroupMode = GroupMode.COMPANY;
					//Toast.makeText(QPosff.this, "mGroupMode="+mGroupMode, Toast.LENGTH_SHORT).show();									
					intent.putExtra("pos_mode", AItem.ItemMode.ADD);
					intent.putExtra("pos_qkind", nKind);
					intent.putExtra("pos_dept",mDept);//理論上為"SOS" 或 門市代號					
					intent.putExtra("pos_where", PItemWhere.Qposf);
					intent.putExtra("pos_group",mGroupMode);
					intent.setClass(QPosff.this,APos.class);
					startActivityForResult(intent,RESULT_APOS);
				}else {
					ProgressDialog mProgress = null;
        		    mProgress = new ProgressDialog(QPosff.this);
        			mProgress.setCancelable(true);
        			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        			mProgress.setMessage(ErrorMsg[isError]);
        			mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
        			mProgress.show();
				}
					break;
				}

				case R.id.btn_state:
				{
					Intent intent = new Intent();										
					intent.setClass(QPosff.this,QRep_01.class);									
					startActivity(intent);
					
					break;
				}

				case R.id.btn_fbatch:  //查詢 依序 
				{
				if (abMode==1 ||(abMode!=1 && (mGroupMode==GroupMode.CATEGORY || mGroupMode==GroupMode.KEEPA ) ) ){
				
					LayoutInflater factory = LayoutInflater.from(QPosff.this);
				    final View v1 = factory.inflate(R.layout.fposf, null);
				    final EditText edtReg = (EditText) v1.findViewById(R.id.edtsh);
				    edtReg.setText("");
				      new AlertDialog.Builder(QPosff.this).setTitle(QPosff.this.getString(R.string.detail_msg_fpos)).setView(v1).setNeutralButton("開始搜尋", new DialogInterface.OnClickListener() {
					      public void onClick(DialogInterface dialog, int which) {
					    	  //開始依條件依序搜尋 
					    	  boolean searched=false;
				    	  		SQLiteDatabase db = Utilis.getDB(QPosff.this);
				    	  		Cursor cs=null;
				    	  		QUA=null;
				    	  		ANS=null;
				    	  		String QstartDay="";
				    	  		String QendDay="";
				    	  		StringBuffer bufSH = new StringBuffer();
				    	  if (edtReg.length()>0){		
			    	  		if (edtReg.getText().toString().substring(0, 1).equalsIgnoreCase("+")){
			    	  				QUA=" ((ATM like '%" + edtReg.getText().toString().substring(1)+"%') or (CARD like '%" + edtReg.getText().toString().substring(1)+"%'";
			    	  				ANS=") or (CASH like '%" + edtReg.getText().toString().substring(1)+"%') or (BSUM like '%" + edtReg.getText().toString().substring(1)+"%'))";
					    	  		bufSH.append("select distinct max(FORMDATE) from qhead");
					    	  		bufSH.append(" where "+QUA+ANS+" and QKIND='"+mKind+"'");
									cs = db.rawQuery(bufSH.toString(), null);
									//Toast.makeText(QPosff.this, bufSH.toString(), Toast.LENGTH_SHORT).show();									
									if (cs != null) {
										if (cs.getCount() > 0 ) {
											cs.moveToFirst();
											QendDay=cs.getString(0);
											if(QendDay != null && QendDay.length() > 0){
												QendDay = QendDay.replace("-", "/");
												QstartDay = DateUtil.addDate(QendDay, -60);
												searched=true;
											}											
										}
									}else {
										QUA=null;
						    	  		ANS=null;
									}
			    	  		}else{
									bufSH.delete(0, bufSH.toString().length());
					    	  		bufSH.append("select distinct max(FORMDATE) from qhead");
					    	  		bufSH.append(" where USERNAME like '%" + edtReg.getText().toString()+"%'  and QKIND='"+mKind+"'");
									cs = db.rawQuery(bufSH.toString(), null);
									if (cs != null) {
										if (cs.getCount() > 0 ) {
											cs.moveToFirst();
											QendDay=cs.getString(0);
											if(QendDay != null && QendDay.length() > 0){
												QendDay = QendDay.replace("-", "/");
												QstartDay = DateUtil.addDate(QendDay, -30);
												QUA=" USERNAME LIKE ";
												ANS="'%"+edtReg.getText().toString()+"%' ";
												searched=true;
											}											
										}
									}
								
								if (searched==false){  //表示沒有符合會員,續找單號
									bufSH.delete(0, bufSH.toString().length());
					    	  		bufSH.append("select distinct max(FORMDATE) from qhead");
					    	  		bufSH.append(" where FORMNO LIKE '" + edtReg.getText().toString()+"%' and QKIND='"+mKind+"'");
									cs = db.rawQuery(bufSH.toString(), null);
									if (cs != null) {
										if (cs.getCount() > 0) {
											cs.moveToFirst();
											QendDay=cs.getString(0);
											if(QendDay != null && QendDay.length() > 0){
												QendDay = QendDay.replace("-", "/");
												QstartDay = DateUtil.addDate(QendDay, -3);
												QUA=" FORMNO LIKE ";
												ANS="'"+edtReg.getText().toString()+"%' ";
												searched=true;
											}
										}
									}
								}
								
								if (searched==false){  //表示沒有符合單號,續找會員名稱
									bufSH.delete(0, bufSH.toString().length());
					    	  		bufSH.append("select distinct max(FORMDATE) from qhead");
					    	  		bufSH.append(" where USER ='" + edtReg.getText().toString()+"' and QKIND='"+mKind+"'");
									cs = db.rawQuery(bufSH.toString(), null);
									if (cs != null) {
										if (cs.getCount() > 0) {
											cs.moveToFirst();
											QUA=" USER=";
											ANS="'"+edtReg.getText().toString()+"' ";
											QendDay=cs.getString(0);
											if(QendDay != null && QendDay.length() > 0){
												QendDay = QendDay.replace("-", "/");
												QstartDay = DateUtil.addDate(QendDay, -30);
												searched=true;
											}
										}
									}
								}
								
								if (searched==false){
					    	  		if ( edtReg.getText().toString().indexOf("-")>=2 ){  //至少類似 xx-xx
					    	  			bufSH.delete(0, bufSH.toString().length());
						    	  		bufSH.append("select distinct max(FORMDATE) from qhead");
						    	  		bufSH.append(" where FORMDATE LIKE '%" + edtReg.getText().toString()+"%' and QKIND='"+mKind+"'");
										cs = db.rawQuery(bufSH.toString(), null);
										if (cs != null) {
											if (cs.getCount() > 0) {
												cs.moveToFirst();
												QUA=" FORMDATE LIKE ";
												ANS="'%"+edtReg.getText().toString()+"%' ";
												QendDay=cs.getString(0);
												if(QendDay != null && QendDay.length() > 0){
													QendDay = QendDay.replace("-", "/");
													QstartDay = QendDay;
													mEndDay=QendDay;
													mStartDay =mEndDay;
													searched=true;
												}											
											}
										}
					    	  		}
								}
			    	  		}
								db.close();
								cs.close();
				    	  }			    	  			
							if (searched==true && (QUA.length()>0)){ //表示有值batch
								setCondition();
								getGroupData(QPosff.this, QstartDay, QendDay, QUA, ANS);
							}else{
				    	  		QUA=null;
				    	  		ANS=null;
				    	  		mEndDay =DateUtil.getCurrentDate();
				    	  		mStartDay =mEndDay;
								setCondition();
								getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
							}
					     }
					    }).setNegativeButton("離開", new DialogInterface.OnClickListener() {
						      public void onClick(DialogInterface dialog, int which) {
					    	  		QUA=null;
					    	  		ANS=null;
					    	  		mEndDay = DateUtil.getCurrentDate();
					    	  		mStartDay =mEndDay;
									setCondition();
									getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
						      }
					    })
					    .show();
				}else if (nPart==0 && (nKind==31 || nKind==41) ){//可以是切換不同門市
					
				}
					break;
				}
				
				case R.id.btn_qmacc:  //收支
				{
					Intent intent = new Intent();
					intent.setClass(QPosff.this, QMacc.class);
					intent.putExtra("search_mode", KeySet.SearchMode.DAY);		
					intent.putExtra("search_group", QMacc.GroupMode.TOP1);	
					startActivity(intent);
					break;
				}	
				
				
				case R.id.btn_account:  //對帳
				{
					if (nKind==10){
						DialogUtilis.showDialog(QPosff.this, "廠商對帳方式", -1,
								new String[] { "依配貨處", "依廠商" }, new IDialog() {
									@Override
									public void onDialogFinish(int pos, String choice) {
										switch (pos) {
										case 0: { //依配貨處 
											Reconciliation(11);
											break;
										}
										case 1: //原始設計,依廠商
										{
											Reconciliation(10);
											break;
										}
									}
								}
						});						
					} else
						Reconciliation(nKind);
					
					break;
				}	
				case R.id.btn_prev_date:  //當按了上一??
				{
					switch(mMode){
						case KeySet.SearchMode.MONTH:  //就是31筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, -1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
							if (WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 && mGroupMode!=GroupMode.CATEGORY && mGroupMode!=GroupMode.KEEPA && (nKind==30 || nKind==31)){
								mStartDay=mLimitDay;
								mEndDay=DateUtil.addDate(mStartDay, +7);
							}
			    			break;
			    		}
						case KeySet.SearchMode.WEEK:  //就是7筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, -7);
							mEndDay = DateUtil.addDate(mEndDay, -7);
							if (WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 && mGroupMode!=GroupMode.CATEGORY && mGroupMode!=GroupMode.KEEPA && (nKind==30 || nKind==31)){
								mStartDay=mLimitDay;
								mEndDay=DateUtil.addDate(mStartDay, +7);
							}
			    			break;
			    		}
						case KeySet.SearchMode.ACTION:  //銷貨單 (單頭+單身)
						{
			    			mStartDay = DateUtil.addDate(mStartDay, -1);
							mEndDay = DateUtil.addDate(mEndDay, -1);
							if (WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 && mGroupMode!=GroupMode.CATEGORY && mGroupMode!=GroupMode.KEEPA && (nKind==30 || nKind==31)){
								mStartDay=mLimitDay;
								mEndDay=mStartDay;
							}
							break;
						}
						case KeySet.SearchMode.DAY:  //就是1筆日結單(日期+單頭)
						{
			    			mStartDay = DateUtil.addDate(mStartDay, -1);
							mEndDay = DateUtil.addDate(mEndDay, -1);
							if (WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 && mGroupMode!=GroupMode.CATEGORY && mGroupMode!=GroupMode.KEEPA && (nKind==30 || nKind==31)){
								mStartDay=mLimitDay;
								mEndDay=mStartDay;
							}
							break;
						}
					}
					setCondition();
					getGroupData(QPosff.this,mStartDay, mEndDay, null, null);
					
					break;
				}
				case R.id.btn_next_date:
				{
					switch(mMode){
			    		case KeySet.SearchMode.MONTH: //就是日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, 1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
			    			break;
			    		}
			    		case KeySet.SearchMode.WEEK:
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, 7);
							mEndDay = DateUtil.addDate(mEndDay, 7);
			    			break;
			    		}
			    		case KeySet.SearchMode.ACTION:
						{
			    			mStartDay = DateUtil.addDate(mStartDay, 1);
							mEndDay = DateUtil.addDate(mEndDay, 1);
							break;
						}
			    		case KeySet.SearchMode.DAY:
						{
			    			mStartDay = DateUtil.addDate(mStartDay, 1);
							mEndDay = DateUtil.addDate(mEndDay, 1);
							break;
						}
					}
					setCondition();
					getGroupData(QPosff.this,mStartDay, mEndDay, null, null);
					break;

				}
				case R.id.text_duration:
				{
					if (mMode!=KeySet.SearchMode.WEEK){
						mMode=KeySet.SearchMode.WEEK;
			    		//String day = Utilis.getWeekDate();
						//String[] days = day.split("~");
			    		//mStartDay = days[0];
			    		//mEndDay = days[1];
						mEndDay = DateUtil.addDate(mStartDay, +7);

						resetButton(R.id.btn_sort_pic);
						mGroupMode = GroupMode.NUMBER;
						abMode=1;
			    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_next_date)).setText("下一週");
			    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_prev_date)).setText("上一週");
						setCondition();
						getGroupData(QPosff.this,mStartDay, mEndDay, null, null);
					}else{
						mMode=KeySet.SearchMode.ACTION;
			    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_next_date)).setText("下一日");
			    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_prev_date)).setText("上一日");
						mEndDay=mStartDay;
						resetButton(R.id.btn_sort_pic);
						mGroupMode = GroupMode.NUMBER;
						abMode=1;
						setCondition();
						getGroupData(QPosff.this,mStartDay, mEndDay, null, null);
					}
					break;
				}
			    case R.id.btn_sort_pic: //日結單
			    	{
			    		abMode=1;
						
		    			resetButton(id);			    		
			    		mGroupMode = GroupMode.NUMBER;
		    			mListView.setVisibility(View.GONE);
		    			mExpandListView.setVisibility(View.VISIBLE);
		    			mExpandListView.setOnChildClickListener(mChildClcik);
						if (WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 && mGroupMode!=GroupMode.CATEGORY && mGroupMode!=GroupMode.KEEPA && (nKind==30 || nKind==31)){
							mStartDay=mLimitDay;
							mEndDay=DateUtil.addDate(mStartDay, +7);
						}
		    			getGroupData(QPosff.this,mStartDay, mEndDay, null, null);
		    			setCondition();
			    		
							DBCloud.aa0_aa1_auto_HI(QPosff.this,nKind);
							DBCloud.aa0_aa1_auto_qdetail_n(QPosff.this);
			   			break;
			    		}
			    case R.id.btn_sort_number:  //標準
			    		{
			    			if (mMode!=KeySet.SearchMode.ACTION){
								mMode=KeySet.SearchMode.ACTION;
					    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
					    		((Button)findViewById(R.id.btn_next_date)).setText("下一日");
					    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
					    		((Button)findViewById(R.id.btn_prev_date)).setText("上一日");
								mEndDay=mStartDay;
			    			}
			    			resetButton(id);
			    			abMode=0;
			    			mGroupMode = GroupMode.NUMBER;
			    			mListView.setVisibility(View.GONE);
			    			mExpandListView.setVisibility(View.VISIBLE);
			    			mExpandListView.setOnChildClickListener(mChildClcik);
							if (WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 && mGroupMode!=GroupMode.CATEGORY && mGroupMode!=GroupMode.KEEPA && (nKind==30 || nKind==31)){
								mStartDay=mLimitDay;
								mEndDay=DateUtil.addDate(mStartDay, +7);
							}
			    			getGroupData(QPosff.this,mStartDay, mEndDay, null, null);
			    			setCondition();
		    				
								DBCloud.aa0_aa1_auto_HI(QPosff.this,nKind);
								DBCloud.aa0_aa1_auto_qdetail_n(QPosff.this);
			    				break;
			    			}
			    case R.id.btn_sort_cate: //原依類別==>預購單
			    		{
			    			if (mMode!=KeySet.SearchMode.ACTION){
								mMode=KeySet.SearchMode.ACTION;
					    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
					    		((Button)findViewById(R.id.btn_next_date)).setText("下一日");
					    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
					    		((Button)findViewById(R.id.btn_prev_date)).setText("上一日");
								mEndDay=mStartDay;
			    			}
			    			resetButton(id);
			    			abMode=0;
			    			mGroupMode = GroupMode.CATEGORY;
			    			mListView.setVisibility(View.GONE);
			    			mExpandListView.setVisibility(View.VISIBLE);
			    			mExpandListView.setOnChildClickListener(mChildClcik);
			    			getGroupData(QPosff.this,mStartDay, mEndDay, null, null);
								DBCloud.aa0_aa1_auto_HI(QPosff.this,nKind);
								DBCloud.aa0_aa1_auto_qdetail_n(QPosff.this);
			    				setCondition();
			    				
			    				break;
			    		}
			    case R.id.btn_sort_company: //原依廠商==>暫存單
			    		{
			    			resetButton(id);
			    			abMode=0;
			    			mGroupMode = GroupMode.COMPANY;
			    			mListView.setVisibility(View.GONE);
			    			mExpandListView.setVisibility(View.VISIBLE);
			    			mExpandListView.setOnChildClickListener(mChildClcik);
			    			getGroupData(QPosff.this,mStartDay, mEndDay, null, null);
							DBCloud.aa0_aa1_auto_HI(QPosff.this,nKind);
							DBCloud.aa0_aa1_auto_qdetail_n(QPosff.this);
			    			setCondition();
			    			
			    			break;
			    		}
			    case R.id.btn_sort_keepa: //原依類別==>預購單
	    		{
	    			if (mMode!=KeySet.SearchMode.ACTION){
						mMode=KeySet.SearchMode.ACTION;
			    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_next_date)).setText("下一日");
			    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_prev_date)).setText("上一日");
						mEndDay=mStartDay;
	    			}
	    			resetButton(id);
	    			abMode=0;
	    			mGroupMode = GroupMode.KEEPA;
	    			mListView.setVisibility(View.GONE);
	    			mExpandListView.setVisibility(View.VISIBLE);
	    			mExpandListView.setOnChildClickListener(mChildClcik);
	    			getGroupData(QPosff.this,mStartDay, mEndDay, null, null);
						DBCloud.aa0_aa1_auto_HI(QPosff.this,nKind);
						DBCloud.aa0_aa1_auto_qdetail_n(QPosff.this);
    				setCondition();
	    				break;
	    		}
					}
		}
	}
	
	private void resetButton(int id){
		((Button)findViewById(R.id.btn_sort_pic)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_cate)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_number)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_company)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_keepa)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_yellow);
	}

	private void askPSWD(int mode){
		String pass = Utilis.getStringSet(QPosff.this, PrefKey.PASSWORD, "");
		if (pass.length()>=2){
		LayoutInflater factory = LayoutInflater.from(QPosff.this);
	    final View v1 = factory.inflate(R.layout.exinput, null);
	    final TextView txtReg = (TextView) v1.findViewById(R.id.TextView01);
	    final EditText edtReg = (EditText) v1.findViewById(R.id.edtReg);
	    final TextView txtWho = (TextView) v1.findViewById(R.id.TextView02);
	    final EditText edtWho = (EditText) v1.findViewById(R.id.edPswd);
	    edtReg.setText("");edtWho.setText("");
	    txtReg.setText("密碼:");txtWho.setText("櫃員編號:");
	    if(mode==0){//修改時
		  new AlertDialog.Builder(QPosff.this).setTitle("修改單據").setMessage("請輸入密碼及櫃員編號").setView(v1).setPositiveButton("OK", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
          		String pass = Utilis.getStringSet(QPosff.this, PrefKey.PASSWORD, "").substring(0,2);
            	  if (edtReg.getText().toString().equalsIgnoreCase(pass) && edtWho.getText().toString().length()>0){
            		  whoDel=edtWho.getText().toString();
            		  modifyF(0);
            	  }              
              }
		  }).setCancelable(false).show();
	    }else{//刪除本單時
			  new AlertDialog.Builder(QPosff.this).setTitle("刪除單據").setMessage("請輸入密碼及櫃員編號").setView(v1).setPositiveButton("OK", new DialogInterface.OnClickListener() {
	              public void onClick(DialogInterface dialog, int which) {
	          		String pass = Utilis.getStringSet(QPosff.this, PrefKey.PASSWORD, "").substring(0,2);
	            	  if (edtReg.getText().toString().equalsIgnoreCase(pass) && edtWho.getText().toString().length()>0){
	            		  whoDel=edtWho.getText().toString();
	            		  modifyF(1);
	            	  }              
	              }
			  }).setCancelable(false).show();
	    	
	    }
		}		  
		  //檢查 YY
	}
	
	public  void outPut_bufStr(String Bufstr,String myFilePath){
	   	if (Bufstr.length()>0){
			Intent intent = new Intent();
	   		try {
	            Writer out = new BufferedWriter(new OutputStreamWriter(
	            	    new FileOutputStream(myFilePath), "UTF-8"));
	            	try {
	            	    out.write(Bufstr);
	            	} 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 Reconciliation(int trKind){
		Intent intent = new Intent();
		String Dept=mDept;if (mDept.equalsIgnoreCase("SOS")) Dept=deptStr[0]; 
		intent.putExtra("QRep_Dept",Dept);
		intent.putExtra("QRep_02",trKind);// @@TR30為預設
		intent.putExtra("QRep_who","QPosff");// @@TR30為預設
		intent.putExtra("QRep_user","");// @@除非針對特定會員櫃員
		intent.setClass(QPosff.this,QRep_02.class);
		startActivityForResult(intent, RESULT_REP_02);					
		
	}
	
	private void rep_today(int groupPosition, int mode){
		GroupData datag =mExpandAdapter.groups.get(groupPosition);
		SQLiteDatabase db = Utilis.getDB(QPosff.this);
		//計算零售業績
		String SQL="select sum(BSUM),sum(ATOT),sum(CASH),sum(CARD),sum(ORDCASH),sum(ORDCARD),sum(DISMONEY),sum(ATM) from qhead where (FORMDATE='"+datag.strTextG1+"' or FINEDATE='"+datag.strTextG1+"' or ORDDATE='"+datag.strTextG1+"') and TRADETYPE='5' and QKIND='"+mKind+"' ";
		SQL=SQL+" and ISCONFIRM='Y' and ISCHECK='N'";  
		if (!mDept.equalsIgnoreCase("SOS")) SQL=SQL+" and DEPTNO='"+mDept+"'";  else SQL=SQL+" and DEPTNO='"+deptStr[0]+"'";
		Cursor trade5=db.rawQuery(SQL, null);

		String compStr[]=Utilis.getIni(QPosff.this,"USER","COMPANY",9).split("!&!");
		if (!compStr[7].equalsIgnoreCase("0")){
			int count =  mExpandAdapter.getChildrenCount(groupPosition);
			if (count>0){  //開始印製日結單
				String sepa="\r\n";
				StringBuffer sPrintB = new StringBuffer();
				sPrintB.append("^QXXXX,0,0"+sepa);
				int Loca=0;
				if (Utilis.toInt(compStr[8])<3){												
					sPrintB.append("^W56"+sepa);
				}else{
					sPrintB.append("^W80"+sepa);
				}
				sPrintB.append("^H8"+sepa+"^P1"+sepa+"^S4"+sepa+"^AD"+sepa+"^C1"+sepa+"^R0"+sepa+"~Q+0"+sepa
				+"^O0"+sepa+"^D0"+sepa+"^E11"+sepa+"~R20"+sepa+"^L"+sepa+"Dy2-me-dd"+sepa+"Th:m:s"+sepa);
				Loca=Loca+30;
						Loca=Loca+2;sPrintB.append("AZ,8,"+Loca+",2,2,0,0,"+compStr[0]+sepa);
						Loca=Loca+50;sPrintB.append("AZ,8,"+Loca+",1,2,0,0,"+datag.strTextG1+" "+pKind[nKind/10-1]+"日結單"+sepa);
						
					SQL="select sum(BSUM)-(sum(CASH)+sum(CARD)+sum(ORDCASH)+sum(ORDCARD)+sum(ATM)) from qhead where QKIND='"+mKind+"' ";
					int ORS=Utilis.toInt(DeptSend[5]);
					if (ORS!=2) //含預購帳 
						SQL=SQL+" and (ISCONFIRM='Y' or (ISCHECK='Y' and ISCONFIRM='N'))";
					else
		    			SQL=SQL+" and ISCONFIRM='Y' and ISCHECK='N'";
						
					if (!mDept.equalsIgnoreCase("SOS")) SQL=SQL+" and DEPTNO='"+mDept+"'"; else SQL=SQL+" and DEPTNO='"+deptStr[0]+"'";  
	    			Cursor allcs=db.rawQuery(SQL, null);allcs.moveToFirst();
					Loca=Loca+21;  //
					sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
	    			Loca=Loca+35;  //印出所有未收款
	    			sPrintB.append("AZ,50,"+Loca+",1,1,0,0,合計未結算金額:"+allcs.getInt(0)+sepa);
						
					if (Utilis.toInt(compStr[8])<3){//寬60MM
						Loca=Loca+2;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,--------------------------------------"+sepa);
						Loca=Loca+50;
		    			for (int i = 0; i <count ; i++){
		    				PxData data =mExpandAdapter.getData(groupPosition, i);
							sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+data.iGoods+sepa);
							sPrintB.append("AZ,270,"+Loca+",1,1,0,0,"+data.iImpo+sepa);
							Loca=Loca+30;  //
							sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+data.iFormdate+"("+data.iName.substring(6)+")"+sepa);
							sPrintB.append("AZ,270,"+Loca+",1,1,0,0,"+data.iMoney+sepa);				
							Loca=Loca+30;  //
							sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+data.iCountry+data.iFormdate+sepa);
							sPrintB.append("AZ,270,"+Loca+",1,1,0,0,"+data.iCompany+sepa);				
							Loca=Loca+5;  //
							sPrintB.append("AZ,10,"+Loca+",1,2,0,0,"+"--------------------------------------"+sepa);
							Loca=Loca+30;  
							//mode==1 就要印製明細
							if (mode==1){
								Cursor ask=db.rawQuery("select GOODSNOS,GOODSNAME,UNIT1,QKIND,UNIT10,UNIT20,UNIT30,UNIT40,UNITPRICE,DISCOUNT,SUBPRICE,PS from qitems where FORMNO='"+data.iFormdate+"'", null);
								if (ask.getColumnCount()>0){
									Loca=Loca+5;  
									while (ask.moveToNext()){
										sPrintB.append("AZ,13,"+Loca+",1,1,0,0,"+ask.getString(0)+"("+ask.getString(2)+")"+ask.getString(1)+sepa);				
										Loca=Loca+30;
										sPrintB.append("AZ,23,"+Loca+",1,1,0,0,"+ask.getString((ask.getInt(3)/10)+3)+"件 X "+ask.getString(8)+" X "+ask.getString(9)+" % = "+ask.getString(10)+" ("+ask.getString(11)+")"+sepa);				
										if (!ask.isLast()) Loca=Loca+30;
									}
									Loca=Loca+5;  //
									sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
									Loca=Loca+35;
								}
								ask.close();
							}
		    			}
		    			sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+datag.strTextG2+sepa);
		    			Loca=Loca+50;  //
		    			sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+datag.strText2+sepa);
		    			Loca=Loca+50;  //
		    			sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+datag.strOriMoney+sepa);
		    			Loca=Loca+50;  //
		    			sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+datag.strMoney+sepa);
						Loca=Loca+35;  //
						sPrintB.append("AZ,8,"+Loca+",1,2,0,0,"+"--------------------------------------"+sepa);
		    			Loca=Loca+35;  //增加印出零售資訊
		    			
		    			if (trade5.getCount()>0){
		    				trade5.moveToFirst();
							sPrintB.append("AZ,10,"+Loca+",1,2,0,0,零售應收:"+trade5.getDouble(0)+sepa);
							sPrintB.append("AZ,270,"+Loca+",1,2,0,0,件數:"+trade5.getDouble(1)+sepa);
			    			Loca=Loca+50;  //增加印出零售資訊
							sPrintB.append("AZ,10,"+Loca+",1,2,0,0,零售現金:"+trade5.getDouble(2)+sepa);
							sPrintB.append("AZ,270,"+Loca+",1,2,0,0,刷卡:"+trade5.getDouble(3)+sepa);
			    			Loca=Loca+50;  //增加印出零售資訊
							sPrintB.append("AZ,10,"+Loca+",1,2,0,0,零售訂金:"+trade5.getDouble(4)+sepa);
							sPrintB.append("AZ,270,"+Loca+",1,2,0,0,刷卡:"+trade5.getDouble(5)+sepa);
			    			Loca=Loca+50;  //增加印出零售資訊
		    			}
					}else{
						Loca=Loca+2;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
						Loca=Loca+50;
		    			for (int i = 0; i <count ; i++){
		    				PxData data =mExpandAdapter.getData(groupPosition, i);
							sPrintB.append("AZ,15,"+Loca+",1,1,0,0,單號:"+data.iFormdate+sepa);//單號
							sPrintB.append("AZ,320,"+Loca+",1,1,0,0,("+data.iName+")"+sepa);//開單時間				
							Loca=Loca+30;  //
							sPrintB.append("AZ,15,"+Loca+",1,1,0,0,"+data.iGoods+sepa);//USERNAME
							sPrintB.append("AZ,320,"+Loca+",1,1,0,0,"+data.iCountry+data.iNumber+sepa);//件
							Loca=Loca+30;  //
							sPrintB.append("AZ,15,"+Loca+",1,1,0,0,"+data.iImpo+sepa);//應
							sPrintB.append("AZ,225,"+Loca+",1,1,0,0,"+data.iMoney+sepa);//現				
							sPrintB.append("AZ,425,"+Loca+",1,1,0,0,"+data.iCompany+sepa);//訂				
							Loca=Loca+5;  //
							sPrintB.append("AZ,15,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
							Loca=Loca+40;  
							//mode==1 就要印製明細
							if (mode==1){
								Cursor ask=db.rawQuery("select GOODSNOS,GOODSNAME,UNIT1,QKIND,UNIT10,UNIT20,UNIT30,UNIT40,UNITPRICE,DISCOUNT,SUBPRICE,PS from qitems where FORMNO='"+data.iFormdate+"'", null);
								if (ask.getColumnCount()>0){
									while (ask.moveToNext()){
										sPrintB.append("AZ,18,"+Loca+",1,1,0,0,"+ask.getString(0)+"("+ask.getString(2)+")"+ask.getString(1)+sepa);				
										Loca=Loca+30;
										sPrintB.append("AZ,28,"+Loca+",1,1,0,0,"+ask.getString((ask.getInt(3)/10)+3)+"件 X "+ask.getString(8)+" X "+ask.getString(9)+" % = "+ask.getString(10)+" ("+ask.getString(11)+")"+sepa);				
										if (!ask.isLast()) Loca=Loca+30;
									}
									Loca=Loca+5;  //
									sPrintB.append("AZ,15,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
									Loca=Loca+35;
								}
								ask.close();
							}
							
		    			}
		    			sPrintB.append("AZ,15,"+Loca+",1,2,0,0,"+datag.strTextG2+sepa);
		    			//保留印製空間(總計:265件 折讓:0)後面目前沒有安排
		    			Loca=Loca+50;//因為多一個[賒]所以跳行顯示
		    			sPrintB.append("AZ,15,"+Loca+",1,2,0,0,"+datag.strText2+sepa);
		    			Loca=Loca+50;  //
		    			sPrintB.append("AZ,15,"+Loca+",1,2,0,0,"+datag.strOriMoney+sepa);
		    			sPrintB.append("AZ,350,"+Loca+",1,2,0,0,"+datag.strMoney+sepa);
						Loca=Loca+35;  //
						sPrintB.append("AZ,15,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
		    			Loca=Loca+35;  //增加印出零售資訊
		    			
		    			if (trade5.getCount()>0){
		    				trade5.moveToFirst();
							sPrintB.append("AZ,15,"+Loca+",1,2,0,0,零售應收:"+trade5.getDouble(0)+sepa);
							sPrintB.append("AZ,350,"+Loca+",1,2,0,0,件數:"+trade5.getDouble(1)+sepa);
			    			Loca=Loca+50;  //增加印出零售資訊
							sPrintB.append("AZ,15,"+Loca+",1,2,0,0,零售現金:"+trade5.getDouble(2)+sepa);
							sPrintB.append("AZ,350,"+Loca+",1,2,0,0,刷卡:"+trade5.getDouble(3)+sepa);
			    			Loca=Loca+50;  //增加印出零售資訊
							sPrintB.append("AZ,15,"+Loca+",1,2,0,0,零售訂金:"+trade5.getDouble(4)+sepa);
							sPrintB.append("AZ,350,"+Loca+",1,2,0,0,刷卡:"+trade5.getDouble(5)+sepa);
		    			}
					}
	    			allcs.close();
					trade5.close();
					//檢查是否有 收支明細
					//將他找出印出
					SQL="select * from qmacc where FORMDATE='"+datag.strTextG1+"' and DEPTNO='"+deptStr[0]+"' and QNOM<>'0000' and QNOM<>'9600' order by CTIME";
					Cursor csMacc=db.rawQuery(SQL, null);
					double maccCash=0;
					if (csMacc.getCount()>0){
		    			Loca=Loca+40;
						sPrintB.append("AZ,15,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
		    			Loca=Loca+30;
						sPrintB.append("AZ,60,"+Loca+",1,2,0,0,營業外收支明細: "+sepa);
		    			Loca=Loca+50;
						while (csMacc.moveToNext())
						{
							sPrintB.append("AZ,15,"+Loca+",1,1,0,0,項目: "+csMacc.getString(csMacc.getColumnIndex("QNOM"))+"/"+csMacc.getString(csMacc.getColumnIndex("QATYPE"))+"/經手:"+csMacc.getString(csMacc.getColumnIndex("EMPID"))+"/"+csMacc.getString(csMacc.getColumnIndex("EMPNAME"))+sepa);
			    			Loca=Loca+30;
							sPrintB.append("AZ,15,"+Loca+",1,1,0,0,收: "+csMacc.getDouble(csMacc.getColumnIndex("MINTO"))+"/支:"+csMacc.getDouble(csMacc.getColumnIndex("MOUT"))+"/PS: "+csMacc.getString(csMacc.getColumnIndex("PS"))+sepa);
							Loca=Loca+30;
							maccCash+=(csMacc.getDouble(csMacc.getColumnIndex("MINTO"))-csMacc.getDouble(csMacc.getColumnIndex("MOUT")));
						}
						int cashM=0;
						String MM=datag.strOriMoney.toString();
						if (MM.indexOf("現金")>=0){
							if (MM.indexOf("/")>0)
								cashM=Utilis.toInt(MM.substring(MM.indexOf("現金")+3,MM.indexOf("/")));
							else
								cashM=Utilis.toInt(MM.substring(MM.indexOf("現金:")+3));
						}
						
						sPrintB.append("AZ,15,"+Loca+",1,1,0,0,本日現金結存 : "+(cashM+maccCash)+sepa);
						Loca=Loca+30;
					}
					
					csMacc.close();
					db.close();
	    			Loca=Loca+80;  
					if (sPrintB.toString().length()>0){
						String lenS="0000"+(int)(Loca/7.32);
						sPrintB.replace(2, 6,lenS.substring(lenS.length()-4,lenS.length()));
						sPrintB.append("E"+sepa);
						//Toast.makeText(QPosff.this, sPrintB.toString(), Toast.LENGTH_LONG).show();						
						
						String address=null;
						int port=0;
						int success=1;
						
						   address = Utilis.getIni(QPosff.this, "SYS","BAR_IP", 4);// 連線的ip
						   port =Utilis.toInt(Utilis.getIni(QPosff.this, "SYS","BAR_IP", 5));// 連線的port
							 InetAddress serverAddr = null;
						        SocketAddress sc_add = null;
						        Socket socket = null;
									 try {
										 serverAddr = InetAddress.getByName(address);
										 sc_add= new InetSocketAddress(serverAddr,port);
											 socket = new Socket();
											 socket.connect(sc_add,2000);
											 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
											 byte data[] = new String(sPrintB.toString().getBytes("UTF8")).getBytes("BIG5");
											 out.write(data, 0, data.length);
											 Toast.makeText(QPosff.this, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();

									 } catch (UnknownHostException e) {
										 success=0;
									 } catch (SocketException e) {
										 success=0;
									 } catch(IOException e) {
										 success=0;
									 } finally{
										 try {
												socket.close();
											} catch (IOException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}				 
										 }
									 
						}
			}
		}
	}

	private void modifyF(int mode){
		if (mode==0){
			DialogUtilis.showDialog(QPosff.this, "變更交易!!直接進入編輯?", -1,
					new String[] { "取消", "變更交易?" }, new IDialog() {
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch (pos) {
							case 0: {break;}
							case 1: // 確定變更交易
							{
									try{
										if (isPass<6 && isPass!=3 && isPass!=4) { //常態才可編輯
										SQLiteDatabase db = Utilis.getDB(QPosff.this);
										db.execSQL("update  qhead  set TR='Y1',ISCONFIRM='N',BANKNAME='"+mBankn+"',PS2='"+whoDel+"' where FORMNO='" + mKey+"' and QKIND LIKE '"+mKind.substring(0,1)+"%'" );//iFormdate其實存的是單號
										db.execSQL("update  qitems  set ISCONFIRM='N' where FORMNO='" + mKey+"' and QKIND LIKE '"+mKind.substring(0,1)+"%'" );//iFormdate其實存的是單號
										db.close();
										
										
											Intent intent = new Intent();										
											intent.putExtra("pos_mode",PItemMode.EDIT);
											intent.putExtra("pos_formno",mKey);
											intent.putExtra("pos_qkind",nKind);// @@TR30為預設(暫時廠進貨單) 
											intent.putExtra("pos_dept",mDept);//理論上為"SOS" 或 門市代號
											intent.putExtra("pos_where",PItemWhere.Qposf);
											intent.putExtra("pos_group",mGroupMode);
											intent.setClass(QPosff.this,APos.class);									
    										startActivityForResult(intent,RESULT_APOS);
										
									}else {
										ProgressDialog mProgress = null;
					        		    mProgress = new ProgressDialog(QPosff.this);
					        			mProgress.setCancelable(true);
					        			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);

					        			mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
					        			mProgress.show();

									}
										
									}catch(Exception e){
										e.printStackTrace();
									}finally{
									}
							}
							}
						}
			});
		}else {
			DialogUtilis.showDialog(QPosff.this, "單號: "+mKey+"確定整張單刪除?", -1,
					new String[] { "不要刪除", "當真刪除!!@#$%?" }, new IDialog() {
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch (pos) {
							case 0: {break;}
							case 1: // 確定刪除
							{
									try{
										SQLiteDatabase db = Utilis.getDB(QPosff.this);

										//刪除時,需要單頭 單身 一起刪除 重要元素 (單號)及(單別)
										//先刪除單身 再刪除單頭
										//@@@@如何維護 SERVER的qitems ORNY
										//應先拜訪伺服器,將qitems一一在伺服器刪除
										//不在LOCAL端qhead qitems留下任何資訊
										db.execSQL("delete from qitems where FORMNO='" + mKey+"'" );//其實存的是單號
										Cursor csH = db.rawQuery("select TR,QKIND from qhead where FORMNO='" + mKey+"'", null);
										if (csH.getCount()>0){
											csH.moveToFirst();
											if (of_line==0) {
													db.execSQL("delete from qhead where FORMNO='" + mKey+"'" );//其實存的是單號
												} else {
													db.execSQL("update qhead set TR='Y2',ID='1008',QKIND='"+mKind.substring(0, 1)+"2',CREATEDATETIME='"+DateUtil.getSystemTime().substring(2, 14)+"',ISCONFIRM='N',ISCHECK='N',BANKNAME='"+mBankn+"',PS2='"+whoDel+"' where FORMNO='" + mKey+"'" );//其實存的是單號
													
												if (of_line==1) {
													SystemClock.sleep(500);
													DBCloud.aa1_aa0_update_HI(QPosff.this);
												}

											}
										}
										csH.close();
										db.close();
										
										Toast.makeText(QPosff.this, "刪除資料成功", Toast.LENGTH_SHORT).show();

										getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
										mExpandAdapter.notifyDataSetChanged();

									}catch(Exception e){
										e.printStackTrace();
									}finally{
									}
							}
						}	
					}
			});

		}
	}

	private void checkABMode(int mode)
	{
		switch (mode) {
			case KeySet.SearchMode.ACTION:		abMode=0;break;
			case KeySet.SearchMode.ACCOUNT:	abMode=1;break;
			case KeySet.SearchMode.DAY:				abMode=1;break;
			case KeySet.SearchMode.MONTH:		abMode=1;break;
			case KeySet.SearchMode.WEEK:			abMode=1;break;
			case KeySet.SearchMode.WIDGET:		abMode=1;break;
		}
	}
	
	private void changeItems(int xx,int yy){
	 if ( of_line==0 || (Utilis.haveInternet(this) && of_line!=0)){
			String Dept=mDept;if (mDept.equalsIgnoreCase("SOS")) Dept=deptStr[0]; 
		 
		 String returnStr=PosUtilis.changeItems(QPosff.this, Dept, mUser, mKey, mGoods, mKind, mTime, locas, xx,yy, f123,0);
					
		    	  if (Utilis.haveInternet(this) && of_line!=0){
					
						StringBuffer bfstr = new StringBuffer();
						StringBuffer bfstrF = new StringBuffer();
						bfstr.append(Utilis.getIni(QPosff.this, "SYS", "IMPORT", 2)).append("!#%");
						bfstrF.append("UID").append("!#%");
						bfstr.append(mBankn).append("!#%");
						bfstrF.append("BANKNAME").append("!#%");
						bfstr.append(Dept).append("!#%");
						bfstrF.append("DEPTNO").append("!#%");
						bfstr.append(deptStr[5]).append("!#%");
						bfstrF.append("QPART").append("!#%");
						bfstr.append("0!#%");
						bfstrF.append("ALONE").append("!#%");
						//if (locas[yy]!=2) bfstr.append("!#%"); else bfstr.append("2!#%");
						bfstr.append("!#%");
						bfstrF.append("MODE").append("!#%");
						bfstr.append(returnStr.toString()).append("!#%");
						bfstrF.append("SERVERSTR").append("!#%");
						bfstr.append(Utilis.getIni(QPosff.this, "SYS", "AUPDATE", 3)).append("!#%");
						bfstrF.append("LUPDATET3").append("!#%");
						//目的是為了減少回傳的更新
						bfstr.append(Utilis.getIni(QPosff.this, "SYS", "AUPDATE", 4));
						bfstrF.append("LUPDATE");

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

					          }
					          catch (Exception e)
					          {
					        	  e.printStackTrace();
					          }
					       }
				      }.start(); /* 開始執行執行緒 */
		    	  }	
	
	 }else Toast.makeText(QPosff.this, "網路不正常,無法進行交易!!!!", Toast.LENGTH_SHORT).show();	        		        	
	 //網路不正常
	}
	
	Handler mHandlerGVOB = new Handler()
	{
		@Override
		public  void handleMessage(Message msg)
		{
			//傳回的//upup_1-30_系統時間
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
				if (Hresult != null ){
					if (Hresult.indexOf("aa1_aa0_gvo;")>0){
						String [] EchoStr=Hresult.split(";");
						Utilis.putIni(QPosff.this, "SYS", "AUPDATE",EchoStr[1] ,4 );//T4_ORNY
				    	getGroupData(QPosff.this, mStartDay, mEndDay, null, null);
						mExpandAdapter.notifyDataSetChanged();
					}
				}
			}
		}
	};
	
	// 搜尋日期 Dialog
    private View makeDateDialog() {
    	View view = LayoutInflater.from(this).inflate(R.layout.search_date, null, false);
    	Calendar c = Calendar.getInstance();
    	c.set(Calendar.DAY_OF_MONTH, 1); // 關鍵
    	
	    mYear1 = c.get(Calendar.YEAR);
		mMonth1 = c.get(Calendar.MONTH) + 1;
		mDay1 = c.get(Calendar.DAY_OF_MONTH);
		c.add(Calendar.MONTH, 1);
		c.add(Calendar.DATE, -1);   // 關鍵
		mYear2 = c.get(Calendar.YEAR);
		mMonth2 = c.get(Calendar.MONTH) + 1;
		mDay2 = c.get(Calendar.DAY_OF_MONTH);
		
		dp1 = (DatePicker)view.findViewById(R.id.dp1);
		dp1.init(mYear1, mMonth1 - 1, mDay1, new DatePicker.OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				mYear1 = year;
				mMonth1 = monthOfYear + 1;
				mDay1 = dayOfMonth;
			}
		});
		
		dp2 = (DatePicker)view.findViewById(R.id.dp2);
		dp2.init(mYear2, mMonth2 - 1, mDay2, new DatePicker.OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				mYear2 = year;
				mMonth2 = monthOfYear + 1;
				mDay2 = dayOfMonth;
			}
		});
		
		return view;
	}
}
