package com.cwbuyer.lib;

import java.io.File;
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.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
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.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.adapter.TableAdapter.TableCell;
import com.cwbuyer.adapter.TableAdapter.TableRow;
import com.cwbuyer.format.IDateDialog;
import com.cwbuyer.format.IDialog;
import com.pwbuyer.main.R;

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

	LinearLayout mDisplayStk;
//ACTION 預設模式 POS定義為 銷貨單;預購單;暫存單;單頭+單身	
	
	private final int RESULT_GALLERY=6666; 		//GALLERY
	private LinkedList<GroupData> mGroupList = new LinkedList<GroupData>();	
	private LinkedList<GroupData> mGroupList1 = new LinkedList<GroupData>();	
	
	int mGroupMode = GroupMode.TOP3;  //預設初始到新品 
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);	
	String dfPic=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/04.jpg";
	private String[] deptStr =Utilis.getIni(this,"SYS", "DEPT",9).split("!&!");
	private String[] importStr =Utilis.getIni(this,"SYS", "IMPORT",9).split("!&!");
	
	int mCloud=Utilis.toInt(importStr[2]);
	String clouds="http://"+importStr[0]+File.separator+importStr[1]+File.separator;
	String uriAPI1=clouds+"qrep06_1.php";
	String mDept=deptStr[5];//預設為 T6
	String aDept=deptStr[0];//預設為 T1
	String bgDate="2016/05/31";
	String enDate="2016/11/31";
	int mYear=2016;
	int mMonth=12;
	int mDay=31;
	int floor=0;//0.第一二層 1.第三四層
	//會因為總倉在單點 可以選擇門市 否則無法異動 aDept
	public ProgressDialog myDialog = null;
	protected static final int REFRESH_DATA = 0x00000001;
	DecimalFormat df = new DecimalFormat();
	//String style = "#,##0";
	String style = ",###";
	
	/** State :  true 正式 , false 樣品*/
	String sepa="\r\n";
	String sepaA4=";";
	StringBuffer sPrintB = new StringBuffer();
	StringBuffer sPrintA4=new StringBuffer(); 

/*	
//期初進入系統時 檢查臨時TABLE 是否存在
//如果存在 詢問 [更新][查詢]
//[更新]時,重新建立最新資訊
 */
	
	int Loca=0;
	int Lgap=230;
	String mTitleP="";
	int PSWD=1;
	int aPart=0;
	String GoodChg="A.GOODSNO";
	String ColorChg="A.COLORS";
	String SizeChg="A.SIZES";
	String ConChg="主貨";
	String SQLADD="(A.QKIND ='30' OR A.QKIND ='31' OR A.QKIND ='40' OR A.QKIND ='41') and A.ISCONFIRM='Y'";
	int deptN=1;
	String [] DepNo;
	String [] DepNa;
	String [] DepPic;
	String DepIndex="";
	int FactN=1;
	String [] FactNo;
	String [] FactNa;
	String [] FactPic;
	String FactIndex="";
	int ColNoSizN=0;
	String [][] ColNoSiz;	
   	int [][] Otott;

	int CountX=7;//指向sql_A的第一欄位為 統計的主題
	String CntmSQL="sum(UNIT10),sum(UNIT20),sum(UNIT21),sum(UNIT34),sum(ACOST),sum(SUBPRICE),sum(DEPTNAME), "; //
								//廠商進貨,門市出貨,門市轉貨,銷貨件數,銷貨成本,銷貨金額,進出貨成本
   	String [] sql_A={ 
   			"",
   			" GOODSNO,GOODSNAME,DEPTNO,PIC from zansly_stk ",
   			" P3,P3,DEPTNO from zansly_stk ",
   			" DEPTNO,DEPTNO,DEPTNO from zansly_stk ",
   			" SUPPLY,SUPPLY,DEPTNO from zansly_stk ",
   			" GOODSTYPE,GOODSTYPE,DEPTNO from zansly_stk",
   			" P5,P5,DEPTNO from zansly_stk",
   			" COUNTRY,COUNTRY,DEPTNO from zansly_stk "
   			};
	String[] sql_D={ "DEPTNO","GOODSNO","P3","DEPTNO","SUPPLY","GOODSTYPE","P5","COUNTRY"};	
	String[] mode_E={ "","依貨品排行", "依批價排行","依門市排行","依廠商排行","依類別排行","依售價排行","依國別排行"};
	String[][] sql_C={{"",""},{"",""},{ "DEPTNO","P3"},{ "DEPTNO","GOODSNO"},{ "DEPTNO","SUPPLY"},{ "DEPTNO","GOODSTYPE"},{ "DEPTNO","P5"},{ "DEPTNO","COUNTRY"}};	
	
	
   	String [] sql_B={ 
   			"",
   			" DEPTNO,GOODSNOS,GOODSNAME,PIC from zansly_stk ",
   			" DEPTNO,P3,P3  from zansly_stk ",
   			" DEPTNO,GOODSNO,GOODSNAME,PIC from zansly_stk ",
   			" DEPTNO,SUPPLY,SUPPLY from zansly_stk ",
   			" DEPTNO,GOODSTYPE,GOODSTYPE from zansly_stk",
   			" DEPTNO,P5,P5 from zansly_stk",
   			" DEPTNO,COUNTRY,COUNTRY from zansly_stk "
   			};
	
	
   	String [] Season_Array = {"春","夏","秋","冬","四季"};
	String mKind=null; //單別 102030405060
	double sSort=0; //0依金額 1.依件數 2.依毛利
	
	int nKind=30;
	DatePicker dp1;
	DatePicker dp2;
	
   	String btns=null;
   	String[] bttns;

   	int TT10=0;  	//總進貨量
   	double TM10=0; 	//總進貨額
   	int TT30=0;	//總銷貨量
   	double TM30=0;	//總銷貨額
   	int TS30=0;	//總銷貨額
   	int StkTT=0;		//總存貨量
   	double StkMM=0;	//總存貨額
   	double Profits=0; //總毛利
   	
   	int T10=0;  	//本進貨量
   	double M10=0; 	//本進貨額
   	int T30=0;		//本銷貨量
   	double M30=0;	//本銷貨額
   	int S30=0;	//本銷貨額
   	double Profit=0; 	//本銷毛利
   	int StkT=0;		//存貨量
   	double StkM=0;	//存貨額
	
	class GroupData{ //第一層版面
		public double Sort=0;
		public String strLeftTop; 		// 左上
		public String strPic; 				// 左中
		public String strLeftM; 			// 左中
		public String strRightTop; 	// 右上
		public String strRightM; 		// 右中
		public String strRightD;  		//右下
		public String strLeftD;  			// 左下		
		public String SEARCH;  		// KEY(第二層)
	}
	
	class PxData{ //第二層版面
		public double Sort;
		public String iPic;  					//左圖
		public String iTopLeft;				//上左 
		public String iTopRight; 				//上右
		public String iMidLeft; 				//中左
		public String iMidRight;			//中右
		public String iDnLeft;			//下左
		public String iDnMid;			//下中
		public String iDnRight;		//下右
		public String iFormdate;		//KEY(第三層)
		
	}
	
//	ListView mListView = null;
	ExpandableListView mExpandListView = null;
	ExpandableListView mExpandListView1 = null;
	
//For  Table
	int Wheight;
	int Wwidth;
	int tableHeight=30;
	int tabless=6;

	private LinearLayout lTableView = null;
	private LinearLayout mLayoutRoot = null;
	private ArrayList<String> mArrayColorNumber = new ArrayList<String>();
	private ArrayList<String> mArrayColorName = new ArrayList<String>();
	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 datax =null;	
