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.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.DisplayMetrics;
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", "InflateParams" })
public class QRep_06 extends Activity{
	
	ExpandItemAdapter mExpandAdapter = null;	
	
	TextView mTextDuration = null;

	LinearLayout mDisplayStk;
//ACTION 預設模式 POS定義為 銷貨單;預購單;暫存單;單頭+單身	
	
	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 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("!&!");
	private String[] adordIni;	
	
	private final int RESULT_GVV=0123; 		//GALLERY
	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=DateUtil.addDate(DateUtil.getCurrentDate(),-7);
	String enDate=DateUtil.addDate(DateUtil.getCurrentDate(),-1);
	String LimitDate=bgDate.replace("/", "-");
	String LastDate=enDate.replace("/", "-");
	//2020/12/03
	int mYear=2016;
	int mMonth=01;
	int mDay=01;
	//會因為總倉在單點 可以選擇門市 否則無法異動 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;
	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=8;//指向sql_A的第一欄位為 統計的主題
	//第一層
	String CntmSQL="sum(AASTK),sum(DSTK),sum(UNIT10),sum(UNIT21_20),sum(UNIT34),sum(UNIT33),sum(UNITDEF),sum(UNITEDIT)";
	//倉存,店存,總進,總出,總銷,本銷,應配,擬配
							
   	String [] sql_A={ 
   			"",
   			" GOODSNO,GOODSNAME,PIC from zadord ",
   			" DEPTNO from zadord ",
   			" GOODSTYPE from zadord ",
   			" SUPPLY from zadord ",
   			};
   	/*
   			" GOODSNO,GOODSNAME,DEPTNO,PIC from zadord ",
   			" DEPTNO from zadord ",
   			" GOODSTYPE,DEPTNO from zadord ",
   	 */
	String[] sql_D={ "DEPTNO","GOODSNO","DEPTNO","GOODSTYPE","SUPPLY"};	
	String[] mode_E={ "","依貨品", "依門市","依類別","依廠商"};
	String[][] sql_C={{"",""},{"",""},{ "DEPTNO","GOODSNO"},{ "DEPTNO","GOODSTYPE"},{ "DEPTNO","SUPPLY"}};	
	
	
   	String [] sql_AAi={ 
   			"",
   			" GOODSNOS,GOODSNAME,COLOR,PIC",
   			" GOODSNOS,GOODSNAME,COLOR,PIC",
   			" GOODSTYPE,PIC",
   			" SUPPLY,PIC",
   			};
	
   	String sql_B=" DEPTNO,GOODSNOS,GOODSNAME,COLOR,PIC";
   	//第二層一致內容
	
	
	double sSort=0; //0依金額 1.依件數 2.依毛利
	
	int nKind=30;
	DatePicker dp1;
	DatePicker dp2;
	
   	String btns=null;
   	String[] bttns;
   	
   	int AA_stk=0;
   	int AA_stkT=0;
   	int D_stk=0;
   	int D_stkT=0;
   	int U33=0;
   	int U33T=0;
   	int AAU34=0;
   	int U34=0;
   	int U34T=0;
   	int defU=0;
   	int defUT=0;
   	int edtU=0;
   	int edtUT=0;

   	int TT10=0;  	//總進貨量
   	int TM10=0; 	//總出貨
   	int TT30=0;	//總銷貨量
   	int TM30=0;	//總銷貨額
   	int TS30=0;	//總銷貨額
   	int StkTT=0;		//總存貨量
   	int StkMM=0;	//總存貨額
   	int Profits=0; //總毛利
   	
   	int T10=0;  	//本進貨量
   	int M10=0; 	//本進貨額
   	int T30=0;		//本銷貨量
   	int M30=0;	//本銷貨額
   	int S30=0;	//本銷貨額
   	int Profit=0; 	//本銷毛利
   	int StkT=0;		//存貨量
   	int 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;
	
//For  Table
	int Wheight;
	int Wwidth;
	int tableHeight=30;
	int tabless=6;

