package com.cwbuyer.lib;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
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.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.format.EMode;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.KeySet;
import com.pwbuyer.main.R;

//銷售王的核心2層式ADAPTER,複製自 MANAGEITEM採購王
@SuppressLint({ "UseSparseArrays", "InflateParams" })
public class QMacc extends Activity{
	
	ExpandItemAdapter mExpandAdapter = null;	
	
	TextView mTextDuration = null;

	int mMode = KeySet.SearchMode.DAY;
	
	private final int RESULT_AMACC=8000; 		//Return_AMacc
	private LinkedList<GroupData> mGroupList = new LinkedList<GroupData>();	
	
	int mGroupMode = GroupMode.TOP1;  //依日期結算 
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);	
	
	//String clouds="http://"+Utilis.getIni(QMacc.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(QMacc.this, "SYS", "IMPORT", 2)+File.separator;
	//String uriAPI1=clouds+"qrep03_1.php";
	
	String mDept=Utilis.getIni(this,"SYS","DEPT",1);
	String mDeptNAME=Utilis.getIni(this,"SYS","DEPT",3);
	//預設為 門市 而非 總倉
	public ProgressDialog myDialog = null;
	protected static final int REFRESH_DATA = 0x00000001;
	DecimalFormat df = new DecimalFormat();
	String style = "#,##0";
	
	/** State :  true 正式 , false 樣品*/
	String mEndDay = null;
	String mStartDay = null;
	String sepa="\r\n";
	String sepaA4=";";
	String CntsSQL=" sum(MINTO),sum(MOUT),sum(MBEFORE),sum(MBETWEEN),sum(MBALANCE), sum(MAFTER),";
	StringBuffer sPrintB = new StringBuffer();
	StringBuffer sPrintA4=new StringBuffer(); 

	int Loca=0;
	int Lgap=230;
	String mTitleP="";
	int PSWD=1;
	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	int delORmodi=0;
	int nPart=0;
	String GoodChg="A.GOODSNO";
	String ColorChg="A.COLORS";
	String SizeChg="A.SIZES";
	String ConChg="主貨";
	String SQLADD="";
	int CountX=0;//還要製作 統計判斷 //03040 1.只要40 2.只要30
	int deptN=1;

	//第一層的搜尋 項目
	String [] sql_A={  
   			"",
   			" MINTO,MOUT,MBEFORE,MBETWEEN,MBALANCE, MAFTER ,FORMDATE,FORMNO,DEPTNO,DEPTNAME,EMPID,EMPNAME,QNOM,QATYPE,CTIME,PIC ,PS",
   			" MINTO,MOUT,MBEFORE,MBETWEEN,MBALANCE, MAFTER ,FORMDATE,FORMNO,DEPTNO,DEPTNAME,EMPID,EMPNAME,QNOM,QATYPE,CTIME,PIC ,PS",
   			" QNOM,QATYPE ",
   			" DEPTNO,DEPTNAME ",
   			" DEPTNO,DEPTNAME,QNOM,QATYPE "
   			};
   	String [] sql_B={ 
   			"",
   			" MINTO,MOUT,MBEFORE,MBETWEEN,MBALANCE, MAFTER ,FORMDATE,FORMNO,DEPTNO,DEPTNAME,EMPID,EMPNAME,QNOM,QATYPE,CTIME,PIC ,PS",
   			" MINTO,MOUT,MBEFORE,MBETWEEN,MBALANCE, MAFTER ,FORMDATE,FORMNO,DEPTNO,DEPTNAME,EMPID,EMPNAME,QNOM,QATYPE,CTIME,PIC ,PS",
   			" DEPTNO,DEPTNAME,QNOM,QATYPE ",
   			" FORMDATE,FORMNO,DEPTNO,DEPTNAME,EMPID,EMPNAME,QNOM,QATYPE,CTIME,PIC ,PS",
   			" DEPTNO,DEPTNAME,QNOM,QATYPE,FORMDATE "
   			};

   	
   	String [] sql_orderBy={ 
   			"",
   			" FORMDATE,DEPTNO",
   			" DEPTNO,FORMDATE ",
   			" DEPTNO,DEPTNAME,QNOM,QATYPE",
   			" DEPTNO,DEPTNAME,FORMDATE",
   			" DEPTNO,DEPTNAME,QNOM,QATYPE,FORMDATE"
   			};
   	
	String[] mode_E={ "","依日期結算", "依門市結算", "依科目統計","依門市結算統計","依門市收支統計"};
	String mKind=null; //單別 102030405060
	double sSort=0; //0依金額 1.依件數 2.依毛利
	
	int nKind=30;
	DatePicker dp1;
	DatePicker dp2;
	
   	String btns=null;
   	String[] bttns;

   	double TT10=0;  	//
   	double TM10=0; 	//總進貨額
   	double TT30=0;	//總銷貨量
   	double TM30=0;	//總銷貨額
   	double TS30=0;	//總銷貨額
   	double StkT=0;		//總存貨量
   	double StkM=0;	//總存貨額
   	
   	double T10=0;  	//本進貨量
   	double M10=0; 	//本進貨額
   	double T30=0;		//本銷貨量
   	double M30=0;	//本銷貨額
   	double S30=0;	//本銷貨額
   	double Profit=0; 	//本期毛利
   	double Profits=0; //本期利率
	
	private int mYear1 = 0;
	private int mYear2 = 0;
	private int mMonth1 = 0;
	private int mMonth2 = 0;
	private int mDay1 = 0;
	private int mDay2 = 0;

	class GroupData{ //第一層版面
		public String Sort;
		public String strKey;
		public String strPic;  // 圖
		public String strTopLeft;  // 左上 TOP1_
		public String strTopRight;  // 右上
		
		public String strMleft; // 左中 
		public String strMright;  // 左下
		
		public String strDleft; // 下左
		public String strDright; // 右下
		public String strDmiddle;  //右中
		
		public String strPs;  //四行
		
	}
	
	class PxData{ //第二層版面
		public String iKey;
		public String iFormdate;
		public String iPic;
		
		public String iTopLeft; 
		public String iTopRight;
		
		public String iMleft; 
		public String iMright;
		
		public String iDleft;
		public String iDmiddle;
		public String iDright;
		public String iPs;
		
	}
	
//	ListView mListView = null;
	ExpandableListView mExpandListView = null;
	