//@@日後需補充用ITEM檢測HEAD是否漏掉的清單,並自動修補	
	private interface GroupMode{//EVERYDAY/WEEK/MONTH 以FORMDATE
		int TOP1 = 1;	//依貨號
		int TOP2 = 2;  	//依批價
		int TOP3 = 3; 	//依門市
		int TOP4 = 4; 	//依廠商
		int TOP5 = 5; 	//依類別
		int TOP6 = 6; 	//依售價
		int TOP7 = 7; 	//依國別
		int TOP8 = 8; 	//依售價
		
	}
	
	@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_GALLERY:
			{
				
			}
		}	
    }

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qrep07);
        
		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Wwidth = dm.widthPixels;
        Wheight = dm.heightPixels;
        lTableView = (LinearLayout)findViewById(R.id.tableview);
		
		tableHeight=(int) (Wheight/24);
		if (Wwidth<=800) tabless=(int) (Wwidth/100)+2; else  tabless=(int) (Wwidth/140)+1;
		
		df.applyPattern(style);
		
        mTextDuration = (TextView)findViewById(R.id.text_stk_duration);
        //@@應增加營業時間的判斷而視為當日或前一天
        
        mGroupMode= getIntent().getIntExtra("search_group", GroupMode.TOP3);	

        ((Button)findViewById(R.id.btn_stk_exit)).setOnClickListener(new MainClick());		//離開
        
        ((Button)findViewById(R.id.btn_stk_top1)).setOnClickListener(new MainClick()); //依會員
        ((Button)findViewById(R.id.btn_stk_top2)).setOnClickListener(new MainClick()); //依櫃員        
        ((Button)findViewById(R.id.btn_stk_top3)).setOnClickListener(new MainClick()); //依門市
        ((Button)findViewById(R.id.btn_stk_top4)).setOnClickListener(new MainClick()); //依廠商
        ((Button)findViewById(R.id.btn_stk_top5)).setOnClickListener(new MainClick()); //依類別
        ((Button)findViewById(R.id.btn_stk_top6)).setOnClickListener(new MainClick()); //依顏色
        ((Button)findViewById(R.id.btn_stk_top7)).setOnClickListener(new MainClick()); //依國別

        ((Button)findViewById(R.id.btn_stk_prev_date)).setOnClickListener(new MainClick());//上一
        ((Button)findViewById(R.id.btn_stk_next_date)).setOnClickListener(new MainClick());//下一
        
        ((Button)findViewById(R.id.btn_stk_btn0)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_stk_btn1)).setOnClickListener(new MainClick());        
        ((Button)findViewById(R.id.btn_stk_btn2)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_stk_btn3)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_stk_btn4)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_stk_btn5)).setOnClickListener(new MainClick());
        
        //預設為四個月前起算
        mTextDuration.setOnClickListener(new MainClick());
		bgDate=Utilis.getIni(QRep_07.this, "INIH", "QHIS",7);
		enDate=Utilis.getIni(QRep_07.this, "INIH", "QHIS",8);
        mTextDuration.setText(bgDate+" ~ "+enDate);

    	mDisplayStk = (LinearLayout)findViewById(R.id.layout_stk_bottom);
    	mDisplayStk.setVisibility(View.GONE);
    	
    	mLayoutRoot = (LinearLayout)findViewById(R.id.root);
        mExpandListView = (ExpandableListView)findViewById(R.id.list_item_stk_expand);    	
        mExpandAdapter = new ExpandItemAdapter(this);
        mExpandListView.setAdapter(mExpandAdapter);
        mExpandListView.setOnChildClickListener(mChildClcik);
        mExpandListView.setOnItemLongClickListener(mLongClickListener);
        
        mExpandListView1 = (ExpandableListView)findViewById(R.id.list_item_stk_expand1);    	
        mExpandAdapter1 = new ExpandItemAdapter(this);
        mExpandListView1.setOnChildClickListener(mChildClcik);
        mExpandListView1.setAdapter(mExpandAdapter1);
        
        if (deptStr[4].equalsIgnoreCase("0")){  //密碼OK 或不用密碼
        	((LinearLayout)findViewById(R.id.layout_stk_top)).setVisibility(View.VISIBLE);
        	PSWD=0;
        }else{
        	((LinearLayout)findViewById(R.id.layout_stk_top)).setVisibility(View.GONE);
        }
        //原先就是執行一遍 因為不會中途改變模式
        //現在是可以切換
        //只要一切換,都會從最近日期範圍貨最近一批最近一季起算
		//應追加 上一批 的程式
        if (!deptStr[0].equalsIgnoreCase(deptStr[5])) aPart=1;  //門市版
        
        SQLiteDatabase db = Utilis.getDB(this);		
		Cursor cs =db.rawQuery("select CUSTNO,CUSTNAME,PIC from qcust where TR='20' and  CUSTNO <>'"+deptStr[5]+"' order by CUSTNO",null);
		if (cs.getCount()>0){
			deptN=cs.getCount()+1;
			DepNo=new String[deptN];
			DepNa=new String[deptN];
			DepPic=new String[deptN];
			DepIndex="_"+deptStr[5]+"_000;";
			cs.moveToFirst();
			for (int i=0;i<cs.getCount();i++){
				DepNo[i+1]=cs.getString(0);
				DepNa[i+1]=cs.getString(1);
				DepPic[i+1]=cs.getString(2);
				String FF=("000"+(i+1));
				DepIndex+="_"+cs.getString(0)+"_"+FF.substring(FF.length()-3)+";";
				cs.moveToNext();
			}
			
		}else{
			deptN=2;
			DepNo=new String[deptN];
			DepNa=new String[deptN];
			DepPic=new String[deptN];
			DepNo[1]=deptStr[5];
			DepNa[1]=deptStr[6];
			DepPic[1]=dfPic;
		}
		DepNo[0]=deptStr[5];
		DepNa[0]=deptStr[6];
		DepPic[0]=dfPic;

		Cursor csf =db.rawQuery("select FACTNO,FACTNAME,PIC from qfact order by FACTNO",null);
		if (csf.getCount()>0){
			FactN=csf.getCount()+1;
			FactNo=new String[FactN];
			FactNa=new String[FactN];
			FactPic=new String[FactN];
			FactIndex="_K001_000;";
			csf.moveToFirst();
			for (int i=0;i<csf.getCount();i++){
				FactNo[i+1]=csf.getString(0);
				FactNa[i+1]=csf.getString(1);
				FactPic[i+1]=csf.getString(2);
				String FF=("000"+(i+1));
				FactIndex+="_"+csf.getString(0)+"_"+FF.substring(FF.length()-3)+";";
				csf.moveToNext();
			}
		}else{
			FactN=1;
			FactNo=new String[FactN];
			FactNa=new String[FactN];
			FactNo[0]="K001";
			FactNa[0]="K001";
		}
		
		db.close();
		cs.close();
		csf.close();
        
        switch(mGroupMode){
        case GroupMode.TOP1:
        	resetButton(R.id.btn_stk_top1);
        	break;
        case GroupMode.TOP2:
        	resetButton(R.id.btn_stk_top2);
        	break;
        case GroupMode.TOP3:
        	resetButton(R.id.btn_stk_top3);
        	break;
        case GroupMode.TOP4:
        	resetButton(R.id.btn_stk_top4);
        	break;
        case GroupMode.TOP5:
        	resetButton(R.id.btn_stk_top5);
        	break;
        case GroupMode.TOP6:
        	resetButton(R.id.btn_stk_top6);
        	break;
        case GroupMode.TOP7:
        	resetButton(R.id.btn_stk_top7);
        	break;
        	
        }
        
        //初始化
        startIniDb(this);
        
        mExpandListView.setOnScrollListener(new OnScrollListener() {
            public void onScrollStateChanged(AbsListView view,
                    int scrollState) { // TODO Auto-generated method stub
            	if(scrollState==SCROLL_STATE_FLING){
            	    }else if(scrollState==SCROLL_STATE_IDLE){
            	    }else if(scrollState==SCROLL_STATE_TOUCH_SCROLL){
                    	mDisplayStk.setVisibility(View.GONE);
            	    }            	
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
            }
        });
        
        mExpandListView1.setOnScrollListener(new OnScrollListener() {
            public void onScrollStateChanged(AbsListView view,
                    int scrollState) { // TODO Auto-generated method stub
            	if(scrollState==SCROLL_STATE_FLING){
            	    }else if(scrollState==SCROLL_STATE_IDLE){
            	    }else if(scrollState==SCROLL_STATE_TOUCH_SCROLL){
                    	mDisplayStk.setVisibility(View.GONE);
            	    }            	
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
            }
        });
        
}	
	
	public void onResume(){
		super.onResume();
		}
	
