package com.cwbuyer.main;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.format.DefaultData;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.ItemData;
import com.cwbuyer.format.KeySet;
import com.cwbuyer.lib.AppUtil;
import com.cwbuyer.lib.AsyncImageFileLoader;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DBUtil;
import com.cwbuyer.lib.DateUtil;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.GalleryView;
import com.cwbuyer.lib.GalleryViewO;
import com.cwbuyer.lib.GalleryViewPic;
import com.cwbuyer.lib.GalleryViewS;
import com.cwbuyer.lib.GalleryViewVP;
import com.cwbuyer.lib.GalleryViewWeb;
import com.cwbuyer.lib.MakeTransDetail;
import com.cwbuyer.lib.PrefKey;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.main.AItem.ItemMode;
import com.pwbuyer.main.R;

@SuppressWarnings("unused")
public class ManageItem extends Activity{
	
	ItemAdapter mAdapter = null;
	ExpandItemAdapter mExpandAdapter = null;
	
	private LinkedList<ItemData> mList = new LinkedList<ItemData>();
	private ArrayList<Integer> mCountryIdList = new ArrayList<Integer>();	
	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<String> mCountryIcon = new ArrayList<String>();
	private ArrayList<String> mTypeList = new ArrayList<String>();
	private ArrayList<Integer> mTypeIdList = new ArrayList<Integer>();
	private DefaultData mDefaultData = null; // 採購參數
	private final int RESULT_AITEM = 1200;
	private final int RESULT_AINCOME = 1201;
	private final int RESULT_GALLERYO=5566; 		//GALLERY
	TextView mTextDuration = null;
//	TextView mTextCount = null;
//	TextView mTextTotal = null;
	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	int nextSwitch=Utilis.toInt(Utilis.getIni(this, "INIH", "SW_REPLUS", 1));
	//nextSwitch上下一批指定門市 0不指定 1指定
	private String[] SysDb = Utilis.getIni(this,"SYS","SDB",9).split("!&!"); 
	private String[] deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");
	int mMode = KeySet.SearchMode.ACTION;
	private int nStates=0;//4全搜 //0配貨結算 1已付自取 2已付未取 3未付未取
	int f123=0;
	private int isOnkey=Utilis.toInt(deptStr[7]);
	private int nPart=0; //0總店 1分店	private int sort=0;  //預設為 0.MID 1.GOODSNO 2
	int mGroupMode = GroupMode.NUMBER;
	private LinkedList<GroupData> mGroupList = new LinkedList<GroupData>();
	
	/** State :  true 正式 , false 樣品*/
	//private boolean mbState = true; 

	String[][] menu_U={
			{ "編輯","本款刪除","(輸出)單筆傳送雲端","瀏覽附圖(單一商品多圖在地端編輯)","補印條碼","網頁附圖編輯輸出","預購留貨清單","只編輯件數","各門市庫存表","返回" },
			{ "編輯","本款刪除","(輸出)單筆傳送雲端","瀏覽附圖(單一商品多圖在地端編輯)","補印條碼","網頁附圖編輯輸出","預購留貨清單","只編輯件數","各門市庫存表","返回" },
			{ "編輯","本款刪除","(輸出)單筆傳送雲端","瀏覽附圖(單一商品多圖在地端編輯)","補印條碼","網頁附圖編輯輸出","預購留貨清單","只編輯件數","各門市庫存表","返回" },
			{ "-------------------","-------------------","裝箱到貨(轉入廠商進貨)","瀏覽附圖(單一商品多圖在地端編輯)","補印條碼","門市配貨(轉入門市出貨)","預購留貨清單","各門市庫存表","返回" }
	};
	
	
	String mEndDay = null;
	String mStartDay = null;
	String mKey = null;
	int isPass=0;
	private int PSWD=Utilis.toInt(deptStr[4]);
	
	public ItemData iData;	
	DatePicker dp1;
	DatePicker dp2;
	private String msFno ="";
	private String batch;
	private String batchPic;
	private int [] getYS={0,2017} ;	
	private String msFdate=DateUtil.getCurrentDateDb(); //預設取得單子的日期
	private int [][] Oinlist; 
	String btn_T[]={"配貨結","付自取","付未取","未付取","全搜"};
	
	private int isNew=0;
	private int mYear1 = 0;
	private int mYear2 = 0;
	private int mMonth1 = 0;
	private int mMonth2 = 0;
	private int mDay1 = 0;
	private int mDay2 = 0;
	
	
	final String file_Rootpath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+	 File.separator + "CWBuyer"  ;
	final String myAlbunPath =file_Rootpath+ File.separator + "ALBUN"+File.separator+"cu_albun.lst";
	final String myImportPath =file_Rootpath+	 File.separator+"IMPORT";	
	ListView mListView = null;
	ExpandableListView mExpandListView = null;
	
	class GroupData{
		public String strPic;
		public String strText0;
		public String strText1;
		public String strText2;
		public String strMoney;
		public String strOriMoney;
		public String search;
		public String strTot1;
	}
	
	interface GroupMode{
		int NUMBER = 0;
		int CATEGORY = 1;
		int COMPANY = 2;
		int INVOICE = 3;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == RESULT_AITEM) {
			if (resultCode == RESULT_OK) {
				String sbatch = data.getStringExtra("item_batch");
				if (!sbatch.equalsIgnoreCase(batch)){
					batch=sbatch;
					getGroupBatchData(this, batch);
				}
				
			}
		}else if (requestCode == RESULT_AINCOME) {
				if (resultCode == RESULT_OK) {
					int total = data.getIntExtra("item_impo", 0);
					// 需避免資料下次傳過去
					String TSIZE = data.getStringExtra("item_size");
					String TCOLOR = data.getStringExtra("item_color");
					String TCOLORNO = data.getStringExtra("item_colorno");
					String TINLIST = data.getStringExtra("item_countlist");
					String [] InListC=TINLIST.split("，");
					String[] Asize=TSIZE.split(","); 
					String[] Acolor=TCOLOR.split("，");
					String[] Acolorno=TCOLORNO.split("，");
					int [][] aList=new int [Acolorno.length][Asize.length];
					int isSame=1;
					for (int xx=0;xx<Acolorno.length;xx++){
						String[] Inlist=InListC[xx].split(",");
						for (int xy=0;xy<Asize.length;xy++){
							aList[xx][xy]=Utilis.toInt(Inlist[xy]);
							if (Oinlist[xx][xy]!=aList[xx][xy]) isSame=0;
						}
					}//已上取得各色尺寸的進貨件數
					if (isNew==1 && total ==0){;}else{
						SQLiteDatabase db = Utilis.getDB(this);
						if (isNew==1 && total !=0){
							msFdate=DateUtil.getCurrentDateDb();
							msFno = Utilis.getNFormno(this,"1");
						}
						if (isNew==0 && isSame==0) db.execSQL("delete from qitems where FORMNO='"+msFno+"' and GOODSNO='"+iData.GoodsNo+"'");
						int inc=0;int Atot=0;
						double Asum=0;
						Cursor cs;
								cs=db.rawQuery("select * from qdetail where BATCH='"+iData.batch+"' and GOODSNO='"+iData.GoodsNo+"'",null);
							if (cs.getCount()>0){
								cs.moveToFirst();
								iData = DBUtil.CItem.parseData(cs, false);
								if (total!=0){
								for (int ji=0;ji<Acolorno.length;ji++){ //逐一讀取顏色代號,顏色名稱
									for (int jk=0;jk<Asize.length;jk++) { //逐一讀取尺寸
										ContentValues value = new ContentValues();
										value.put("TR", "10");
										value.put("ID","10");										
										value.put("QKIND","10" );
										value.put("HANDNO",iData.batch);
										value.put("GOODSNO",iData.GoodsNo);
										value.put("SOURCENO",iData.sourceNo);
										value.put("GOODSNOS",iData.GoodsNo+"-"+Acolorno[ji]+"-"+Asize[jk]);
										//GOODSTYPE須先換回文字
										int gtype = iData.nGoodsType;  //代號需轉換為文字
							        	int index = mTypeIdList.indexOf(gtype);
							        	if(index >= 0){	value.put("GOODSTYPE",mTypeList.get(index));	}
							        	else {
							        		value.put("GOODSTYPE",String.valueOf(iData.nGoodsType));
							        	}																			
										value.put("GOODSNAME",iData.goodsname);
										value.put("COLORS",TCOLOR);
										value.put("SIZES",TSIZE);//去掉前後雙引號
										value.put("COLOR",Acolorno[ji]);
										value.put("SIZE",Asize[jk]);
										value.put("UNIT1",Acolor[ji]);
										value.put("UNIT2",TCOLORNO);
										value.put("UNIT10",aList[ji][jk]);
										value.put("UNIT20",0);
										value.put("UNIT30",0);
										value.put("UNIT40",0);
										value.put("SUPPLY",iData.supply);
										value.put("USER",iData.supply);
										value.put("BATCH",iData.batch);
										value.put("FORMNO",msFno);  
										value.put("RATE",iData.dBillRate);
										value.put("P0",iData.dP0);
										value.put("P1",iData.dP1);
										value.put("P2",iData.dP2);
										value.put("P3",iData.dP3);
										value.put("P4",iData.dP4);
										value.put("P5",iData.dP5);
										value.put("PIC",iData.pic1);
										value.put("SEASON",iData.nSeason);
										int gcountry = iData.nCountry;  //代號需轉換為文字
							        	int cindex = mCountryIdList.indexOf(gcountry);
							        	if(cindex >= 0){	value.put("COUNTRY",mCountryList.get(cindex));}
							        	else {
							        		value.put("COUNTRY",iData.country);
							        	}																			
										value.put("EMPID",iData.nUnit1); //櫃員統計要用 EMPNAME
										value.put("YEAR",iData.nUnit2);
										value.put("CREATEDATETIME",DateUtil.getSystemTime().substring(2,12)); 
										value.put("FORMDATE",msFdate);
										value.put("DISCOUNT",100.0); //預設為100.0折數
										value.put("UNITPRICE",iData.dP0);
										value.put("TRADETYPE","0"); //外幣
										double dSUB=Math.round(iData.dP0*aList[ji][jk]);
										if (f123==0) dSUB=Utilis.dedb(iData.dP0*aList[ji][jk],2);
										value.put("ACOST",dSUB);
										 value.put("SUBPRICE",dSUB);
										value.put("RATEPRICE",dSUB);
										value.put("ISCONFIRM","N");
										value.put("ISCHECK","N");
										value.put("DEPTNO",Utilis.getIni(this,"SYS","DEPT",1));
										long result = db.insert(TbName.QITEMS, null, value);
										//完成了QITEMS存檔後
									}
								}	
							}	
						}
								//製作QHEAD
								//先求出 qitems _total's
								cs=db.rawQuery("select sum(UNIT10),sum(SUBPRICE) from qitems where FORMNO='"+msFno+"' and QKIND='10'",null);
								if (cs.getCount()>0){
									cs.moveToFirst();
									Atot=cs.getInt(0);
									Asum=Math.round(cs.getDouble(1));
								}
								ContentValues value = new ContentValues();
								value.put("TR", "10");
								value.put("ID","10");										
								value.put("QKIND","10" );
								if (Atot>0) value.put("HANDNO","+"+Atot); else value.put("HANDNO","+0"+Atot); 
								//GOODSTYPE須先換回文字
								value.put("USER",iData.supply);
								value.put("FORMNO",msFno);  
								value.put("CREATEDATETIME",DateUtil.getSystemTime().substring(2,12));
								value.put("FORMDATE",msFdate);
								value.put("FINEDATE","");
								value.put("ORDDATE","");
								value.put("TRADETYPE","0"); //外幣			
								value.put("EMPID",iData.nUnit1);
								value.put("EMPNAME",iData.batch);
								value.put("BILLRATE",iData.dBillRate);
								value.put("USER",iData.supply);
								value.put("DEPTNO",Utilis.getIni(this,"SYS","DEPT",1));
								value.put("ATOT",Atot);
								value.put("ASUM",Asum);
								value.put("BSUM",Asum);
								value.put("CASH",0);
								value.put("CARD",0);
								value.put("ORDCASH",0);
								value.put("ORDCARD",0);
								value.put("DISMONEY",0);
								value.put("TURESUM",Asum);
								value.put("COSTS",Asum);
								value.put("ISCONFIRM","N");
								value.put("ISCHECK","N");
								value.put("BANKNO",iData.nCountry);
								value.put("BANKNAME",Utilis.getIni(this,"SYS","DEPT",1)+Utilis.getIni(this,"SYS","DEPT",6));
								
								
								if (isNew==1){ //INSERT
									long result = db.insert(TbName.QHEAD, null, value);
								}else{ //update
									String[] args = {msFno,"10"};
									long result = db.update(TbName.QHEAD, value,"FORMNO=? and QKIND=?", args);
								}
								db.close();
								
								getGroupBatchData(this, batch);
					}
				}
		}else if (requestCode == 1001) {
			if (resultCode == RESULT_OK) {
			}else{
				finish();
			}
		}
    }

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.manage_item);
        
        mTextDuration = (TextView)findViewById(R.id.text_duration);
		batch = AppUtil.getRecentBatch(ManageItem.this);
        if (SysDb[6].equalsIgnoreCase("1")) f123=1; //需要小數位
        
        mMode = getIntent().getIntExtra("search_mode", KeySet.SearchMode.ACTION);
        //@@@目前並未攜入參數
        ((Button)findViewById(R.id.btn_new)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_account)).setOnClickListener(new MainClick());        
        ((Button)findViewById(R.id.btn_sort_cate)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_sort_number)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_sort_company)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_sort_pic)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_sort_invoice)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_prev_date)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_next_date)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_state)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_states)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_fbatch)).setOnClickListener(new MainClick());
        ((TextView)findViewById(R.id.text_duration)).setOnClickListener(new MainClick());
        //btn_fbatch
        if(PSWD==1){
        ((Button)findViewById(R.id.btn_new)).setVisibility(View.INVISIBLE);
        }
        
		isPass=AppUtil.isRegSucceed(this,1);
				
        mExpandListView = (ExpandableListView)findViewById(R.id.list_item_expand);