	@SuppressWarnings("unused")
	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; 	//依廠商
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent dataR) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, dataR);
		
		switch(requestCode){
		
		case RESULT_GVV:
			{
				if (resultCode == RESULT_OK) {
					if(dataR.getIntExtra("GVP_modify",0)==1){
		    			Toast.makeText(QRep_06.this,"配貨表的擬配已歸零成功!!", Toast.LENGTH_SHORT).show();
						//有異動配貨
						getGroupData(QRep_06.this, null, null);
					}
				}
				break;
			}
		}
	}

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qrep06);
        
		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.TOP1);	

        ((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_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_btn4)).setOnClickListener(new MainClick());
        
        //預設為四個月前起算
        mTextDuration.setOnClickListener(new MainClick());
        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);
        
        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;

		db.close();
		cs.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;
        }
        
        //初始化
        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) {
            }
        });
        
}	
	
	public void onResume(){
		super.onResume();
		DBCloud.aa0_aa1_auto_HI(QRep_06.this,nKind);
		SystemClock.sleep(500);
		DBCloud.aa0_aa1_auto_qdetail_n(QRep_06.this);
		
		}
	
public void getGroupData(Context context,String condition, String conditionValue) {
	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();

			   	AA_stk=0;AA_stkT=0;  	D_stk=0;D_stkT=0;
			   	U33=0;U33T=0;			   	U34=0;U34T=0;AAU34=0;
			   	defU=0;defUT=0;		   	edtU=0;edtUT=0;
			   	T10=0;TT10=0;			   	StkT=0;StkTT=0;
			   	M30=0;TM10=0;
			   	
        		bufCategory.append("select "+CntmSQL);
        		bufCategory.append(" from zadord");
				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();
	        		//取得總量
					T10=cursorGroup.getInt(2);//廠商總進
					U34=cursorGroup.getInt(4);//總銷
					U33=cursorGroup.getInt(5);//本銷
					D_stk=cursorGroup.getInt(1);//店存合計
					M30=cursorGroup.getInt(3);	//門市總進
				   	defU=cursorGroup.getInt(6);	
				   	edtU=cursorGroup.getInt(7);	
				   	StkT=T10-U34;//本期商品尚未售出
				   	AA_stk=T10-U34-D_stk;
					}
				}

 				((TextView)findViewById(R.id.text_stk_t10)).setText("本期總進:"+df.format(T10)+"件 /總共已銷:"+df.format(U34)+"件");
 				((TextView)findViewById(R.id.text_stk_r10)).setText("本期總倉還有:"+df.format(AA_stk)+"件存貨 /本期共銷:"+df.format(U33)+"件");
 				((TextView)findViewById(R.id.text_stk_t30)).setText("本期店面還有:"+df.format(D_stk)+"件未銷");
 				((TextView)findViewById(R.id.text_stk_r30)).setText("本期未銷貨還有:"+df.format(StkT)+"件");  //存
 				
				bufCategory=bufCategory.delete(0, bufCategory.toString().length());
	        		bufCategory .append("select "+CntmSQL+",");
	        		bufCategory.append(sql_A[mGroupMode]);
	        		bufCategory.append(" where DEPTNO<>'"+mDept+"'");
					bufCategory.append(" group by "+sql_A[mGroupMode].substring(1,sql_A[mGroupMode].indexOf(" from")));
					bufCategory.append(" order by sum(UNIT33) desc"); 
					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();
							
							bufCategory=bufCategory.delete(0, bufCategory.toString().length());
			        		bufCategory.append("select "+CntmSQL+",");
			        		bufCategory.append(sql_A[mGroupMode]);
			        		//bufCategory.append(" where DEPTNO='"+mDept+"' and "+sql_D[mGroupMode]+"='"+cursorGroup.getString(CountX)+"'");
			        		if (mGroupMode==GroupMode.TOP2){
			        			bufCategory.append(" where DEPTNO='"+mDept+"'");
			        		}else{
				        		bufCategory.append(" where DEPTNO='"+mDept+"' and "+sql_D[mGroupMode]+"='"+cursorGroup.getString(CountX)+"'");
			        		}
							bufCategory.append(" group by "+sql_A[mGroupMode].substring(1,sql_A[mGroupMode].indexOf(" from"))+" order by GOODSNOS");
							
		 				Cursor cursorAA = db.rawQuery(bufCategory.toString(), null);
						if (cursorAA != null) {
							if (cursorAA.getCount() > 0) {
								//開出第一筆並初始化
								cursorAA.moveToFirst();
								T10=cursorAA.getInt(2);//廠商總進
								AAU34=cursorAA.getInt(4);//總倉總銷
							}else{
								T10=0;AAU34=0;
							}
						}
						cursorAA.close();
							
							U34=cursorGroup.getInt(4);//總銷
							U33=cursorGroup.getInt(5);//本銷							
							D_stk=cursorGroup.getInt(1);//店存合計
							M30=cursorGroup.getInt(3);	//門市總進						
						   	defU=cursorGroup.getInt(6);	
						   	edtU=cursorGroup.getInt(7);	
						   	AA_stk=T10-U34-D_stk;
						   	
							//AASTK,DSTK,UNIT10,UNIT21_20,UNIT34,UNIT33,UNITDEF,UNITEDIT,
							if (mGroupMode==GroupMode.TOP2){
								//DEPTNO
								data.strLeftTop = cursorGroup.getString(CountX)+"/"+DepNa[getDeptIndex("_"+cursorGroup.getString(CountX)+"_")];
								data.strPic = DepPic[getDeptIndex("_"+cursorGroup.getString(CountX)+"_")];
									data.strLeftM="門市總進:"+df.format(M30)+" 件/ 門市已銷"+df.format(U34)+"件";
									StkT=M30-U34;
							}else if (mGroupMode==GroupMode.TOP1){
									//GOODSNO
									data.strLeftTop = cursorGroup.getString(CountX)+"/"+cursorGroup.getString(CountX+1);
									data.strPic=cursorGroup.getString(CountX+2);  //圖片
									data.strLeftM="廠商總進:"+df.format(T10)+" 件/ 總銷"+df.format(U34)+"件";
									StkT=T10-U34;
							}else{//GOODSTYPE,SUPPLY
									data.strLeftTop = cursorGroup.getString(CountX)+"/";
									data.strPic=dfPic;
									data.strLeftM="廠商總進:"+df.format(T10)+" 件/ 總銷"+df.format(U34)+"件";
									StkT=T10-U34;
							}
							
							data.strLeftD="尚未銷:"+df.format(StkT)+" 件/ 店存:"+df.format(D_stk)+" 件";
							if (mGroupMode==GroupMode.TOP2)
								data.strRightTop="本銷:"+df.format(U33)+"件";
							else
								data.strRightTop="本銷:"+df.format(U33)+"件/ 總倉存:"+df.format(AA_stk)+" 件";
							
							data.strRightD="應配:"+df.format(cursorGroup.getInt(6));
							defUT+=cursorGroup.getInt(6);
							
							data.strRightM="擬配:"+df.format(cursorGroup.getInt(7));
							edtUT+=cursorGroup.getInt(7);
							
							data.SEARCH = cursorGroup.getString(CountX);
							
							groups.add(data);
							cursorGroup.moveToNext();
						}					
					}
 				}
				cursorGroup.close();
				

 				if (groups.size() > 0) {  //製作第二層因為進10出20銷30櫃40 件數 金額 預購 
					for (int i = 0; i < groups.size(); i++) {
						String SQL2=" select "+CntmSQL+","+sql_B+" from zadord where DEPTNO<>'"+mDept+"' and ("+sql_D[mGroupMode]+"='"+groups.get(i).SEARCH+"')";
						SQL2+=" group by "+sql_B +" order by GOODSNOS";
						
						//排除總倉
						List<PxData> listData = new ArrayList<PxData>();							
						Cursor cursor2 = db.rawQuery(SQL2, null);
						//商品明細總分析各數據
						if (cursor2 != null) {
							if (cursor2.getCount() > 0) {
								cursor2.moveToFirst();
								for (int x = 0; x < cursor2.getCount(); x++) {
										U34=cursor2.getInt(4);//總銷
										U33=cursor2.getInt(5);//本銷							
										D_stk=cursor2.getInt(1);//店存合計
										M30=cursor2.getInt(3);//門市總進						
									   	defU=cursor2.getInt(6);
									   	edtU=cursor2.getInt(7);
								   	if (U33>0){
										PxData datax= new PxData();
										//String SQLAA="select UNIT10,UNIT34 from zadord where DEPTNO='"+mDept+"' and GOODSNOS='"+cursor2.getString(CountX+1)+"'";
										String SQLAA="select sum(UNIT10),sum(UNIT34),sum(DSTK) from zadord where GOODSNOS='"+cursor2.getString(CountX+1)+"'";
										Cursor cursorAA = db.rawQuery(SQLAA, null);
										T10=0;U34T=0;
										if (cursorAA != null) {
											if (cursorAA.getCount() > 0) {
												cursorAA.moveToFirst();
												T10=cursorAA.getInt(0);
												U34T=cursorAA.getInt(1);
												D_stkT=cursorAA.getInt(2);
											}
										}
										cursorAA.close();
									   	AA_stk=T10-U34T-D_stkT;
										
										//右上_門市本銷
										//左上_明細貨號/品名(色)
										datax.iFormdate=cursor2.getString(CountX+1);
										datax.iTopLeft = cursor2.getString(CountX+1)+"/"+cursor2.getString(CountX+2)+"("+cursor2.getString(CountX+3)+")";
										//左中_門市
										datax.iMidLeft = cursor2.getString(CountX)+"/"+DepNa[getDeptIndex("_"+cursor2.getString(CountX)+"_")];
										datax.iPic = cursor2.getString(CountX+4);
										datax.iDnLeft = "門市總銷:"+df.format(U34)+" 件/ 店存:"+df.format(D_stk)+" 件";
										//左下_門市總銷_店存
	
										datax.iTopRight ="本銷:"+df.format(U33)+"件/ 總倉存:"+df.format(AA_stk)+" 件";
										datax.iMidRight ="應配:"+df.format(defU)+"件";
										datax.iDnRight ="擬配:"+df.format(edtU)+"件";
										
					 					listData.add(datax);
					 					//listData.set(location, datax);
					 					//編輯後,置回
								   	}
									cursor2.moveToNext();
								}	
							}
									
						}
						cursor2.close();
						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);
						//childs.set(location, listData);
	 					//編輯後,置回
					}
 				}
 				db.close();
				mExpandAdapter.setData(groups, childs);
				mExpandAdapter.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);
            	String SerchTop ="";
            	int TopK=mGroupMode;
                
                if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
                	//head
                	GroupData data =mExpandAdapter.groups.get(groupPosition);
            		SerchTop=data.SEARCH;
                }else{//items 
	    			PxData datax;
					datax = mExpandAdapter.getData(groupPosition, childPosition);
					SerchTop=datax.iFormdate;
					if (SerchTop.indexOf("-")>0) SerchTop= SerchTop.substring(0,SerchTop.indexOf("-"));
					TopK=1;
                }                	
 					Utilis.runVibrate(QRep_06.this);
					Bundle bundle = new Bundle();
					Intent intent = new Intent();
					bundle = new Bundle();
					bundle.putString("GalleryChild",SerchTop+";1;"+TopK);
					//主貨號 指1單一貨號0全部 modify 0未異動 1傳回表示有異動
					intent.putExtras(bundle);
					intent.setClass(QRep_06.this, GalleryViewV.class);
					startActivityForResult(intent, RESULT_GVV);
					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(QRep_06.this);
			PxData datax;
				datax = mExpandAdapter.getData(groupPosition, childPosition);
				String GoodsNo=datax.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_06.this, GalleryViewS.class);
					intent.putExtras(bundle);
					startActivity(intent);
				}else {
		        	mDisplayStk.setVisibility(View.VISIBLE);
		    		SQLiteDatabase db = Utilis.getDB(QRep_06.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();
			}
			return false;
		}
	}
	
	
	class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QRep_06.this);
			switch (id) {
				case R.id.btn_stk_exit:
				{
					finish();
					break;
				}
				case R.id.btn_stk_btn0:  //配貨表
				{
 					Utilis.runVibrate(QRep_06.this);
					Bundle bundle = new Bundle();
					Intent intent = new Intent();
					bundle = new Bundle();
					bundle.putString("GalleryChild",";1;0");
					//主貨號 指1單一貨號0全部 modify 0未異動 1傳回表示有異動
					intent.putExtras(bundle);
					intent.setClass(QRep_06.this, GalleryViewV.class);
					startActivityForResult(intent, RESULT_GVV);
					break;
				}
				case R.id.btn_stk_btn2:  //配貨歸零
				{
					String [] Lmenu={"所有擬配歸零@#$%","不要歸零"};
					DialogUtilis.showDialog(QRep_06.this, "請注意,一旦歸零,回不去了", -1,
						Lmenu, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								switch (pos) {
										case 0: //
										{
								    		SQLiteDatabase db = Utilis.getDB(QRep_06.this);
											String zeroUnit33SQL="update zadord set UNITEDIT=0";
											db.execSQL(zeroUnit33SQL);
							    			Toast.makeText(QRep_06.this,"配貨表的擬配已歸零成功!!", Toast.LENGTH_SHORT).show();
											getGroupData(QRep_06.this, null, null);
											break;
										}
										case 1: //不更新 繼續查詢
										{
											break;
										}
									}
								}
				});
					
					break;
				}
					
				case R.id.btn_stk_btn4:  //更新,但須警告
		    		SQLiteDatabase db = Utilis.getDB(QRep_06.this);
		    		int YN=0;
					String chkUnit33SQL="select sum(UNITEDIT) from zadord where FDEPTNO='NEED' ";
					Cursor cst =db.rawQuery(chkUnit33SQL, null);
					if (cst != null && cst.getCount()>0){
						cst.moveToFirst();
						if (cst.getInt(0)!=0) YN=1;
					}
					
						if (YN==0){
							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_06.this, "請輸入交易起算日期", c, new IDateDialog(){
								@Override
								public void onDateDialogFinish(String date, int year, int month, int day) {
				            		bgDate=date.replace("-","/");
				            		enDate=DateUtil.addDate(DateUtil.getCurrentDate(),-1);
						    			Toast.makeText(QRep_06.this,"起算日期已改為:"+bgDate, Toast.LENGTH_SHORT).show();
										startDB();
										//應該重新拜訪 重建 統計
								}
							});
						}else{
			    			Toast.makeText(QRep_06.this,"還有預定配貨資料,無法更新!! 請先配貨歸零!!", Toast.LENGTH_SHORT).show();
						}
					cst.close();
					db.close();
					break;
				case R.id.text_stk_duration:  //可以定義統計庫存的起算日期
				{
					break;
				}
				case R.id.btn_stk_prev_date:  //暢銷排行
				{
					sSort=0;
					getGroupData(QRep_06.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_06.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_06.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_06.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_06.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_06.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(id)).setBackgroundResource(R.drawable.keypad_yellow);
	}

	@SuppressWarnings("unused")
	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 {  
    @SuppressWarnings("unused")
	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_06.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_06.this,textCell.getText().toString());
                	String [] colors=colorN.split(";");
                	if (((i+1) %3)==0){	
                		colStr=textCell.getText().toString();
                		colorN=DBUtil.ColorGetTxt(QRep_06.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);
    }  
}
	
	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 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();
			}
				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_06.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_06.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 void startDB(){
		SQLiteDatabase db = Utilis.getDB(QRep_06.this);
		String SQL="delete from zansly_adord";
		db.execSQL(SQL);
		SQL="delete from zadord";
		db.execSQL(SQL);

		LimitDate=bgDate.replace("/", "-");
		LastDate=enDate.replace("/", "-");
		//CLOUD版 可以在MySQL into file 產生檔案,送回 LOCAL端,再一一寫入
		
		SQL="insert into zansly_adord (DEPTNO,GOODSNO,"+
				"GOODSNOS,GOODSNAME,GOODSTYPE,P1,P3,P5,"+
				"SUPPLY,PIC,SEASON,COUNTRY,COLOR,SIZE,COLORS,SIZES,YEAR,"+
				"ACOST,SUBPRICE,UNIT10,UNIT20,UNIT21,UNIT34,AASTK,DSTK,UNIT21_20)"+
				" 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.UNIT30*a.P1)+sum(a.UNIT40*a.P1),sum(a.UNIT30*a.UNITPRICE*a.DISCOUNT)/100+sum(a.UNIT40*a.UNITPRICE*a.DISCOUNT)/100,sum(a.UNIT10),sum(a.UNIT20),0,sum(a.UNIT30+a.UNIT40),0,0,0"+
				//"sum(a.ACOST),sum(a.SUBPRICE,sum(a.UNIT10),sum(a.UNIT20),0,sum(a.UNIT30+a.UNIT40),0,0,0"+
				// acost ,subprice 這兩個欄位,只能計入銷貨資料
				
				//針對 DEPTNO 而產生的 總倉進貨UNIT10 銷貨UNIT34 門市轉貨轉入(供扣除門市庫存)UNIT21
				//避開總倉出貨不計
				//LimitDate指日期後,有交易的商品為範圍
				//所以取得了總進轉出銷量
				" from qitems as a"+
				" where ((a.QKIND<>'20' and DEPTNO<>'"+deptStr[5]+"') or (a.QKIND<>'21') ) and (a.ISCONFIRM='Y' or (a.ISCHECK='Y' and a.ISCONFIRM<>'R'))"+
				" and DEPTNO in (select CUSTNO from qcust where TR='20')"+
				" and GOODSNO in (select distinct 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);
				//純脆算出UNIT21 各門市 轉貨入庫 總倉出貨各門市
				SQL="insert into zansly_adord (DEPTNO,GOODSNO,"+
						"GOODSNOS,GOODSNAME,GOODSTYPE,P1,P3,P5,"+
						"SUPPLY,PIC,SEASON,COUNTRY,COLOR,SIZE,COLORS,SIZES,YEAR,ACOST,SUBPRICE,"+
						"UNIT10,UNIT20,UNIT21,UNIT34,AASTK,DSTK,UNIT21_20)"+
						" 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,0,0,sum(a.UNIT20),0,0,0,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 distinct 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_adord where UNIT10=0 and UNIT20=0 and UNIT21=0 and UNIT34=0";
						//清除 件數為0
						db.execSQL(SQL);
						
						SQL="update zansly_adord set ACOST=0 where ACOST isnull or ACOST='';";
						db.execSQL(SQL);
						SQL="update zansly_adord set SUBPRICE=0 where SUBPRICE isnull or SUBPRICE='';";
						db.execSQL(SQL);
						SystemClock.sleep(500);
						//20200227
						//還沒用到 DEPTNAME 可以將進(出)貨成本填入10/(21-20)
						SQL="update zansly_adord set DEPTNAME=0,AASTK=0,DSTK=0";
						db.execSQL(SQL);
						SQL="update zansly_adord set PIC=replace(PIC,'//','/')";
						db.execSQL(SQL);
						SQL="update zansly_adord set PIC='"+dfPic+"' where PIC isnull or PIC='' ";
						db.execSQL(SQL);

						SQL="update zansly_adord set DEPTNAME=(UNIT21-UNIT20)*P1 where DEPTNO<>'AA'";
						//門市出轉貨成本
						db.execSQL(SQL);
						SystemClock.sleep(500);
						SQL="update zansly_adord set DEPTNAME=(UNIT10-UNIT20)*P1 where DEPTNO='AA'";
						//總倉進貨(扣除門市出貨)成本
						db.execSQL(SQL);
						
						SQL="update zansly_adord set AASTK=0,DSTK=0,UNIT21_20=0 ";
						db.execSQL(SQL);
						
						SQL="update zansly_adord set AASTK=(UNIT10-UNIT21-UNIT34) where DEPTNO='AA' ";
						db.execSQL(SQL);
						
						SQL="update zansly_adord set DSTK=(UNIT21-UNIT20-UNIT34),UNIT21_20=(UNIT21-UNIT20) where DEPTNO<>'AA' ";
						db.execSQL(SQL);
						
						//@@@增 UNIT10() UNIT21_20
						SQL="insert into zadord (DEPTNO,GOODSNO,GOODSNOS,GOODSNAME,GOODSTYPE,SUPPLY"+
								",COLOR,SIZE,COLORS,SIZES,PIC,AASTK,DSTK,UNIT10,UNIT21_20,UNIT33,UNIT34,FDEPTNO,UNITDEF,UNITEDIT) "+
								"select A.DEPTNO,A.GOODSNO,A.GOODSNOS,A.GOODSNAME,GOODSTYPE,SUPPLY"+
								",A.COLOR,A.SIZE,max(A.COLORS),max(A.SIZES),max(A.PIC),sum(A.AASTK),sum(A.DSTK),sum(UNIT10),sum(UNIT21_20),0,sum(A.UNIT34),"+
								" '',0,0 from zansly_adord as A "+ 
								"group by A.DEPTNO,A.GOODSNO,A.GOODSNOS,A.GOODSNAME,A.GOODSTYPE,A.SUPPLY"+
								",A.COLOR,A.SIZE "+ 
								"having sum(A.UNIT34)>0 or sum(A.DSTK)>0 or sum(A.AASTK)>0 ";
						db.execSQL(SQL);

						//@@@ UNIT33本銷
						SQL="insert into zadord (DEPTNO,GOODSNO,GOODSNOS,GOODSNAME,GOODSTYPE,SUPPLY"+
								",COLOR,SIZE,COLORS,SIZES,PIC,AASTK,DSTK,UNIT10,UNIT21_20,UNIT33,UNIT34,FDEPTNO,UNITDEF,UNITEDIT) "+
								"select A.DEPTNO,A.GOODSNO,A.GOODSNOS,A.GOODSNAME,A.GOODSTYPE,A.SUPPLY"+
								",A.UNIT1,A.SIZE,max(A.COLORS),max(A.SIZES),max(A.PIC),0,0,0,0,"+
								"sum(UNIT30)+sum(UNIT40),0,'NEED',sum(UNIT30)+sum(UNIT40),0 from qitems as A "+
								"where (A.FORMDATE>='"+LimitDate+"' and "+"A.FORMDATE<='"+LastDate+"') "+
								" and (A.ISCONFIRM='Y' or (A.ISCHECK='Y' and A.ISCONFIRM<>'R')) and "+
								"(A.QKIND=30 or A.QKIND=31)  "+  
								"group by A.DEPTNO,A.GOODSNO,A.GOODSNOS,A.GOODSNAME,A.GOODSTYPE,A.SUPPLY"+
								",A.COLOR,A.SIZE "+ 
								"having sum(A.UNIT30+A.UNIT40)>0";

						db.execSQL(SQL);
						
						SQL="update zadord set PIC= (select PIC from qdetail where qdetail.goodsno=zadord.goodsno) ";
						db.execSQL(SQL);
						
						SQL="update zadord set PIC='"+dfPic+"' where PIC isnull or PIC='' ";
						db.execSQL(SQL);


						Cursor csf =db.rawQuery("select FACTNO,FACTNAME,PIC from qfact where FACTNO in (select distinct SUPPLY from zadord) 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";
						}
						csf.close();
						
						db.close();
						
						

						Utilis.putIni(QRep_06.this, "INIH", "ADORD",bgDate,7);
						Utilis.putIni(QRep_06.this, "INIH", "ADORD",enDate,8);
				        mTextDuration.setText(bgDate+" ~ "+enDate);
						getGroupData(QRep_06.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_adord ("+ 
				"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( 12 ),"+
				"PIC            TEXT( 128 ),"+
				"SEASON         VARCHAR( 10 ),"+
				"COUNTRY        VARCHAR( 20 ),"+
				"COLOR          VARCHAR( 8 ),"+
				"SIZE           VARCHAR( 8 ),"+
				"COLORS          VARCHAR( 128 ),"+
				"SIZES           VARCHAR( 128 ),"+
				"YEAR           VARCHAR( 4 ),"+ 
				"ACOST          DOUBLE,"+
				"SUBPRICE       DOUBLE,"+
				"UNIT10         DOUBLE,"+
				"UNIT20         DOUBLE,"+
				"UNIT21         DOUBLE,"+
				"UNIT34         DOUBLE,"+
				"AASTK         DOUBLE,"+
				"DSTK         DOUBLE,"+
				"UNIT21_20         DOUBLE); ";
	
		db_chk.execSQL(SQL_INI);
		
		SQL_INI="CREATE TABLE  IF NOT EXISTS zadord ( "+
				"DEPTNO    VARCHAR( 12 ),"+
				"GOODSNO   VARCHAR( 16 ),"+
				"GOODSNOS  VARCHAR( 20 ),"+
				"GOODSNAME VARCHAR( 20 ),"+
				"GOODSTYPE      VARCHAR( 20 ),"+
				"SUPPLY         VARCHAR( 12 ),"+
				"COLOR     VARCHAR( 10 ),"+
				"SIZE      VARCHAR( 10 ),"+
				"COLORS    VARCHAR( 254 ),"+
				"SIZES     VARCHAR( 128 ),"+
				"PIC       VARCHAR( 512 ),"+
				"AASTK     DOUBLE,"+
				"DSTK      DOUBLE,"+
				"UNIT10    DOUBLE,"+
				"UNIT21_20    DOUBLE,"+
				"UNIT33    DOUBLE,"+
				"UNIT34    DOUBLE,"+
				"FDEPTNO   VARCHAR( 12 ),"+
				"UNITDEF   DOUBLE,"+
				"UNITEDIT  DOUBLE );";
		
		db_chk.execSQL(SQL_INI);
		SQL_INI="create index IF NOT EXISTS ZADORD_D on zadord (DEPTNO)";
		db_chk.execSQL(SQL_INI);
		SQL_INI="create index IF NOT EXISTS ZADORD_G on zadord (GOODSNO)";
		db_chk.execSQL(SQL_INI);
		SQL_INI="create index IF NOT EXISTS ZADORD_GS on zadord (GOODSNOS)";
		db_chk.execSQL(SQL_INI);
		SQL_INI="create index IF NOT EXISTS ZADORD_F on zadord (SUPPLY)";
		db_chk.execSQL(SQL_INI);

		Cursor cs;
		cs=db_chk.rawQuery("select distinct DEPTNO from zansly_adord", null);
		if (cs.getCount()>0){
			exist_db=1;
		}else{
	        bgDate=DateUtil.addDate(DateUtil.getCurrentDate(),-7);
	        enDate=DateUtil.addDate(DateUtil.getCurrentDate(),-1);
	        mTextDuration.setText(bgDate+" ~ "+enDate);
			mYear=Utilis.toInt(enDate.substring(0, 4));
			mMonth=Utilis.toInt(enDate.substring(5, 7));
			mDay=Utilis.toInt(enDate.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);
				//2020/12/03
			DateUtil.showDateDialog(QRep_06.this, "請輸入統計起始日期", c, new IDateDialog(){
				@Override
				public void onDateDialogFinish(String date, int year, int month, int day) {
            		bgDate=date.replace("-", "/");
		    			Toast.makeText(QRep_06.this,"統計起始日期:"+bgDate, Toast.LENGTH_SHORT).show();
						startDB();
						//應該重新拜訪 重建 統計
				}
			});
	        
		}
		cs.close();
		db_chk.close();
		
	    try {
		      File file = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+ "/cwbuyer/para/ini.sdb");
		      SQLiteDatabase db_ini = SQLiteDatabase.openOrCreateDatabase(file, null);
		      String SQL="select _ID from system where _ID='3100' and POINT='3100'";
				Cursor csIni =db_ini.rawQuery(SQL,null);
				if (csIni !=null && csIni.getCount()>0){
				}else{
					ContentValues valueT = new ContentValues();
			    	valueT.put("_ID", "3100");
			    	valueT.put("POINT", "3100");
			    	valueT.put("OBJ", "INIH");
			    	valueT.put("KEY", "ADORD_PARA");
			    	valueT.put("T1", "銷售日從幾天前起算");
			    	valueT.put("T2", "倉存商品最少幾件或以上才要配貨");
			    	valueT.put("T3", "門市商品最少幾件或以下才要配貨");
			    	valueT.put("T4", "門市銷售率最少幾%以上才要配貨");
			    	valueT.put("T5", "最後配貨的門市清單(A1.A2...)");
			    	valueT.put("T6", "是否倉存量>=配貨門市總數才要配貨(Y/N)");
			    	valueT.put("T7", "總進銷存分析起算日");
			    	valueT.put("T8", "最後銷售為止日期");
			    	valueT.put("T9", "保留");
			    	valueT.put("PS", "自動補貨必要的參數設定");
			    	valueT.put("PIC", "");
					db_ini.insert("system", null, valueT);
					
					ContentValues value = new ContentValues();
			    	value.put("_ID", "3101");
			    	value.put("POINT", "3100");
			    	value.put("OBJ", "INIH");
			    	value.put("KEY", "ADORD");
			    	value.put("T1", "7");
			    	value.put("T2", "5");
			    	value.put("T3", "1");
			    	value.put("T4", "50");
			    	value.put("T5", "A1.A2");
			    	value.put("T6", "Y");
			    	value.put("T7", "2020/12/03");
			    	value.put("T8", "2020/12/10");
			    	value.put("T9", "");
			    	value.put("PS", "");
			    	value.put("PIC", "");
					db_ini.insert("system", null, value);
				}
			      db_ini.close();
	    } catch (SQLException e) {
	    } finally {
			adordIni =Utilis.getIni(this,"INIH", "ADORD",9).split("!&!");
	    }	

		//如果雲端版,拜訪 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=adordIni[6];
										enDate=adordIni[7];
								        mTextDuration.setText(bgDate+" ~ "+enDate);
										
										getGroupData(QRep_06.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();
		}	
		
		
	}

}