public void getGroupData(Context context,String condition, String conditionValue) {
	floor=0;
	mExpandListView1.setVisibility(View.GONE);					
	mExpandListView.setVisibility(View.VISIBLE);
	((Button)findViewById(R.id.btn_stk_exit)).setText("離開");
	if (mGroupList != null) mGroupList.clear();
	
	SQLiteDatabase db = Utilis.getDB(context);
		
	try {
				StringBuffer bufCategory = new StringBuffer();

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

				bufCategory=bufCategory.delete(0, bufCategory.toString().length());
	        		bufCategory.append("select "+CntmSQL);
	        		bufCategory.append(sql_A[mGroupMode]);
					bufCategory.append(" group by "+sql_A[mGroupMode].substring(1,sql_A[mGroupMode].indexOf(" from")));
					//if (sSort==0) bufCategory.append(" order by '"+sql_D[mGroupMode]+"',sum(UNIT34)  desc"); else bufCategory.append(" order by '"+sql_D[mGroupMode]+"',sum(UNIT34),sum(UNIT10+UNIT21-UNIT20-UNIT34)"); 
					//if (sSort==0) bufCategory.append(" order by sum(UNIT34)  desc"); else bufCategory.append(" order by sum(UNIT34),sum(UNIT10+UNIT21-UNIT20-UNIT34)"); 

				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) {
					if (cursorGroup.getCount() > 0) {
						//開出第一筆並初始化
						cursorGroup.moveToFirst();
						GroupData data= new GroupData();
						//String mDeptO=cursorGroup.getString(CountX+2);//門市代號,作為總倉或門市(不同庫存運算)
						String mMkey=cursorGroup.getString(CountX);//
						data.strLeftTop = cursorGroup.getString(CountX);
						
						//TOP3,4,5,6,7求出 名稱 圖檔
						if (mGroupMode==GroupMode.TOP1)
							data.strPic=cursorGroup.getString(CountX+3);  //圖片
						else if (mGroupMode==GroupMode.TOP3){
							data.strLeftTop = cursorGroup.getString(CountX)+"/"+DepNa[getDeptIndex("_"+cursorGroup.getString(CountX)+"_")];
							data.strPic = DepPic[getDeptIndex("_"+cursorGroup.getString(CountX)+"_")];
						}else if (mGroupMode==GroupMode.TOP4){
							data.strLeftTop = cursorGroup.getString(CountX)+"/"+FactNa[getFactIndex("_"+cursorGroup.getString(CountX)+"_")];
							data.strPic = FactPic[getFactIndex("_"+cursorGroup.getString(CountX)+"_")];
						}else data.strPic=dfPic;
						data.strLeftM=cursorGroup.getString(CountX+1); //主題二
						data.SEARCH = cursorGroup.getString(CountX);
						
						for (int i = 0; i < cursorGroup.getCount(); i++) {
							//若換了不同主題 需存入再初始化
							if (!mMkey.equalsIgnoreCase(cursorGroup.getString(CountX))){
								data.strRightTop="("+df.format(M10)+")進:"+df.format(T10);
								if(PSWD==0)
									data.strRightD="(利:"+df.format(Profit)+")銷:("+df.format(M30)+")"+df.format(T30)+"件";
								else
									data.strRightD="銷:("+df.format(M30)+")"+df.format(T30)+"件";
									
								data.strRightM="("+df.format(StkM)+")存:"+df.format(StkT);
								groups.add(data);

								//增一筆&初始化
								mMkey=cursorGroup.getString(CountX);
								data= new GroupData();
								T10=0;  	 M10=0; 	T30=0;	M30=0;
								S30=0;	 StkT=0;		StkM=0;	
								//TT10=0;  TM10=0; 	TT30=0;	TM30=0;
								//StkTT=0;		StkMM=0;
								Profit=0;
								data.strLeftTop = cursorGroup.getString(CountX);
								
								//TOP3,4,5,6,7求出 名稱 圖檔
								if (mGroupMode==GroupMode.TOP1)
									data.strPic=cursorGroup.getString(CountX+3);  //圖片
								else if (mGroupMode==GroupMode.TOP3){
									data.strLeftTop = cursorGroup.getString(CountX)+"/"+DepNa[getDeptIndex("_"+cursorGroup.getString(CountX)+"_")];
									data.strPic = DepPic[getDeptIndex("_"+cursorGroup.getString(CountX)+"_")];
								}else if (mGroupMode==GroupMode.TOP4){
									data.strLeftTop = cursorGroup.getString(CountX)+"/"+FactNa[getFactIndex("_"+cursorGroup.getString(CountX)+"_")];
									data.strPic = FactPic[getFactIndex("_"+cursorGroup.getString(CountX)+"_")];
								}else data.strPic=dfPic;
								data.strLeftM=cursorGroup.getString(CountX+1); //主題二
								data.SEARCH = cursorGroup.getString(CountX);

							}
									T30+=cursorGroup.getInt(3);//銷件
									TT30+=cursorGroup.getInt(3);//銷件
									M30+=cursorGroup.getDouble(5);//銷額
									TM30+=cursorGroup.getDouble(5);//銷額
									S30+=cursorGroup.getInt(4);//銷貨成本
									TS30+=cursorGroup.getInt(4);//總銷貨成本
									Profit+=(cursorGroup.getDouble(5)-cursorGroup.getInt(4));//銷貨毛利
									Profits+=(cursorGroup.getDouble(5)-cursorGroup.getInt(4));//總銷貨毛利
									StkM+=cursorGroup.getInt(6)-cursorGroup.getInt(4);//總倉存貨金額???
									StkMM+=cursorGroup.getInt(6)-cursorGroup.getInt(4);//總存貨金額
									//總倉存貨小計=總倉進貨-門市出貨-總倉銷貨件小計
									//門市存貨小計=門市出貨-門市銷貨件小計
									
									M10+=cursorGroup.getInt(6);//(總倉(進貨-門市出貨)成本)
									TM10+=cursorGroup.getInt(6);//總進貨成本(含門市+總倉)
									
										if (cursorGroup.getString(CountX+2).equalsIgnoreCase(deptStr[5])){
											T10+=cursorGroup.getInt(0)-cursorGroup.getInt(1);//總倉進貨件扣除出貨
											TT10+=cursorGroup.getInt(0)-cursorGroup.getInt(1);
											StkT+=cursorGroup.getInt(0)-cursorGroup.getInt(1)-cursorGroup.getInt(3);
											StkTT+=cursorGroup.getInt(0)-cursorGroup.getInt(1)-cursorGroup.getInt(3);//總存貨件數(含門市+總倉)
										}else{
											T10+=cursorGroup.getInt(2)-cursorGroup.getInt(1);//門市出轉件小計
											TT10+=cursorGroup.getInt(2)-cursorGroup.getInt(1);
											StkT+=cursorGroup.getInt(2)-cursorGroup.getInt(1)-cursorGroup.getInt(3);
											StkTT+=cursorGroup.getInt(2)-cursorGroup.getInt(1)-cursorGroup.getInt(3);//總存貨件數(含門市+總倉)
										}
								
									cursorGroup.moveToNext();
						}
						if(T10!=0 || M10!=0 || T30!=0 || M30!=0 ||	S30!=0 || StkT!=0 || 	StkM!=0){
							data.strRightTop="("+df.format(M10)+")進:"+df.format(T10);							
							if(PSWD==0)
								data.strRightD="(利:"+df.format(Profit)+")銷:("+df.format(M30)+")"+df.format(T30)+"件";
							else
								data.strRightD="銷:("+df.format(M30)+")"+df.format(T30)+"件";
							
							data.strRightM="("+df.format(StkM)+")存:"+df.format(StkT)+"件";
							groups.add(data);
						}
					}
 				}
				cursorGroup.close();
				
 				((TextView)findViewById(R.id.text_stk_t10)).setText("總進:"+df.format(TT10)+"件$: "+df.format(TM10));
 				((TextView)findViewById(R.id.text_stk_r10)).setText("總銷:"+df.format(TT30)+"件 $: "+df.format(TM30));
 				((TextView)findViewById(R.id.text_stk_t30)).setText("總利:"+df.format(Profits));
 				((TextView)findViewById(R.id.text_stk_r30)).setText("總存:"+df.format(StkTT)+"件$: "+df.format(StkMM));  //存
			if (groups.size() > 0) {  //製作第二層因為進10出20銷30櫃40 件數 金額 預購 
				StringBuffer bufList = new StringBuffer();
				for (int i = 0; i < groups.size(); i++) {
					bufList.delete(0, bufList.toString().length());
					bufList.append("select "+CntmSQL);
					bufList.append(sql_B[mGroupMode]);
					
					if (aPart==1) {
						bufList.append(" where DEPTNO ='"+deptStr[0]+"'");
						bufList.append(" and "+sql_D[mGroupMode]+"='"+groups.get(i).SEARCH+"'");						
					}else
						bufList.append(" where "+sql_D[mGroupMode]+"='"+groups.get(i).SEARCH+"'");						
					
					bufList.append(" group by "+sql_B[mGroupMode].substring(1,sql_B[mGroupMode].indexOf(" from")));
					//bufList.append(" having (sum(UNIT10)+sum(UNIT21-UNIT20)-sum(UNIT34))>0 ");
					if (sSort==0) bufList.append(" order by sum(UNIT34)  desc"); else bufCategory.append(" order by sum(UNIT34),sum(UNIT10+UNIT21-UNIT20-UNIT34)"); 
						//單機
						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++) {
									datax=new PxData();
									
									datax.iTopLeft = cursor.getString(CountX)+"/"+DepNa[getDeptIndex("_"+cursor.getString(CountX)+"_")];
									datax.iMidLeft = cursor.getString(CountX+1)+"/";
									datax.iDnLeft=cursor.getString(CountX+2);
									datax.iFormdate=cursor.getString(CountX+1);
									if (mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP3){
										datax.iPic=cursor.getString(CountX+3);
									}else if (mGroupMode==GroupMode.TOP4){
										datax.iMidLeft = cursor.getString(CountX+1)+"/"+FactNa[getFactIndex("_"+cursor.getString(CountX+1)+"_")];
									}else	datax.iPic=dfPic;
									
									T30=cursor.getInt(3);//銷件
									M30=cursor.getDouble(5);//銷額
									S30=cursor.getInt(4);//銷貨成本
									
										if (cursor.getString(CountX).equalsIgnoreCase(deptStr[5])){
											T10=cursor.getInt(0)-cursor.getInt(1);//總倉進貨件扣除出貨
											StkT=cursor.getInt(0)-cursor.getInt(1)-cursor.getInt(3);
											//總倉存貨小計=總倉進貨-門市出貨-總倉銷貨件小計
											M10=cursor.getInt(6);//(總倉(進貨-門市出貨)成本)
											StkM=M10-S30;//總倉存貨金額???
											
										}else{
											T10=cursor.getInt(2)-cursor.getInt(1);//門市出轉件小計
											StkT=cursor.getInt(2)-cursor.getInt(1)-cursor.getInt(3);
											//門市存貨小計=門市出貨-門市銷貨件小計
											M10=cursor.getInt(6);//各門市出轉總額
											StkM=M10-S30;//門市存貨金額
										}

									if (StkT>0){	
										datax.iTopRight ="("+df.format(M10)+")進:"+ df.format(T10)+"件";
										if (PSWD==0)
											datax.iMidRight ="(利:"+df.format(M30-S30)+")銷:("+df.format(M30)+")"+ df.format(T30)+"件:";
										else
											datax.iMidRight ="銷:("+df.format(M30)+")"+ df.format(T30)+"件:";
											
										datax.iDnRight ="("+df.format(StkM)+")存:"+ df.format(StkT)+"件:";
					 					listData.add(datax);
									}
				 				cursor.moveToNext();
							}
						}	
						if (listData.isEmpty()){
							datax=new PxData();
							datax.iFormdate="none";
							datax.iTopLeft = "已無存貨";
							datax.iMidLeft ="";
							datax.iPic=dfPic;
							datax.iTopRight ="進:";
							datax.iMidRight ="銷:";
							datax.iDnRight ="存:";
		 					listData.add(datax);
						}
						childs.add(listData);
					}
					cursor.close();	
				}
			}
				db.close();
				mExpandAdapter.setData(groups, childs);
				mExpandAdapter.notifyDataSetChanged();

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