//For  Table
	int Wheight;
	int Wwidth;

	LinkedList<String> mSizeLink = new LinkedList<String>();
	LinkedList<String> mSizeLink1 = new LinkedList<String>();
	LinkedList<String> mColorLink = new LinkedList<String>();
	
	HashMap<Integer,Integer> mCountRow = new HashMap<Integer,Integer>(); // 顏色行資料
	HashMap<Integer,String> mCountCell = new HashMap<Integer,String>();  // 尺寸欄資料
	
	PxData datai =null;	
	GroupData dataH=null;//@@日後需補充用ITEM檢測HEAD是否漏掉的清單,並自動修補	
	public interface GroupMode{//EVERYDAY/WEEK/MONTH 以FORMDATE
		int TOP1 = 1;	//依日期結算
		int TOP2 = 2;  	//依門市結算
		int TOP3 = 3; 	//依總收支統計
		int TOP4 = 4; 	//依門市結算統計
		int TOP5 = 5; 	//依門市收支統計
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent dataR) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, dataR);
		
		switch(requestCode){
		
		case RESULT_AMACC:
			{
				if (resultCode == RESULT_OK) {
			    	getGroupData(mStartDay, mEndDay, null, null);
				}
				break;
			}
		}	
    }
	
	
	
	@SuppressWarnings("deprecation")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qmacc_rep);
        
		Wheight = this.getWindowManager().getDefaultDisplay().getHeight();
		Wwidth = this.getWindowManager().getDefaultDisplay().getWidth();
		
		df.applyPattern(style);
		
        mTextDuration = (TextView)findViewById(R.id.text_durationa);
        //@@應增加營業時間的判斷而視為當日或前一天
        mStartDay =DateUtil.getCurrentDate();
        mEndDay=mStartDay;
        
        mMode = getIntent().getIntExtra("search_mode", KeySet.SearchMode.DAY);		
        mGroupMode= getIntent().getIntExtra("search_group", GroupMode.TOP1);	
        
        ((Button)findViewById(R.id.btn_exita)).setOnClickListener(new MainClick());		//離開
        
        ((Button)findViewById(R.id.btn_top1a)).setOnClickListener(new MainClick()); //依會員
        ((Button)findViewById(R.id.btn_top2a)).setOnClickListener(new MainClick()); //依櫃員        
        ((Button)findViewById(R.id.btn_top3a)).setOnClickListener(new MainClick()); //依門市
        ((Button)findViewById(R.id.btn_top4a)).setOnClickListener(new MainClick()); //依廠商
        ((Button)findViewById(R.id.btn_top5a)).setOnClickListener(new MainClick()); //依類別
        ((Button)findViewById(R.id.btn_prev_datea)).setOnClickListener(new MainClick());//上一
        ((Button)findViewById(R.id.btn_next_datea)).setOnClickListener(new MainClick());//下一
        
        ((Button)findViewById(R.id.btn_btn0a)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_btn1a)).setOnClickListener(new MainClick());        
        ((Button)findViewById(R.id.btn_btn2a)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_btn3a)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_btn4a)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_btn5a)).setOnClickListener(new MainClick());
        //mTextDuration.setOnClickListener(new MainClick());
    	
        mExpandListView = (ExpandableListView)findViewById(R.id.list_item_expanda);    	
        mExpandAdapter = new ExpandItemAdapter(this);
        mExpandListView.setAdapter(mExpandAdapter);
        mExpandListView.setOnChildClickListener(mChildClcik);
        mExpandListView.setOnItemLongClickListener(mLongClickListener);
        
        if (Utilis.getIni(this,"SYS","DEPT",5).equalsIgnoreCase("0")){  //密碼OK 或不用密碼
        	((LinearLayout)findViewById(R.id.layout_topsa)).setVisibility(View.VISIBLE);
        	PSWD=0;
        }else{
        	((LinearLayout)findViewById(R.id.layout_topsa)).setVisibility(View.GONE);
        }
        //原先就是執行一遍 因為不會中途改變模式
        //現在是可以切換
        //只要一切換,都會從最近日期範圍貨最近一批最近一季起算
		//應追加 上一批 的程式
        if (!Utilis.getIni(this,"SYS","DEPT",1).equalsIgnoreCase(Utilis.getIni(this,"SYS","DEPT",6))) nPart=1;  //門市版
        
        switch(mGroupMode){
        case GroupMode.TOP1:
        	resetButton(R.id.btn_top1a);
        	break;
        case GroupMode.TOP2:
        	resetButton(R.id.btn_top2a);
        	break;
        case GroupMode.TOP3:
        	resetButton(R.id.btn_top3a);
        	break;
        case GroupMode.TOP4:
        	resetButton(R.id.btn_top4a);
        	break;
        case GroupMode.TOP5:
        	resetButton(R.id.btn_top5a);
        	break;
        }
        chkMode();
        
        mExpandListView.setOnScrollListener(new OnScrollListener() {
            public void onScrollStateChanged(AbsListView view,
                    int scrollState) { // TODO Auto-generated method stub
            	if(scrollState==SCROLL_STATE_FLING){
            	     //Toast.makeText(QRep_01.this,"Fling",Toast.LENGTH_SHORT).show();
            	    }else if(scrollState==SCROLL_STATE_IDLE){
            	     //Toast.makeText(QRep_01.this,"Idle",Toast.LENGTH_SHORT).show();
            	    }            	
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {

            }
        });
}	
	
	
	
	public void onResume(){
		super.onResume();
		DBCloud.aa0_aa1_auto_qmacc(QMacc.this);
		}
	
	private void setCondition(){
		
		//台頭:CWBuyer銷售王+[進貨]
		//(APos.java)[新增][查詢][編輯] 帶過去的引數
		//現階段可分為:[交易中][統計中]
		
    	switch(mMode){ 
    	
			case KeySet.SearchMode.DAY:
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
    			setTitle(getString(R.string.app_name)+":[依每日]"+mode_E[mGroupMode]+"("+ConChg+")");
				break;
			}
			case KeySet.SearchMode.WEEK:
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
    			setTitle(getString(R.string.app_name)+":[依每週]"+mode_E[mGroupMode]+"("+ConChg+")");
				break;
			}
			case KeySet.SearchMode.MONTH:
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
				setTitle(getString(R.string.app_name)+":[依每月]"+mode_E[mGroupMode]+"("+ConChg+")");
				break;
			}
			default:
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
				setTitle(getString(R.string.app_name)+":[依日期範圍]"+mode_E[mGroupMode]+"("+ConChg+")");
				break;
			}
    	}
	}
	
	// 特別處理 日結單 GROUPS第一層 是以(日/週/月)為統計結算 childs第二層 才是單頭
	//如何分開 日結+單頭  及 單頭+單身 的製作就是關鍵
	private void getGroupData( String dbStartDay, String dbEndDay, String condition, String conditionValue) {
				
		if (mGroupList != null) {
			mGroupList.clear();
		}
			
	try {
				StringBuffer bufCategory = new StringBuffer();
				if(dbStartDay != null && dbStartDay.length() > 0)	dbStartDay = dbStartDay.replace("/", "-");
				if(dbEndDay != null && dbEndDay.length() > 0) dbEndDay = dbEndDay.replace("/", "-");

				T10=0;  	 M10=0; 	T30=0;	M30=0;
				TT10=0;  TM10=0; 	TT30=0;	TM30=0;
				TS30=0;	 StkT=0;		StkM=0;	
				Profit=0; Profits=0; 

				bufCategory=bufCategory.delete(0, bufCategory.toString().length());
				
				if (mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP2){
					//依日期結算 依門市結算
					bufCategory.append("select "+sql_A[mGroupMode]+""); //總件數,總實應收,總成本
						bufCategory.append(" from qmacc where FORMDATE >= '").append(dbStartDay).append("'")
						.append(" and FORMDATE <= '").append(dbEndDay).append("'");
						
					if (nPart==1){
						bufCategory.append(" and DEPTNO ='"+Utilis.getIni(this,"SYS","DEPT",1)+"'");
					}		//只限結算表
					bufCategory.append(" and QNOM='0000' and TR<>'Y2' order by "+sql_orderBy[mGroupMode]);
				}else {
					//第 三四五 層
					bufCategory.append("select "+CntsSQL+sql_A[mGroupMode]+""); //總件數,總實應收,總成本
					bufCategory.append(" from qmacc where FORMDATE >= '").append(dbStartDay).append("'")
						.append(" and FORMDATE <= '").append(dbEndDay).append("'");
					//2019-04-07 增設門市 只能看到 自己的統計
					if (nPart==1){
						bufCategory.append(" and DEPTNO ='"+Utilis.getIni(this,"SYS","DEPT",1)+"'");
					}		//只限結算表
					
					if (mGroupMode==GroupMode.TOP3 || mGroupMode==GroupMode.TOP5)
						bufCategory.append(" and QNOM<>'0000'");
					else
						bufCategory.append(" and QNOM='0000'");
					
					bufCategory.append(" and TR<>'Y2' group by "+sql_A[mGroupMode]+" order by "+sql_A[mGroupMode]);
				}						

				SQLiteDatabase db = Utilis.getDB(QMacc.this);
				Cursor cursorGroup = null;
				LinkedList<GroupData> groups = new LinkedList<GroupData>();
				LinkedList<List<PxData>> childs = new LinkedList<List<PxData>>();

 				cursorGroup = db.rawQuery(bufCategory.toString(), null);
				if (cursorGroup != null && cursorGroup.getCount()> 0) {
						cursorGroup.moveToFirst();
						for (int i = 0; i < cursorGroup.getCount(); i++) {
							GroupData data = new GroupData();
//" 0_MINTO,1_MOUT,2_MBEFORE,3_MBETWEEN,4_MBALANCE,"							
//" 5_MAFTER ,6_FORMDATE,7_FORMNO,8_DEPTNO,9_DEPTNAME"							
//"10_EMPID,11_EMPNAME,12_QNOM,13_QATYPE,"							
//" 14_CTIME,15_PIC ,16_PS"
							
						if (mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP2){
							data.strKey=cursorGroup.getString(7)+"/"+cursorGroup.getString(14);
							//FORMNO,CTIME
							data.strTopLeft = cursorGroup.getString(6)+"/"+cursorGroup.getString(8)+"/"+cursorGroup.getString(9);
							//FORMDATE 門市 名稱 
							data.strTopRight="現收: "+df.format(cursorGroup.getDouble(3));
							//現收
							data.strDleft = cursorGroup.getString(10)+"/"+cursorGroup.getString(11);
							//櫃員/名稱
							data.strDright ="提存: "+df.format(cursorGroup.getDouble(1));
							//提存
							data.strMleft="短溢: "+df.format(cursorGroup.getDouble(4))+"  零用金: "+df.format(cursorGroup.getDouble(5));
							//溢收款
							data.strMright ="收支: "+df.format(cursorGroup.getDouble(0));
							//收支
							TT10+=cursorGroup.getDouble(1);//總提存
							TM10+=cursorGroup.getDouble(3);//總營收
							TT30+=cursorGroup.getDouble(4);//短溢金
							TM30+=cursorGroup.getDouble(0);//收支
							
							data.strDmiddle=cursorGroup.getString(7);
							//單號
							data.strPs=cursorGroup.getString(16);
							//備註
							data.strPic=cursorGroup.getString(15);  
							//圖片
						}else{ //針對第三四五層 各自規格
//0_ sum(MINTO),1_sum(MOUT),2_sum(MBEFORE)
//,3_sum(MBETWEEN),4_sum(MBALANCE),
// 5_sum(MAFTER)
							
//TOP3 6_QNOM,7_QATYPE
//TOP4 6_DEPTNO,7_DEPTNAME ",
//TOP5 6_DEPTNO,7_DEPTNAME,8_QNOM,9_QATYPE "
							if (mGroupMode==GroupMode.TOP3){							
								data.strKey=cursorGroup.getString(6);
								data.strTopLeft = cursorGroup.getString(6)+"/"+cursorGroup.getString(7);
								//收支/名稱
								data.strMright ="收入: "+df.format(cursorGroup.getDouble(0));
								//收支
								data.strDright ="支出: "+df.format(cursorGroup.getDouble(1));
								//提存
							
							}else if (mGroupMode==GroupMode.TOP4){
								data.strKey=cursorGroup.getString(6);
								data.strTopLeft = cursorGroup.getString(6)+"/"+cursorGroup.getString(7);
								//門市/名稱
								data.strTopRight="現收: "+df.format(cursorGroup.getDouble(3));
								//營收
								data.strMleft="短溢: "+df.format(cursorGroup.getDouble(4));
								//溢收款
								data.strMright ="收支: "+df.format(cursorGroup.getDouble(0));
								//收支
								data.strDright ="提存: "+df.format(cursorGroup.getDouble(1));
								//提存
								
							}else{
								data.strKey=cursorGroup.getString(6)+"/"+cursorGroup.getString(8);
								data.strTopLeft = cursorGroup.getString(8)+"/"+cursorGroup.getString(9);
								//收支/名稱
								data.strMleft = cursorGroup.getString(6)+"/"+cursorGroup.getString(7);
								//門市/名稱
								data.strMright ="收入: "+df.format(cursorGroup.getDouble(0));
								//收支
								data.strDright ="支出: "+df.format(cursorGroup.getDouble(1));
								//提存
								
							}							
							TT10+=cursorGroup.getDouble(1);//總提存
							TM10+=cursorGroup.getDouble(3);//總營收
							TT30+=cursorGroup.getDouble(4);//短溢金
							TM30+=cursorGroup.getDouble(0);//收支
							
						}
		 					groups.add(data);
							cursorGroup.moveToNext();

						}	
 				}
				cursorGroup.close();
				
 				((TextView)findViewById(R.id.text_t10a)).setText("總提存$"+df.format(TT10));
 				((TextView)findViewById(R.id.text_r10a)).setText("總營收$:"+df.format(TM10));
 				((TextView)findViewById(R.id.text_t30a)).setText("總短溢$:"+df.format(TT30));
 				((TextView)findViewById(R.id.text_r30a)).setText("總收支$:"+df.format(TM30));
			
			if (groups.size() > 0) {  //製作第二層 
				StringBuffer bufList = new StringBuffer();
				
				for (int i = 0; i < groups.size(); i++) {
						bufList.delete(0, bufList.length());
						if (mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP2){
							bufList.append("select "+sql_B[mGroupMode]); //總件數,總實應收,總成本
							String aKey[] =groups.get(i).strTopLeft.split("/");
							bufList.append(" from qmacc where FORMDATE='"+aKey[0]+"' and DEPTNO='"+aKey[1]+"'")
							.append("  and QNOM <> '0000' and TR<>'Y2' order by CTIME ");
							//所有欄位 且 日期 門市 相符 且 非 結算表
							//單純的 顯示 每筆收支 明細
						}else {
							//第 三四五 層
							bufList.append("select "+CntsSQL+sql_B[mGroupMode]); //總件數,總實應收,總成本
							bufList.append(" from qmacc where FORMDATE >= '").append(dbStartDay).append("'")
								.append(" and FORMDATE <= '").append(dbEndDay).append("'");
							if (nPart==1){
								bufList.append(" and DEPTNO ='"+Utilis.getIni(this,"SYS","DEPT",1)+"'");
							}		//只限結算表
							
							if (mGroupMode==GroupMode.TOP3 ){
								if (nPart==1){
									bufList.append(" and DEPTNO ='"+Utilis.getIni(this,"SYS","DEPT",1)+"'");
								}		//2019-04-07 各門市只能看到自己的統計
								bufList.append(" and QNOM='"+groups.get(i).strKey+"'");
								bufList.append(" and QNOM<>'0000'");
								bufList.append(" and TR<>'Y2' group by "+sql_B[mGroupMode]+" order by "+sql_B[mGroupMode]);
							}else if (mGroupMode==GroupMode.TOP4){
								bufList.append(" and DEPTNO='"+groups.get(i).strKey+"'");
								bufList.append(" and QNOM='0000'");
								bufList.append(" and TR<>'Y2' group by "+sql_B[mGroupMode]+" order by "+sql_B[mGroupMode]);
							}else{
								String aKey[] =groups.get(i).strKey.split("/");
								bufList.append(" and DEPTNO='"+aKey[0]+"' and QNOM='"+aKey[1]+"'");
								bufList.append(" and QNOM<>'0000'");
								bufList.append(" and TR<>'Y2' group by "+sql_B[mGroupMode]+" order by "+sql_B[mGroupMode]);
							}
						}
						Cursor cursor = db.rawQuery(bufList.toString(), null);
						List<PxData> listData = new ArrayList<PxData>();
						
						if (mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP2){
							datai=new PxData();
							datai.iTopLeft = "按我可以新增一筆 [收支]";
							datai.iPic ="drawable.icon";
							//附圖新增圖樣
		 					listData.add(datai);
						}
						
					if (cursor != null) {
						if (cursor.getCount() > 0) {
							cursor.moveToFirst();
							for (int k = 0; k < cursor.getCount(); k++) {
								datai=new PxData();
								if (mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP2){
//" 0_MINTO,1_MOUT,2_MBEFORE,3_MBETWEEN,4_MBALANCE,"							
//" 5_MAFTER ,6_FORMDATE,7_FORMNO,8_DEPTNO,9_DEPTNAME"							
//"10_EMPID,11_EMPNAME,12_QNOM,13_QATYPE,"							
//" 14_CTIME,15_PIC ,16_PS"
									datai.iKey=cursor.getString(6)+"/"+cursor.getString(8)+"/"+cursor.getString(9);
									datai.iTopLeft = cursor.getString(6);
									//日期
									datai.iTopRight =cursor.getString(7);
									//單號
									datai.iMleft = cursor.getString(12)+"/"+ cursor.getString(13);
									//收支/科目
									datai.iMright ="收入: "+df.format(cursor.getDouble(0));
									//收入
									datai.iDleft = cursor.getString(10)+"/"+ cursor.getString(11);
									//櫃員/名稱
									datai.iDmiddle =cursor.getString(14);
									//開單時間
									datai.iDright =" 支出: "+df.format(cursor.getDouble(1));
									//支出
									datai.iPs =cursor.getString(16);
									datai.iPic =cursor.getString(15);
									//備註 附圖
									
								}else{
//0_ sum(MINTO),1_sum(MOUT),2_sum(MBEFORE)
//,3_sum(MBETWEEN),4_sum(MBALANCE),5_sum(MAFTER)
// 6_DEPTNO,7_DEPTNAME,8_QNOM,9_QATYPE ",
// 6_DEPTNO,7_DEPTNAME,8_FORMDATE ",
// 6_DEPTNO,7_DEPTNAME,8_QNOM,9_QATYPE,10_FORMDATE "
																	
									if (mGroupMode==GroupMode.TOP3){
										datai.iKey=cursor.getString(6)+"/"+cursor.getString(8);
										datai.iTopLeft = cursor.getString(8)+"/"+cursor.getString(9);
										datai.iMleft = cursor.getString(6)+"/"+cursor.getString(7);
										datai.iMright ="收入: "+df.format(cursor.getDouble(0));
										//收入
										datai.iDright ="支出: "+df.format(cursor.getDouble(1));
										//支出
									}else	if (mGroupMode==GroupMode.TOP4){
										datai.iKey=cursor.getString(6)+"/"+cursor.getString(10);
										datai.iTopLeft = cursor.getString(6);

			 							datai.iTopRight="現收: "+df.format(cursor.getDouble(3));
										//現收
										datai.iDleft = cursor.getString(10)+"/"+cursor.getString(11);
										//櫃員/名稱
										datai.iDright ="提存: "+df.format(cursor.getDouble(1));
										//提存
										datai.iMleft="短溢: "+df.format(cursor.getDouble(4))+"  零用金: "+df.format(cursor.getDouble(5));
										//溢收款
										datai.iMright ="收支: "+df.format(cursor.getDouble(0));
										//收支
										datai.iDmiddle=cursor.getString(7);
										//單號
										datai.iPs=cursor.getString(16);
										//備註
										datai.iPic=cursor.getString(15);  
										
									}else{
										datai.iKey=cursor.getString(6)+"/"+cursor.getString(8);
										datai.iTopLeft = cursor.getString(8)+"/"+cursor.getString(9);
										datai.iMleft = cursor.getString(6)+"/"+cursor.getString(7);
										datai.iDleft = cursor.getString(10);
										datai.iMright ="收入: "+df.format(cursor.getDouble(0));
										//收入
										datai.iDright ="支出: "+df.format(cursor.getDouble(1));
										//支出
									}
								}
			 					listData.add(datai);
				 				cursor.moveToNext();
							}
						}
					}
					if (listData.size()>0) childs.add(listData);
					cursor.close();	
				}
				mExpandAdapter.setData(groups, childs);
				mExpandAdapter.notifyDataSetChanged();
			}
			db.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
			
	}
	
	private LongClick mLongClickListener = new LongClick();

	
	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);
                
                if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
					if (mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP2){
	                	
	        			String [] Lmenu={"編輯-結算單","刪除-結算單","返回"};
		    			DialogUtilis.showDialog(QMacc.this, "請選擇以下功能", -1,
		    					Lmenu, new IDialog() {
		    						@Override
		    						public void onDialogFinish(int pos, String choice) {
		    							switch (pos) {
			    								case 0: //編輯-結算單
			    								{
													dataH =mExpandAdapter.groups.get(groupPosition);
			    									String TitleS=dataH.strKey+"_結算單,[編輯]";
			    									delORmodi=1;	askPSWD(TitleS);
			    									break;
		    									}
			    								case 1: //刪除-結算單
			    								{
													dataH =mExpandAdapter.groups.get(groupPosition);
			    									String TitleS=dataH.strKey+"_結算單[刪除],該所有收支單一併刪除";
			    									delORmodi=0;	askPSWD(TitleS);
			    									break;
		    									}
			    								case 3: //返回
			    									
		    								}
		    							}
		    			});
					}else{
	            	     Toast.makeText(QMacc.this,"統計資料,不可編輯",Toast.LENGTH_SHORT).show();
					}
                }else{//CHILD
					if ((mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP2) && childPosition>0){
	        			String [] Lmenu={"編輯-收支單","刪除-收支單","返回"};
		    			DialogUtilis.showDialog(QMacc.this, "請選擇以下功能", -1,
		    					Lmenu, new IDialog() {
		    						@Override
		    						public void onDialogFinish(int pos, String choice) {
		    							switch (pos) {
	    								case 0: //編輯-收支單
	    								{
	    									datai = mExpandAdapter.getData(groupPosition, childPosition);
	    									String TitleS=datai.iKey+"收支單,[編輯]";
	    									delORmodi=1;	askPSWDi(TitleS);
	    									break;
										}
	    								case 1: //刪除-收支單
	    								{
	    									datai = mExpandAdapter.getData(groupPosition, childPosition);
	    									String TitleS=datai.iKey+"收支單,[刪除]";
	    									delORmodi=0;	askPSWDi(TitleS);
    										break;
										}
	    								case 3: //返回
		    								}
		    							}
		    			});
					}else if ((mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP2) && childPosition==0){
						GroupData data =mExpandAdapter.groups.get(groupPosition);
						String mKey[]=data.strKey.split("/");
						String mKey1[]=data.strTopLeft.split("/");
						Intent intent = new Intent();
						intent.putExtra("FORMDATE",mKey1[0]);
						intent.putExtra("FORMNO",mKey[0]);
						intent.putExtra("DEPTNO",mKey1[1]);
						intent.putExtra("DEPTNAME",mKey1[2]);
						intent.putExtra("CTIME","");
						intent.putExtra("PART",nPart);
						intent.putExtra("ADDEDIT",EMode.ADD);
						intent.putExtra("MODE",1);//0結算.1支出

						intent.setClass(QMacc.this, AMacc.class);
						startActivityForResult(intent, RESULT_AMACC);
					}else
	            	     Toast.makeText(QMacc.this,"統計資料,不可編輯",Toast.LENGTH_SHORT).show();
                }
				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(QMacc.this);
			
			return false;
		}
	}
	
	
	class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QMacc.this);
			switch (id) {
				case R.id.btn_exita:
				{
					finish();
					break;
				}
				case R.id.btn_btn0a:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.DAY;
					chkMode();
					break;
				}
				case R.id.btn_btn1a:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.WEEK;
					chkMode();
					break;
				}
				case R.id.btn_btn2a:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.MONTH;
					chkMode();
					break;
				}
				case R.id.btn_btn3a:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.SEASON;
					chkMode();
					break;
				}
				case R.id.btn_btn4a:  //新增一筆[收支]
				{
					Intent intent = new Intent();
			   		String FormD=DateUtil.getCurrentDate();  //2012-10-22
			   		int Ttime=Utilis.toInt(DateUtil.getSystemTime().substring(8, 10));  //取得目前幾點
					if (Ttime<=5)  FormD = DateUtil.addDate(FormD, -1);
					FormD = FormD.replace("/", "-");
					intent.putExtra("FORMDATE",FormD);
					intent.putExtra("FORMNO","");
					intent.putExtra("DEPTNO",mDept);
					intent.putExtra("DEPTNAME",mDeptNAME);
					intent.putExtra("CTIME","");
					intent.putExtra("PART",nPart);
					intent.putExtra("ADDEDIT",EMode.ADD);
					intent.putExtra("MODE",1);

					intent.setClass(QMacc.this, AMacc.class);
					startActivityForResult(intent, RESULT_AMACC);
					
					break;
				}
				case R.id.btn_btn5a:  //新增一筆[結算]
				{
					Intent intent = new Intent();
			   		String FormD=DateUtil.getCurrentDate();  //2012-10-22
			   		int Ttime=Utilis.toInt(DateUtil.getSystemTime().substring(8, 10));  //取得目前幾點
					if (Ttime<=5)  FormD = DateUtil.addDate(FormD, -1);
					FormD = FormD.replace("/", "-");
					intent.putExtra("FORMDATE",FormD);
					intent.putExtra("FORMNO","");
					intent.putExtra("DEPTNO",mDept);
					intent.putExtra("DEPTNAME",mDeptNAME);
					intent.putExtra("CTIME","");
					intent.putExtra("PART",nPart);
					intent.putExtra("ADDEDIT",EMode.ADD);
					intent.putExtra("MODE",0);

					intent.setClass(QMacc.this, AMacc.class);
					startActivityForResult(intent, RESULT_AMACC);
					
					break;
				}

				case R.id.btn_prev_datea:  //當按了上一??
				{
					switch(mMode){
						case KeySet.SearchMode.MONTH:  //就是31筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, -1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
			    			break;
			    		}
						case KeySet.SearchMode.DAY:  //就是7筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, -1);
							mEndDay = DateUtil.addDate(mEndDay, -1);
			    			break;
			    		}
						case KeySet.SearchMode.WEEK:  //就是7筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, -7);
							mEndDay = DateUtil.addDate(mEndDay, -7);
			    			break;
			    		}
					}
					getGroupData(mStartDay, mEndDay, null, null);
					int count =  mExpandAdapter.getGroupCount(); 
					for (int i = 0; i <count ; i++) 
					mExpandListView.collapseGroup(i); 
					mExpandAdapter.notifyDataSetChanged();
					break;
				}
				case R.id.btn_next_datea:
				{
					switch(mMode){
			    		case KeySet.SearchMode.MONTH: //就是日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, 1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
			    			break;
			    		}
			    		case KeySet.SearchMode.DAY:
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, 1);
							mEndDay = DateUtil.addDate(mEndDay, 1);
			    			break;
			    		}
			    		case KeySet.SearchMode.WEEK:
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, 7);
							mEndDay = DateUtil.addDate(mEndDay, 7);
			    			break;
			    		}
					}

					getGroupData(mStartDay, mEndDay, null, null);
					int count =  mExpandAdapter.getGroupCount(); 
					for (int i = 0; i <count ; i++) 
					mExpandListView.collapseGroup(i); 
					mExpandAdapter.notifyDataSetChanged();
					break;

				}
						
			    case R.id.btn_top1a: //依日期結算
			    	{
		    			resetButton(id);			    		
			    		mGroupMode = GroupMode.TOP1;
		    			getGroupData(mStartDay, mEndDay, null, null);
		    			int count =  mExpandAdapter.getGroupCount(); 
		    			for (int i = 0; i <count ; i++) 
		    			mExpandListView.collapseGroup(i); 
		    			mExpandAdapter.notifyDataSetChanged();
		    			DBCloud.aa0_aa1_auto_qmacc(QMacc.this);
		    				
			   			break;
			    		}
			    case R.id.btn_top2a:  //依門市結算
			    		{
			    			resetButton(id);
			    			mGroupMode = GroupMode.TOP2;
			    			getGroupData(mStartDay, mEndDay, null, null);
			    			int count =  mExpandAdapter.getGroupCount(); 
			    			for (int i = 0; i <count ; i++) 
			    			mExpandListView.collapseGroup(i); 
			    			mExpandAdapter.notifyDataSetChanged();
			    			DBCloud.aa0_aa1_auto_qmacc(QMacc.this);
			    				
			    				break;
			    			}
			    case R.id.btn_top3a: //依收支明細統計
			    		{
			    			resetButton(id);
			    			mGroupMode = GroupMode.TOP3;
			    			getGroupData(mStartDay, mEndDay, null, null);
			    			int count =  mExpandAdapter.getGroupCount(); 
			    			for (int i = 0; i <count ; i++) 
			    			mExpandListView.collapseGroup(i); 
			    			mExpandAdapter.notifyDataSetChanged();
			    			DBCloud.aa0_aa1_auto_qmacc(QMacc.this);
			    				
			    				break;
			    		}
			    case R.id.btn_top4a: //依門市結算統計
			    		{
			    			resetButton(id);
			    			mGroupMode = GroupMode.TOP4;
			    			getGroupData(mStartDay, mEndDay, null, null);
			    			int count =  mExpandAdapter.getGroupCount(); 
			    			for (int i = 0; i <count ; i++) 
			    			mExpandListView.collapseGroup(i); 
			    			mExpandAdapter.notifyDataSetChanged();
			    			DBCloud.aa0_aa1_auto_qmacc(QMacc.this);
			    			
			    			break;
			    		}
			    case R.id.btn_top5a: //依門市收支統計
	    		{
	    			resetButton(id);
	    			mGroupMode = GroupMode.TOP5;
	    			getGroupData(mStartDay, mEndDay, null, null);
	    			int count =  mExpandAdapter.getGroupCount(); 
	    			for (int i = 0; i <count ; i++) 
	    			mExpandListView.collapseGroup(i); 
	    			mExpandAdapter.notifyDataSetChanged();
	    			DBCloud.aa0_aa1_auto_qmacc(QMacc.this);
	    			
	    			break;
	    		}
			}
			setCondition();
		}
	}
	
	private void resetButton(int id){
		((Button)findViewById(R.id.btn_top1a)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_top2a)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_top3a)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_top4a)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_top5a)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_yellow);
	}
			
	// 搜尋日期 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;
	}
    
	private void askPSWD(String TitleS){
		if (PSWD==0) goAction();
		else{
			String pass = Utilis.getStringSet(QMacc.this, PrefKey.PASSWORD, "");
			if (pass.length()>=3){
				LayoutInflater factory = LayoutInflater.from(QMacc.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("櫃員編號:");
				    
				  new AlertDialog.Builder(QMacc.this).setTitle(TitleS).setMessage("請輸入密碼及櫃員編號").setView(v1).setPositiveButton("OK", new DialogInterface.OnClickListener() {
		              public void onClick(DialogInterface dialog, int which) {
		          		String pass = Utilis.getStringSet(QMacc.this, PrefKey.PASSWORD, "").substring(0,3);//需要正確前3碼
		            	  if (edtReg.getText().toString().equalsIgnoreCase(pass) && edtWho.getText().toString().length()>0){
		            		  goAction();
		            	  }              
		              }
				  }).setCancelable(false).show();
			}
		}
	}
	
	private void goAction(){
		String mKey[]=dataH.strKey.split("/");
		String mKey1[]=dataH.strTopLeft.split("/");
		if (delORmodi==1){//Edit_
			Intent intent = new Intent();
			intent.putExtra("FORMDATE",mKey1[0]);
			intent.putExtra("FORMNO",mKey[0]);
			intent.putExtra("DEPTNO",mKey1[1]);
			intent.putExtra("DEPTNAME",mKey1[2]);
			intent.putExtra("CTIME",mKey[1]);
			intent.putExtra("PART",nPart);
			intent.putExtra("ADDEDIT",EMode.EDIT);
			intent.putExtra("MODE",0);//0結算.1支出
	
			intent.setClass(QMacc.this, AMacc.class);
			startActivityForResult(intent, RESULT_AMACC);
		}else{//刪除
			SQLiteDatabase db = Utilis.getDB(QMacc.this);
			//條件 FORMDATE DEPTNO 
			if (of_line==1){//雲端版
	    		String[] args = {mKey1[1],mKey1[0]};
	    		ContentValues value = new ContentValues();
		    	value.put("TR", "Y2");
	    		db.update(TbName.QMACC, value,
					"DEPTNO=? and FORMDATE=? ", args);
				DBCloud.aa1_aa0_update_qmacc(QMacc.this);
	    		
			}else{
				String SQL="delete from qmacc where FORMDATE='"+mKey1[0]+"' and DEPTNO='"+mKey1[1]+"'";
				db.execSQL(SQL);
			}
			db.close();
      	     Toast.makeText(QMacc.this,mKey1[1]+"_"+mKey1[0]+"結算檔已刪除成功",Toast.LENGTH_SHORT).show();
	    	getGroupData(mStartDay, mEndDay, null, null);
			
		}
	}
	
    
	private void askPSWDi(String TitleS){
		if (PSWD==0) goActioni();
		else{
			String pass = Utilis.getStringSet(QMacc.this, PrefKey.PASSWORD, "");
			if (pass.length()>=3){
				LayoutInflater factory = LayoutInflater.from(QMacc.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("櫃員編號:");
				    
				  new AlertDialog.Builder(QMacc.this).setTitle(TitleS).setMessage("請輸入密碼及櫃員編號").setView(v1).setPositiveButton("OK", new DialogInterface.OnClickListener() {
		              public void onClick(DialogInterface dialog, int which) {
		          		String pass = Utilis.getStringSet(QMacc.this, PrefKey.PASSWORD, "").substring(0,3);//需要正確前3碼
		            	  if (edtReg.getText().toString().equalsIgnoreCase(pass) && edtWho.getText().toString().length()>0){
		            		  goActioni();
		            	  }              
		              }
				  }).setCancelable(false).show();
			}
		}
	}
	
	private void goActioni(){
		String mKey[]=datai.iKey.split("/");
		if (delORmodi==1){//Edit_
			Intent intent = new Intent();
			intent.putExtra("FORMDATE",datai.iTopLeft);
			intent.putExtra("FORMNO",datai.iTopRight);
			intent.putExtra("DEPTNO",mKey[1]);
			intent.putExtra("DEPTNAME",mKey[2]);
			intent.putExtra("CTIME",datai.iDmiddle);
			intent.putExtra("PART",nPart);
			intent.putExtra("ADDEDIT",EMode.EDIT);
			intent.putExtra("MODE",1);//0結算.1支出
	
			intent.setClass(QMacc.this, AMacc.class);
			startActivityForResult(intent, RESULT_AMACC);
		}else{//刪除
			SQLiteDatabase db = Utilis.getDB(QMacc.this);
    		ContentValues value = new ContentValues();
			String SQL="delete from qmacc where FORMDATE='"+datai.iTopLeft+"' and DEPTNO='"+mKey[1]+"' and CTIME='"+datai.iDmiddle+"' and QNOM<>'0000' ";
			//條件 FORMDATE DEPTNO 
			if (of_line==1){//雲端版
	    		String[] args = {mKey[1],datai.iTopLeft,datai.iDmiddle};
		    	value.put("TR", "Y2");
	    		db.update(TbName.QMACC, value,
					"DEPTNO=? and FORMDATE=? and CTIME=? and QNOM<>'0000' ", args);
	    		
			}else{
				db.execSQL(SQL);
			}
     	     Toast.makeText(QMacc.this,datai.iTopLeft+"_"+mKey[1]+"結算檔已刪除成功",Toast.LENGTH_SHORT).show();
	    	getGroupData(mStartDay, mEndDay, null, null);

			//還要重新運算 結算表(收入支出)欄位
			double mINTO=0;
			double mOUT=0;
			SQL="select sum(MINTO),sum(MOUT) from "+TbName.QMACC+" where FORMDATE='"+datai.iTopLeft+"' and DEPTNO='"+mKey[1]+"' and QNOM<>'0000' and TR<>'Y2'";
			Cursor cs=db.rawQuery(SQL,null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				mINTO=cs.getDouble(0);
				mOUT=cs.getDouble(1);
			}
			cs.close();
			
    		String[] args = {mKey[1],datai.iTopLeft};
    		value.clear();
	    	value.put("TR", "0");
	    	value.put("MINTO", (mINTO-mOUT));
    		db.update(TbName.QMACC, value,
				"DEPTNO=? and FORMDATE=? and QNOM='0000' ", args);
			
			db.close();
	    	getGroupData(mStartDay, mEndDay, null, null);
			
			if (of_line==1) DBCloud.aa1_aa0_update_qmacc(QMacc.this);
		}
	}
	

	
	private void chkMode(){

        switch(mMode){ //剛進入主程式的狀態,初始的模式
        
	    	case KeySet.SearchMode.DAY:
	    	{
	    		mStartDay = DateUtil.getCurrentDate();
	    		mEndDay = mStartDay;
	    		
		    	getGroupData(mStartDay, mEndDay, null, null);
		    	
	    		((Button)findViewById(R.id.btn_next_datea)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_datea)).setText("下一日");
	    		((Button)findViewById(R.id.btn_prev_datea)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_datea)).setText("上一日");
	    		setTitle(getString(R.string.app_name)+":[每日]"+mode_E[mGroupMode]);
	    		break;
	    	}
	    	case KeySet.SearchMode.WEEK:
	    	{
	    		String day = Utilis.getWeekDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
//@@				mGroupMode = GroupMode.TOP2;
	    		
		    	getGroupData(mStartDay, mEndDay, null, null);
		    	
	    		((Button)findViewById(R.id.btn_next_datea)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_datea)).setText("下一週");
	    		((Button)findViewById(R.id.btn_prev_datea)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_datea)).setText("上一週");
	    		setTitle(getString(R.string.app_name)+":[每週]"+mode_E[mGroupMode]);
	    		break;
	    	}
	    	case KeySet.SearchMode.MONTH:
	    	{
	    		String day = Utilis.getMonthDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
	    		
		    	getGroupData(mStartDay, mEndDay, null, null);
		    	
	    		((Button)findViewById(R.id.btn_next_datea)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_datea)).setText("下個月");
	    		((Button)findViewById(R.id.btn_prev_datea)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_datea)).setText("上個月");
	    		
	    		setTitle(getString(R.string.app_name)+":[每月]"+mode_E[mGroupMode]);
	    		break;
	    	}
	    	case KeySet.SearchMode.SEASON:  //自定日期範圍
	    	{
	    		new AlertDialog.Builder(QMacc.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;
//		            	mTextDuration.setText(getString(R.string.str_duration) + " : " + mStartDay + "~" + mEndDay);
		            	mTextDuration.setText( mStartDay + "~" + mEndDay);
		            	
		            	getGroupData(mStartDay, mEndDay, null, null);
		            	
		            	setTitle(getString(R.string.app_name)+":[日期範圍]"+mode_E[mGroupMode]);
		            	
		            }
		          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            }
		          }).show();
	    		break;
	    	}
        }
        
		int count =  mExpandAdapter.getGroupCount(); 
		for (int i = 0; i <count ; i++) 
		mExpandListView.collapseGroup(i); 
        mExpandAdapter.notifyDataSetChanged();        
        setCondition();
        
    }

	class ExpandItemAdapter extends BaseExpandableListAdapter{
		private Context context;

		LinkedList<GroupData> groups = new LinkedList<GroupData>();
		LinkedList<List<PxData>> childs = new LinkedList<List<PxData>>();
		@SuppressWarnings("unused")
		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 textTopLeftI;
			TextView textTopRightI;
			
			TextView textMleftI;
			TextView textMrightI;
			
			TextView textDleftI;
			TextView textDmiddleI;
			TextView textDrightI;
			TextView textPsI;
		}
		
		/* class GroupViewHolder */
		private class GroupViewHolder {
			TextView textTopLeft;
			TextView textTopRight;
			
			TextView textMleft;
			TextView textMright;
			
			TextView textDleft;
			TextView textDmiddle;
			TextView textDright;
			TextView textPs;
		}

		//獲取二級清單的View物件
		@SuppressWarnings("unused")
		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_posi, null);
				holder = new ViewHolder();
				holder.imageItem = (ImageView)convertView.findViewById(R.id.img_ppic);
				holder.textTopLeftI = (TextView) convertView.findViewById(R.id.text_toplefti);
				holder.textTopRightI = (TextView) convertView.findViewById(R.id.text_toprighti);
				
				holder.textMleftI = (TextView) convertView.findViewById(R.id.text_mlefti);
				holder.textMrightI = (TextView) convertView.findViewById(R.id.text_mrighti);
				
				holder.textDleftI = (TextView) convertView.findViewById(R.id.text_dlefti);
				holder.textDmiddleI = (TextView) convertView.findViewById(R.id.text_dmiddlei);
				holder.textDrightI = (TextView) convertView.findViewById(R.id.text_drighti);
				holder.textPsI = (TextView) convertView.findViewById(R.id.text_psi);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
				try{
					if (mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP2){
						if(data.iPic != null && data.iPic.length() > 0 && data.iPic != "drawable.icon")
							holder.imageItem.setImageDrawable(Utilis.getResourceImage(QMacc.this, data.iPic));
						else
							holder.imageItem.setImageResource(R.drawable.add_o);
					}else{
						holder.imageItem.setImageResource(R.drawable.m1);
					}
						
				}catch(Exception e){
					e.printStackTrace();
				}
			holder.textTopLeftI.setText(data.iTopLeft);
			holder.textTopRightI.setText(data.iTopRight);
			
			holder.textMleftI.setText(data.iMleft);
			holder.textMrightI.setText(data.iMright);
			
			holder.textDleftI.setText(data.iDleft);
			holder.textDmiddleI.setText(data.iDmiddle);
			holder.textDrightI.setText(data.iDright);
			holder.textPsI.setText(data.iPs);
			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_groupi, null);
				holder = new GroupViewHolder();
				//id/text_ttime
				holder.textTopLeft = (TextView) convertView.findViewById(R.id.topleft);
				holder.textTopRight = (TextView) convertView.findViewById(R.id.topright);
				holder.textMleft = (TextView) convertView.findViewById(R.id.mleft);
				holder.textMright = (TextView) convertView.findViewById(R.id.mright);
				holder.textDleft = (TextView) convertView.findViewById(R.id.dleft);
				holder.textDmiddle = (TextView)convertView.findViewById(R.id.dmiddle);
				holder.textDright = (TextView)convertView.findViewById(R.id.dright);
				holder.textPs = (TextView) convertView.findViewById(R.id.text_ps);
				convertView.setTag(holder);
				
			} else {
				holder = (GroupViewHolder) convertView.getTag();
			}
			holder.textTopLeft.setText(data.strTopLeft);
			holder.textTopRight.setText(data.strTopRight);
			holder.textMleft.setText(data.strMleft);
			holder.textMright.setText(data.strMright);
			holder.textDleft.setText(data.strDleft);
			holder.textDmiddle.setText(data.strDmiddle);
			holder.textDright.setText(data.strDright);
			holder.textPs.setText(data.strPs);
			return convertView;
		}

		public boolean hasStableIds()
		{
		return false;
		}

		public boolean isChildSelectable(int groupPosition, int childPosition)
		{
		return true;
		}
	}

}