//        mExpandAdapter = new ExpandItemAdapter(this, groups, childs);
        mExpandAdapter = new ExpandItemAdapter(this);
        if (!deptStr[0].equalsIgnoreCase(deptStr[5])) nPart=1;        
        mExpandListView.setAdapter(mExpandAdapter);
        mExpandListView.setOnChildClickListener(mChildClcik);
        mExpandListView.setOnItemLongClickListener(mLongClickListener);
        
        mListView = (ListView)findViewById(R.id.list_item);
        mAdapter = new ItemAdapter(this);
        mListView.setAdapter(mAdapter);
        
        switch(mMode){
	    	case KeySet.SearchMode.ACTION:
	    	{
	    		mStartDay = Utilis.getRecentDate(this);
				mEndDay = mStartDay;
	        	mKey = "";
	    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_date)).setText("下一批");
	    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_date)).setText("上一批");
	    		break;
	    	}
	    	case KeySet.SearchMode.WEEK:
	    	{
	    		String day = Utilis.getWeekDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
	    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_date)).setText("下一週");
	    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_date)).setText("上一週");
	    		((Button)findViewById(R.id.btn_account)).setVisibility(View.INVISIBLE);	    		
	    		break;
	    	}
	    	case KeySet.SearchMode.MONTH:
	    	{
	    		String day = Utilis.getMonthDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
	    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_date)).setText("下個月");
	    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_date)).setText("上個月");
	    		((Button)findViewById(R.id.btn_account)).setVisibility(View.INVISIBLE);	    		
	    		break;
	    	}
	    	case KeySet.SearchMode.WIDGET:
	    	{
	    		((Button)findViewById(R.id.btn_account)).setVisibility(View.INVISIBLE);
	    		new AlertDialog.Builder(ManageItem.this).setTitle("資料搜尋(起始、結束日期)")
				.setView(makeDateDialog())
				.setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            	String startDay = "" + mYear1 + "/" + Utilis.formatDate(mMonth1) + "/" + Utilis.formatDate(mDay1);
		            	String endDay = "" + mYear2 + "/" + Utilis.formatDate(mMonth2) + "/" + Utilis.formatDate(mDay2);
		            	
		            	mStartDay = startDay;
		            	mEndDay = endDay;
		            	mKey = null;

		            	mTextDuration.setText(getString(R.string.str_duration) + " : " + mStartDay + "~" + mEndDay);
		            	getGroupData(ManageItem.this, mStartDay, mEndDay, null, null);
		            }
		          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            }
		          }).show();
	    		
	    		// 先判斷時間有沒有過 ， 有過的話再判斷密碼
	            try{
	                ProgressDialog mProgress = null;
						if (isPass<6 && isPass!=3 && isPass!=4) { 
	    	        	boolean bIsWidget = getIntent().getBooleanExtra(KeySet.WIDGET, false);
	    	        	if(bIsWidget == true){
	    	        		String pass = Utilis.getStringSet(this, PrefKey.PASSWORD, "");
	    	                if(pass != null && pass.length() > 0){
	    	                	// 啟動密碼保護
	    	                	Intent newIntent = new Intent();
	    	                	newIntent.setClass(this, APassword.class);
	    	                	this.startActivityForResult(newIntent, 1001);
	    	                }

	            	}else{
	        		    mProgress = new ProgressDialog(this);
	        			mProgress.setCancelable(true);
	        			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//	        			mProgress.setMessage(ErrorMsg[isError]);
	        			mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
	        			mProgress.show();
	            	}
	            	}	
	            }catch(Exception e){
	            	e.printStackTrace();
	            }
	    		break;
	    	}
	    	case KeySet.SearchMode.ACCOUNT:
	    	{
	    		((Button)findViewById(R.id.btn_account)).setVisibility(View.INVISIBLE);
	    		final int nAccountId = getIntent().getIntExtra("accountid", 0);
	    		new AlertDialog.Builder(ManageItem.this).setTitle("資料搜尋(起始、結束日期)")
				.setView(makeDateDialog())
				.setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            	String startDay = "" + mYear1 + "/" + Utilis.formatDate(mMonth1) + "/" + Utilis.formatDate(mDay1);
		            	String endDay = "" + mYear2 + "/" + Utilis.formatDate(mMonth2) + "/" + Utilis.formatDate(mDay2);
		            	
		            	mStartDay = startDay;
		            	mEndDay = endDay;
		            	mKey = null;
		            	
		            	mTextDuration.setText(getString(R.string.str_duration) + " : " + mStartDay + "~" + mEndDay);
		            	getGroupData(ManageItem.this, mStartDay, mEndDay, "account", String.valueOf(nAccountId));
		            }
		          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            }
		          }).show();
	    		break;
	    	}
        }
        
        setCondition();
        
        resetButton(R.id.btn_sort_number);
		mGroupMode = GroupMode.NUMBER;
		mListView.setVisibility(View.GONE);
		mExpandListView.setVisibility(View.VISIBLE);
		mExpandListView.setOnChildClickListener(mChildClcik);
		mExpandAdapter.notifyDataSetChanged();
		
    }
	
	public void onResume(){
		super.onResume();
		getCountryData(this);
		getTypeData(this);
		getDefaultData();  //呼叫時,一定要放在 getCountryData(this) 之後 否則 error
		
		DBCloud.aa0_aa1_auto_qdetail_n(this);
		SystemClock.sleep(500);
//		DBCloud.aa0_aa1_auto_HI(this,30);
		//雲端須要進行 DOWNLOAD_CHK  有網路的狀態 && nline  && auto_update下
		
		// getRecent  要特別處理
		if(mMode != KeySet.SearchMode.WIDGET && mMode != KeySet.SearchMode.ACCOUNT){
			getGroupData(ManageItem.this, mStartDay, mEndDay, null, null);
			/*
			int count =  mExpandAdapter.getGroupCount(); 
			for (int i = 0; i <count ; i++) 
				mExpandListView.collapseGroup(i); 
			mExpandAdapter.notifyDataSetChanged();
			*/
		}
	}
	
	private void setCondition(){
    	switch(mMode){
    	
    	case KeySet.SearchMode.ACTION:
    	{
    		mTextDuration.setText("批號 : " + batch);
	    	break;
    	}
			case KeySet.SearchMode.WEEK:
			{
				mTextDuration.setText(getString(R.string.str_duration) + " : " + mStartDay + "~" + mEndDay);
				break;
			}
			case KeySet.SearchMode.MONTH:
			{
				mTextDuration.setText(getString(R.string.str_duration) + " : " + mStartDay + "~" + mEndDay);
				break;
			}
			default:
			{
//				mAdapter.getAllData(this);
		    	mTextDuration.setText(getString(R.string.str_duration) + " : " + getString(R.string.str_nolimit));
//		    	mTextCondition.setText(getString(R.string.str_condition) + " : " + getString(R.string.str_depend_date));
				break;
			}
    	}
	}
	
	// 需在加上時間的參數
	// 可能需要再加上 Account 參數!
	public void getGroupData(Context context, String startDay, String endDay, String condition, String conditionValue) {

		//invoice
		
		// 特別處理 Batch
		if ( mMode == KeySet.SearchMode.ACTION ) {
			if(batch != null && batch.length() > 0){
				// 直接搜尋批號
				getGroupBatchData(context, batch);
				return;
			}
		}
		
		//int nState = mbState == true ? 0 : 1; // 0 正式 1 樣品
		if(startDay != null && startDay.length() > 0){
			startDay = startDay.replace("/", "-");
		}
		if(endDay != null && endDay.length() > 0){
			endDay = endDay.replace("/", "-");
		}
		
		LinkedList<GroupData> groups = new LinkedList<GroupData>();
		LinkedList<List<ItemData>> childs = new LinkedList<List<ItemData>>();
		if (mGroupList != null) {
			mGroupList.clear();
		}
		SQLiteDatabase db = Utilis.getDB(context);
		try {
			Cursor cursorGroup = null;
			Cursor cursor = null;
			StringBuffer bufCategory = new StringBuffer();
			if(mGroupMode == GroupMode.NUMBER){
				bufCategory.append("select distinct BATCH from qdetail");
				bufCategory.append(" where CREATEDATETIME >= '").append(startDay).append("'")
			    .append(" and CREATEDATETIME <= '").append(endDay).append("'");
				bufCategory.append(getStates(0));
			}else if(mGroupMode == GroupMode.CATEGORY){
				bufCategory.append("select distinct A.GOODSTYPE,B.GOODTYPE,B.PIC from qdetail A left join qc_type B on A.GOODSTYPE=B._id ");
				bufCategory.append(" where A.CREATEDATETIME >= '").append(startDay).append("'")
			    .append(" and A.CREATEDATETIME <= '").append(endDay).append("'");
				bufCategory.append(getStates(1));
			}else if(mGroupMode == GroupMode.COMPANY){
				bufCategory.append("select distinct A.SUPPLY,B.PIC,B.FACTNAME,B.MOBIL from qdetail A left join qfact B on A.SUPPLY=B.FACTNO");
				bufCategory.append(" where A.CREATEDATETIME >= '").append(startDay).append("'")
			    .append(" and A.CREATEDATETIME <= '").append(endDay).append("'");
				bufCategory.append(getStates(1));
			} else if(mGroupMode == GroupMode.INVOICE){ // 採購進貨表
				bufCategory.append("select distinct GOODSNO,GOODSNAME,PIC from qdetail");
				bufCategory.append(" where CREATEDATETIME >= '").append(startDay).append("'")
			    .append(" and CREATEDATETIME <= '").append(endDay).append("'");
				bufCategory.append(getStates(0));
			}
			
			if(condition != null && condition.length() > 0){
				bufCategory.append(" and ").append(condition).append("=").append(conditionValue);
			}
			if(mGroupMode == GroupMode.NUMBER){
				bufCategory.append(" order by BATCH DESC, GOODSNO ");
			}else if(mGroupMode == GroupMode.CATEGORY){
				bufCategory.append(" order by B.GOODTYPE, A.GOODSNO ");
			}else if(mGroupMode == GroupMode.COMPANY){
				bufCategory.append(" order by A.SUPPLY , A.GOODSNO ");
			} else if(mGroupMode == GroupMode.INVOICE){ // 採購進貨表
				bufCategory.append(" order by GOODSNO 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();
						if(mGroupMode == GroupMode.NUMBER){
							// 沒有圖片
							data.search = cursorGroup.getString(0);
							data.strText1 = data.search;
						}else if(mGroupMode == GroupMode.CATEGORY){
							data.search = cursorGroup.getString(0);
							data.strText1 =  cursorGroup.getString(1);;
							data.strPic = cursorGroup.getString(2);
						}else if(mGroupMode == GroupMode.COMPANY){
							data.search = cursorGroup.getString(0);
							data.strText1 = cursorGroup.getString(0);
							data.strPic = cursorGroup.getString(1);
							data.strText0 = cursorGroup.getString(2)+"/"+cursorGroup.getString(3);
						}else if(mGroupMode == GroupMode.INVOICE){
							data.search = cursorGroup.getString(0);
							data.strText1 = cursorGroup.getString(0);
							data.strText0 = cursorGroup.getString(1);
							data.strPic = cursorGroup.getString(2);
						}
						{
							// 計算數量
							Cursor countCursor = null;
							StringBuffer bufCount = new StringBuffer();
							bufCount.append("select count(*),sum(IMPO) from qdetail where");
							if(mGroupMode == GroupMode.NUMBER){
								bufCount.append(" BATCH='").append(data.search+"'");
							}else if(mGroupMode == GroupMode.CATEGORY){
								bufCount.append(" GOODSTYPE=").append(data.search);
							}else if(mGroupMode == GroupMode.COMPANY){// GroupMode.COMPANY
								bufCount.append(" SUPPLY ='").append(data.search).append("'");
							}else if(mGroupMode == GroupMode.INVOICE){// GroupMode.COMPANY
								bufCount.append(" GOODSNO='").append(data.search).append("'");
							}
							bufCount.append(" and CREATEDATETIME >= '").append(startDay).append("'")
								    .append(" and CREATEDATETIME <= '").append(endDay).append("'");
							bufCount.append(getStates(0));
							if(condition != null && condition.length() > 0){
								bufCount.append(" and ").append(condition).append("=").append(conditionValue);
							}
							countCursor = db.rawQuery(bufCount.toString(), null);
							if(countCursor != null){
								countCursor.moveToFirst();
								data.strText2 = String.valueOf(countCursor.getInt(0));
								if(mGroupMode != GroupMode.INVOICE){
									data.strTot1= "共:("+String.valueOf(countCursor.getInt(0))+")款"+String.valueOf(countCursor.getInt(1))+"件" ;//"共("+ ")款"
								}else{
									data.strTot1= "共:("+String.valueOf(countCursor.getInt(0))+")批"+String.valueOf(countCursor.getInt(1))+"件" ;//"共("+ ")款"
								}
/* 
									// 可以取得該批號 已到貨YN或暫存單
				    				Cursor csi= db.rawQuery("select ISCONFIRM,sum(UNIT10) from qitems where GOODSNO='"+data.search+"' and QKIND='10' and FORMDATE >= '"+startDay+"' and FORMDATE <= '"+endDay+"' group by ISCONFIRM",null);
				    				int itemUnit10=0;int itemUnit11=0;
				    				if (csi.getCount()>0){
				    					while (csi.moveToNext()){
					    					if (csi.getString(0)!=null && csi.getString(0).equalsIgnoreCase("Y"))
					    						itemUnit10+=csi.getInt(1);
					    					else 
					    						itemUnit11+=csi.getInt(1);
				    					}
				    				}
				    				csi.close();
									data.strTot1= "共:"+String.valueOf(countCursor.getInt(0))+"批(訂"+String.valueOf(countCursor.getInt(1))+")(已到"+String.valueOf(itemUnit10)+")(擬配"+String.valueOf(itemUnit11)+")" ;
									
								}
*/								
								countCursor.close();
								countCursor = null;
							}
							// 計算每一個 Group 的總數需要一個一個計算了 寫個 Function
							Cursor tCur = null;
							StringBuffer bufMoney = new StringBuffer();
							bufMoney.append("select P0,P1,IMPO from qdetail where");
							
							if(mGroupMode == GroupMode.NUMBER){
								bufMoney.append(" BATCH='").append(data.search+"'");
								bufMoney.append(" and CREATEDATETIME >= '").append(startDay).append("'")
								.append(" and CREATEDATETIME <= '").append(endDay).append("'");
								
							}else if(mGroupMode == GroupMode.CATEGORY){
								bufMoney.append(" GOODSTYPE=").append(data.search);
								bufMoney.append(" and CREATEDATETIME >= '").append(startDay).append("'")
								.append(" and CREATEDATETIME <= '").append(endDay).append("'");
								
							}else if(mGroupMode == GroupMode.COMPANY){// GroupMode.COMPANY
								// 2012/08/27  Fix  廠商編號會搜尋到旁邊的值如  KOE1001  >  KOE10012
								bufMoney.append(" SUPPLY ='").append(data.search).append("'");
								bufMoney.append(" and CREATEDATETIME >= '").append(startDay).append("'")
								.append(" and CREATEDATETIME <= '").append(endDay).append("'");
								
							}else if(mGroupMode == GroupMode.INVOICE){
								// 2012/08/27  Fix  廠商編號會搜尋到旁邊的值如  KOE1001  >  KOE10012
								bufMoney.append(" GOODSNO='").append(data.search).append("'");
							}
							if(condition != null && condition.length() > 0){
								bufMoney.append(" and ").append(condition).append("=").append(conditionValue);
							}
							bufMoney.append(getStates(0));
							tCur = db.rawQuery(bufMoney.toString(), null);
							double nTotal = 0;
							double nOriTotal = 0;
							int nImpo = 0;
							java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
							if(tCur != null){
								if(tCur.getCount() > 0){
									tCur.moveToFirst();
									for(int x = 0; x < tCur.getCount(); x++){
										nImpo = tCur.getInt(2);
										nOriTotal += (tCur.getDouble(0) * nImpo);
										nTotal += (tCur.getDouble(1) * nImpo);
										tCur.moveToNext();
									}
								}
								tCur.close();
							}
							if (mGroupMode != GroupMode.INVOICE){
								data.strOriMoney = "合計外幣:"+myformat.format(nOriTotal);  // 原幣
								data.strMoney ="合計台幣:"+myformat.format(nTotal); // 
							}else{
			    				Cursor csi= db.rawQuery("select ISCONFIRM,sum(UNIT10),sum(UNIT30),sum(UNIT40) from qitems where GOODSNO='"+data.search+"' group by ISCONFIRM",null);
			    				if (csi.getCount()>0){
				    				int itemUnit10=0;int itemUnit30=0;int itemUnit31=0;
				    				if (csi.getCount()>0){
				    					while (csi.moveToNext()){
				    						itemUnit10+=csi.getInt(1);
					    					if (csi.getString(0)!=null && csi.getString(0).equalsIgnoreCase("Y"))
					    						itemUnit30+=csi.getInt(2)+csi.getInt(3);
					    					else 
					    						itemUnit31+=csi.getInt(2)+csi.getInt(3);
				    					}
				    				}
				    				csi.close();
			    					data.strOriMoney ="總訂:"+nImpo+"到貨("+itemUnit10+")"; // 總訂總進
			    					data.strMoney = "總銷:"+itemUnit30+"客訂:"+itemUnit31;
			    				}else{
			    					data.strOriMoney ="總訂:"+nImpo; // 總訂總進
			    					data.strMoney = "合計外幣:"+myformat.format(nOriTotal);  // 原幣		
			    				}
							}
						}
						if(Utilis.toInt(data.strText2) > 0){
							groups.add(data);
						}
						cursorGroup.moveToNext();
					}
				}
				if (groups.size() > 0) {
					StringBuffer bufList = new StringBuffer();
					for (int i = 0; i < groups.size(); i++) {
						if(bufList.length() > 0){
							bufList.delete(0, bufList.length());
						}
						bufList.append("select B.Name,A.* from qdetail A left join qc_country B on A.COUNTRY=B._ID");
						
						if(mGroupMode == GroupMode.NUMBER){
							bufList.append(" WHERE A.BATCH='").append(groups.get(i).search+"'");
						}else if(mGroupMode == GroupMode.CATEGORY){
							bufList.append(" WHERE A.GOODSTYPE=").append(groups.get(i).search);
						}else if(mGroupMode == GroupMode.COMPANY){
							bufList.append(" WHERE A.SUPPLY ='").append(groups.get(i).search).append("'");
						}else if(mGroupMode == GroupMode.INVOICE){
							bufList.append(" WHERE A.GOODSNO='").append(groups.get(i).search+"'");
						}
						
						bufList.append(" and A.CREATEDATETIME >= '").append(startDay).append("'")
							.append(" and A.CREATEDATETIME <= '").append(endDay).append("'");
						bufList.append(getStates(1));
						
							if(condition != null && condition.length() > 0){
								bufList.append(" and ").append(condition).append("=").append(conditionValue);
							}
						bufList.append(" order by A.GOODSNO ");
						
						cursor = db.rawQuery(bufList.toString(), null);
						List<ItemData> listData = new ArrayList<ItemData>();
						if (cursor != null) {
							if (cursor.getCount() > 0) {
								cursor.moveToFirst();
								for (int k = 0; k < cursor.getCount(); k++) {
									iData = DBUtil.CItem.parseData(cursor, true);
									if(mGroupMode != GroupMode.INVOICE){
										listData.add(iData);
									}else{//訂單進貨比較表
										String [] ColNa=iData.mColors.split("，");
										String [] ColNo=iData.mColorsNo.split("，");
										String [] SizNo=iData.mSizes.split(",");
						        		String [] numberLevel1=iData.mCountList.split("，");
							        	for(int nRow = 0; nRow < ColNo.length; nRow++){
						    				String [] numberLevel2=numberLevel1[nRow].split(",");
							    			for(int ij = 0 ; ij < SizNo.length; ij++){
							    				iData = DBUtil.CItem.parseData(cursor, true);
							    				String aGoodsnos=iData.GoodsNo+"-"+ColNo[nRow]+"-"+SizNo[ij];
							    				Cursor csi= db.rawQuery("select sum(UNIT10) from qitems where HANDNO='"+iData.batch+"' and GOODSNOS='"+aGoodsnos+"'",null);
							    				int itemUnit10=0;
							    				if (csi.getCount()>0) {
							    					csi.moveToFirst();
							    					itemUnit10=csi.getInt(0);
							    				}
							    				csi.close();
							    				iData.goodsname=ColNo[nRow]+"-"+SizNo[ij];
							    				iData.country=ColNa[nRow];
							    				iData.sourceNo="("+String.valueOf(iData.batch)+")";
							    				iData.nTotalCount=Utilis.toInt(numberLevel2[ij]);
							    				iData.pic2=String.valueOf(itemUnit10);
							    				iData.supply=String.valueOf(iData.nTotalCount-itemUnit10);
												listData.add(iData);
							    			}
							        	}
									}
									cursor.moveToNext();
								}
								childs.add(listData);
							}
							cursor.close();
						}
					}
				}
			}
			if(groups != null && groups.size() > 0 && childs != null && childs.size() > 0){
				mExpandAdapter.setData(groups, childs);
				mExpandAdapter.notifyDataSetChanged();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(groups != null && childs != null && groups.size() <= 0 && childs.size() <=0){
			mExpandAdapter.setData(groups, childs);
			mExpandAdapter.notifyDataSetChanged();
		}
		db.close();
		db = null;
	}
	
	
	// 可能需要再加上 Account 參數!
		public void getGroupBatchData(Context context, String batch) {
			//int nState = mbState == true ? 0 : 1; // 0 正式 1 樣品
			
			LinkedList<GroupData> groups = new LinkedList<GroupData>();
			LinkedList<List<ItemData>> childs = new LinkedList<List<ItemData>>();
			if (mGroupList != null) {
				mGroupList.clear();
			}
			
			SQLiteDatabase db = Utilis.getDB(context);
			try {
				Cursor cursorGroup = null;
				Cursor cursor = null;
				StringBuffer bufCategory = new StringBuffer();
				if(mGroupMode == GroupMode.NUMBER){
					bufCategory.append("select distinct BATCH from qdetail");
					bufCategory.append(" where BATCH='" + batch+"'");
					bufCategory.append(getStates(0));
					
				}else if(mGroupMode == GroupMode.CATEGORY){
					bufCategory.append("select distinct A.GOODSTYPE,B.GOODTYPE,B.PIC from qdetail A left join qc_type B on A.GOODSTYPE=B._id ");
					bufCategory.append(" where BATCH='" + batch+"'");
					bufCategory.append(getStates(1));
					bufCategory.append(" order by B.GOODTYPE, A.GOODSNO ");
				}else if(mGroupMode == GroupMode.COMPANY){ // GroupMode.COMPANY
					bufCategory.append("select distinct A.SUPPLY,B.PIC,B.FACTNAME,B.MOBIL from qdetail A left join qfact B on A.SUPPLY=B.FACTNO");
					bufCategory.append(" where BATCH='" + batch+"'");
					bufCategory.append(getStates(1));
					bufCategory.append(" order by A.SUPPLY , A.GOODSNO ");
				}else if(mGroupMode == GroupMode.INVOICE){
					bufCategory.append("select distinct GOODSNO,GOODSNAME,PIC from qdetail");
					bufCategory.append(" where BATCH='" + batch+"'");
					bufCategory.append(getStates(0));
					bufCategory.append(" order by GOODSNO 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();
							if(mGroupMode == GroupMode.NUMBER){
								// 沒有圖片
								data.search = cursorGroup.getString(0);
								data.strText1 = data.search;
							}else if(mGroupMode == GroupMode.CATEGORY){
								data.search = cursorGroup.getString(0);
								data.strText1 =  cursorGroup.getString(1);
								data.strPic = cursorGroup.getString(2);
							}else if(mGroupMode == GroupMode.COMPANY){// GroupMode.COMPANY
								data.search = cursorGroup.getString(0);
								data.strText1 = cursorGroup.getString(0);
								data.strPic = cursorGroup.getString(1);
								data.strText0 = cursorGroup.getString(2)+"/"+cursorGroup.getString(3);
							}else if(mGroupMode == GroupMode.INVOICE){
								data.search = cursorGroup.getString(0);
								data.strText1 = cursorGroup.getString(0);
								data.strText0 = cursorGroup.getString(1);
								data.strPic = cursorGroup.getString(2);
							}
								// 計算數量
								Cursor countCursor = null;
								StringBuffer bufCount = new StringBuffer();
								bufCount.append("select count(*),sum(IMPO) from qdetail where");
								if(mGroupMode == GroupMode.NUMBER){//依批號
								}else if(mGroupMode == GroupMode.CATEGORY){//依類別
									bufCount.append(" GOODSTYPE=").append(data.search).append(" and ");
								}else if(mGroupMode == GroupMode.COMPANY){//依廠商
									bufCount.append(" SUPPLY ='").append(data.search).append("'").append(" and ");
								}else if(mGroupMode == GroupMode.INVOICE){//依批號的所有商品
									bufCount.append(" GOODSNO='").append(data.search).append("'").append(" and ");
								}
								bufCount.append(" BATCH='" + batch+"'");
								bufCount.append(getStates(0));
								
								countCursor = db.rawQuery(bufCount.toString(), null);
								if(countCursor != null){
									countCursor.moveToFirst();
									data.strText2 = String.valueOf(countCursor.getInt(0));
									if(mGroupMode != GroupMode.INVOICE){
										data.strTot1= "共:("+String.valueOf(countCursor.getInt(0))+")款"+String.valueOf(countCursor.getInt(1))+"件" ;//"共("+ ")款"
									}else{
					    				Cursor csi= db.rawQuery("select ISCONFIRM,sum(UNIT10) from qitems where HANDNO='"+batch+"' and GOODSNO='"+data.search+"' group by ISCONFIRM",null);
					    				
					    				int itemUnit10=0;int itemUnit11=0;
					    				if (csi.getCount()>0){
					    					while (csi.moveToNext()){
						    					if (csi.getString(0)!=null && csi.getString(0).equalsIgnoreCase("Y"))
						    						itemUnit10+=csi.getInt(1);
						    					else 
						    						itemUnit11+=csi.getInt(1);
					    					}
					    				}
					    				csi.close();
										data.strTot1= "共:"+String.valueOf(countCursor.getInt(0))+"批(訂"+String.valueOf(countCursor.getInt(1))+")(已到"+String.valueOf(itemUnit10)+")(擬到"+String.valueOf(itemUnit11)+")" ;
									}
									countCursor.close();
									countCursor = null;
								}
								// 計算每一個 Group 的總數需要一個一個計算了 寫個 Function
								Cursor tCur = null;
								StringBuffer bufMoney = new StringBuffer();
								bufMoney.append("select P0,P1,IMPO from qdetail where");
								if(mGroupMode == GroupMode.NUMBER){
									bufMoney.append(" BATCH='").append(batch+"'");
								}else if(mGroupMode == GroupMode.CATEGORY){
									bufMoney.append(" GOODSTYPE=").append(data.search).append(" and ");
									bufMoney.append(" BATCH='").append(batch+"'");
								}else if(mGroupMode == GroupMode.COMPANY){//依廠商
									// 2012/08/27  Fix  廠商編號會搜尋到旁邊的值如  KOE1001  >  KOE10012
									bufMoney.append(" SUPPLY ='").append(data.search).append("'").append(" and ");
									bufMoney.append(" BATCH='").append(batch+"'");
								}else if(mGroupMode == GroupMode.INVOICE){
									// 2012/08/27  Fix  廠商編號會搜尋到旁邊的值如  KOE1001  >  KOE10012
									bufMoney.append(" GOODSNO='").append(data.search).append("'");
								}
								bufMoney.append(getStates(0));
								
								tCur = db.rawQuery(bufMoney.toString(), null);
								double nTotal = 0;
								double nOriTotal = 0;
								int nImpo = 0;
								
								java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
								if(tCur != null){
									if(tCur.getCount() > 0){
										tCur.moveToFirst();
										for(int x = 0; x < tCur.getCount(); x++){
											nImpo = tCur.getInt(2);
											nOriTotal += (tCur.getDouble(0) * nImpo);
											nTotal += (tCur.getDouble(1) * nImpo);
											tCur.moveToNext();
										}
									}
									tCur.close();
								}
								if (mGroupMode != GroupMode.INVOICE){
									data.strOriMoney = "合計外幣:"+myformat.format(nOriTotal);  // 原幣
									data.strMoney ="合計台幣:"+myformat.format(nTotal); // 
								}else{
				    				Cursor csi= db.rawQuery("select ISCONFIRM,sum(UNIT10),sum(UNIT30),sum(UNIT40) from qitems where GOODSNO='"+data.search+"' group by ISCONFIRM",null);
				    				if (csi.getCount()>0){
					    				int itemUnit10=0;int itemUnit30=0;int itemUnit31=0;
					    				if (csi.getCount()>0){
					    					while (csi.moveToNext()){
					    						itemUnit10+=csi.getInt(1);
						    					if (csi.getString(0)!=null && csi.getString(0).equalsIgnoreCase("Y"))
						    						itemUnit30+=csi.getInt(2)+csi.getInt(3);
						    					else 
						    						itemUnit31+=csi.getInt(2)+csi.getInt(3);
					    					}
					    				}
					    				csi.close();
				    					data.strOriMoney ="總訂:"+nImpo+"到貨("+itemUnit10+")"; // 總訂總進
				    					data.strMoney = "總銷:"+itemUnit30+"客訂:"+itemUnit31;
				    				}else{
				    					data.strOriMoney ="總訂:"+nImpo; // 總訂總進
				    					data.strMoney = "合計外幣:"+myformat.format(nOriTotal);  // 原幣		
				    				}
								}
								
							if(Utilis.toInt(data.strText2) > 0){
								groups.add(data);
							}
							cursorGroup.moveToNext();
						}
					}
					if (groups.size() > 0) {
						StringBuffer bufList = new StringBuffer();
						for (int i = 0; i < groups.size(); i++) {
							if(bufList.length() > 0){
								bufList.delete(0, bufList.length());
							}
							bufList.append("select B.Name,A.* from qdetail A left join qc_country B on A.COUNTRY=B._ID WHERE");
							if(mGroupMode == GroupMode.NUMBER){
								
							}else if(mGroupMode == GroupMode.CATEGORY){
								bufList.append(" A.GOODSTYPE=").append(groups.get(i).search).append(" and ");
							}else if(mGroupMode == GroupMode.COMPANY){// GroupMode.COMPANY
								// 2012/08/27  Fix  廠商編號會搜尋到旁邊的值如  KOE1001  >  KOE10012
								bufList.append(" A.SUPPLY = '").append(groups.get(i).search).append("'").append(" and ");
							}else if(mGroupMode == GroupMode.INVOICE){								
								bufList.append(" A.GOODSNO='").append(groups.get(i).search+"'").append(" and ");
							}
							bufList.append(" A.BATCH='" + batch+"'");
							
							bufList.append(getStates(1));
							
							if(mGroupMode == GroupMode.NUMBER)
								if (SysDb[4].equalsIgnoreCase("1"))					
									bufList.append(" order by GOODSNO DESC");
								else if (SysDb[4].equalsIgnoreCase("2"))
									bufList.append(" order by SOURCENO DESC");
								else
									bufList.append(" order by MID DESC");
							else
								bufList.append(" order by A.GOODSNO");
							
							cursor = db.rawQuery(bufList.toString(), null);
							List<ItemData> listData = new ArrayList<ItemData>();
							if (cursor != null) {
								if (cursor.getCount() > 0) {
									cursor.moveToFirst();
									for (int k = 0; k < cursor.getCount(); k++) {
										iData = DBUtil.CItem.parseData(cursor, true);
											if(mGroupMode != GroupMode.INVOICE){
												listData.add(iData);
											}else{//訂單進貨比較表
												String [] ColNa=iData.mColors.split("，");
												String [] ColNo=iData.mColorsNo.split("，");
												String [] SizNo=iData.mSizes.split(",");
								        		String [] numberLevel1=iData.mCountList.split("，");
									        	for(int nRow = 0; nRow < ColNo.length; nRow++){
								    				String [] numberLevel2=numberLevel1[nRow].split(",");
									    			for(int ij = 0 ; ij < SizNo.length; ij++){
									    				iData = DBUtil.CItem.parseData(cursor, true);
									    				String aGoodsnos=iData.GoodsNo+"-"+ColNo[nRow]+"-"+SizNo[ij];
									    				Cursor csi= db.rawQuery("select sum(UNIT10) from qitems where HANDNO='"+iData.batch+"' and GOODSNOS='"+aGoodsnos+"'",null);
									    				int itemUnit10=0;
									    				if (csi.getCount()>0) {
									    					csi.moveToFirst();
									    					itemUnit10=csi.getInt(0);
									    				}
									    				csi.close();
									    				iData.goodsname=ColNo[nRow]+"-"+SizNo[ij];
									    				iData.country=ColNa[nRow];
									    				iData.sourceNo="("+String.valueOf(iData.batch)+")";
									    				iData.nTotalCount=Utilis.toInt(numberLevel2[ij]);
									    				iData.pic2=String.valueOf(itemUnit10);
									    				iData.supply=String.valueOf(iData.nTotalCount-itemUnit10);
														listData.add(iData);
									    			}
									        	}
											}
										cursor.moveToNext();
									}
									childs.add(listData);
								}
								cursor.close();
							}
						}
					}
				}
				if(groups != null && groups.size() > 0 && childs != null && childs.size() > 0){
					mExpandAdapter.setData(groups, childs);
					mExpandAdapter.notifyDataSetChanged();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(groups != null && childs != null && groups.size() <= 0 && childs.size() <=0){
				mExpandAdapter.setData(groups, childs);
				mExpandAdapter.notifyDataSetChanged();
			}
			db.close();
			db = null;
		}
	
	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(ManageItem.this);
			DialogUtilis.showDialog(ManageItem.this, "請選擇以下功能", -1,
					menu_U[mGroupMode], new IDialog() {
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch (pos) {
								case 0: // 編輯資料
								{
								if (mGroupMode != GroupMode.INVOICE){
										if (isPass<6 && isPass!=3 && isPass!=4) { 
										if(PSWD!=1){
											iData = mExpandAdapter.getData(groupPosition, childPosition);
											Intent intent = new Intent();
											intent.setClass(ManageItem.this,AItem.class);
											intent.putExtra("item_mode", AItem.ItemMode.EDIT);
											intent.putExtra("item_mid", iData.nMid);
											intent.putExtra("item_from", 0);//0.ManagerItem 1.GalleryView
											startActivity(intent);
										}else{
											Toast.makeText(ManageItem.this, "請注意權限!!", Toast.LENGTH_SHORT).show();
										}
									} else {
										ProgressDialog mProgress = null;
					        		    mProgress = new ProgressDialog(ManageItem.this);
					        			mProgress.setCancelable(true);
					        			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	//				        			mProgress.setMessage(ErrorMsg[isError]);
					        			mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
					        			mProgress.show();
	
									}
								}
									break;
								}
								case 1:
								{
									if(PSWD!=1 && menu_U[mGroupMode][pos].indexOf("----")<0){
										DialogUtilis.showDialog(ManageItem.this, "確定刪除?", -1,
											new String[] { "取消", "刪除" }, new IDialog() {
												@Override
												public void onDialogFinish(int pos, String choice) {
													switch (pos) {
													case 0: {break;}
													case 1: // 確定刪除
													{
															try{
																iData = mExpandAdapter.getData(groupPosition, childPosition);
																SQLiteDatabase db = Utilis.getDB(ManageItem.this);
																String delSQL="delete from qdetail where GOODSNO='" + iData.GoodsNo+"' and  BATCH='"+iData.batch+"' and MID='"+iData.nMid+"'";
																delSQL+=getStates(0);
																db.execSQL(delSQL);
																Toast.makeText(ManageItem.this, "刪除資料成功", Toast.LENGTH_SHORT)
																.show();
																//@@ delete 雲端 qdetail
																db.close();
//																更新資料
																getGroupData(ManageItem.this, mStartDay, mEndDay, null, null);
																/*
																	int count =  mExpandAdapter.getGroupCount(); 
																	for (int i = 0; i <count ; i++) 
																		mExpandListView.collapseGroup(i);
																	mExpandAdapter.notifyDataSetChanged();
																 */
															}catch(Exception e){
																e.printStackTrace();
															}finally{
															}
													}
												}	
											}
										});
									}
									break;
								}
								case 2:{//裝箱到貨
									/*
									  先檢查有否該批號的廠商進貨暫存單
									  否則開出一張新的單號,預設今天日期
									  QHEAD的EMPNAME要=BATCH= QITEMS_HANDNO
									  USER放SUPPLY (放配貨處的代號)
									  系統重新運算
									  @@全無Qitems 表尚未到貨 直接帶入 Qdetail訂單量
									  @@有Qitems暫存單時,直接帶入 暫存單
									  @@有Qitems已到貨時,Qdetail-Qitems
									  從Aincome回來時,再呼叫一次運算
									  @@@目前運算 已到量 Qitems 包含已到貨 & 已配貨 
									 */
								if (mGroupMode != GroupMode.INVOICE){
									//2015-01-03 增設為 單筆商品 上傳雲端,以修正資訊
									if ((mMode == KeySet.SearchMode.ACTION) && (batch != null && batch.length() > 0)) {
    									if (isPass<6 && isPass!=3 && isPass!=4) { 

											iData = mExpandAdapter.getData(groupPosition, childPosition);
											batch=iData.batch;

											if (iData.GoodsNo !=null && iData.GoodsNo.length()>0 )
											{	
												Toast.makeText(ManageItem.this, "單品上傳雲端!!", Toast.LENGTH_SHORT).show();
												Intent intent = new Intent();
												intent.setClass(ManageItem.this,MakeTransDetail.class);
												intent.putExtra("make_batch",batch);
												intent.putExtra("make_mode",0);
												intent.putExtra("make_kind",0);
												intent.putExtra("make_user",iData.GoodsNo);
												intent.putExtra("make_01",1);
												startActivity(intent);
											}
										}else{
											ProgressDialog mProgress = null;
						        		    mProgress = new ProgressDialog(ManageItem.this);
						        			mProgress.setCancelable(true);
						        			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//						        			mProgress.setMessage(ErrorMsg[isError]);
						        			mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
						        			mProgress.show();
										}					
									}

								}else{
									iData = mExpandAdapter.getData(groupPosition, childPosition);
									SQLiteDatabase db = Utilis.getDB(ManageItem.this);
									batch=iData.batch;
									int isIn=0;
									String selSQL="select * from qdetail where MID='"+iData.nMid+"'";
									selSQL+=getStates(0);
									Cursor cs=db.rawQuery(selSQL, null);
									if (cs.getCount()>0){
										cs.moveToFirst();
										iData = DBUtil.CItem.parseData(cs, true);
										String TSIZE=cs.getString(cs.getColumnIndex("SIZE"));
										String TCOLOR=cs.getString(cs.getColumnIndex("COLOR"));
										String TCOLORNO=cs.getString(cs.getColumnIndex("COLORNO"));
										String TINLIST=cs.getString(cs.getColumnIndex("INLIST"));
										String [] InListC=TINLIST.split("，");
										String[] Asize=TSIZE.split(","); 
										String[] Acolor=TCOLOR.split("，");
										String[] Acolorno=TCOLORNO.split("，");
										int [][] aList=new int [Acolor.length][Asize.length];
										Oinlist =new int [Acolor.length][Asize.length];
										for (int xx=0;xx<Acolor.length;xx++){
											String[] Inlist=InListC[xx].split(",");
											for (int xy=0;xy<Asize.length;xy++){
												aList[xx][xy]=Utilis.toInt(Inlist[xy]);
											}
										}//已上取得各色尺寸的訂單件數
										
										//iData = mExpandAdapter.getData(groupPosition, childPosition);
										//找有否本單(暫存單)
										Cursor csh=db.rawQuery("select * from qhead where EMPNAME='"+iData.batch+"' and ISCONFIRM<>'Y' and QKIND='10'", null);
										if (csh.getCount()>0){ //
											csh.moveToFirst();
											msFno=csh.getString(csh.getColumnIndex("FORMNO"));
											msFdate=csh.getString(csh.getColumnIndex("FORMDATE"));
											isNew=0;
								        	Cursor csi=db.rawQuery("select COLOR,SIZE,sum(UNIT10) from qitems where FORMNO='"+msFno+"' and ISCONFIRM<>'Y' and GOODSNO='"+iData.GoodsNo+"' and QKIND='10' group by COLOR,SIZE order by COLOR,SIZE", null);
								        	if (csi.getCount()>0){
								        		while (csi.moveToNext()){
													for (int xx=0;xx<Acolor.length;xx++){
														for (int xy=0;xy<Asize.length;xy++){
															if (csi.getString(0).equalsIgnoreCase(Acolorno[xx]) && csi.getString(1).equalsIgnoreCase(Asize[xy])){
																aList[xx][xy]=csi.getInt(2);
															}
														}
													}//將暫存單量 填入 陣列
								        		}
								        	}
								        	csi.close();
										}else{
											isNew=1; //目前沒有暫存單
										}
										
							        	Cursor csi=db.rawQuery("select COLOR,SIZE,sum(UNIT10) from qitems where HANDNO='"+iData.batch+"' and ISCONFIRM='Y' and GOODSNO='"+iData.GoodsNo+"' and QKIND='10' group by COLOR,SIZE", null);
							        	if (csi.getCount()>0){
							        		while (csi.moveToNext()){
												for (int xx=0;xx<Acolor.length;xx++){
													for (int xy=0;xy<Asize.length;xy++){
														if (csi.getString(0).equalsIgnoreCase(Acolorno[xx]) && csi.getString(1).equalsIgnoreCase(Asize[xy])){
															aList[xx][xy]-=csi.getInt(2);
														}
													}
												}//將已到貨部份扣除
							        		}
							        	}
							        	csi.close();

										StringBuffer AlistA=new StringBuffer();
										for (int xx=0;xx<Acolor.length;xx++){
											String[] Inlist=InListC[xx].split(",");
											AlistA.append(String.valueOf(aList[xx][0]));
											Oinlist[xx][0]=aList[xx][0];
											for (int xy=1;xy<(Asize.length);xy++){
												AlistA.append(",").append(String.valueOf(aList[xx][xy]));
												Oinlist[xx][xy]=aList[xx][xy];
											}
											AlistA.append("，");
										}//已上取得各色尺寸的訂單件數
										TINLIST=AlistA.toString().substring(0,AlistA.lastIndexOf("，"));
											Intent intent = new Intent();
											intent.putExtra("mid", iData.nMid);
											intent.putExtra("batch", String.valueOf(iData.GoodsNo));
											intent.putExtra("item_mode", 5); // 僅唯讀查詢
											intent.putExtra("unit", iData.nUnit); //每手有幾段(童裝)
											intent.putExtra("cong", 0);
											intent.putExtra("size", TSIZE);
											intent.putExtra("colorno", TCOLORNO);
											intent.putExtra("color",TCOLOR);
											intent.putExtra("countlist", TINLIST);
					 						intent.putExtra("mkind", "10");
											intent.putExtra("unitprice", cs.getDouble(cs.getColumnIndex("P0")));
											intent.putExtra("discount", 100.0);
											if (isOnkey==1)
												intent.setClass(ManageItem.this, AIncomePc.class);
											else
												intent.setClass(ManageItem.this, AIncome.class);
											
											startActivityForResult(intent, RESULT_AINCOME);
									}
									db.close();
									cs.close();
								}
									break;
								}
								case 3:  //閱覽商品資訊附圖(可以傳送)
								{
									
								if (menu_U[mGroupMode][pos].indexOf("----")<0){	
									iData = mExpandAdapter.getData(groupPosition, childPosition);

									Bundle bundle = new Bundle();
									Intent intent = new Intent();
									bundle.putString("GalleryPic",iData.batch+","+iData.GoodsNo);									
									intent.setClass(ManageItem.this, GalleryViewPic.class);
//原先的 LINE 輸出									
//									bundle.putString("MkqrList",iData.GoodsNo+","+0+",0");
//									intent.setClass(ManageItem.this, MkqrList.class);
									
									intent.putExtras(bundle);
									startActivity(intent);
									
								}
									
									break;
								}
								case 4://補印條碼 應取得該筆商品,進入AIncome "item_mode"==2
								{ 			//有可能來自於採購(ManageItem)(Qposff)2種,但是帶入的格式一致
											//查詢 (非編輯新增)
								if (menu_U[mGroupMode][pos].indexOf("----")<0){	
									
									iData = mExpandAdapter.getData(groupPosition, childPosition);
									SQLiteDatabase db = Utilis.getDB(ManageItem.this);
									Cursor cs=db.rawQuery("select * from qdetail where MID='"+iData.nMid+"'", null);
									if (cs.getCount()>0){
										cs.moveToFirst();
										Intent intent = new Intent();
										intent.putExtra("mid", iData.nMid);
										intent.putExtra("batch", cs.getString(cs.getColumnIndex("GOODSNO")));
										intent.putExtra("item_mode", 3); // 僅唯讀查詢
										intent.putExtra("cong", 0);
										intent.putExtra("unit", iData.nUnit); //每手有幾段(童裝)
										intent.putExtra("size", cs.getString(cs.getColumnIndex("SIZE")));
										intent.putExtra("colorno", cs.getString(cs.getColumnIndex("COLORNO")));
										intent.putExtra("color", cs.getString(cs.getColumnIndex("COLOR")));
										intent.putExtra("countlist", cs.getString(cs.getColumnIndex("INLIST")));
				 						intent.putExtra("mkind", "10");
										intent.putExtra("unitprice", cs.getDouble(cs.getColumnIndex("P0")));
										intent.putExtra("discount", 100.0);
										if (isOnkey==1)
											intent.setClass(ManageItem.this, AIncomePc.class);
										else
											intent.setClass(ManageItem.this, AIncome.class);

										startActivity(intent);
										}
									db.close();
									cs.close();
								}	
									break;
								}
								case 5:{//門市出貨
									if (mGroupMode == GroupMode.INVOICE){
									
									/*
									  先檢查有否該批號的門市出貨單empname
									  否則開出一張新的單號,預設今天日期
									  QHEAD的EMPNAME要=BATCH= QITEMS_HANDNO
									  USER放SUPPLY (放配貨處的代號)
									  系統重新運算
									  @@全無Qitems 表尚未到貨 直接帶入 Qdetail訂單量
									  @@有Qitems暫存單時,直接帶入 暫存單
									  @@有Qitems已到貨時,Qdetail-Qitems
									  從Aincome回來時,再呼叫一次運算
									  @@@目前運算 已到量 Qitems 包含已到貨 & 已配貨 
									 */
									iData = mExpandAdapter.getData(groupPosition, childPosition);
									SQLiteDatabase db = Utilis.getDB(ManageItem.this);
									batch=iData.batch;
									String sqlSQL="select * from qdetail where MID='"+iData.nMid+"'";
									sqlSQL+=getStates(0);
									Cursor cs=db.rawQuery(sqlSQL, null);
									if (cs.getCount()>0){
										cs.moveToFirst();
										iData = DBUtil.CItem.parseData(cs, true);
										String TSIZE=cs.getString(cs.getColumnIndex("SIZE"));
										String TCOLOR=cs.getString(cs.getColumnIndex("COLOR"));
										String TCOLORNO=cs.getString(cs.getColumnIndex("COLORNO"));
										String TINLIST=cs.getString(cs.getColumnIndex("INLIST"));
										String [] InListC=TINLIST.split("，");
										String[] Asize=TSIZE.split(","); 
										String[] Acolor=TCOLOR.split("，");
										String[] Acolorno=TCOLORNO.split("，");
										int [][] aList=new int [Acolor.length][Asize.length];
										Oinlist =new int [Acolor.length][Asize.length];
										for (int xx=0;xx<Acolor.length;xx++){
											String[] Inlist=InListC[xx].split(",");
											for (int xy=0;xy<Asize.length;xy++){
												aList[xx][xy]=Utilis.toInt(Inlist[xy]);
											}
										}//已上取得各色尺寸的訂單件數
										
										//iData = mExpandAdapter.getData(groupPosition, childPosition);
										//找有否本單(暫存單)
										Cursor csh=db.rawQuery("select * from qhead where EMPNAME='"+iData.batch+"' and ISCONFIRM<>'Y' and QKIND='10'", null);
										if (csh.getCount()>0){ //
											csh.moveToFirst();
											msFno=csh.getString(csh.getColumnIndex("FORMNO"));
											msFdate=csh.getString(csh.getColumnIndex("FORMDATE"));
											isNew=0;
								        	Cursor csi=db.rawQuery("select COLOR,SIZE,sum(UNIT10) from qitems where FORMNO='"+msFno+"' and ISCONFIRM<>'Y' and GOODSNO='"+iData.GoodsNo+"' and QKIND='10' group by COLOR,SIZE order by COLOR,SIZE", null);
								        	if (csi.getCount()>0){
								        		while (csi.moveToNext()){
													for (int xx=0;xx<Acolor.length;xx++){
														for (int xy=0;xy<Asize.length;xy++){
															if (csi.getString(0).equalsIgnoreCase(Acolorno[xx]) && csi.getString(1).equalsIgnoreCase(Asize[xy])){
																aList[xx][xy]=csi.getInt(2);
															}
														}
													}//將暫存單量 填入 陣列
								        		}
								        	}
								        	csi.close();
										}else{
										//建立新單找有否(已配單)
											isNew=1; //
											csh=db.rawQuery("select * from qhead where EMPNAME='"+iData.batch+"' and ISCONFIRM='Y' and QKIND='10'", null);
											if (csh.getCount()>0){
									        	Cursor csi=db.rawQuery("select COLOR,SIZE,sum(UNIT10) from qitems where HANDNO='"+iData.batch+"' and ISCONFIRM='Y' and GOODSNO='"+iData.GoodsNo+"' and QKIND='10' group by COLOR,SIZE", null);
									        	if (csi.getCount()>0){
									        		while (csi.moveToNext()){
														for (int xx=0;xx<Acolor.length;xx++){
															for (int xy=0;xy<Asize.length;xy++){
																if (csi.getString(0).equalsIgnoreCase(Acolorno[xx]) && csi.getString(1).equalsIgnoreCase(Asize[xy])){
																	aList[xx][xy]-=csi.getInt(2);
																}
															}
														}//將暫存單量 填入 陣列
									        		}
									        	}
									        	csi.close();
											}
												//將訂單-已配後 , 再給 Aincome	
										}
										csh.close();

										StringBuffer AlistA=new StringBuffer();
										for (int xx=0;xx<Acolor.length;xx++){
											String[] Inlist=InListC[xx].split(",");
											AlistA.append(String.valueOf(aList[xx][0]));
											Oinlist[xx][0]=aList[xx][0];
											for (int xy=1;xy<(Asize.length);xy++){
												AlistA.append(",").append(String.valueOf(aList[xx][xy]));
												Oinlist[xx][xy]=aList[xx][xy];
											}
											AlistA.append("，");
										}//已上取得各色尺寸的訂單件數
										TINLIST=AlistA.toString().substring(0,AlistA.lastIndexOf("，"));
										db.close();
										cs.close();
											Intent intent = new Intent();
											intent.putExtra("mid", iData.nMid);
											intent.putExtra("batch", String.valueOf(iData.GoodsNo));
											intent.putExtra("item_mode", 5); // 僅唯讀查詢
											intent.putExtra("cong", 0);
											intent.putExtra("unit", iData.nUnit); //每手有幾段(童裝)
											intent.putExtra("size", TSIZE);
											intent.putExtra("colorno", TCOLORNO);
											intent.putExtra("color",TCOLOR);
											intent.putExtra("countlist", TINLIST);
					 						intent.putExtra("mkind", "10");
											intent.putExtra("unitprice", cs.getDouble(cs.getColumnIndex("P0")));
											intent.putExtra("discount", 100.0);
											if (isOnkey==1)
												intent.setClass(ManageItem.this, AIncomePc.class);
											else
												intent.setClass(ManageItem.this, AIncome.class);
											startActivityForResult(intent, RESULT_AINCOME);
									}
								}else{//嘗試發展出 WEB 上架多圖的程式
									if (Utilis.haveInternet(ManageItem.this) && of_line!=0){  //雲端&&網路OK
										iData = mExpandAdapter.getData(groupPosition, childPosition);
										Bundle bundle = new Bundle();
										Intent intent = new Intent();
										bundle = new Bundle();
										bundle.putString("GalleryChild",iData.GoodsNo+","+0+",0");
										intent.setClass(ManageItem.this, GalleryViewWeb.class);
										intent.putExtras(bundle);
										startActivity(intent);
									}
								}
									break;
								}
								case 6:{

										iData = mExpandAdapter.getData(groupPosition, childPosition);
 
     										Intent intent = new Intent();
    					    				intent.putExtra("GalleryUser","");
    					    				intent.putExtra("GalleryGoods",iData.GoodsNo);
    										intent.putExtra("GalleryDept",Utilis.getIni(ManageItem.this,"SYS","DEPT",1));    					    				
    					    				intent.putExtra("GalleryASK"," and GOODSNO='"+iData.GoodsNo+"' ");
    					    				intent.putExtra("FormNo","");
    					    				if (nPart==0) 
    					    					intent.putExtra("GalleryQKIND","30");
    					    				else
    					    					intent.putExtra("GalleryQKIND","31");
    					    				
    					    				intent.putExtra("GalleryMode",1);//0mUser 1mGoods 2KeepaToSale
    										intent.setClass(ManageItem.this, GalleryViewO.class);
											startActivityForResult(intent, RESULT_GALLERYO);

									break;
								}
								case 7:{
									if (isPass<6 && isPass!=3 && isPass!=4) {
										iData = mExpandAdapter.getData(groupPosition, childPosition);
										
										if (iData.GoodsNo !=null && iData.GoodsNo.length()>0 &&  iData.nGoodsType>0 && iData.batch!=null && iData.batch.length()>0){
	
											Intent intent = new Intent();
											intent.putExtra("mid", iData.nMid);
											intent.putExtra("batch", iData.GoodsNo);
											intent.putExtra("item_mode", ItemMode.EDIT); // 新增 對應帳戶使用
											intent.putExtra("cong", 0);
											intent.putExtra("unit", iData.nUnit);
											intent.putExtra("size", iData.mSizes);
											intent.putExtra("colorno", iData.mColorsNo);
											intent.putExtra("color", iData.mColors);
											intent.putExtra("countlist", iData.mCountList);
					 						intent.putExtra("mkind", "10");
											intent.putExtra("unitprice",iData.dP0 );
											intent.putExtra("discount", 100.0);
						
											if (isOnkey==1)
												intent.setClass(ManageItem.this, AIncomePc.class);
											else
												intent.setClass(ManageItem.this, AIncome.class);
											
											startActivity(intent);
										}
									} else{
										ProgressDialog mProgress = null;
					        		    mProgress = new ProgressDialog(ManageItem.this);
					        			mProgress.setCancelable(true);
					        			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					        			mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
					        			mProgress.show();

									}
									break;
								}
								case 8:{
									iData = mExpandAdapter.getData(groupPosition, childPosition);
									if (iData.GoodsNo !=null && iData.GoodsNo.length()>0){
										Bundle bundle = new Bundle();
										Intent intent = new Intent();
										bundle = new Bundle();
										bundle.putString("GalleryChild","'"+iData.GoodsNo+"';0;1");

										intent.setClass(ManageItem.this, GalleryViewS.class);
										intent.putExtras(bundle);
										startActivity(intent);
										
									}
									
									break;
								}
							}
						}
			});
			
			return false;
		}
	}

	private String getStates(int mode){
		String adds=" ";
		if (nStates==4) return adds;
		else{
			if (mode==0){
				adds=" and STATE ="+nStates;
				if(nextSwitch==1)
					adds+=" and ((UNIT1 like '"+deptStr[5]+"%') or (UNIT1 like '"+deptStr[0]+"%'))";

			}else{ 
				adds=" and A.STATE ="+nStates;
				if(nextSwitch==1)
				adds+=" and ((A.UNIT1 like '"+deptStr[5]+"%') or (A.UNIT1 like '"+deptStr[0]+"%'))";
			}
		}
		
		return adds;
	}
	class ExpandItemAdapter extends BaseExpandableListAdapter{
		private Context context;

		LinkedList<GroupData> groups = new LinkedList<GroupData>();
		LinkedList<List<ItemData>> childs = new LinkedList<List<ItemData>>();
		private AsyncImageFileLoader asyncImageFileLoader;
		/*
		* 構造函數:
		* 參數1:context物件
		* 參數2:一級清單資料來源
		* 參數3:二級清單資料來源
		*/
		public ExpandItemAdapter(Context context)
		{
			this.context = context;
			asyncImageFileLoader = new AsyncImageFileLoader();
		}
		
		public void setData(LinkedList<GroupData> groups, LinkedList<List<ItemData>> childs){
			if(this.groups != null){
				this.groups.clear();
			}
			if(this.childs != null){
				this.childs.clear();
			}
			this.groups = groups;
			this.childs = childs;
		}
		
		public ItemData 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 ViewHolder */
		private class GroupViewHolder {
			ImageView imageIcon;
			TextView text0;
			TextView text1;
			TextView text2;
			TextView textMoney;
			TextView textOriMoney;
		}

		//獲取二級清單的View物件
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
		ViewGroup parent)
		{
			ItemData data = childs.get(groupPosition).get(childPosition);
		//
		LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			ViewHolder holder;
			if (convertView == null) {
				convertView = layoutInflater.inflate(R.layout.list_item, null);
				holder = new ViewHolder();
				holder.imageItem = (ImageView)convertView.findViewById(R.id.img_pic);
				holder.textGoodsNo = (TextView) convertView.findViewById(R.id.text_goodsno);
				holder.textImpo = (TextView) convertView.findViewById(R.id.text_impo);
				holder.textName = (TextView) convertView.findViewById(R.id.text_name);
				holder.textNumber = (TextView) convertView.findViewById(R.id.text_number);
				holder.textMoney = (TextView) convertView.findViewById(R.id.text_money);
				holder.textCountry = (TextView) convertView.findViewById(R.id.text_country);
				holder.textCompany = (TextView) convertView.findViewById(R.id.text_company);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
			holder.imageItem.setImageBitmap(Utilis.getLimitBitmap(data.pic1, 80, 80));
			holder.textName.setText(data.goodsname);
			holder.textGoodsNo.setText(data.GoodsNo);
			if(mGroupMode != GroupMode.INVOICE){
				holder.textImpo.setText("總件數 " + data.nTotalCount);
				holder.textMoney.setText(" $" + myformat.format((data.nTotalCount * data.dP1)));
				holder.textCompany.setText(data.supply);
			}else{
				holder.textImpo.setText("本訂:" + data.nTotalCount);
				holder.textMoney.setText("已到:" + data.pic2);
				holder.textCompany.setText("未到:"+data.supply);
			}
			holder.textCountry.setText(data.country);
			holder.textNumber.setText(data.sourceNo);
			
	        if (PSWD!=0){  //密碼不OK
	        	holder.textMoney.setVisibility(View.INVISIBLE);
	        	holder.textCountry.setVisibility(View.INVISIBLE);
	        	holder.textCompany.setVisibility(View.INVISIBLE);
	        }
			
			return convertView;
		}

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

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

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

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

		//獲取一級清單View物件
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
		{
//			String text = groups.get(groupPosition).get("group");
			GroupData data = groups.get(groupPosition);
			
			LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			GroupViewHolder holder;
			if (convertView == null) {
				convertView = layoutInflater.inflate(R.layout.elist_group, null);
				holder = new GroupViewHolder();
				holder.imageIcon = (ImageView)convertView.findViewById(R.id.img_icon);
				holder.text0 = (TextView) convertView.findViewById(R.id.text0);
				holder.text1 = (TextView) convertView.findViewById(R.id.text1);
				holder.text2 = (TextView) convertView.findViewById(R.id.text2);
				holder.textMoney = (TextView)convertView.findViewById(R.id.textMoney);
				holder.textOriMoney = (TextView)convertView.findViewById(R.id.textOriMoney);
				convertView.setTag(holder);
				
			} else {
				holder = (GroupViewHolder) convertView.getTag();
			}
			if(mGroupMode == GroupMode.NUMBER){
				holder.imageIcon.setVisibility(View.GONE);
			}else{
				holder.imageIcon.setVisibility(View.VISIBLE);
				try{
					if(data.strPic != null && data.strPic.length() > 0){
						holder.imageIcon.setImageDrawable(Utilis.getResourceImage(ManageItem.this, data.strPic));
					}else{
						holder.imageIcon.setImageResource(R.drawable.icon_store);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			switch(mGroupMode){
				case GroupMode.NUMBER:
				{
					holder.text1.setText("批號 : " + data.strText1);
					break;
				}
				case GroupMode.CATEGORY:
				{
					holder.text1.setText(data.strText1);
					break;
				}
				case GroupMode.COMPANY:
				{
					holder.text1.setText(data.strText1);
					break;
				}
				case GroupMode.INVOICE:
				{
					holder.text1.setText(data.strText1);
					break;
				}
			}
			holder.text0.setText(data.strText0);
			holder.text2.setText(data.strTot1);
			holder.textOriMoney.setText(data.strOriMoney);
			holder.textMoney.setText(data.strMoney);
	        if (PSWD!=0){  //密碼不OK
	        	holder.textMoney.setVisibility(View.INVISIBLE);
	        	holder.textOriMoney.setVisibility(View.INVISIBLE);
	        }
			
			
			return convertView;
		}

		public boolean hasStableIds()
		{
		return false;
		}

		public boolean isChildSelectable(int groupPosition, int childPosition)
		{
		return true;
		}
	}
	
	
	class ItemAdapter extends BaseAdapter{
		
		private LayoutInflater mInflater;
		
		public ItemAdapter (Context context){
		      mInflater = LayoutInflater.from(context);
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_item, null);
				holder = new ViewHolder();
				holder.imageItem = (ImageView)convertView.findViewById(R.id.img_pic);
				holder.textGoodsNo = (TextView) convertView.findViewById(R.id.text_goodsno);
				holder.textImpo = (TextView) convertView.findViewById(R.id.text_impo);
				holder.textName = (TextView) convertView.findViewById(R.id.text_name);
				holder.textMoney = (TextView) convertView.findViewById(R.id.text_money);
				holder.textNumber = (TextView) convertView.findViewById(R.id.text_number);
				holder.textCountry = (TextView) convertView.findViewById(R.id.text_country);
				holder.textCompany = (TextView) convertView.findViewById(R.id.text_company);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
			iData = mList.get(position);
			holder.imageItem.setImageBitmap(Utilis.getSmallPic(iData.pic1));
			
			holder.textGoodsNo.setText(iData.GoodsNo);
			if(mGroupMode != GroupMode.INVOICE){
				holder.textImpo.setText("總件數 " + iData.nTotalCount);
				holder.textMoney.setText(" $ " + myformat.format((iData.nTotalCount * iData.dP1)));
			}else{
				holder.textImpo.setText("本訂:" + iData.nTotalCount);
				holder.textMoney.setText(" 已到 " + (iData.nTotalCount * iData.dP1));
			}
			holder.textName.setText(iData.goodsname);
			holder.textCountry.setText(iData.country);
			holder.textCompany.setText(iData.supply);
			holder.textNumber.setText(iData.sourceNo);
			
	        if (PSWD!=0){  //密碼不OK
	        	holder.textMoney.setVisibility(View.INVISIBLE);
	        	holder.textCountry.setVisibility(View.INVISIBLE);
	        	holder.textCompany.setVisibility(View.INVISIBLE);
	        }
			
			return convertView;
		}

		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textGoodsNo;
			TextView textImpo;
			TextView textName;
			TextView textMoney;
			TextView textCountry;
			TextView textNumber;
			TextView textCompany;
			
		}
	    
	}
	    
	class MainClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(ManageItem.this);
			switch (id) {
				case R.id.btn_new:
				{
					if (isPass<6 && isPass!=3 && isPass!=4) { 
					if (PSWD!=1){
					Utilis.runVibrate(ManageItem.this);
					Intent intent = new Intent();
					intent.setClass(ManageItem.this,AItem.class);
					intent.putExtra("item_mode", AItem.ItemMode.ADD);
					intent.putExtra("item_mid", 0);
					intent.putExtra("item_from", 0);//0.ManagerItem 1.GalleryView
					startActivity(intent);
					}else{
						Toast.makeText(ManageItem.this, "請注意權限!!", Toast.LENGTH_SHORT).show();										
					}
				} else {
					ProgressDialog mProgress = null;
        		    mProgress = new ProgressDialog(ManageItem.this);
        			mProgress.setCancelable(true);
        			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        			mProgress.setMessage(ErrorMsg[isError]);
        			mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
        			mProgress.show();

				}
					break;
				}
				case R.id.btn_states:
				{
					if (nStates==0){ 
						nStates=1;
					}else if (nStates==1){ 
						nStates=2;
					}else if (nStates==2){ 
						nStates=3;
					}else if (nStates==3){
						nStates=4;
					}else if (nStates==4){ 
						nStates=0;
					}
					((Button)findViewById(R.id.btn_states)).setText(btn_T[nStates]);
					getGroupData(ManageItem.this,mStartDay, mEndDay, null, null);
					
					break;
				}
				case R.id.btn_state:
				{
					Utilis.runVibrate(ManageItem.this);
					Bundle bundle = new Bundle();
					Intent intent = new Intent();
					bundle = new Bundle();
					bundle.putString("GalleryChild",batch+";1;0");
					intent.setClass(ManageItem.this, GalleryViewVP.class);
					intent.putExtras(bundle);
					startActivity(intent);					
					break;
				}
				
				case R.id.btn_fbatch:  //查詢  以批號做為查詢
				{
					LayoutInflater factory = LayoutInflater.from(ManageItem.this);
				    final View v1 = factory.inflate(R.layout.fbatch, null);
				    final EditText edtReg = (EditText) v1.findViewById(R.id.edtsh);
				    edtReg.setText("");
				      new AlertDialog.Builder(ManageItem.this).setTitle(ManageItem.this.getString(R.string.detail_msg_fbatch)).setView(v1).setNeutralButton("開始搜尋", new DialogInterface.OnClickListener() {
					      public void onClick(DialogInterface dialog, int which) {
					    	  //開始依條件依序搜尋
					    	  boolean searched=false;
				    	  		SQLiteDatabase db = Utilis.getDB(ManageItem.this);
				    	  		Cursor cs=null;;
				    	  		StringBuffer bufSH = new StringBuffer();
				    	  		if ( edtReg.getText().toString().indexOf("-")==2 ){  //至少類似 xx-xx
					    	  		bufSH.append("select distinct BATCH from qdetail");
					    	  		bufSH.append(" where CREATEDATETIME LIKE '%" + edtReg.getText().toString()+"%'");
					    	  		bufSH.append(" order by BATCH DESC limit 1");
									cs = db.rawQuery(bufSH.toString(), null);
									if (cs != null) {
										if (cs.getCount() > 0) {
											cs.moveToFirst();
											batch = cs.getString(0);
											searched=true;
										}
									}
				    	  		}
				    	  		
								if (!searched){  //表示沒有符合批號,續找或號
									bufSH.delete(0, bufSH.toString().length());
					    	  		bufSH.append("select distinct BATCH from qdetail");
					    	  		bufSH.append(" where BATCH LIKE '%" + edtReg.getText().toString()+"%'");
					    	  		bufSH.append(" order by BATCH DESC limit 1");
									cs = db.rawQuery(bufSH.toString(), null);
									if (cs != null) {
										if (cs.getCount() > 0) {
											cs.moveToFirst();
											batch = cs.getString(0);
											searched=true;
										}
									}
								}
								if (!searched){  //表示沒有符合批號,續找或號
									bufSH.delete(0, bufSH.toString().length());
					    	  		bufSH.append("select distinct BATCH from qdetail");
					    	  		bufSH.append(" where GOODSNO LIKE '%" + edtReg.getText().toString()+"%'");
					    	  		bufSH.append(" order by BATCH DESC limit 1");
									cs = db.rawQuery(bufSH.toString(), null);
									if (cs != null) {
										if (cs.getCount() > 0) {
											cs.moveToFirst();
											batch = cs.getString(0);
											searched=true;
										}
									}
								}
								if (!searched){  //表示沒有符合批號,續找或號
									bufSH.delete(0, bufSH.toString().length());
					    	  		bufSH.append("select distinct BATCH from qdetail");
					    	  		bufSH.append(" where GOODSNAME LIKE '%" + edtReg.getText().toString()+"%'");
					    	  		bufSH.append(" order by BATCH DESC limit 1");
									cs = db.rawQuery(bufSH.toString(), null);
									if (cs != null) {
										if (cs.getCount() > 0) {
											cs.moveToFirst();
											batch = cs.getString(0);
											searched=true;
										}
									}
								}
								db.close();
								cs.close();
								if (searched && (batch.length()>0)){ //表示有值batch
									mGroupMode=GroupMode.CATEGORY;					
									if (mMode != KeySet.SearchMode.ACTION){
										mMode=KeySet.SearchMode.ACTION;
							    		mStartDay = Utilis.getRecentDate(ManageItem.this);
										mEndDay = mStartDay;
							    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
							    		((Button)findViewById(R.id.btn_next_date)).setText("下一批");
							    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
							    		((Button)findViewById(R.id.btn_prev_date)).setText("上一批");
										
									}
									resetButton(R.id.btn_sort_cate);
									setCondition();
									getGroupBatchData(ManageItem.this, batch);									
								}
					      }
					    }).setNegativeButton("離開", new DialogInterface.OnClickListener() {
						      public void onClick(DialogInterface dialog, int which) {
						      }
					    })
					    .show();
					      
					break;
				}
				
				case R.id.btn_account://輸出
				{
				if ((mMode == KeySet.SearchMode.ACTION) && (batch != null && batch.length() > 0)) {
					if (isPass<6 && isPass!=3 && isPass!=4) { 
						//須檢查該批號 所有商品都符合才可以輸出
						StringBuffer bufSH= new StringBuffer();  
						bufSH.delete(0, bufSH.toString().length());
		    	  		bufSH.append("select * from qdetail");
		    	  		bufSH.append(" where BATCH ='" +batch+"'");
						SQLiteDatabase db = Utilis.getDB(ManageItem.this);
						Cursor cs = db.rawQuery(bufSH.toString(), null);
						int chked=1;
						while (cs.moveToNext()) {
							if (cs.getString(cs.getColumnIndex("GOODSNO"))==null || cs.getString(cs.getColumnIndex("GOODSNO")).length()<=0
								|| cs.getString(cs.getColumnIndex("GOODSTYPE"))==null || cs.getInt(cs.getColumnIndex("GOODSTYPE"))<=0
								|| cs.getString(cs.getColumnIndex("INLIST"))==null || cs.getString(cs.getColumnIndex("INLIST")).length()<=0
								|| cs.getString(cs.getColumnIndex("SOURCENO"))==null || cs.getString(cs.getColumnIndex("SOURCENO")).length()<=0	
								|| cs.getString(cs.getColumnIndex("SUPPLY"))==null || cs.getString(cs.getColumnIndex("SUPPLY")).length()<=0	
								)
							{	chked=0;
								Toast.makeText(ManageItem.this, cs.getString(cs.getColumnIndex("GOODSNO"))+" 的資料不完整!!", Toast.LENGTH_SHORT).show();
								break;		}
						}
						db.close();
						cs.close();
						
						if (chked==1){	
							Intent intent = new Intent();
							intent.setClass(ManageItem.this,MakeTransDetail.class);
							intent.putExtra("make_mode",0);
							intent.putExtra("make_batch",batch);
							intent.putExtra("make_kind",0);
							intent.putExtra("make_01",0);
							intent.putExtra("make_user","");
							startActivity(intent);
						}
					}else{
						ProgressDialog mProgress = null;
	        		    mProgress = new ProgressDialog(ManageItem.this);
	        			mProgress.setCancelable(true);
	        			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//	        			mProgress.setMessage(ErrorMsg[isError]);
	        			mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
	        			mProgress.show();
					}					
				}
					break;
				}
				case R.id.btn_exit:
				{
					finish();
					break;
				}
				case R.id.btn_prev_date:
				{
					switch(mMode){
						case KeySet.SearchMode.MONTH:
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, -1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
			    			break;
			    		}
						case KeySet.SearchMode.WEEK:
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, -7);
							mEndDay = DateUtil.addDate(mEndDay, -7);
			    			break;
			    		}
						case KeySet.SearchMode.ACTION:
						{
				    		//應追加 上一批 的程式							
							SQLiteDatabase db = Utilis.getDB(ManageItem.this);
							Cursor cursorAlbun = null;							
							if(batch != null && batch.length() > 0){
								StringBuffer bufCategory = new StringBuffer();
								String SQL="select distinct BATCH from qdetail where BATCH<";
								if (nextSwitch==0)
									bufCategory.append(SQL+"'" + batch+"'");
								else
									bufCategory.append(SQL+"'" + batch+"' and ((UNIT1 like '"+deptStr[5]+"%') or (UNIT1 like '"+deptStr[0]+"%'))");
									bufCategory.append(" order by BATCH DESC limit 1");
									cursorAlbun = db.rawQuery(bufCategory.toString(), null);
									
									if (cursorAlbun != null) {
										if (cursorAlbun.getCount() > 0) {
											cursorAlbun.moveToFirst();
											batch = cursorAlbun.getString(0);
										}
									}
							}
							db.close();
							break;
						}
					}
					setCondition();
					getGroupData(ManageItem.this,mStartDay, mEndDay, null, null);
					break;
				}
				case R.id.btn_next_date:
				{
					switch(mMode){
			    		case KeySet.SearchMode.MONTH:
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, 1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
			    			break;
			    		}
			    		case KeySet.SearchMode.WEEK:
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, 7);
							mEndDay = DateUtil.addDate(mEndDay, 7);
			    			break;
			    		}
			    		case KeySet.SearchMode.ACTION:
						{			    		
			    		//應追加 下一批 的程式
						SQLiteDatabase db = Utilis.getDB(ManageItem.this);
						Cursor cursorAlbun = null;							
						if(batch != null && batch.length() > 0){
							StringBuffer bufCategory = new StringBuffer();
							String SQL="select distinct BATCH from qdetail where BATCH>";
							if (nextSwitch==0)
								bufCategory.append(SQL+"'" + batch+"'");
							else
								bufCategory.append(SQL+"'" + batch+"' and ((UNIT1 like '"+deptStr[5]+"%') or (UNIT1 like '"+deptStr[0]+"%'))");
							
								bufCategory.append(" order by BATCH limit 1");
								cursorAlbun = db.rawQuery(bufCategory.toString(), null);
								
								if (cursorAlbun != null) {
									if (cursorAlbun.getCount() > 0) {
										cursorAlbun.moveToFirst();
										batch = cursorAlbun.getString(0);
									}
								}
						}
						db.close();
						break;
						}
					}
					setCondition();
					getGroupData(ManageItem.this,mStartDay, mEndDay, null, null);
					break;
				}
				case R.id.text_duration:
				{
					if (mMode==KeySet.SearchMode.ACTION){
						mMode=KeySet.SearchMode.WEEK;
			    		String day = Utilis.getWeekDate();
						String[] days = day.split("~");
			    		mStartDay = days[0];
			    		mEndDay = days[1];
				        resetButton(R.id.btn_sort_pic);
						mGroupMode = GroupMode.NUMBER;
			    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_next_date)).setText("下一週");
			    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_prev_date)).setText("上一週");
						
					} else if (mMode==KeySet.SearchMode.WEEK){
						mMode=KeySet.SearchMode.ACTION;
			    		mStartDay = Utilis.getRecentDate(ManageItem.this);
						mEndDay = mStartDay;
			        	mKey = "";
						//@@@mGroupMode = GroupMode.NUMBER;
			    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_next_date)).setText("下一批");
			    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_prev_date)).setText("上一批");
					} 
					

					setCondition();
					getGroupData(ManageItem.this,mStartDay, mEndDay, null, null);
					break;
				}
				
				case R.id.btn_sort_pic:
				{
					Utilis.runVibrate(ManageItem.this);
					Bundle bundle = new Bundle();
					Intent intent = new Intent();
					bundle = new Bundle();
					bundle.putString("GalleryChild",batch+","+0+",0");
					intent.setClass(ManageItem.this, GalleryView.class);
					intent.putExtras(bundle);
					startActivity(intent);					
					break;
				}
				case R.id.btn_sort_number:
				{
					DBCloud.aa0_aa1_auto_qdetail_n(ManageItem.this);
					//DBCloud.aa0_aa1_auto_HI(ManageItem.this,30);
					resetButton(id);
					mGroupMode = GroupMode.NUMBER;
					mListView.setVisibility(View.GONE);
					mExpandListView.setVisibility(View.VISIBLE);
					mExpandListView.setOnChildClickListener(mChildClcik);
					getGroupData(ManageItem.this,mStartDay, mEndDay, null, null);
					break;
				}
				case R.id.btn_sort_cate:
				{
					DBCloud.aa0_aa1_auto_qdetail_n(ManageItem.this);
					//DBCloud.aa0_aa1_auto_HI(ManageItem.this,30);
					resetButton(id);
					mGroupMode = GroupMode.CATEGORY;
					mListView.setVisibility(View.GONE);
					mExpandListView.setVisibility(View.VISIBLE);
					mExpandListView.setOnChildClickListener(mChildClcik);
					getGroupData(ManageItem.this,mStartDay, mEndDay, null, null);
					break;
				}
				case R.id.btn_sort_company:
				{
					DBCloud.aa0_aa1_auto_qdetail_n(ManageItem.this);
					//DBCloud.aa0_aa1_auto_HI(ManageItem.this,30);
					resetButton(id);
					mGroupMode = GroupMode.COMPANY;
					mListView.setVisibility(View.GONE);
					mExpandListView.setVisibility(View.VISIBLE);
					mExpandListView.setOnChildClickListener(mChildClcik);
					getGroupData(ManageItem.this,mStartDay, mEndDay, null, null);
					int count =  mExpandAdapter.getGroupCount(); 
					for (int i = 0; i <count ; i++) 
						mExpandListView.collapseGroup(i); 
					mExpandAdapter.notifyDataSetChanged();
					break;
				}
				case R.id.btn_sort_invoice:
				{
					DBCloud.aa0_aa1_auto_qdetail_n(ManageItem.this);
					//DBCloud.aa0_aa1_auto_HI(ManageItem.this,30);
					resetButton(id);
					mGroupMode = GroupMode.INVOICE;
					mListView.setVisibility(View.GONE);
					mExpandListView.setVisibility(View.VISIBLE);
					mExpandListView.setOnChildClickListener(mChildClcik);
					getGroupData(ManageItem.this,mStartDay, mEndDay, null, null);
					break;
				}
				
			}
		}
	}
	
	private void resetButton(int id){
		((Button)findViewById(R.id.btn_sort_pic)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_cate)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_number)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_company)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_invoice)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_yellow);
	}


	private LongClick mLongClickListener = new LongClick();
	
	class LongClick implements OnItemLongClickListener {
		@SuppressWarnings("static-access")
		@Override
		 public boolean onItemLongClick(AdapterView<?> parent, View childView,int flatPos, long id) {  			
			long packedPos = ((ExpandableListView) parent).getExpandableListPosition(flatPos);  
			final int groupPosition = mExpandListView.getPackedPositionGroup(packedPos);
			final int childPosition = ExpandableListView.getPackedPositionChild(id);
                
            if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
            	if(mGroupMode == GroupMode.NUMBER){//是在依批號的模式上                	
        		  GroupData datag =mExpandAdapter.groups.get(groupPosition);
        		  batchPic=datag.search;
				  String [] Lmenu={"批號: "+batchPic+"_整張刪除","批號: "+batchPic+"_再度下載自雲端圖檔","批號: "+batchPic+"_編輯年度季節","所有圖片檢查太大時,進行縮圖","工程專用,禁止使用","返回"};
        		
    			  DialogUtilis.showDialog(ManageItem.this, "請選擇以下功能", -1,
				  Lmenu, new IDialog() {
				  @Override
					public void onDialogFinish(int pos, String choice) {
					switch (pos) {
					case 0: //整張批號刪除
					{
					if(PSWD!=1 && menu_U[mGroupMode][pos].indexOf("----")<0){
						DialogUtilis.showDialog(ManageItem.this, "確定刪除?", -1,
							new String[] { "取消", batchPic+"_整張批號刪除" }, new IDialog() {
								@Override
								public void onDialogFinish(int pos, String choice) {
									switch (pos) {
									case 0: {break;}
									case 1: // 確定刪除
									{
											try{
												SQLiteDatabase db = Utilis.getDB(ManageItem.this);
												String delSQL="delete from qdetail where BATCH='"+batchPic+"'";
												db.execSQL(delSQL);
												Toast.makeText(ManageItem.this, "刪除資料成功", Toast.LENGTH_SHORT)
												.show();
												//@@ delete 雲端 qdetail
												db.close();
												//更新資料
												getGroupData(ManageItem.this, mStartDay, mEndDay, null, null);
											}catch(Exception e){
												e.printStackTrace();
											}finally{
											}
										break;	
									}
								}	
							}
						});
					}
						
					break;
					}
					
					case 1:{//檢查該批號 是否有圖檔沒有下載成功的 再度下載一次
						StringBuffer ftpPic= new StringBuffer();
	        		    int intPic=0;
						try{
							SQLiteDatabase db = Utilis.getDB(ManageItem.this);
							String serpicSQL="select PIC,PICTURE from qdetail where BATCH='"+batchPic+"'";
							String picAgain="";
							String serverFile1="";
							Cursor cs=db.rawQuery(serpicSQL, null);
							if (cs.getCount()>0){
								while (cs.moveToNext()){
									if (cs.getString(0).length()>0){
									File picFile=new File(cs.getString(0));
									if (picFile.exists()); else
									{
										if (ftpPic.toString().indexOf("\r\n"+cs.getString(0).substring(14)+"\r\n")<0)
											serverFile1 =cs.getString(0).replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
										ftpPic.append(serverFile1.substring(14)+"\r\n");//製作SERVER圖片路徑,一次性的ZIP後,取回解壓縮
										intPic+=1;
									}
									}
									if (cs.getString(1).length()>0){
									File picFile=new File(cs.getString(1));
									if (picFile.exists()); else
									{
										if (ftpPic.toString().indexOf("\r\n"+cs.getString(1).substring(14)+"\r\n")<0)
											serverFile1 =cs.getString(1).replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
										ftpPic.append(serverFile1.substring(14)+"\r\n");//製作SERVER圖片路徑,一次性的ZIP後,取回解壓縮
										intPic+=1;
									}
									}
								}
							}
							db.close();
						}catch(Exception e){
							e.printStackTrace();
						}finally{
							if (intPic>0){
								Toast.makeText(ManageItem.this, "預計將有 "+intPic+" 個圖檔,試著從伺服器,重新下載,請稍後......", Toast.LENGTH_SHORT).show();
								DBCloud.aa0_aa1_auto_pic_n(ManageItem.this,ftpPic.toString());
							}
						}
						ftpPic.delete(0, ftpPic.toString().length());
					break;
					}
					case 2://開啟年度季節,輸入 確認後傳回 更新本批號 所有商品
					{
						SQLiteDatabase db = Utilis.getDB(ManageItem.this);
						String SQL="select UNIT2,SEASON from qdetail where BATCH='"+batchPic+"'";
						Cursor cs=db.rawQuery(SQL, null);
						if (cs.getCount()>0){
							cs.moveToFirst();
							getYS[0]=cs.getInt(0);
							getYS[1]=cs.getInt(1);
							getYS = DateUtil.showSeason(ManageItem.this,0,batchPic,getYS[0],getYS[1],2);
						}
						cs.close();
						db.close();
						break;
					}
					case 3:
					{
						SQLiteDatabase db = Utilis.getDB(ManageItem.this);
						String SQL="select PIC,PICTURE from qdetail where length(PIC)>20 or length(PICTURE)>20";
						Cursor cs=db.rawQuery(SQL, null);
						if (cs.getCount()>0){
							while (cs.moveToNext()){
								for (int p=0;p<2;p++){
									Utilis.checkPicSize(cs.getString(p));
								}
							}
						}
						cs.close();
						db.close();
						break;
					}
					case 4:
					{//@@@應改為以(批號)重新雲端下載資料及圖片
						//原先設計為輸出
						Intent intent = new Intent();
						intent.setClass(ManageItem.this,MakeTransDetail.class);
						intent.putExtra("make_batch",batch);
						intent.putExtra("make_mode",0);
						intent.putExtra("make_kind",0);
						intent.putExtra("make_user","");
						intent.putExtra("make_01",9);
						startActivity(intent);
						
						break;
					}
					}
					}
	    		  });
            	}
            }
          return true;      
		}
	}
                
	
	public void getTypeData(Context context){
		if(mTypeList != null){
			mTypeList.clear();
		}
		if(mTypeIdList != null){
			mTypeIdList.clear();
		}
		SQLiteDatabase dbs = Utilis.getDB(context);
		Cursor cursor = dbs.rawQuery("select GOODTYPE,_ID from qc_type order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						String name = cursor.getString(cursor.getColumnIndex("GOODTYPE"));
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						mTypeList.add(name);
						mTypeIdList.add(id);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		dbs.close();
		dbs = null;
	}
	
	public void getCountryData(Context context){
		if(mCountryIcon != null){
			mCountryIcon.clear();
		}
		if(mCountryList != null){
			mCountryList.clear();
		}
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cursor = db.rawQuery("select _ID,NAME,PIC from qc_country order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						String pic = cursor.getString(cursor.getColumnIndex("PIC"));
						String name = cursor.getString(cursor.getColumnIndex("NAME"));
						mCountryIdList.add(id);
						mCountryIcon.add(pic);
						mCountryList.add(name);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}
	
	// 取得預設參數
	private void getDefaultData() {
		SQLiteDatabase db = Utilis.getDB(this);
		if (db != null) {
			Cursor cursor = db.rawQuery("select * from qc_default", null);
			if (cursor != null) {
				try {
					if (cursor.getCount() > 0) {
						cursor.moveToFirst();
						mDefaultData = new DefaultData();
						mDefaultData.nCountry = cursor.getInt(cursor
								.getColumnIndex("COUNTRY"));
						mDefaultData.country = mCountryList
								.get(mDefaultData.nCountry - 1);
						mDefaultData.dBillRate = cursor.getDouble(cursor
								.getColumnIndex("BILLRATE"));
						mDefaultData.batch = cursor.getString(cursor
								.getColumnIndex("BATCH"));
						mDefaultData.factno = cursor.getString(cursor
								.getColumnIndex("FACTNO"));
						mDefaultData.nItemState = cursor.getInt(cursor
								.getColumnIndex("STATE"));
						mDefaultData.nSourceNumber = cursor.getInt(cursor
								.getColumnIndex("SOURCENO"));
						mDefaultData.nItemProduct = cursor.getInt(cursor
								.getColumnIndex("PRODUCT"));
						mDefaultData.nItemFirst = cursor.getInt(cursor
								.getColumnIndex("ITEMFIRST"));
						mDefaultData.nSeason = cursor.getInt(cursor
								.getColumnIndex("SEASON"));
						mDefaultData.nYear = cursor.getInt(cursor
								.getColumnIndex("YEAR"));
						mDefaultData.employ = cursor.getString(cursor
								.getColumnIndex("EMPLOY"));
						mDefaultData.nAccountId = cursor.getInt(cursor
								.getColumnIndex("ACCOUNT"));
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					cursor.close();
				}
			}
			db.close();
		}
	}
	
	// 搜尋日期 Dialog
    private View makeDateDialog() {
    	View view = LayoutInflater.from(this).inflate(R.layout.search_date, null, false);
    	Calendar c = Calendar.getInstance();
    	c.set(Calendar.DAY_OF_MONTH, 1); // 關鍵
    	
	    mYear1 = c.get(Calendar.YEAR);
		mMonth1 = c.get(Calendar.MONTH) + 1;
		mDay1 = c.get(Calendar.DAY_OF_MONTH);
		c.add(Calendar.MONTH, 1);
		c.add(Calendar.DATE, -1);   // 關鍵
		mYear2 = c.get(Calendar.YEAR);
		mMonth2 = c.get(Calendar.MONTH) + 1;
		mDay2 = c.get(Calendar.DAY_OF_MONTH);
		
		dp1 = (DatePicker)view.findViewById(R.id.dp1);
		dp1.init(mYear1, mMonth1 - 1, mDay1, new DatePicker.OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				mYear1 = year;
				mMonth1 = monthOfYear + 1;
				mDay1 = dayOfMonth;
			}
		});
		
		dp2 = (DatePicker)view.findViewById(R.id.dp2);
		dp2.init(mYear2, mMonth2 - 1, mDay2, new DatePicker.OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				mYear2 = year;
				mMonth2 = monthOfYear + 1;
				mDay2 = dayOfMonth;
			}
		});
		
		return view;
	}
}