public void getGroupData1(Context context,String field1, String field2) {
	//通常是 帶入 兩組條件
	//門市 + TOP
	if (mGroupList1 != null) mGroupList1.clear();
	
	SQLiteDatabase db = Utilis.getDB(context);
		
	try {
				StringBuffer bufCategory = new StringBuffer();
				//這是由第二層條件 帶來一個範圍而取得
				//通常是 因著TOP1-TOP6 內容不一樣
				//TOP1 TOP3 不再進一步分析
				//例如 類別+門市 需顯示所有相符的商品內容
				T10=0;  	 M10=0; 	T30=0;	M30=0;
				TT10=0;  TM10=0; 	TT30=0;	TM30=0;
				S30=0;	TS30=0;	 StkT=0;		StkM=0;	StkTT=0;		StkMM=0;
				Profit=0; Profits=0; 


				bufCategory=bufCategory.delete(0, bufCategory.toString().length());
	        		bufCategory.append("select "+CntmSQL);
	        		bufCategory.append(" GOODSNO,GOODSNAME,PIC,max(COLORS),max(SIZES) from zansly_stk ");
	        		bufCategory.append(" where "+sql_C[mGroupMode][0]+"='"+field1+"' and "+sql_C[mGroupMode][1]+"='"+field2+"'");
					bufCategory.append(" group by GOODSNO,GOODSNAME,PIC ");
					//bufCategory.append(" having (sum(UNIT10-UNIT34)>0) ");
					if (sSort==0) bufCategory.append(" order by GOODSNO,sum(UNIT34)  desc"); else bufCategory.append(" order by GOODSNO,sum(UNIT34),sum(UNIT10+UNIT21-UNIT20-UNIT34)"); 

				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) {
					if (cursorGroup.getCount() > 0) {
						cursorGroup.moveToFirst();
						for (int i = 0; i < cursorGroup.getCount(); i++) {
							GroupData data = new GroupData();
							data.SEARCH = cursorGroup.getString(CountX);
							T30=cursorGroup.getInt(3);//銷件
							M30=cursorGroup.getDouble(5);//銷額
							S30=cursorGroup.getInt(4);//銷貨成本
							StkM=cursorGroup.getInt(6)-cursorGroup.getInt(4);//總倉存貨金額???
							//總倉存貨小計=總倉進貨-門市出貨-總倉銷貨件小計
							//門市存貨小計=門市出貨-門市銷貨件小計
							M10=cursorGroup.getInt(6);//(總倉(進貨-門市出貨)成本)
							TM10=cursorGroup.getInt(6);//總進貨成本(含門市+總倉)
							
							if (field1.equalsIgnoreCase(deptStr[5])){
								T10=cursorGroup.getInt(0)-cursorGroup.getInt(1);//總倉進貨件扣除出貨
								StkT=cursorGroup.getInt(0)-cursorGroup.getInt(1)-cursorGroup.getInt(3);
							}else{
								T10=cursorGroup.getInt(2)-cursorGroup.getInt(1);//門市出轉件小計
								StkT=cursorGroup.getInt(2)-cursorGroup.getInt(1)-cursorGroup.getInt(3);
							}
							
							if (StkT>0){
								data.strRightTop="("+df.format(M10)+")進:"+df.format(T10);							
								data.strRightD="("+df.format(M30)+")銷:"+df.format(T30);							
								data.strRightM="("+df.format(StkM)+")存:"+df.format(StkT);
								
								data.strLeftTop = cursorGroup.getString(CountX)+"/"+cursorGroup.getString(CountX+1);
								data.strPic=cursorGroup.getString(CountX+2);  //圖片
								data.strLeftM=cursorGroup.getString(CountX+3); //主題二
								data.strLeftD=cursorGroup.getString(CountX+4); //主題三
			 					groups.add(data);
							}
							cursorGroup.moveToNext();
						}	
 					}	
 				}
				cursorGroup.close();
				
			if (groups.size() > 0) {  //製作第二層因為進10出20銷30櫃40 件數 金額 預購 
				StringBuffer bufList = new StringBuffer();
				for (int i = 0; i < groups.size(); i++) {
					bufList.delete(0, bufList.toString().length());
					bufList.append("select "+CntmSQL);
					bufList.append(" GOODSNOS,GOODSNAME,PIC,COLOR,SIZE from zansly_stk ");
					bufList.append(" where "+sql_C[mGroupMode][0]+"='"+field1+"' and "+sql_C[mGroupMode][1]+"='"+field2+"' and GOODSNO='"+groups.get(i).SEARCH+"'");
					bufList.append(" group by GOODSNOS,GOODSNAME,PIC,COLOR,SIZE ");
					if (sSort==0) bufList.append(" order by sum(UNIT34)  desc"); else bufCategory.append(" order by sum(UNIT34),sum(UNIT10+UNIT21-UNIT20-UNIT34) "); 

						//單機
						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++) {
									datax=new PxData();
									
									datax.iTopLeft = cursor.getString(CountX);
									datax.iMidLeft = cursor.getString(CountX+1);
									datax.iFormdate=cursor.getString(CountX);
									datax.iDnLeft = cursor.getString(CountX+3)+"/"+cursor.getString(CountX+4);
									datax.iPic=cursor.getString(CountX+2);

									T30=cursor.getInt(3);//銷件
									M30=cursor.getDouble(5);//銷額
									S30=cursor.getInt(4);//銷貨成本
									
										if (field1.equalsIgnoreCase(deptStr[5])){
											T10=cursor.getInt(0)-cursor.getInt(1);//總倉進貨件扣除出貨
											StkT=cursor.getInt(0)-cursor.getInt(1)-cursor.getInt(3);
											//總倉存貨小計=總倉進貨-門市出貨-總倉銷貨件小計
											M10=cursor.getInt(6);//(總倉(進貨-門市出貨)成本)
											StkM=M10-S30;//總倉存貨金額???
											
										}else{
											T10=cursor.getInt(2)-cursor.getInt(1);//門市出轉件小計
											StkT=cursor.getInt(2)-cursor.getInt(1)-cursor.getInt(3);
											//門市存貨小計=門市出貨-門市銷貨件小計
											M10=cursor.getInt(6);//各門市出轉總額
											StkM=M10-S30;//門市存貨金額
										}
										if (StkT>0){	
										datax.iTopRight ="("+df.format(M10)+")進:"+ df.format(T10)+"件";
										datax.iMidRight ="("+df.format(M30)+")銷:"+ df.format(T30)+"件:";
										datax.iDnRight ="("+df.format(StkM)+")存:"+ df.format(StkT)+"件:";
					 					listData.add(datax);
										}
				 				cursor.moveToNext();
							}
							if (listData.isEmpty()){
								datax=new PxData();
								datax.iFormdate="none";
								datax.iTopLeft = "已無存貨";
								datax.iMidLeft ="";
								datax.iPic=dfPic;
								datax.iTopRight ="進:";
								datax.iMidRight ="銷:";
								datax.iDnRight ="存:";
			 					listData.add(datax);
							}
						}	
						childs.add(listData);

					}
					cursor.close();	
				}
			}
				db.close();
				mExpandAdapter1.setData(groups, childs);
				mExpandAdapter1.notifyDataSetChanged();

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


	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 = mExpandListView.getPackedPositionChild(id);
				final String compStr[]=Utilis.getIni(QRep_07.this,"USER","COMPANY",9).split("!&!");

				sPrintB.delete(0, sPrintB.toString().length());
				Loca=0;
				sPrintB.append("^QXXXX,0,0"+sepa);
				if (Utilis.toInt(compStr[8])<3){												
					sPrintB.append("^W56"+sepa);
				}else{
					sPrintB.append("^W75"+sepa);
					Lgap=280;
				}
				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,30,"+Loca+",1,2,0,0,"+compStr[0]+"  銷售分析"+sepa);
				Loca=Loca+50;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,"+getTitleP(mGroupMode)+" "+sepa);
				Loca=Loca+20;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
				Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
                
                if (mExpandListView.getPackedPositionType(id) == mExpandListView.PACKED_POSITION_TYPE_GROUP) {
        			String [] Lmenu={"印製總表(不印明細)","印製指定資料(含所有明細)","印製總表(不印明細)A4","印製指定資料(含所有明細)A4","返回"};
	    			DialogUtilis.showDialog(QRep_07.this, "請選擇以下功能", -1,
	    					Lmenu, new IDialog() {
	    						@Override
	    						public void onDialogFinish(int pos, String choice) {
	    							switch (pos) {
		    								case 0: //印製總表(不印明細)
		    								{//只印 總計 及 總表
												Loca=Loca+40;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,"+"總進: "+df.format(TT10)+"件"+sepa);
												sPrintB.append("AZ,"+Lgap+","+Loca+",1,2,0,0,"+"$ "+df.format(TM10)+sepa);
												Loca=Loca+40;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,"+"總銷: "+df.format(TT30)+"件"+sepa);
												sPrintB.append("AZ,"+Lgap+","+Loca+",1,2,0,0,"+"$ "+df.format(TM30)+sepa);
												Loca=Loca+50;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,"+"總毛利:$ "+df.format(Profits)+sepa);
												sPrintB.append("AZ,"+Lgap+","+Loca+",1,2,0,0,"+"總存 "+df.format(StkTT)+"件/$ "+df.format(StkMM)+sepa);
												Loca=Loca+20;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
												Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
												Loca=Loca+10;
												int count =  mExpandAdapter.getGroupCount(); //得知總筆數
												for (int g=0;g<count;g++){
													GroupData datag =mExpandAdapter.groups.get(g);
													Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+datag.strLeftTop+sepa);													
													sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datag.strRightTop+sepa);
													Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+datag.strLeftM+sepa);													
													sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datag.strRightD+sepa);
													Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+datag.strLeftD+sepa);													
													sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datag.strRightM+sepa);
													Loca=Loca+15;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
													if (Loca>2400){
														PosUtilis.startPartPrint(QRep_07.this,sPrintB,Loca );
														sPrintB.delete(0, sPrintB.toString().length());
														SystemClock.sleep(3000);
														sPrintB=PosUtilis.getPrintKind(QRep_07.this,1);
														Loca=0;
													}
													
												}
												sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
								    			Loca=Loca+80;
								    			//呼叫 開始列印 BarCodePrinter Socket
								    			PosUtilis.startPrint(QRep_07.this,sPrintB,Loca );
								    			
		    									break;
	    									}
		    								case 1: //印製指定第一層(及所有明細)
		    								{//
		    									
												int count =  mExpandAdapter.getGroupCount(); //得知總筆數
												
													GroupData datag =mExpandAdapter.groups.get(groupPosition);
													Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+datag.strLeftTop+sepa);													
													sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datag.strRightTop+sepa);
													Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+datag.strLeftM+sepa);													
													sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datag.strRightD+sepa);
													Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+datag.strLeftD+sepa);													
													sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datag.strRightM+sepa);
													Loca=Loca+15;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
													Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);

													int countC =  mExpandAdapter.getChildrenCount(groupPosition);
													
									    			for (int i = 0; i <countC ; i++){
									    				datax =mExpandAdapter.getData(groupPosition, i);
														Loca=Loca+25;  //
														sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+datax.iTopLeft+sepa);
														sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datax.iTopRight+sepa);
														Loca=Loca+25;  //
														sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+datax.iMidLeft+sepa);
														sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datax.iMidRight+sepa);				
														Loca=Loca+25;  //
														sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+datax.iDnRight+"  ("+datax.iDnLeft+datax.iDnMid+")"+sepa);
														if (i<(countC-1)){
														Loca=Loca+12;  //
														sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+"-------------------------------------------------"+sepa);
														}
									    			}
										    			
														Loca=Loca+10;
													if (Loca>2400){
														PosUtilis.startPartPrint(QRep_07.this,sPrintB,Loca );
														sPrintB.delete(0, sPrintB.toString().length());
														SystemClock.sleep(3000);
														sPrintB=PosUtilis.getPrintKind(QRep_07.this,1);
														Loca=0;
													}
													
												Loca=Loca+1;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
												Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
								    			Loca=Loca+80;
								    			//呼叫 開始列印 BarCodePrinter Socket
								    			PosUtilis.startPrint(QRep_07.this,sPrintB,Loca );
		    									
		    									break;
	    									}
		    								case 2: //印製總表(不印明細)A4
		    								{
		    									sPrintA4.delete(0, sPrintA4.toString().length());
		    									StringBuffer sPrintA4T=new StringBuffer(); 
		    									sPrintA4T.append(compStr[0]+"  庫存分析("+getTitleP(mGroupMode)+")"+sepaA4);
												sPrintA4T.append("總進: "+df.format(TT10)+"件		($ "+df.format(TM10)+")"+sepaA4);
												sPrintA4T.append("總銷: "+df.format(TT30)+"件		($ "+df.format(TM30)+")"+sepaA4);
												sPrintA4T.append("總毛利 $"+df.format(Profits)+"		總存 "+df.format(Profits)+df.format(StkTT)+"件	($ "+df.format(StkMM)+")"+sepaA4);
		    									sPrintA4T.append(""+sepaA4);
		    									sPrintA4T.append(""+sepaA4);
												int count =  mExpandAdapter.getGroupCount(); //得知總筆數
												
												for (int g=0;g<count;g++){
													GroupData datag =mExpandAdapter.groups.get(g);
													sPrintA4.append(datag.strLeftTop+sepaA4);													
													sPrintA4.append(datag.strRightTop+sepaA4);
													sPrintA4.append(sepaA4);													
													sPrintA4.append(datag.strRightD+sepaA4);
													sPrintA4.append(sepaA4);													
													//sPrintA4.append(datag.strLeftD+sepaA4);													
													sPrintA4.append("庫 "+datag.strRightM+sepaA4);
								    				sPrintA4.append(";SSSS"+"\r\n");
												}
							    				sPrintA4.append(";HHHH"+"\r\n");
												Intent intent = new Intent();
												//bundle.putString("Mkqrs" , "STD,"+mKind+",11,"+deptStr[5]+","+sPrintA4T.toString()+","+sPrintA4.toString());
												intent.putExtra("SERCH","STD");
												intent.putExtra("QKIND",""+nKind);
												intent.putExtra("MODE",15);
												intent.putExtra("DEPTNO",deptStr[5]);
												intent.putExtra("BUFSTR",sPrintA4.toString());
												intent.putExtra("BUFTITLE",sPrintA4T.toString());
												intent.putExtra("STARTDAY","");
												intent.putExtra("ENDDAY","");

												intent.setClass(QRep_07.this, MkqrSt.class);
												startActivity(intent);
		    									
		    									break;
	    									}
		    								case 3: //印製總表(所有明細)A4
		    								{
		    									sPrintA4.delete(0, sPrintA4.toString().length());
		    									StringBuffer sPrintA4T=new StringBuffer(); 
		    									sPrintA4T.append(compStr[0]+"  銷售分析"+sepaA4);
		    									sPrintA4T.append(getTitleP(mGroupMode)+" "+sepaA4);
												sPrintA4T.append("總銷: "+df.format(StkT)+"件"+sepaA4);
												sPrintA4T.append("$ "+df.format(StkM)+sepaA4);
												sPrintA4T.append("成本:$ "+df.format(TM10)+sepaA4);
												sPrintA4T.append("毛利 "+df.format(Profit)+"/"+df.format(Profits)+"%"+sepaA4);
												int count =  mExpandAdapter.getGroupCount(); //得知總筆數
												for (int g=0;g<count;g++){
													GroupData datag =mExpandAdapter.groups.get(g);
													sPrintA4.append(datag.strLeftTop+sepaA4);													
													sPrintA4.append(datag.strRightTop+sepaA4);
													sPrintA4.append(datag.strLeftM+sepaA4);													
													sPrintA4.append(datag.strRightD+sepaA4);
													sPrintA4.append(datag.strLeftD+sepaA4);													
													sPrintA4.append(datag.strRightM+sepaA4);
								    				sPrintA4.append(";SSSS"+"\r\n");

								    				int countC =  mExpandAdapter.getChildrenCount(g);
									    			for (int i = 0; i <countC ; i++){
									    				datax =mExpandAdapter.getData(g, i);
									    				sPrintA4.append(datax.iTopLeft+sepaA4);
									    				sPrintA4.append(datax.iTopRight+sepaA4);
									    				sPrintA4.append(datax.iMidLeft+sepaA4);
									    				sPrintA4.append(datax.iMidRight+sepaA4);				
									    				sPrintA4.append(datax.iDnRight+sepaA4);
									    				sPrintA4.append(datax.iDnLeft+datax.iDnMid+sepaA4);
									    				sPrintA4.append(";SSSS"+"\r\n");
									    			}
													sPrintA4.append(";HHHH"+"\r\n");
												}
												Intent intent = new Intent();
												//bundle.putString("Mkqrs" , "STD,"+mKind+",12,"+deptStr[5]+","+sPrintA4T.toString()+","+sPrintA4.toString());
												intent.putExtra("SERCH","STD");
												intent.putExtra("QKIND",""+nKind);
												intent.putExtra("MODE",12);
												intent.putExtra("DEPTNO",deptStr[5]);
												intent.putExtra("BUFSTR",sPrintA4.toString());
												intent.putExtra("BUFTITLE",sPrintA4T.toString());
												intent.putExtra("STARTDAY","");
												intent.putExtra("ENDDAY","");

												intent.setClass(QRep_07.this, MkqrSt.class);
												startActivity(intent);
		    									
		    									break;
	    									}
		    								case 4: //返回
		    								{
		    									
		    									break;
	    									}
	    								}
	    							}
	    			});

                }else{//CHILD
        			String [] Lmenu={"印製單項(明細)","印製單項(明細)A4","追蹤","返回"};
	    			DialogUtilis.showDialog(QRep_07.this, "請選擇以下功能", -1,
	    					Lmenu, new IDialog() {
	    						@Override
	    						public void onDialogFinish(int pos, String choice) {
	    							switch (pos) {
		    								case 0: //印製單項(明細)
		    								{
													GroupData datag =mExpandAdapter.groups.get(groupPosition);
													Loca=Loca+40;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+datag.strLeftTop+sepa);													
													sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datag.strRightTop+sepa);
													Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+datag.strLeftM+sepa);													
													sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datag.strRightD+sepa);
													Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+datag.strLeftD+sepa);													
													sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+datag.strRightM+sepa);
													Loca=Loca+15;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
													Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);

													int countC =  mExpandAdapter.getChildrenCount(groupPosition);
													
									    			for (int i = 0; i <countC ; i++){
									    				PxData data =mExpandAdapter.getData(groupPosition, i);
														Loca=Loca+25;  //
														sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+data.iTopLeft+sepa);
														sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+data.iTopRight+sepa);
														Loca=Loca+25;  //
														sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+data.iMidLeft+sepa);
														sPrintB.append("AZ,"+Lgap+","+Loca+",1,1,0,0,"+data.iMidRight+sepa);				
														Loca=Loca+25;  //
														sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+data.iDnRight+"  ("+data.iDnLeft+data.iDnMid+")"+sepa);
														if (i<(countC-1)){
														Loca=Loca+12;  //
														sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+"-------------------------------------------------"+sepa);
														}
														if (Loca>2400){
															PosUtilis.startPartPrint(QRep_07.this,sPrintB,Loca );
															sPrintB.delete(0, sPrintB.toString().length());
															SystemClock.sleep(3000);
															sPrintB=PosUtilis.getPrintKind(QRep_07.this,1);
															Loca=0;
														}														
									    			}
										    			Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,"+"-------------------------------------------------"+sepa);
										    			Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,"+"-------------------------------------------------"+sepa);
														Loca=Loca+10;
								    			Loca=Loca+80;
								    			//呼叫 開始列印 BarCodePrinter Socket
								    			PosUtilis.startPrint(QRep_07.this,sPrintB,Loca );
		    									
		    									break;
	    									}
		    								case 1: //印製單項(明細)A4
		    								{
		    									
		    									break;
	    									}
		    								case 2://追蹤
		    								{
		    									if (mGroupMode==GroupMode.TOP3 ){
		    									datax = mExpandAdapter.getData(groupPosition, childPosition);
		    									goQhis();
		    									}
		    									break;
		    								}
		    								
		    								case 3: //返回
		    								{
		    									
		    									break;
	    									}
	    								}
	    							}
	    			});
                }
				return true;
		}
	}
	

	private String getTitleP(int nGroupMode){
		String titleP="";
        switch(nGroupMode){
        case GroupMode.TOP1:
        	titleP=((Button)findViewById(R.id.btn_stk_top1)).getText().toString();
        	break;
        case GroupMode.TOP2:
        	titleP=((Button)findViewById(R.id.btn_stk_top2)).getText().toString();
        	break;
        case GroupMode.TOP3:
        	titleP=((Button)findViewById(R.id.btn_stk_top3)).getText().toString();
        	break;
        case GroupMode.TOP4:
        	titleP=((Button)findViewById(R.id.btn_stk_top4)).getText().toString();
        	break;
        case GroupMode.TOP5:
        	titleP=((Button)findViewById(R.id.btn_stk_top5)).getText().toString();
        	break;
        case GroupMode.TOP6:
        	titleP=((Button)findViewById(R.id.btn_stk_top6)).getText().toString();
        	break;
        case GroupMode.TOP7:
        	titleP=((Button)findViewById(R.id.btn_stk_top7)).getText().toString();
        	break;
        }
        return titleP;
	}
	
	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(QRep_07.this);
			PxData data;
			if (floor==0)
				data = mExpandAdapter.getData(groupPosition, childPosition);
			else
				data = mExpandAdapter1.getData(groupPosition, childPosition);
			
			if ((floor==0 && (mGroupMode==GroupMode.TOP1 || mGroupMode==GroupMode.TOP3)) || floor==1){

				String GoodsNo=data.iFormdate;
				if (GoodsNo.indexOf("-")>0) GoodsNo= GoodsNo.substring(0,GoodsNo.indexOf("-"));
				
				if (deptN>1){ //表示有總倉&多門市
					Bundle bundle = new Bundle();
					Intent intent = new Intent();
					bundle = new Bundle();
					bundle.putString("GalleryChild","'"+GoodsNo+"';0;1");
					intent.setClass(QRep_07.this, GalleryViewS.class);
					intent.putExtras(bundle);
					startActivity(intent);
				}else {
		        	mDisplayStk.setVisibility(View.VISIBLE);
		    		SQLiteDatabase db = Utilis.getDB(QRep_07.this);
					StringBuffer mColno=new StringBuffer();
					StringBuffer mColname=new StringBuffer();
					StringBuffer mSiz=new StringBuffer();
					Cursor cst =db.rawQuery("select COLOR,UNIT1 from qitems  where GOODSNO='" + GoodsNo+"' group by COLOR,UNIT1", null);
					if (cst.getCount()>0) {
						cst.moveToFirst();
						for (int x=0;x<cst.getCount();x++){
							if (mColno.length()<=0){
								mColno.append(cst.getString(0));	mColname.append(cst.getString(1));
							} else {
								mColno.append("，"+cst.getString(0));	mColname.append("，"+cst.getString(1));
							}
								cst.moveToNext();	
						}
					}
					cst =db.rawQuery("select SIZE from qitems  where GOODSNO='" + GoodsNo+"' group by SIZE", null);
					if (cst.getCount()>0) {
						cst.moveToFirst();
						for (int x=0;x<cst.getCount();x++){
							if (mSiz.length()<=0 ){
								mSiz.append(cst.getString(0));
							}else {
								mSiz.append(","+cst.getString(0));
							}	
						cst.moveToNext();	
						}
					}
					cst.close();
					makeTable(GoodsNo,mColno.toString(),mColname.toString(),mSiz.toString());
					db.close();
				}
			}else{//展開第三四層
				floor=1;
				mExpandListView.setVisibility(View.GONE);					
				mExpandListView1.setVisibility(View.VISIBLE);
				((Button)findViewById(R.id.btn_stk_exit)).setText("返回");
				String field1=data.iTopLeft.substring(0,data.iTopLeft.indexOf("/"));
				String field2=data.iFormdate;
				getGroupData1(QRep_07.this, field1, field2);
				int count =  mExpandAdapter1.getGroupCount();
				if (count>0){
					for (int i = 0; i <count ; i++) 
					mExpandListView1.collapseGroup(i); 
					mExpandAdapter1.notifyDataSetChanged();
				}
			}
			return false;
		}
	}
	
	
	class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QRep_07.this);
			switch (id) {
				case R.id.btn_stk_exit:
				{
					if (floor==0){
					finish();
					}else{
						floor=0;
						mExpandListView1.setVisibility(View.GONE);					
						mExpandListView.setVisibility(View.VISIBLE);
						((Button)findViewById(R.id.btn_stk_exit)).setText("離開");

					}
					break;
				}
/*				
				case R.id.btn_stk_btn0:  //總績
				{
					mDept=deptStr[5];
					//也要分在哪一層
					//哪一個分析
					break;
				}
				case R.id.btn_stk_btn1:  //選擇了單一門市
				{
					mDept=deptStr[0];
					//也要分在哪一層
					//哪一個分析
					break;
				}
				case R.id.btn_stk_btn2:  //主貨清單
				{
					GoodChg="A.GOODSNO";
					ColorChg="A.COLORS";
					SizeChg="A.SIZES";
					ConChg="主貨";
					getGroupData(QRep_06.this, null, null);				
					break;
				}
				case R.id.btn_stk_btn3:  //明細清單
				{
					GoodChg="A.GOODSNOS";
					ColorChg="A.UNIT1";
					SizeChg="A.SIZES";
					ConChg="明細";
					break;
				}
*/				
				case R.id.btn_stk_btn4:  //更新,但須警告
				case R.id.text_stk_duration:  //可以定義統計庫存的起算日期
				{
					mYear=Utilis.toInt(bgDate.substring(0, 4));
					mMonth=Utilis.toInt(bgDate.substring(5, 7));
					mDay=Utilis.toInt(bgDate.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(QRep_07.this, "請輸入正確交易日期", c, new IDateDialog(){
						@Override
						public void onDateDialogFinish(String date, int year, int month, int day) {
		            		bgDate=date.replace("-", "/");
				    			Toast.makeText(QRep_07.this,"統計日期已改為:"+bgDate, Toast.LENGTH_SHORT).show();
								startDB();
								//應該重新拜訪 重建 統計
						}
					});
					break;
				}
				case R.id.btn_stk_prev_date:  //暢銷排行
				{
					sSort=0;
					getGroupData(QRep_07.this, null, null);
					int count =  mExpandAdapter.getGroupCount(); 
					for (int i = 0; i <count ; i++) 
					mExpandListView.collapseGroup(i); 
					mExpandAdapter.notifyDataSetChanged();
					break;
				}
				case R.id.btn_stk_next_date:  //滯銷排行
				{
					sSort=1;
					getGroupData(QRep_07.this, null, null);
					int count =  mExpandAdapter.getGroupCount(); 
					for (int i = 0; i <count ; i++) 
					mExpandListView.collapseGroup(i); 
					mExpandAdapter.notifyDataSetChanged();
					break;
				}
			    case R.id.btn_stk_top1: //依主貨品明細排行
			    	{
		    			resetButton(id);			    		
			    		mGroupMode = GroupMode.TOP1;
						getGroupData(QRep_07.this, null, null);
						int count =  mExpandAdapter.getGroupCount(); 
						for (int i = 0; i <count ; i++) 
						mExpandListView.collapseGroup(i); 
						mExpandAdapter.notifyDataSetChanged();
						
			   			break;
			    		}
			    case R.id.btn_stk_top2:  //依批價貨品排行
			    		{
		    			resetButton(id);
		    			mGroupMode = GroupMode.TOP2;
		    			getGroupData(QRep_07.this, null, null);
		    			int count =  mExpandAdapter.getGroupCount(); 
		    			for (int i = 0; i <count ; i++) 
		    			mExpandListView.collapseGroup(i); 
		    			mExpandAdapter.notifyDataSetChanged();
		    			
	    				break;
		    			}
			    case R.id.btn_stk_top3: //依門市貨品排行
			    		{
		    			resetButton(id);
		    			mGroupMode = GroupMode.TOP3;
		    			getGroupData(QRep_07.this, null, null);
		    			int count =  mExpandAdapter.getGroupCount(); 
		    			for (int i = 0; i <count ; i++) 
		    			mExpandListView.collapseGroup(i); 
		    			mExpandAdapter.notifyDataSetChanged();
		    			
	    				break;
			    		}
			    case R.id.btn_stk_top4: //依廠商分布排行
			    		{
		    			resetButton(id);
		    			mGroupMode = GroupMode.TOP4;
		    			getGroupData(QRep_07.this, null, null);
		    			int count =  mExpandAdapter.getGroupCount(); 
		    			for (int i = 0; i <count ; i++) 
		    			mExpandListView.collapseGroup(i); 
		    			mExpandAdapter.notifyDataSetChanged();
		    			
		    			break;
			    		}
			    case R.id.btn_stk_top5: //依類別分布排行
		    		{
		    			resetButton(id);
		    			mGroupMode = GroupMode.TOP5;
		    			getGroupData(QRep_07.this, null, null);
		    			int count =  mExpandAdapter.getGroupCount(); 
		    			for (int i = 0; i <count ; i++) 
		    			mExpandListView.collapseGroup(i); 
		    			mExpandAdapter.notifyDataSetChanged();
		    			
		    			break;
		    		}
			    case R.id.btn_stk_top6: //依售價商品排行
		    		{
		    			resetButton(id);
		    			mGroupMode = GroupMode.TOP6;
		    			getGroupData(QRep_07.this, null, null);
		    			int count =  mExpandAdapter.getGroupCount(); 
		    			for (int i = 0; i <count ; i++) 
		    			mExpandListView.collapseGroup(i); 
		    			mExpandAdapter.notifyDataSetChanged();
		    			
		    			break;
		    		}
			    case R.id.btn_stk_top7: //依國別分布排行
		    		{
		    			resetButton(id);
		    			mGroupMode = GroupMode.TOP7;
		    			getGroupData(QRep_07.this, null, null);
		    			int count =  mExpandAdapter.getGroupCount(); 
		    			for (int i = 0; i <count ; i++) 
		    			mExpandListView.collapseGroup(i); 
		    			mExpandAdapter.notifyDataSetChanged();
		    			
		    			break;
		    		}
			}
		}
	}
	
	private void resetButton(int id){
		((Button)findViewById(R.id.btn_stk_top1)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_stk_top2)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_stk_top3)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_stk_top4)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_stk_top5)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_stk_top6)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_stk_top7)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_yellow);
	}

	private void goQhis(){
		String GoodsNo=datax.iFormdate;
		if (GoodsNo.indexOf("-")>0) GoodsNo= GoodsNo.substring(0,GoodsNo.indexOf("-"));
		try{
			Intent intent = new Intent();
			intent.putExtra("QHis_kind", nKind);
			intent.putExtra("QHis_mode", 1);
			intent.putExtra("QHis_User","" );
			intent.putExtra("QHis_Goods",GoodsNo );
			intent.setClass(QRep_07.this, QHis.class);
			startActivity(intent);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
		}
		

	}

	private void makeTable(String kGoods,String kSplitColorNo,String kSplitColor,String kSplitSizes){
		
		//展開用的引用在庫存表
		String[] anames;	
		String[] anumber;
		String[] asizes;
		double[] attot;
	
		if(kSplitSizes != null && kSplitSizes.length() > 0
    		&& kSplitColorNo != null && kSplitColorNo.length() > 0
    		&& kSplitColor != null && kSplitColor.length() > 0){
			
			    	mArrayColorNumber.clear();
			    	mArrayColorNumber.removeAll(mArrayColorNumber);
			    	mArrayColorName.clear();
			    	mArrayColorName.removeAll(mArrayColorName);
			    	
		        	anumber = kSplitColorNo.split("，"); //取得各色號字串
		        	anames = kSplitColor.split("，");
		        	asizes = kSplitSizes.split(",");
		        	attot=new double[asizes.length*anumber.length];
			    	
			    	
			    	for(int i = 0; i < anumber.length; i++){ 
			    		mArrayColorNumber.add(anumber[i]); //從numbers字串陣列 存入 List_mArrayColorNumber
			    	}
			    	
			    	anames = kSplitColor.split("，");
			    	
			    	for(int i = 0; i < anames.length; i++){
			    		mArrayColorName.add(anames[i]);
			    	}
				
			    	//努力歸零 very important
			    	mLayoutRoot.removeAllViews(); //***************
					mSizeLink.clear();
					mCountRow.clear();	        		
					mCountCell.clear();
					
			    	mSizeLink.add("代碼"); // 顏色
			    	mSizeLink.add("顏色"); // 尺寸
			    	// 設定 Title 行 //使每個尺寸都有3格(進/銷/存)
			    	String ttot[] =new String[asizes.length*3*anumber.length] ; //進銷存統計用
			    	String ptot[] =new String[asizes.length*anumber.length] ;	//展開用
			    	for(int i = 0; i < asizes.length*3*anumber.length; i++){ttot[i]="0";}
			    	for(int i = 0; i < asizes.length*anumber.length; i++){ptot[i]="";}
			    	for(int i = 0; i < asizes.length; i++){
			    		mSizeLink.add(asizes[i]+"進");
			    		mSizeLink.add(asizes[i]+"銷(訂)");
			    		mSizeLink.add(asizes[i]+"存");
			    	}
			    	// 設定初始Row 列
			    	for(int i = 0; i <= mArrayColorName.size(); i++){
			    		// 設定Row會包含哪些 Key
			    		mCountRow.put(i, i * 100);
			    		for(int k = 0; k < mSizeLink.size(); k ++){ //s1,s2,s3,m1,m2,m3,l1,l2,l3,x1,x2,x3
			        		if( i == 0){
			        			mCountCell.put(k, mSizeLink.get(k)); //原先 i*100+k 沒有意義
			        		}
			        		else{ // 第二列以後
			        			if( k == 0){ // 新增號碼
			        					mCountCell.put(i * 100 + k, mArrayColorNumber.get(i - 1));
			        			} else {
			        					mCountCell.put(i * 100 + k, mArrayColorName.get(i - 1)); 
			        			}
			
			        		}			
			    		}
			    	}
			    	
					try{
						
					String mCountList= PosUtilis.getQMtrioArray(this,kGoods,kSplitColorNo,kSplitColor,kSplitSizes,deptStr[5],"" , aPart,1);
						
			    	String[] numberLevel1 = mCountList.toString().split("，");
			    	for(int nRow = 1; nRow < mCountRow.size(); nRow++){
			    		String[] numberLevel2 = numberLevel1[nRow - 1].split(",");
			    		int nLevel2 = 0;
						int nCellKey = mCountRow.get(nRow);
						for(int i = 2 ; i < mSizeLink.size(); i++){
							if(nLevel2 < numberLevel2.length){
								mCountCell.put(nCellKey + i, numberLevel2[nLevel2]);
							}
							nLevel2++;
						}
					}
					
				}catch(Exception e){
					e.printStackTrace();
				}
					
					ArrayList<TableRow> table = new ArrayList<TableRow>();
				table.removeAll(table);
			
				for(int i = 0; i <= mArrayColorName.size(); i++){
					TableCell[] titles = new TableCell[mSizeLink.size()];
			
					for(int k = 0; k < titles.length; k++){
		    			if (k<=1) titles[k] = new TableCell((Wwidth/(tabless+1))-8,tableHeight,TableCell.STRING);
		    			else titles[k] = new TableCell((Wwidth/tabless)-8,tableHeight,TableCell.STRING);
					}
					table.add(new TableRow(titles));
				}
				
				TableRow tableRow = table.get(0);
				for(int i = 0; i <=mArrayColorName.size(); i ++){
					TableRowView row = new TableRowView(this, tableRow, 0,i);
					mLayoutRoot.addView(row);
				}
		
		}
	}
   	
public class TableRowView extends LinearLayout {  
    public TableRowView(Context context, TableRow tableRow,int imode, int position) {  
        super(context);  
        this.setOrientation(LinearLayout.HORIZONTAL);
        String colStr="01";
        for (int i = 0; i < tableRow.getSize(); i++) { 
            TableCell tableCell = tableRow.getCellValue(i);  
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(  
                    tableCell.width, tableCell.height);  
            layoutParams.setMargins(0, 0, 1, 1);  
            TextView textCell = new TextView(context);  
                textCell.setLines(1);  
                textCell.setGravity(Gravity.CENTER);  
                textCell.setBackgroundColor(Color.WHITE);
                if(mCountRow.containsKey(position) == true){
                	int key = mCountRow.get(position);  //keep
                	if( mCountCell.containsKey(key + i)){
                		textCell.setText(String.valueOf(mCountCell.get(key + i))); //keep
                	}else{
                		textCell.setText("X");
                	}
                }else{
                	textCell.setText("X");
                }
                textCell.setId(position * 200 + i);
                textCell.setTextColor(Color.BLACK);
                if(position >=1 && i >= 2){
                	if ((i+2) %3==1){
                	textCell.setBackgroundResource(R.drawable.keypad_yellow);
                	} else if((i+2) %3==2) {
                    	textCell.setBackgroundResource(R.drawable.keypad_green);                    		
                	} else if((i+2) %3==0) {
                    	textCell.setBackgroundResource(R.drawable.keypad_blue2);                    		
                	}
                	
                }else  if(position > 0 && i ==0 && imode==0){  //
                	String colorN=DBUtil.ColorGetTxt(QRep_07.this,textCell.getText().toString());
                	String [] colors=colorN.split(";");
                	textCell.setBackgroundColor(Utilis.toInt(colors[2]));
                }else  if(position == 0 && imode==1 && i>1 ){  //
                	String colorN=DBUtil.ColorGetTxt(QRep_07.this,textCell.getText().toString());
                	String [] colors=colorN.split(";");
                	if (((i+1) %3)==0){	
                		colStr=textCell.getText().toString();
                		colorN=DBUtil.ColorGetTxt(QRep_07.this,textCell.getText().toString());
                		colors=colorN.split(";");
                	}
               		if (((i+1) %3)==2){
               			textCell.setBackgroundResource(R.drawable.keypad_blue2);
               		}else{	
                		textCell.setBackgroundColor(Utilis.toInt(colors[2]));
               		}
                } else {
                	textCell.setBackgroundColor(Color.rgb(208, 208, 208));
                }
                
                addView(textCell, layoutParams);
                
        }  
        this.setBackgroundColor(Color.BLACK);
    }  
}
	
	private int ColorGetnumber(Context context,String key){
		int number=0;
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cs = null;					
		StringBuffer mySqlBuf = new StringBuffer();
			mySqlBuf.append("select distinct NO,PIC from qc_color where NO='"+key+"'");
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				number=cs.getInt(1);
			}
			db.close();
			cs.close();
		return number;	
	}

	Handler mHandlerQm = 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 ){
					Log.i("DOWNLOAD_QRep_03_qmtrio","Hresult="+Hresult );
					if (Hresult.indexOf("\r\n")>2){
				    	mLayoutRoot.removeAllViews(); //***************
						mCountRow.clear();	        		
						mCountCell.clear();
						String Lines [] = Hresult.split("\r\n");
						for (int xx=0;xx<Lines.length;xx++){
				  		mCountRow.put(xx, xx * 200);
							String[] data= Lines [xx].split(",");
							ColNoSizN=(data.length-2)/3;
							for (int jj=0;jj<data.length;jj++){
							mCountCell.put(xx * 200 + jj, data[jj]);
							
							}	
						}
						if (mCountCell.size()>0){
							ArrayList<TableRow> table = new ArrayList<TableRow>();
							table.removeAll(table);
						
							for(int i = 0; i <= (deptN+1); i++){  //縱向一一
								TableCell[] titles = new TableCell[ColNoSizN*3+2]; //橫向一一
						
								for(int k = 0; k < titles.length; k++){
									titles[k] = new TableCell((Wwidth/tabless)-8,tableHeight,TableCell.STRING);
								}
								table.add(new TableRow(titles));
							}
							
							TableRow tableRow = table.get(0);
							for(int i = 0; i <=(deptN+1); i ++){
								TableRowView row = new  TableRowView(QRep_07.this, tableRow,1, i);
								mLayoutRoot.addView(row);
							}
						}
					}
				}
			}
		}
	};

	

	Handler mHandlerQDR_31 = 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("HHHH\r\n")>2){

						Hresult=	Hresult.substring(Hresult.indexOf("rep03;")+6);
						
						Log.i("DOWNLOAD_31",Hresult );
						
						String LineH [] = Hresult.substring(0, Hresult.length()-6).split(";HHHH\r\n");

						LinkedList<GroupData> groups = new LinkedList<GroupData>();
						LinkedList<List<PxData>> childs = new LinkedList<List<PxData>>();
						
						for (int xx=0;xx<LineH.length;xx++){
							String LinesH[] =LineH[xx].substring(0, LineH[xx].length()-6).split(";SSSS\r\n");
							
							GroupData datah = new GroupData();

							String Lineshh[] =LinesH[0].split(";");
							
							datah.SEARCH = Lineshh[5];
							T30=Utilis.toInt(Lineshh[0])+Utilis.toInt(Lineshh[1]);//總件數
							TT30=TT30+T30;
							M30=Utilis.toDouble(Lineshh[2]);//總金額
							TM30=TM30+M30;
							M10=Utilis.toDouble(Lineshh[3]);//總成本
							TM10=TM10+M10;
							datah.strRightTop="銷:"+df.format(T30)+"件";							
							datah.strRightD="銷$:"+df.format(M30);
							
							if (M30 >0 && PSWD==0)	{
								datah.strLeftD="成本$:"+df.format(M10); //總成本strLeftD
								datah.strRightM="毛:$"+df.format(M30-M10)+"/"+df.format(Math.round((M30-M10)*100/M30))+"%";
							} else {
								datah.strRightM="毛:xxxxxx";
							}
							
								
			 				StkT=TT30;  //總銷貨量
			 				StkM=TM30; //總銷金額
			 				Profit=TM30-TM10; //總毛利
			 				Profits=Math.round(Profit*100/TM30); //總毛利率
							if (Lineshh[7] ==null || Lineshh[7].length()<=0 ) datah.strPic="drawable.icon"; 
							else datah.strPic=Lineshh[7];  //圖片
							datah.strLeftTop=Lineshh[5]; //主題一
							datah.strLeftM=Lineshh[6]; //主題二
			 				groups.add(datah);
			 				
							
								List<PxData> listData = new ArrayList<PxData>();							
				 				for (int yy=1;yy<LinesH.length;yy++){
									String Lines[] =LinesH [yy].split(";");
									if (Lines.length>=10){
										PxData data=new PxData();
	
										data.iTopLeft =Lines[5] ;
										data.iMidLeft =Lines[6] ;
										data.iPic=Lines[7] ;
										data.iTopRight ="銷:"+df.format(Utilis.toInt(Lines[0])+Utilis.toInt(Lines[1]))+"件/$"+ df.format(Utilis.toDouble(Lines[2]));
										if (PSWD==0)
											data.iMidRight ="銷:$"+ df.format(Utilis.toDouble(Lines[2]))+"("+df.format(Utilis.toDouble(Lines[3]))+")";
										else
											data.iMidRight ="銷:$"+ df.format(Utilis.toDouble(Lines[2]));
										
										M10=Utilis.toDouble(Lines[3]);
										M30=Utilis.toDouble(Lines[2]);
										data.iDnLeft=Lines[8];
										data.iDnMid=Lines[9];
	
										if (M30 >0 && PSWD==0)	{
											data.iDnRight="毛:$"+df.format((M30-M10))+"/"+df.format(Math.round((M30-M10)*100/M30))+"%";
										} else {
											data.iDnRight="毛:xxxxxx";
										}
										
					 					listData.add(data);
								}
				 			}
								childs.add(listData);
						}
						mExpandAdapter.setData(groups, childs);
						mExpandAdapter.notifyDataSetChanged();
		 				((TextView)findViewById(R.id.text_t10)).setText(""+df.format(StkT)+"件");//總進->銷件
		 				((TextView)findViewById(R.id.text_r10)).setText("$:"+df.format(StkM));  //盈虧 ->銷額
		 				((TextView)findViewById(R.id.text_t30)).setText("$:"+df.format(TM10));  //本銷->毛利
		 				((TextView)findViewById(R.id.text_r30)).setText("$:"+df.format(Profit)+"/"+df.format(Profits)+"%");
						
				}
			}
		}
	}
	};

	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;
		}
		
		/* class GroupViewHolder */
		private class GroupViewHolder {
			ImageView imageIcon;
			TextView text1;
			TextView text2;
			TextView textMoney;
			TextView textOriMidRight;
			TextView textG1;
			TextView textG2;
		}

		//獲取二級清單的View物件
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
		ViewGroup parent)
		{
		PxData datax = 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(datax.iPic != null && datax.iPic.length() > 0){
					//if(mGroupMode != GroupMode.TOP6 && datax.iPic != null && datax.iPic.length() > 0){
						holder.imageItem.setImageDrawable(Utilis.getResourceImage(QRep_07.this, datax.iPic));
					}else{
						holder.imageItem.setImageResource(R.drawable.icon_store);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			holder.textGoodsNo.setText(datax.iTopLeft);
			holder.textName.setText(datax.iMidLeft);
			holder.textImpo.setText(datax.iTopRight);			
			holder.textMoney.setText(datax.iMidRight);
			holder.textCountry.setText(datax.iDnLeft);
			holder.textNumber.setText(datax.iDnMid);
			holder.textCompany.setText(datax.iDnRight);
			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();
				//id/text_ttime
				((TextView) convertView.findViewById(R.id.text_ttime)).setVisibility(View.INVISIBLE);
				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.textOriMidRight = (TextView)convertView.findViewById(R.id.textOriMoney);
				holder.textG1 = (TextView) convertView.findViewById(R.id.textg1);
				holder.textG2 = (TextView) convertView.findViewById(R.id.textg2);
				convertView.setTag(holder);
				
			} else {
				holder = (GroupViewHolder) convertView.getTag();
			}
			//@@應該區隔進貨單mKind=10 或日結單abMode==1 與不是進貨單
				holder.imageIcon.setVisibility(View.VISIBLE);
				try{
					if(data.strPic != null && data.strPic.length() > 0){
					//if(mGroupMode != GroupMode.TOP6 && data.strPic != null && data.strPic.length() > 0){
						holder.imageIcon.setImageDrawable(Utilis.getResourceImage(QRep_07.this, data.strPic));
					}else{
						holder.imageIcon.setImageResource(R.drawable.icon_store);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
				
			holder.text2.setText(data.strRightTop);
			holder.textMoney.setText(data.strRightM);
			holder.textOriMidRight.setText(data.strRightD);
			holder.textG1.setText(data.strLeftTop);
			holder.text1.setText(data.strLeftM);
			holder.textG2.setText(data.strLeftD);
			return convertView;
		}

		public boolean hasStableIds()
		{
		return false;
		}

		public boolean isChildSelectable(int groupPosition, int childPosition)
		{
		return true;
		}
	}
	
	private int  getDeptIndex(String serch){
		int value=0;
		int x=DepIndex.indexOf(serch)+serch.length();
		value=Utilis.toInt(DepIndex.substring(x,x+3));
		return value;
	}

	private int  getFactIndex(String serch){
		int value=0;
		int x=FactIndex.indexOf(serch)+serch.length();
		value=Utilis.toInt(FactIndex.substring(x,x+3));
		return value;
	}

	private void startDB(){
		SQLiteDatabase db = Utilis.getDB(QRep_07.this);
		String SQL="delete from zansly_stk";
		db.execSQL(SQL);
		SystemClock.sleep(1000);
		String LimitDate=bgDate.replace("/", "-");
		
		//
		//如果為CLOUD版 可以在MySQL into file 產生檔案,送回 LOCAL端,再一一寫入
		//zansly_stk 可能速度會慢很多???
		
		SQL="insert into zansly_stk (DEPTNO,GOODSNO,"+
				"GOODSNOS,GOODSNAME,GOODSTYPE,P1,P3,P5,"+
				"SUPPLY,PIC,SEASON,COUNTRY,COLOR,SIZE,COLORS,SIZES,YEAR,"+
				"UNIT10,UNIT20,UNIT21,UNIT34,ACOST,SUBPRICE)"+
				" select a.DEPTNO,a.GOODSNO,a.GOODSNOS,"+
				"a.GOODSNAME,a.GOODSTYPE,max(a.P1),max(a.P3),max(a.P5),"+
				"a.SUPPLY,min(a.PIC),a.SEASON,a.COUNTRY,a.UNIT1,a.SIZE,"+
				"a.COLORS,a.SIZES,a.YEAR,"+
				"sum(a.UNIT10),sum(a.UNIT20),0,sum(a.UNIT30+a.UNIT40),sum(a.UNIT30*a.P1),sum(a.UNIT30*a.UNITPRICE*a.DISCOUNT)/100"+
				// acost ,subprice 這兩個欄位,只能計入銷貨資料
				//"sum(a.UNIT10),sum(a.UNIT20),0,sum(a.UNIT30+a.UNIT40),sum(a.ACOST),sum(a.SUBPRICE)"+  
				" from qitems as a"+
				" where ((a.QKIND<>'20' and DEPTNO<>'"+deptStr[5]+"') or (a.QKIND<>'21') ) and a.ISCONFIRM='Y'"+
				" and DEPTNO in (select CUSTNO from qcust where TR='20')"+
				" and GOODSNO in (select GOODSNO from qitems where FORMDATE>='"+LimitDate+"')"+
				" group by a.DEPTNO,a.GOODSNO,a.GOODSNOS,"+
				"a.GOODSNAME,a.GOODSTYPE,"+
				"a.SUPPLY,a.SEASON,a.COUNTRY,a.UNIT1,a.SIZE,"+
				"a.COLORS,a.SIZES,a.YEAR";
				
				db.execSQL(SQL);
				SystemClock.sleep(1000);

				SQL="insert into zansly_stk (DEPTNO,GOODSNO,"+
						"GOODSNOS,GOODSNAME,GOODSTYPE,P1,P3,P5,"+
						"SUPPLY,PIC,SEASON,COUNTRY,COLOR,SIZE,COLORS,SIZES,YEAR,"+
						"UNIT10,UNIT20,UNIT21,UNIT34)"+
						" select a.USER,a.GOODSNO,a.GOODSNOS,"+
						"a.GOODSNAME,a.GOODSTYPE,max(a.P1),max(a.P3),max(a.P5),"+
						"a.SUPPLY,min(a.PIC),a.SEASON,a.COUNTRY,a.UNIT1,a.SIZE,"+
						"a.COLORS,a.SIZES,a.YEAR,"+
						"0,0,sum(a.UNIT20),0"+  
						" from qitems as a"+
						" where (a.QKIND='20' or a.QKIND='21')  and a.ISCONFIRM='Y'"+
						" and USER in (select CUSTNO from qcust where TR='20')"+
						" and GOODSNO in (select GOODSNO from qitems where FORMDATE>='"+LimitDate+"')"+
						" group by a.USER,a.GOODSNO,a.GOODSNOS,"+
						"a.GOODSNAME,a.GOODSTYPE,"+
						"a.SUPPLY,a.SEASON,a.COUNTRY,a.UNIT1,a.SIZE,"+
						"a.COLORS,a.SIZES,a.YEAR";

						db.execSQL(SQL);

						SystemClock.sleep(1000);
						SQL="delete from zansly_stk where UNIT10=0 and UNIT20=0 and UNIT21=0 and UNIT34=0";
						//清除 件數為0
						db.execSQL(SQL);
						
						SQL="update zansly_stk set ACOST=0 where ACOST isnull or ACOST='';";
						db.execSQL(SQL);
						SQL="update zansly_stk set SUBPRICE=0 where SUBPRICE isnull or SUBPRICE='';";
						db.execSQL(SQL);
						SystemClock.sleep(500);
						//20200227
						//還沒用到 DEPTNAME 可以將進(出)貨成本填入10/(21-20)
						SQL="update zansly_stk set DEPTNAME=0";
						db.execSQL(SQL);
						SQL="update zansly_stk set PIC=(select distinct PIC from qdetail where zansly_stk.GOODSNO=qdetail.GOODSNO)";
						//SQL="update zansly_stk set PIC=replace(PIC,'//','/')";
						db.execSQL(SQL);
						SystemClock.sleep(500);
						SQL="update zansly_stk set PIC='"+dfPic+"' where PIC isnull or PIC='';";
						db.execSQL(SQL);
						SystemClock.sleep(500);
						SQL="update zansly_stk set DEPTNAME=(UNIT21-UNIT20)*P1 where DEPTNO<>'AA'";
						//門市出轉貨成本
						db.execSQL(SQL);
						SystemClock.sleep(500);
						SQL="update zansly_stk set DEPTNAME=(UNIT10-UNIT20)*P1 where DEPTNO='AA'";
						//總倉進貨(扣除門市出貨)成本
						db.execSQL(SQL);
						db.close();

						Utilis.putIni(QRep_07.this, "INIH", "QHIS",bgDate,7);
						Utilis.putIni(QRep_07.this, "INIH", "QHIS",DateUtil.getCurrentDate(),8);
						enDate=DateUtil.getCurrentDate();
				        mTextDuration.setText(bgDate+" ~ "+enDate);
						getGroupData(QRep_07.this, null, null);
						int count =  mExpandAdapter.getGroupCount(); 
						for (int i = 0; i <count ; i++) 
						mExpandListView.collapseGroup(i); 
						mExpandAdapter.notifyDataSetChanged();
						
	}
	private void startIniDb(Context context){
		
		SQLiteDatabase db_chk = Utilis.getDB(context);
		int exist_db=0;
		//第一段 無論如何 建立	TABLE  
		String SQL_INI="	CREATE TABLE  IF NOT EXISTS zansly_stk ("+ 
				"	    DEPTNO         VARCHAR( 8 ),"+
				"	    DEPTNAME         VARCHAR( 20 ),"+    
				"	    GOODSNO        VARCHAR( 20 ),"+
				"	    GOODSNOS       VARCHAR( 20 ),"+
				"	    GOODSNAME      VARCHAR( 20 ),"+
				"	    GOODSTYPE      VARCHAR( 20 ),"+
				"	    P1             DOUBLE,"+
				"	    P3             DOUBLE,"+
				"	    P5             DOUBLE,"+
				"	    SUPPLY         VARCHAR( 10 ),"+
				"	    PIC            TEXT( 128 ),"+
				"	    SEASON         VARCHAR( 10 ),"+
				"	    COUNTRY        VARCHAR( 20 ),"+
				"	    COLOR          VARCHAR( 6 ),"+
				"	    SIZE           VARCHAR( 6 ),"+
				"	    COLORS          VARCHAR( 128 ),"+
				"	    SIZES           VARCHAR( 128 ),"+
				"	    YEAR           VARCHAR( 4 ),"+ 
				"	    ACOST          DOUBLE,"+
				"	    SUBPRICE       DOUBLE,"+
				"	    UNIT10         DOUBLE,"+
				"	    UNIT20         DOUBLE,"+
				"	    UNIT21         DOUBLE,"+
				"	    UNIT34         DOUBLE	); ";
	
		db_chk.execSQL(SQL_INI);
		
		Cursor cs;
		cs=db_chk.rawQuery("select distinct DEPTNO from zansly_stk", null);
		if (cs.getCount()>0){
			exist_db=1;
		}else{
	        bgDate=DateUtil.addMonth(DateUtil.getCurrentDate(), -4);
	        enDate=DateUtil.getCurrentDate();
	        mTextDuration.setText(bgDate+" ~ "+enDate);
			mYear=Utilis.toInt(bgDate.substring(0, 4));
			mMonth=Utilis.toInt(bgDate.substring(5, 7));
			mDay=Utilis.toInt(bgDate.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(QRep_07.this, "請輸入正確交易日期", c, new IDateDialog(){
				@Override
				public void onDateDialogFinish(String date, int year, int month, int day) {
            		bgDate=date.replace("-", "/");
		    			Toast.makeText(QRep_07.this,"統計起始日期:"+bgDate, Toast.LENGTH_SHORT).show();
						startDB();
						//應該重新拜訪 重建 統計
				}
			});
	        
		}
		cs.close();
		db_chk.close();

		//如果雲端版,拜訪 INI 檢查 最後 T3T4 拜訪時間
		//Local端 則抓取?
		if (exist_db==1){
				String [] Lmenu={"更新","繼續"};
				DialogUtilis.showDialog(context, "最後統計期間:\r\n"+mTextDuration.getText().toString(), -1,
					Lmenu, new IDialog() {
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch (pos) {
									case 0: //更新
									{
										bgDate=DateUtil.addDate(DateUtil.getCurrentDate(),-7);
										enDate=DateUtil.addDate(DateUtil.getCurrentDate(),-1);
										startDB();
										break;
									}
									case 1: //不更新 繼續查詢
									{
										bgDate=Utilis.getIni(QRep_07.this, "INIH", "QHIS",7);
										enDate=Utilis.getIni(QRep_07.this, "INIH", "QHIS",8);
								        mTextDuration.setText(bgDate+" ~ "+enDate);
										
										getGroupData(QRep_07.this, null, null);
										int count =  mExpandAdapter.getGroupCount(); 
										for (int i = 0; i <count ; i++) 
										mExpandListView.collapseGroup(i); 
										mExpandAdapter.notifyDataSetChanged();
										
										break;
									}
										
								}
							}
			});
		}else{
			bgDate=DateUtil.addDate(DateUtil.getCurrentDate(),-7);
			enDate=DateUtil.addDate(DateUtil.getCurrentDate(),-1);
			startDB();
		}
		
		
	}

}
