package com.cwbuyer.lib;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.adapter.TableAdapter.TableCell;
import com.cwbuyer.adapter.TableAdapter.TableRow;
import com.cwbuyer.code.CodeList;
import com.cwbuyer.code.CodeMode;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.ItemData;
import com.cwbuyer.format.KeySet;
import com.pwbuyer.main.R;

//銷售王的核心2層式ADAPTER,複製自 MANAGEITEM採購王
@SuppressLint({ "UseSparseArrays", "InflateParams", "HandlerLeak" })
@SuppressWarnings("unused")
public class QRep_01 extends Activity{
	
	ReportAdapter mAdapter = null;
	
//	private LinkedList<RepData> mList = new LinkedList<RepData>();
	
	TextView mTextDuration = null;

	LinearLayout mDisplayStk;
//ACTION 預設模式 POS定義為 銷貨單;預購單;暫存單;單頭+單身	
	int mMode = KeySet.SearchMode.WEEK;
	RepData datas=null;	
	private final int RESULT_GALLERY=6666; 		//GALLERY
	
	private final int COUNTRY_CODE = 1001;
	final String myAlbunList =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",8)+File.separator+"Goods_albun.lst";	
	String countryN="";
	int country = 0;
	private List<HashMap<String, Object>> albun_list = null;
	
	int mGroupMode = GroupMode.TOP1;  //預設初始到新品 

	ItemData detailData;	
	/** State :  true 正式 , false 樣品*/
	String mEndDay = null;
	String mStartDay = null;
	String dbEndDay = null;
	String dbStartDay = null;
	String mLimitDay = null;//WeiLa七天限制
	int WeiLa=0; //0不限制 1限七天
	int PSWD=0;
	String[] dataSend =Utilis.getIni(this,"SYS","DATA_SEND",9).split("!&!");	
	
	int off_line=Utilis.toInt(Utilis.getIni(QRep_01.this, "SYS", "IMPORT", 3));
	int nPart=0;
	String isSupply="1";
	int orderMode=9;
	StringBuffer sPrintB = new StringBuffer();
	String[] deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");	
	String[] ImportStr =Utilis.getIni(this,"SYS","IMPORT",9).split("!&!");	
	int mCloud=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT_SEND",4));
	String clouds="http://"+Utilis.getIni(this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(this, "SYS", "IMPORT", 2)+File.separator;
	String uriAPI1=clouds+"qrep01_1.php";
	String uriAPI2=clouds+"qrep01_2.php";
	String uriAPI3=clouds+"qrep01_3.php";
	String uriAPI30=clouds+"qrep01_30.php";
	String SQLADD="";	
	int deptN=1;
	String mDept="";
	String mPart="";
	String [] DepNo;
	String [] DepNa;
	int ColNoSizN=0;
	String [][] ColNoSiz;	
   	int [][] Otott;
   	
	String ColorSplit [];
	String SizeSplit [];
	protected static final int REFRESH_DATA = 0x00000001;
	public ProgressDialog myDialog = null;  	

	String[] mode_E={ "","新品排行", "暢銷排行","下單排行","追加排行","預購排行"};
	String mKind=null; //單別 102030405060
	private String batch;
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);
	final String myPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"cwbuyer/IMPORT/";
	final String defPic=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png";	
	
	int nKind=30;
	DatePicker dp1;
	DatePicker dp2;
	
   	String btns=null;
   	String[] bttns;
   	int TT10=0;  	//總進貨量
   	int TM10=0; 	//總進貨額
   	int TT30=0;	//總銷貨量
   	int TM30=0;	//總銷貨額
   	int TS30=0;	//總銷貨額
   	int StkT=0;		//總存貨量
   	int StkM=0;	//總存貨額
   	
   	int T10=0;  	//本進貨量
   	int M10=0; 	//本進貨額
   	int T30=0;		//本銷貨量
   	int M30=0;	//本銷貨額
   	int S30=0;	//本銷貨額
   	int Profit=0; 	//本期毛利
   	int Profits=0; //本期利率
	
	private int mYear1 = 0;
	private int mYear2 = 0;
	private int mMonth1 = 0;
	private int mMonth2 = 0;
	private int mDay1 = 0;
	private int mDay2 = 0;
	
	ListView mListView = null;
	ExpandableListView mExpandListView = null;
	
//For  Table
	int Wheight;
	int Wwidth;
	int tableHeight=30;
	int tabless=6;

	private LinearLayout lTableView = null;
	private LinearLayout mLayoutRoot = null;
	private ArrayList<String> mArrayColorNumber = new ArrayList<String>();
	private ArrayList<String> mArrayColorName = new ArrayList<String>();
	LinkedList<String> mSizeLink = new LinkedList<String>();
	LinkedList<String> mSizeLink1 = new LinkedList<String>();
	LinkedList<String> mColorLink = new LinkedList<String>();
	
	HashMap<Integer,Integer> mCountRow = new HashMap<Integer,Integer>(); // 顏色行資料
	HashMap<Integer,String> mCountCell = new HashMap<Integer,String>();  // 尺寸欄資料
	

	public class RepData{ 
		public String iPic;  
		public String iGoods; 
		public String iImpo; 
		public String iName; 
		public String iMoney;
		public String iCountry;
		public String iNumber;
		public String iCompany;
		public String iFormdate;
		public String iUnit2;
		public int iSort;
		
	}
	
	
	
	
//@@日後需補充用ITEM檢測HEAD是否漏掉的清單,並自動修補	
	public interface GroupMode{//EVERYDAY/WEEK/MONTH 以FORMDATE
		int TOP1=1;		//到新品 //依會員
		int TOP2 = 2;  	//暢銷品 	//依櫃員
		int TOP3 = 3; 	//預購區 	//依門市
		int TOP4 = 4; 	//追加品	//依廠商
		int TOP5 = 5; 	//預購統計輸出圖6X3  (日期範圍)拉出所有銷貨訂單或留貨
		int TOP6 = 6; 	//依顏色
		int TOP7 = 7; 	//依尺寸
		int TOP8 = 8; 	//依國別
		int TOP9 = 9; 	//依季節
		
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent dataR) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, dataR);
		
		if (requestCode == COUNTRY_CODE) {
			if (resultCode == RESULT_OK) {
				country = dataR.getIntExtra("country_id", 0);
				//String pid = dataR.getStringExtra("country_pic");
				countryN = dataR.getStringExtra("country_name");
				//double rate = dataR.getDoubleExtra("country_rate", 0);
				try{
		//以日期範圍,輸出貨號或來源編號,國別,門市代號,總倉或門市帶入雲端
		//參考MakeTransDetail 兩段程式碼
		//門市與總倉需判斷 區隔是門市統計 或 全面統計
		//這是第一層,先取得CLOUD
		//第二層 從第一層 一一統計,並從Cloud 產生出MKQRST所要的規格List 帶回
		//就可以直接呼叫 Mkqrst
		//如何防範 QDETAIL 找不到 這是因為需要統一 內容
					
			final StringBuffer bufi = new StringBuffer();
	    	//int mkqrSource=Utilis.toInt(dataSend[5]);//0預購或號1預購來源
			dbStartDay=mStartDay.replace("/", "-");
			dbEndDay=mEndDay.replace("/", "-");
			//應包含 SOURCENO,SUPPLY
    		//order by SUPPLY,GOODSNO
			bufi.append("select GOODSNO,SUPPLY,SOURCENO,UNIT1,SIZE,sum(UNIT) from qitems ")
			.append(" where FORMDATE>='").append(dbStartDay).append("' and FORMDATE<='").append(dbEndDay).append("'")
	   		.append(" and (QKIND='30' or QKIND='31') and (COUNTRY='"+countryN+"' or COUNTRY='"+country+"')")
			.append("  and (ISCONFIRM='O' or (ISCONFIRM='N' and ISCHECK='Y'))");
			bufi.append(SQLADD);
			bufi.append(" group by SUPPLY,GOODSNO,SOURCENO,UNIT1,SIZE order by SUPPLY,GOODSNO,UNIT1,SIZE");
			
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
			
				bfstr.append(Utilis.getIni(QRep_01.this, "SYS", "IMPORT", 2)).append(";");
				bfstrF.append("UID").append(";");
				bfstr.append(dbStartDay).append(";");
				bfstrF.append("STARTDAY").append(";");
				bfstr.append(dbEndDay).append(";");
				bfstrF.append("ENDDAY").append(";");
				bfstr.append(bufi.toString());
				bfstrF.append("SQLADD");
				final String []fields=bfstr.toString().split(";");
				final String []fieldFs=bfstrF.toString().split(";");
				
			      myDialog = ProgressDialog.show(QRep_01.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
				  
			      new Thread()
			      { 
			        public void run()
			        { 
			          try
			          { 
							HttpPost httpRequest = new HttpPost(uriAPI30);
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+bufi.toString());
							for(int x=0;x<fields.length;x++){
								params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
							}
							try {
								// 發出HTTP request(請求) 
								httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								// 取得HTTP response(回傳) 
								HttpResponse httpResponse = new DefaultHttpClient()
										.execute(httpRequest);
								if (httpResponse.getStatusLine().getStatusCode() == 200)
								{
									// 取出回應字串
									String strResult = EntityUtils.toString(httpResponse	.getEntity());
									mHandlerQDR_30.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
								}
								
							} catch (Exception e)
							{
								e.printStackTrace();
							}

			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			            // 卸載所建立的myDialog物件。
			            myDialog.dismiss();
			          }
			        }
			      }.start(); 
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
			
    }

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qrep01);
        PSWD=Utilis.toInt(deptStr[4]);
        if (PSWD!=0 && Utilis.toInt(Utilis.getIni(this,"SYS","DEPT_SEND",2))==1) WeiLa=1;
		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Wwidth = dm.widthPixels;
        Wheight = dm.heightPixels;

		tableHeight=(int) (Wheight/24);
		if (Wwidth<=800) tabless=(int) (Wwidth/100)+2; else  tabless=(int) (Wwidth/140)+1;
		
        mTextDuration = (TextView)findViewById(R.id.text_duration);
        //@@應增加營業時間的判斷而視為當日或前一天
        mStartDay =DateUtil.getCurrentDate();  //2012/10/15 將 batch 視為當日的關鍵"/"
        mEndDay=mStartDay;
        
        mMode = getIntent().getIntExtra("search_mode", KeySet.SearchMode.WEEK);		
        mGroupMode= getIntent().getIntExtra("search_group", GroupMode.TOP1);	
        
//        mMode = getIntent().getIntExtra("search_mode", SearchModeS.WEEK);
        //暫時不開放外部決定哪一種方式 預設為 週
//        nKind =getIntent().getIntExtra("QRep_01", PItemKind.TR10); //預設為進貨單
//        mKind=""+nKind;

        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());		//離開
        
        ((Button)findViewById(R.id.btn_sort_top1)).setOnClickListener(new MainClick()); //到新品
        ((Button)findViewById(R.id.btn_sort_top2)).setOnClickListener(new MainClick()); //暢銷品
        ((Button)findViewById(R.id.btn_sort_top3)).setOnClickListener(new MainClick()); //預購區
        ((Button)findViewById(R.id.btn_sort_top4)).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_btn0)).setOnClickListener(new MainClick());	//日        
        ((Button)findViewById(R.id.btn_btn1)).setOnClickListener(new MainClick());	//週        
        ((Button)findViewById(R.id.btn_btn2)).setOnClickListener(new MainClick());  //月
        ((Button)findViewById(R.id.btn_btn3)).setOnClickListener(new MainClick());//季
        ((Button)findViewById(R.id.btn_btn4)).setOnClickListener(new MainClick()); //批號        

        lTableView = (LinearLayout)findViewById(R.id.tableview);
    	mLayoutRoot = (LinearLayout)findViewById(R.id.root);
        
    	mDisplayStk = (LinearLayout)findViewById(R.id.layout_bottom);
    	mDisplayStk.setVisibility(View.GONE);
    	
        mListView = (ListView)findViewById(R.id.list_item);
        mAdapter = new ReportAdapter(this);
        mListView.setAdapter(mAdapter);
        
        if (PSWD!=0 || mGroupMode==GroupMode.TOP3){  //密碼OK 或不用密碼
        	((LinearLayout)findViewById(R.id.layout_top)).setVisibility(View.GONE);
        }else{
        	((LinearLayout)findViewById(R.id.layout_top)).setVisibility(View.VISIBLE);
        }
        
        //原先就是執行一遍 因為不會中途改變模式
        //現在是可以切換
        //只要一切換,都會從最近日期範圍貨最近一批最近一季起算
		//應追加 上一批 的程式
        mDept=deptStr[0];
        mPart=deptStr[5];
        if (!mDept.equalsIgnoreCase(mPart)) nPart=1;  //門市版
        SQLiteDatabase db = Utilis.getDB(this);		
		Cursor cs =db.rawQuery("select CUSTNO,CUSTNAME from qcust where TR='20' and  CUSTNO <>'"+mPart+"' order by CUSTNO",null);
		if (cs.getCount()>0){
			deptN=cs.getCount()+1;
			DepNo=new String[deptN];
			DepNa=new String[deptN];
			cs.moveToFirst();
			for (int i=0;i<cs.getCount();i++){
				DepNo[i+1]=cs.getString(0);
				DepNa[i+1]=cs.getString(1);
				cs.moveToNext();
			}
		}else{
			deptN=1;
			DepNo=new String[deptN];
			DepNa=new String[deptN];
		}
		DepNo[0]=mPart;
		DepNa[0]=deptStr[6];
		
		db.close();
		cs.close();
        
        switch(mGroupMode){
        case GroupMode.TOP1:
        	resetButton(R.id.btn_sort_top1);
        	break;
        case GroupMode.TOP2:
        	resetButton(R.id.btn_sort_top2);
        	break;
        case GroupMode.TOP3:
        	resetButton(R.id.btn_sort_top3);
        	break;
        case GroupMode.TOP4:
        	resetButton(R.id.btn_sort_top4);
        	break;
        case GroupMode.TOP5:  //預購統計出圖
        	resetButton(R.id.btn_sort_top3);
        	break;
        }
        chkMode();
        
        
        
        mListView.setOnItemLongClickListener(new OnItemLongClickListener(){

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				datas = (RepData) mAdapter.getItem(arg2);
				
				//應在MKQR make_mode=9:同單 10:依廠商分單
				//可以在門市也可以產生採購單
				String E_Menu[];
			if(mGroupMode==GroupMode.TOP3 || mGroupMode==GroupMode.TOP5){
					E_Menu=new String[] {"輸出採購訂單(附圖)","依廠商輸出採購訂單(附圖)","產生採購訂單(放在採購新品)","依廠商產生採購訂單(放在採購新品)","追蹤","返回"};
				Utilis.runVibrate(QRep_01.this);
				DialogUtilis.showDialog(QRep_01.this, "請選擇以下功能", -1,
						E_Menu, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								switch (pos) {
								case 0: //輸出採購訂單
								{
//									if  (Utilis.haveInternet(QRep_01.this) && off_line==1){
//										//詢問國別
//										isSupply="1";
//										orderMode=9;
//										selectCountry();
										
//									}else{
										Intent intent = new Intent();
										intent.setClass(QRep_01.this,MakeTransDetail.class);
										intent.putExtra("make_mode",9);   //不分廠商,全放在一起
										intent.putExtra("make_batch","");  //空値  如果非空値視為單號條件
										intent.putExtra("make_user","");  //空値
										intent.putExtra("make_kind",1);  //0.採購單  1.非採購單 10203040213141可以輸入單別
										intent.putExtra("make_startday",mStartDay);  
										intent.putExtra("make_endday",mEndDay);  
										startActivity(intent);
//									}
									break;	
								}
								case 1: //依廠商輸出採購訂單
								{
//									if  (Utilis.haveInternet(QRep_01.this) && off_line==1){
										//詢問國別
//										isSupply="4";
//										orderMode=10;
//										selectCountry();
										
//									}else{
									Intent intent = new Intent();
									intent.setClass(QRep_01.this,MakeTransDetail.class);
									intent.putExtra("make_mode",10);   //分廠商,分圖
									intent.putExtra("make_batch","");  //空値  如果非空値視為單號條件
									intent.putExtra("make_user","");  //空値
									intent.putExtra("make_kind",1);  //0.採購單  1.非採購單 10203040213141可以輸入單別
									intent.putExtra("make_startday",mStartDay);  
									intent.putExtra("make_endday",mEndDay);  
									startActivity(intent);
//									}
									break;	
								}
								case 2: //產生採購訂單
								{
								        SQLiteDatabase db = Utilis.getDB(QRep_01.this);		
										Cursor cs = null;
										StringBuffer bufItems =new StringBuffer();
										//先檢查該批號存在否? 應先清除!!
										String Ddy1=mStartDay.replaceAll("/", "-");
										String Ddy2=mEndDay.replaceAll("/", "-");
										String mBATCH=(Ddy1.replaceAll("-","").substring(3)+Ddy2.replaceAll("-","").substring(3));
										db.execSQL("delete from qdetail where BATCH='"+mBATCH+"'");
										
										bufItems.append("select GOODSNO,COLOR,SIZE,sum(UNIT) as SUM30 from qitems")
										.append(" where FORMDATE >= '").append(Ddy1).append("'").append(" and FORMDATE <= '").append(Ddy2).append("'")
										.append(" and ISCONFIRM<>'R' and (QKIND ='30' or QKIND ='31')")
										.append(SQLADD)
										.append(" group by GOODSNO,COLOR,SIZE");
										//可以取得條件內的預購單
										String Goods="";
										String GoodsO="";
										int nNew=0;
										cs=db.rawQuery(bufItems.toString(), null);
										if (cs.getCount()>0){
											cs.moveToFirst();
											Goods=cs.getString(0);GoodsO=Goods;
											String SQLdetail="select * from qdetail where GOODSNO='"+Goods+"' order by MID DESC LIMIT 1";
											Cursor csd=db.rawQuery(SQLdetail, null);
											if (csd.getCount()>0){
												csd.moveToFirst();
												detailData = DBUtil.CItem.parseData(csd, true);
												//讀取了內容 最後只要 改 CREATEDATETIME BILL INLIST BATCH
											}else{ //找不到QDETAIL,自行產生一份
												detailData=makeD(db,Goods);
											}
											makeE();//歸零&初始化
											for(int ii=0;ii<cs.getCount();ii++){
												Goods=cs.getString(0);
												if (!GoodsO.equalsIgnoreCase(Goods)){
													//存入一筆新的
													//@@@須檢查是否重複_DATA 則需更新
													//傳入批號&IMPO總件數
													makeF(db,mBATCH,nNew);//整頓存入檔
													nNew=0;
													 GoodsO=Goods;
														SQLdetail="select * from qdetail where GOODSNO='"+Goods+"' order by MID DESC LIMIT 1";
														csd=db.rawQuery(SQLdetail, null);
														if (csd.getCount()>0){
															csd.moveToFirst();
															detailData = DBUtil.CItem.parseData(csd, true);
															//讀取了內容 最後只要 改 CREATEDATETIME BILL INLIST BATCH
														}else{ //找不到QDETAIL,自行產生一份
															detailData=makeD(db,Goods);
														}
														makeE();//歸零&初始化
												}//繼續將顏色尺進行裝填
														for(int ix=0;ix<ColorSplit.length;ix++){
															if (ColorSplit[ix].equalsIgnoreCase(cs.getString(1))){
																for(int iy=0;iy<SizeSplit.length;iy++){
																	if (SizeSplit[iy].equalsIgnoreCase(cs.getString(2))){
																		ColNoSiz[ix][iy]=cs.getString(3);
																		nNew=nNew+cs.getInt(3);
																		break;
																	}
																}
																break;
															}	
														}
												cs.moveToNext();
											}
										}
										if (nNew!=0){//最後一筆,要寫入
											makeF(db,mBATCH,nNew);//整頓存入檔
										}
										//@@@也要把所有圈定的客訂Qitems 的HANDNO 存入廠商訂單
										//@@@qitems HENDNO 卻影響到歷史價的問題
/*										
										bufItems.delete(0, bufItems.toString().length());
										bufItems.append(" update qitems set HANDNO='").append(mBATCH).append("',BATCH='").append(mBATCH)
										.append("' where FORMDATE >= '").append(Ddy1).append("'").append(" and FORMDATE <= '").append(Ddy2).append("'")
										.append(" and ISCONFIRM<>'R' and (QKIND ='30' or QKIND ='31')");
										db.execSQL(bufItems.toString());
										
										bufItems.delete(0, bufItems.toString().length());
										bufItems.append(" update qhead set TR='Y1',EMPNAME='").append(mBATCH)
										.append("' where FORMDATE >= '").append(Ddy1).append("'").append(" and FORMDATE <= '").append(Ddy2).append("'")
										.append(" and ISCONFIRM <>'R' and (QKIND ='30' or QKIND ='31')");
										db.execSQL(bufItems.toString());
										//@@@還須思考 這是在總倉完成的客訂追加的資料,也須更新後Y1 讓資料回傳門市
										//如何可以讓銷貨單頭也可以註解
*/										  
										 
										db.close();
										cs.close();
										//Toast.makeText(QRep_01.this, "將預購統計存入[採購新品]批號:"+mBATCH+" 成功了!!", Toast.LENGTH_SHORT).show();
									break;	
								}
								case 3: //依廠商產生採購訂單
								{
								        SQLiteDatabase db = Utilis.getDB(QRep_01.this);		
										Cursor cs = null;
										StringBuffer bufItems =new StringBuffer();
										//先檢查該批號存在否? 應先清除!!
										String Ddy1=mStartDay.replaceAll("/", "-");
										String Ddy2=mEndDay.replaceAll("/", "-");
										String Supplys="";
										String mBATCH="";
										String SQLdetail="select SUPPLY from qitems where FORMDATE>='"+Ddy1+"' and FORMDATE<='"+Ddy2+"' and ISCONFIRM<>'R' and (QKIND ='30' or QKIND ='31') group by SUPPLY";
										Cursor csSupply=db.rawQuery(SQLdetail, null);
										if (csSupply.getCount()>0){		
											csSupply.moveToFirst();
											for(int i=0;i<csSupply.getCount();i++){
												Supplys=csSupply.getString(0);
												mBATCH=(Ddy1.replaceAll("-","").substring(3)+Ddy2.replaceAll("-","").substring(3))+"_"+Supplys;
												db.execSQL("delete from qdetail where BATCH='"+mBATCH+"'");
												bufItems.delete(0, bufItems.toString().length());
												
												bufItems.append("select GOODSNO,COLOR,SIZE,sum(UNIT) as SUM30 from qitems")
												.append(" where FORMDATE >= '").append(Ddy1).append("'").append(" and FORMDATE <= '").append(Ddy2).append("'")
												.append(" and ISCONFIRM<>'R' and (QKIND ='30' or QKIND ='31')")
												.append(" and SUPPLY='"+Supplys+"' group by GOODSNO,COLOR,SIZE");
												//可以取得條件內的預購單
												String Goods="";
												String GoodsO="";
												int nNew=0;
												cs=db.rawQuery(bufItems.toString(), null);
												if (cs.getCount()>0){
													cs.moveToFirst();
													Goods=cs.getString(0);GoodsO=Goods;
													SQLdetail="select * from qdetail where GOODSNO='"+Goods+"' order by MID DESC LIMIT 1";
													Cursor csd=db.rawQuery(SQLdetail, null);
													if (csd.getCount()>0){
														csd.moveToFirst();
														detailData = DBUtil.CItem.parseData(csd, true);
														//讀取了內容 最後只要 改 CREATEDATETIME BILL INLIST BATCH
													}else{ //找不到QDETAIL,自行產生一份
														detailData=makeD(db,Goods);
													}
													makeE();//歸零&初始化
													for(int ii=0;ii<cs.getCount();ii++){
														Goods=cs.getString(0);
														if (!GoodsO.equalsIgnoreCase(Goods)){
															//存入一筆新的
															//@@@須檢查是否重複_DATA 則需更新
															//傳入批號&IMPO總件數
															makeF(db,mBATCH,nNew);//整頓存入檔
															nNew=0;
															 GoodsO=Goods;
																SQLdetail="select * from qdetail where GOODSNO='"+Goods+"' order by MID DESC LIMIT 1";
																csd=db.rawQuery(SQLdetail, null);
																if (csd.getCount()>0){
																	csd.moveToFirst();
																	detailData = DBUtil.CItem.parseData(csd, true);
																	//讀取了內容 最後只要 改 CREATEDATETIME BILL INLIST BATCH
																}else{ //找不到QDETAIL,自行產生一份
																	detailData=makeD(db,Goods);
																}
																makeE();//歸零&初始化
														}//繼續將顏色尺進行裝填
																for(int ix=0;ix<ColorSplit.length;ix++){
																	if (ColorSplit[ix].equalsIgnoreCase(cs.getString(1))){
																		for(int iy=0;iy<SizeSplit.length;iy++){
																			if (SizeSplit[iy].equalsIgnoreCase(cs.getString(2))){
																				ColNoSiz[ix][iy]=cs.getString(3);
																				nNew=nNew+cs.getInt(3);
																				break;
																			}
																		}
																		break;
																	}	
																}
														cs.moveToNext();
													}
												}
												if (nNew!=0){//最後一筆,要寫入
													makeF(db,mBATCH,nNew);//整頓存入檔
												}
												//Toast.makeText(QRep_01.this, "將預購統計存入[採購新品]批號:"+mBATCH+" 成功了!!", Toast.LENGTH_SHORT).show();
												csSupply.moveToNext();
											}
											csSupply.close();
/*											
											//@@@也要把所有圈定的客訂Qitems 的HANDNO 存入廠商訂單
											bufItems.delete(0, bufItems.toString().length());
											bufItems.append(" update qitems set HANDNO='").append(mBATCH).append("',BATCH='").append(mBATCH)
											.append("' where FORMDATE >= '").append(Ddy1).append("'").append(" and FORMDATE <= '").append(Ddy2).append("'")
											.append(" and ISCONFIRM<>'R' and (QKIND ='30' or QKIND ='31')")
											.append(" and SUPPLY='"+Supplys+"'");
											db.execSQL(bufItems.toString());
											
											bufItems.delete(0, bufItems.toString().length());
											bufItems.append(" update qhead set TR='Y1',EMPNAME='").append((Ddy1.replaceAll("-","").substring(3)+Ddy2.replaceAll("-","").substring(3)))
											.append("' where FORMDATE >= '").append(Ddy1).append("'").append(" and FORMDATE <= '").append(Ddy2).append("'")
											.append("and ISCONFIRM <>'R' and (QKIND ='30' or QKIND ='31')");
											db.execSQL(bufItems.toString());
											//@@@還須思考 這是在總倉完成的客訂追加的資料,也須更新後Y1 讓資料回傳門市
											//如何可以讓銷貨單頭也可以註解
*/
											db.close();
											cs.close();
										}
									break;	
								}
								case 4://追蹤
								{
									goQhis();									
									break;
								}
								case 5: //返回
								}
							}
						});
				return false;
			//}else if(mGroupMode==GroupMode.TOP1|| mGroupMode==GroupMode.TOP2 || mGroupMode==GroupMode.TOP4){
			}else if(mGroupMode==GroupMode.TOP4){
				E_Menu=new String[]{"印製廠商追加清單","印製廠商追加清單A4","追蹤","返回",};
				Utilis.runVibrate(QRep_01.this);
				DialogUtilis.showDialog(QRep_01.this, "請選擇以下功能", -1,
						E_Menu, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								switch (pos) {
								case 0: //
								{
					    			int count =mAdapter.getCount()  ;
					    			if (count>0){  //
									String compStr[]=Utilis.getIni(QRep_01.this,"USER","COMPANY",9).split("!&!");
									String sepa="\r\n";
									sPrintB = new StringBuffer();
									
									int Loca=0;
									sPrintB=PosUtilis.getPrintKind(QRep_01.this,Utilis.toInt(compStr[8]));
									Loca=0;
									
									Loca=Loca+32;	sPrintB.append("AZ,20,"+Loca+",2,2,0,0,"+compStr[0]+sepa);
									Loca=Loca+50;	sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+"期間:"+mStartDay+"~"+mEndDay+"  商品暢銷追加建議表 "+sepa);
									Loca=Loca+30;	sPrintB.append("AZ,20,"+Loca+",2,2,0,0,"+"==============================="+sepa);
									Loca=Loca+22;
						    			for (int i = 0; i <count ; i++){
											datas = (RepData) mAdapter.getItem(i);
											String ColName=ColorGetName(QRep_01.this,datas.iGoods.substring(datas.iGoods.indexOf("-")+1,datas.iGoods.lastIndexOf("-")));
											Loca=Loca+50;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+datas.iName+"/  貨號:"+datas.iGoods+"("+ColName+")"+sepa);
											Loca=Loca+50;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,品名:"+datas.iCountry+"/    "+datas.iCompany.substring(0,datas.iCompany.indexOf("/"))+"件"+sepa);
											Loca=Loca+50;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+datas.iImpo.substring(0,datas.iImpo.lastIndexOf("/"))+"    "+datas.iMoney.substring(0,datas.iMoney.lastIndexOf("/"))+"  "+datas.iCompany.substring(datas.iCompany.indexOf("/"))+sepa);
											Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",2,2,0,0,"+"--------------------------"+sepa);

											if (Loca>2400){
												PosUtilis.startPartPrint(QRep_01.this,sPrintB,Loca );
												sPrintB.delete(0, sPrintB.toString().length());
												SystemClock.sleep(3000);
												sPrintB=PosUtilis.getPrintKind(QRep_01.this,Utilis.toInt(compStr[8]));
												Loca=0;
											}
						    			}
										if (sPrintB.toString().length()>0){
											PosUtilis.startPrint(QRep_01.this,sPrintB,Loca);
										}
						    			
					    			}
					    			break;
								}
								case 1: //廠商追加印製A4
								{
									if (PSWD!=1){
						    			int count =mAdapter.getCount()  ;
						    			if (count>0){  //
										String compStr[]=Utilis.getIni(QRep_01.this,"USER","COMPANY",9).split("!&!");
										String sepa=";SSSS\r\n";
										sPrintB = new StringBuffer();
										sPrintB.append("期間:"+mStartDay+"~"+mEndDay+"  商品暢銷追加建議表 "+sepa);
							    			for (int i = 0; i <count ; i++){
												datas = (RepData) mAdapter.getItem(i);
												String ColName=ColorGetName(QRep_01.this,datas.iGoods.substring(datas.iGoods.indexOf("-")+1,datas.iGoods.lastIndexOf("-")));
												sPrintB.append(datas.iName+";"+datas.iGoods+"("+ColName+");");
												sPrintB.append(datas.iCountry+";"+datas.iCompany.substring(datas.iCompany.indexOf(":")+1,datas.iCompany.indexOf("/"))+";");
												sPrintB.append(datas.iImpo.substring(datas.iImpo.indexOf(":")+1,datas.iImpo.indexOf("/")+1)+datas.iImpo.substring(datas.iImpo.lastIndexOf(":")+1,datas.iImpo.lastIndexOf("/"))+";");
												sPrintB.append(datas.iMoney.substring(datas.iMoney.indexOf(":")+1,datas.iMoney.indexOf("/")+1)+datas.iMoney.substring(datas.iMoney.lastIndexOf(":")+1,datas.iMoney.lastIndexOf("/"))+";");
												sPrintB.append(datas.iCompany.substring(datas.iCompany.lastIndexOf(":")+1)+sepa);
							    			}
							    			//呼叫MktrSt (xMode=7 廠商追加建議 
											Intent intent = new Intent();
											//bundle.putString("Mkqrs",compStr[0]+",  期間:"+mStartDay+"~"+mEndDay+"  商品暢銷追加建議表,7,,"+sPrintB.toString());
											intent.putExtra("SERCH",compStr[0]);
											intent.putExtra("QKIND",mStartDay+"~"+mEndDay+"  最新商品排行");
											intent.putExtra("MODE",7);
											intent.putExtra("DEPTNO",mDept);
											intent.putExtra("BUFSTR",sPrintB.toString());
											intent.putExtra("BUFTITLE","1;2;3");
											intent.putExtra("STARTDAY",mStartDay);
											intent.putExtra("ENDDAY",mEndDay);
	
											intent.setClass(QRep_01.this, MkqrSt.class);
											startActivity(intent);
						    			}
					    			}
					    			break;
								}
								case 2://追蹤
								{
									goQhis();									
									break;
								}
								case 3:break;
								
								}
							}
				});
				return false;
			}else if(mGroupMode==GroupMode.TOP1){ //新品排行
				E_Menu=new String[]{"印製新品排行","印製新品排行A4","追蹤","返回",};
				Utilis.runVibrate(QRep_01.this);
				DialogUtilis.showDialog(QRep_01.this, "請選擇以下功能", -1,
						E_Menu, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								switch (pos) {
								case 0: //印製新品排行
								{
//								if (PSWD!=1){
					    			int count =mAdapter.getCount()  ;
					    			if (count>0){  //
									String compStr[]=Utilis.getIni(QRep_01.this,"USER","COMPANY",9).split("!&!");
									String sepa="\r\n";
									sPrintB = new StringBuffer();
									int Loca=0;
									sPrintB=PosUtilis.getPrintKind(QRep_01.this,Utilis.toInt(compStr[8]));
									
									Loca=Loca+32;	sPrintB.append("AZ,20,"+Loca+",2,2,0,0,"+compStr[0]+sepa);
									Loca=Loca+50;	sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+"期間:"+mStartDay+"~"+mEndDay+"  新品排行 "+sepa);
									Loca=Loca+30;	sPrintB.append("AZ,20,"+Loca+",2,2,0,0,"+"==============================="+sepa);
									Loca=Loca+10;
						    			for (int i = 0; i <count ; i++){
											datas = (RepData) mAdapter.getItem(i);
											Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+"商品:"+datas.iGoods+"/"+datas.iName+" ("+datas.iNumber+")"+sepa);
											Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+datas.iMoney+"  ("+datas.iCountry+")"+sepa);
											Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+datas.iImpo+"  "+datas.iCompany+sepa);
											Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",2,1,0,0,"+"--------------------------"+sepa);
											if (Loca>2400){
												PosUtilis.startPartPrint(QRep_01.this,sPrintB,Loca );
												sPrintB.delete(0, sPrintB.toString().length());
												SystemClock.sleep(3000);
												sPrintB=PosUtilis.getPrintKind(QRep_01.this,Utilis.toInt(compStr[8]));
												Loca=0;
											}
						    			}
						    			
						    			if (sPrintB.toString().length()>0){
											PosUtilis.startPrint(QRep_01.this,sPrintB,Loca);
										}
						    			
					    			}
//								}else{
//									Toast.makeText(QRep_01.this, "請注意權限!!", Toast.LENGTH_SHORT).show();										
//								}
					    			break;
								}
								case 1: //印製新品排行A4
								{
//									if (PSWD!=1){
						    			int count =mAdapter.getCount()  ;
						    			if (count>0){  //
										String compStr[]=Utilis.getIni(QRep_01.this,"USER","COMPANY",9).split("!&!");
										String sepa=";SSSS\r\n";
										sPrintB = new StringBuffer();
										sPrintB.append("期間:"+mStartDay+"~"+mEndDay+"  最新商品排行 "+sepa);
							    			for (int i = 0; i <count ; i++){
												datas = (RepData) mAdapter.getItem(i);
												sPrintB.append(datas.iGoods+";");
												String GoodsName=datas.iName;
												if (datas.iName.length()>10) GoodsName=datas.iName.substring(0, 10);
												sPrintB.append(GoodsName+";");
												String ColorName=datas.iCountry;
												if (ColorName.length()>8) ColorName=ColorName.substring(0, 8);
												sPrintB.append(""+ColorName+";"+datas.iImpo+";");
												sPrintB.append(datas.iMoney+";"+datas.iCompany+sepa);
							    			}
							    			//呼叫MktrSt (xMode=8  
											//Bundle bundle = new Bundle();
											//bundle = new Bundle();
											//bundle.putString("Mkqrs",compStr[0]+",  期間:"+mStartDay+"~"+mEndDay+"  最新商品排行,8,,"+sPrintB.toString());
											//intent.putExtras(bundle);
							    			
											Intent intent = new Intent();
											
											intent.putExtra("SERCH",compStr[0]);
											intent.putExtra("QKIND",mStartDay+"~"+mEndDay+"  最新商品排行");
											intent.putExtra("MODE",8);
											intent.putExtra("DEPTNO",mDept);
											intent.putExtra("BUFSTR",sPrintB.toString());
											intent.putExtra("BUFTITLE","1;2;3");
											intent.putExtra("STARTDAY",mStartDay);
											intent.putExtra("ENDDAY",mEndDay);

											intent.setClass(QRep_01.this, MkqrSt.class);
											startActivity(intent);
						    			}
//									}else{
//										Toast.makeText(QRep_01.this, "請注意權限!!", Toast.LENGTH_SHORT).show();										
//									}
					    			break;
								}
								case 2://追蹤
								{
									goQhis();									
									break;
								}
								case 3:break;
								
								}
							}
				});
				return false;
			}else if(mGroupMode==GroupMode.TOP2){ //暢銷排行
				E_Menu=new String[]{"印製暢銷排行","印製暢銷排行A4","追蹤","返回",};
				Utilis.runVibrate(QRep_01.this);
				DialogUtilis.showDialog(QRep_01.this, "請選擇以下功能", -1,
						E_Menu, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								switch (pos) {
								case 0: //印製暢銷排行
								{
					    			int count =mAdapter.getCount()  ;
					    			if (count>0){  //
									String compStr[]=Utilis.getIni(QRep_01.this,"USER","COMPANY",9).split("!&!");
									String sepa="\r\n";
									sPrintB = new StringBuffer();
									int Loca=0;
									sPrintB=PosUtilis.getPrintKind(QRep_01.this,Utilis.toInt(compStr[8]));
									
									Loca=Loca+32;	sPrintB.append("AZ,20,"+Loca+",2,2,0,0,"+compStr[0]+sepa);
									Loca=Loca+50;	sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+"期間:"+mStartDay+"~"+mEndDay+"  商品暢銷排行 "+sepa);
									Loca=Loca+30;	sPrintB.append("AZ,20,"+Loca+",2,2,0,0,"+"==============================="+sepa);
									Loca=Loca+10;
						    			for (int i = 0; i <count ; i++){
											datas = (RepData) mAdapter.getItem(i);
											Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+"商品:"+datas.iGoods+"/"+datas.iName+" ("+datas.iNumber+")"+sepa);
											Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+datas.iMoney+"  ("+datas.iCountry+")"+sepa);
											Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+datas.iImpo+"  "+datas.iCompany+sepa);
											Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",2,1,0,0,"+"--------------------------"+sepa);
											if (Loca>2400){
												PosUtilis.startPartPrint(QRep_01.this,sPrintB,Loca );
												sPrintB.delete(0, sPrintB.toString().length());
												SystemClock.sleep(3000);
												sPrintB=PosUtilis.getPrintKind(QRep_01.this,Utilis.toInt(compStr[8]));
												Loca=0;
											}
						    			}
										if (sPrintB.toString().length()>0){
											PosUtilis.startPrint(QRep_01.this,sPrintB,Loca);
										}
						    			
					    			}
					    			break;
								}
								case 1: //印製暢銷排行A4
								{
						    			int count =mAdapter.getCount()  ;
						    			if (count>0){  //
										String compStr[]=Utilis.getIni(QRep_01.this,"USER","COMPANY",9).split("!&!");
										String sepa=";SSSS\r\n";
										sPrintB = new StringBuffer();
										sPrintB.append("期間:"+mStartDay+"~"+mEndDay+"  商品暢銷排行 "+sepa);
							    			for (int i = 0; i <count ; i++){
												datas = (RepData) mAdapter.getItem(i);
												sPrintB.append(datas.iGoods+";");
												String GoodsName=datas.iName;
												if (datas.iName.length()>10) GoodsName=datas.iName.substring(0, 10);
												sPrintB.append(GoodsName+";");
												sPrintB.append(datas.iImpo.substring(datas.iImpo.indexOf(":")+1)+";");
												sPrintB.append(datas.iMoney.substring(datas.iMoney.indexOf(":")+1)+";");
												sPrintB.append(datas.iCompany.substring(datas.iCompany.indexOf(":")+1)+sepa);
							    			}
							    			//呼叫MktrSt (xMode=9  
											Intent intent = new Intent();
											//bundle.putString("Mkqrs",compStr[0]+",  期間:"+mStartDay+"~"+mEndDay+"  商品暢銷排行,9,,"+sPrintB.toString());
											intent.putExtra("SERCH",compStr[0]);
											intent.putExtra("QKIND",mStartDay+"~"+mEndDay+"  最新商品排行");
											intent.putExtra("MODE",9);
											intent.putExtra("DEPTNO",mDept);
											intent.putExtra("BUFSTR",sPrintB.toString());
											intent.putExtra("BUFTITLE","1;2;3");
											intent.putExtra("STARTDAY",mStartDay);
											intent.putExtra("ENDDAY",mEndDay);
	
											intent.setClass(QRep_01.this, MkqrSt.class);
											startActivity(intent);
									}
					    			break;
								}
								case 2://追蹤
								{
									goQhis();									
									break;
								}
								case 3:break;
								
								}
							}
				});
				return false;
			}
			return false;
			}
       });
        
    	//mListView.setChoiceMode(mListView.CHOICE_MODE_MULTIPLE);

        mListView.setOnScrollListener(new OnScrollListener() {
            public void onScrollStateChanged(AbsListView view,
                    int scrollState) { // TODO Auto-generated method stub
            	if(scrollState==SCROLL_STATE_FLING){
            	     //Toast.makeText(QRep_01.this,"Fling",Toast.LENGTH_SHORT).show();
            	    }else if(scrollState==SCROLL_STATE_IDLE){
            	     //Toast.makeText(QRep_01.this,"Idle",Toast.LENGTH_SHORT).show();
            	    }else if(scrollState==SCROLL_STATE_TOUCH_SCROLL){
                    	mDisplayStk.setVisibility(View.GONE);
            	     Toast.makeText(QRep_01.this,"touch",Toast.LENGTH_SHORT).show();
            	    }            	
            }

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

            }
        });
        
        mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long ids) {
				// TODO Auto-generated method stub
				int locations=position;
				datas = (RepData) mAdapter.getItem(locations);

				String mSplitSizes=null; //所有尺寸 L，XL
				String mSplitColorNo=null; //顏色代號 01，02
				String mSplitColor=null; //顏色 黑色，白色
		        SQLiteDatabase db = Utilis.getDB(QRep_01.this);		
				Cursor cs = null;
				StringBuffer mySqlBuf = new StringBuffer();
				//目的只是判斷為單筆多筆,交給編輯顯示總件數
		//---------需改寫成DISPLAY的時候,要檢查是否存在該單,且一次到位,否則後續一視同仁-------
				//先歸零
				
				if (deptN>0){ //表示有總倉&多門市
					Bundle bundle = new Bundle();
					Intent intent = new Intent();
					bundle = new Bundle();
					bundle.putString("GalleryChild","'"+datas.iFormdate+"';0;1");
					intent.setClass(QRep_01.this, GalleryViewS.class);
					intent.putExtras(bundle);
					startActivity(intent);
				}else {
	            	mDisplayStk.setVisibility(View.VISIBLE);
					StringBuffer mColno=new StringBuffer();
					StringBuffer mColname=new StringBuffer();
					StringBuffer mSiz=new StringBuffer();

					String iGoods=datas.iGoods;
					if (datas.iGoods.indexOf("-")>0) iGoods=datas.iGoods.substring(0, datas.iGoods.indexOf("-"));
					
					Cursor cst =db.rawQuery("select COLOR,UNIT1 from qitems  where GOODSNO='" + iGoods+"' group by COLOR,UNIT1", null);
					if (cst.getCount()>0) {
						cst.moveToFirst();
						for (int x=0;x<cst.getCount();x++){
							if (mColno.length()<=0){
								mColno.append(cst.getString(0));	mColname.append(cst.getString(1));
							} else {
								mColno.append("，"+cst.getString(0));	mColname.append("，"+cst.getString(1));
							}
								cst.moveToNext();	
						}
					}
					cst =db.rawQuery("select SIZE from qitems  where GOODSNO='" + iGoods+"' group by SIZE", null);
					if (cst.getCount()>0) {
						cst.moveToFirst();
						for (int x=0;x<cst.getCount();x++){
							if (mSiz.length()<=0 ){
								mSiz.append(cst.getString(0));
							}else {
								mSiz.append(","+cst.getString(0));
							}	
						cst.moveToNext();	
						}
					}
					cst.close();
						mSplitSizes=mSiz.toString();
						mSplitColorNo=mColno.toString();
						mSplitColor=mColname.toString();
						makeTable(datas.iFormdate,mSplitColorNo,mSplitColor,mSplitSizes);
				}
				db.close();
			}
		});
	
}	
	
	public void onResume(){
		super.onResume();
		
		DBCloud.aa0_aa1_auto_HI(this,nKind);
		
			mAdapter.notifyDataSetChanged();
		}

	
	private void goQhis(){
		try{
			Intent intent = new Intent();
			intent.putExtra("QHis_kind", nKind);
			if(mGroupMode==GroupMode.TOP3)			
				intent.putExtra("QHis_mode", 3);
			else
				intent.putExtra("QHis_mode", 1);
			
			intent.putExtra("QHis_User","" );
			intent.putExtra("QHis_Goods",datas.iFormdate );
			intent.setClass(QRep_01.this, QHis.class);
			startActivity(intent);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
		}
		

	}
	
	private void setCondition(){
		
		//台頭:CWBuyer銷售王+[進貨]
		//(APos.java)[新增][查詢][編輯] 帶過去的引數
		//現階段可分為:[交易中][統計中]
		
    	switch(mMode){ 
    	
			case KeySet.SearchMode.DAY: //就是日結單(日期+單頭)
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
    			setTitle(getString(R.string.app_name)+":[依每日]"+mode_E[mGroupMode]);
				break;
			}
    		case KeySet.SearchMode.BATCH:
    		{
    			mTextDuration.setText("  批號 : " +batch);
    			setTitle(getString(R.string.app_name)+":[依批號]"+mode_E[mGroupMode]);
	    	break;
    		}
			case KeySet.SearchMode.WEEK:
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
    			setTitle(getString(R.string.app_name)+":[依每週]"+mode_E[mGroupMode]);
				break;
			}
			case KeySet.SearchMode.MONTH:
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
				setTitle(getString(R.string.app_name)+":[依每月]"+mode_E[mGroupMode]);
				break;
			}
			case KeySet.SearchMode.ORDER:
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
				setTitle(getString(R.string.app_name)+":[依日期範圍]"+mode_E[mGroupMode]);
				break;
			}
			default:
			{
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
				setTitle(getString(R.string.app_name)+":[依日期範圍]"+mode_E[mGroupMode]);
				break;
			}
    	}
	}
	
	// 特別處理 日結單 GROUPS第一層 是以(日/週/月)為統計結算 childs第二層 才是單頭
	//如何分開 日結+單頭  及 單頭+單身 的製作就是關鍵
	public void getGroupData(Context context, String dbStartDay, String dbEndDay, String condition, String conditionValue) {
					
			if (mAdapter.mList != null) {
				mAdapter.mList.clear();
			}
			
			SQLiteDatabase db = Utilis.getDB(context);
//			try {
				Cursor cursorGroup = null;

				StringBuffer bufCategory = new StringBuffer();
				if(dbStartDay != null && dbStartDay.length() > 0)	dbStartDay = dbStartDay.replace("/", "-");
				if(dbEndDay != null && dbEndDay.length() > 0) dbEndDay = dbEndDay.replace("/", "-");
			
				StringBuffer theDay = new StringBuffer();
				theDay.append("9999999999");

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

				//以日期範圍依進貨優先定出商品範圍,再讀取 到目前總進 總銷
				//所取得的商品,再一一檢查之前不存在,才能視為新品
				//GroupMode.TOP1 到新品   TOP2 暢銷  TOP3 預購  TOP4 追加
				//@@@應重新思考 新品&追加的定義
		if ((mGroupMode==GroupMode.TOP1 ) && mMode !=KeySet.SearchMode.BATCH) {
				//還需進一步 分析 總倉(立場) 或 各門市(立場)
			//追加需求表 
					bufCategory=bufCategory.delete(0, bufCategory.toString().length());
					bufCategory.append("SELECT GOODSNO,GOODSNAME,max(COLORS),max(SIZES)," +
							"max(PIC),max(UNIT2),round(sum(UNIT10)),round(sum(UNIT10*P1)),round(sum(UNIT10-UNIT30-UNIT40))" +
							",sum(UNIT30)+sum(UNIT40) as FORSALE ,round(sum(UNIT30*UNITPRICE*DISCOUNT/100))" +
							",round(sum(UNIT30*UNITPRICE*DISCOUNT/100-UNIT30*P1))" +
							",round(sum(UNIT30*UNITPRICE*DISCOUNT/100-UNIT30*P1)/(sum(UNIT30*UNITPRICE)/100))" +
							",round(sum(UNIT30*P1)),round(sum(UNIT10-UNIT30-UNIT40)*P1) FROM qitems" +
							" WHERE GOODSNO not in (select distinct GOODSNO from qitems where" +
							//@@@應加入 若選擇批號 做統計時
							" FORMDATE<'"+dbStartDay+"') and ISCONFIRM='Y'" +
							SQLADD+
							" group by GOODSNO,GOODSNAME order by FORSALE DESC");
					
					if  (Utilis.haveInternet(QRep_01.this) && off_line==1 && mCloud>0){
						StringBuffer bfstr = new StringBuffer();
						StringBuffer bfstrF = new StringBuffer();
						
							bfstr.append(Utilis.getIni(QRep_01.this, "SYS", "IMPORT", 2)).append(";");
							bfstrF.append("UID").append(";");
							
							if (nPart==1) bfstr.append(mDept).append(";"); else bfstr.append("").append(";"); 
							bfstrF.append("DEPTNO").append(";"); 
							
							bfstr.append(dbStartDay).append(";");
							bfstrF.append("STARTDAY").append(";");
							bfstr.append(dbEndDay).append(";");
							bfstrF.append("ENDDAY").append(";");
							bfstr.append(bufCategory.toString()).append(";");
							bfstrF.append("SQLADD").append(";");  

							//if (mMode==KeySet.SearchMode.BATCH) bfstr.append(batch).append(";");
							//@@@好像多了;
							if (mMode==KeySet.SearchMode.BATCH) bfstr.append(batch);
							else bfstr.append("");
							bfstrF.append("BATCH"); 
							
							final String []fields=bfstr.toString().split(";");
							final String []fieldFs=bfstrF.toString().split(";");
							
						      myDialog = ProgressDialog.show(QRep_01.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
							  
						      new Thread()
						      { 
						        public void run()
						        { 
						          try
						          { 
										HttpPost httpRequest = new HttpPost(uriAPI1);
										// Post運作傳送變數必須用NameValuePair[]陣列儲存
										//Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI1);

										
										List<NameValuePair> params = new ArrayList<NameValuePair>();
										for(int x=0;x<fields.length;x++){
											params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
										}
										try {
											// 發出HTTP request(請求) 
											httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
											// 取得HTTP response(回傳) 
											HttpResponse httpResponse = new DefaultHttpClient()
													.execute(httpRequest);
											if (httpResponse.getStatusLine().getStatusCode() == 200)
											{
												// 取出回應字串
												String strResult = EntityUtils.toString(httpResponse	.getEntity());
												mHandlerQDR_11.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
											}
											
										} catch (Exception e)
										{
											e.printStackTrace();
										}

						          }
						          catch (Exception e)
						          {
						            e.printStackTrace();
						          }
						          finally
						          {
						            // 卸載所建立的myDialog物件。
						            myDialog.dismiss();
						          }
						        }
						      }.start(); 
					}else{	
					
					
									
					cursorGroup = db.rawQuery(bufCategory.toString(), null);
				 				//表示有銷貨紀錄
						if (cursorGroup.getCount() > 0) {  //有各種QKIND
							cursorGroup.moveToFirst();
							
							for (int x=0;x<cursorGroup.getCount();x++){
										
									RepData data = new RepData();
									
									data.iPic=cursorGroup.getString(4);  //圖片
									data.iFormdate=cursorGroup.getString(0); //主貨號 做為KEY 不顯示
									data.iGoods=cursorGroup.getString(0); //主貨號
									data.iName=cursorGroup.getString(1); //品名
									data.iCountry=cursorGroup.getString(2);
									data.iNumber=cursorGroup.getString(3);
									data.iUnit2=cursorGroup.getString(5);
									if (PSWD==0) {
										data.iImpo="進:"+cursorGroup.getString(6)+"/$:"+cursorGroup.getString(7)+" 存:"+cursorGroup.getString(8);									
										data.iCompany="毛:"+cursorGroup.getString(11)+" "+cursorGroup.getString(12)+"%";								
									}else {
										data.iImpo="進:"+cursorGroup.getString(6)+" 存:"+cursorGroup.getString(8);									
											data.iCompany="";
									}
									data.iMoney="銷:"+cursorGroup.getString(9)+" /$:"+cursorGroup.getString(10);
												
												TS30+=cursorGroup.getInt(12); //總銷貨成本
												TT30+=cursorGroup.getInt(9);//總銷量
												TM30+=cursorGroup.getInt(10); //總銷額
									
									data.iSort=cursorGroup.getInt(9);
									TT10+=cursorGroup.getInt(6);
					 				StkT+=cursorGroup.getInt(8);  //總存貨量
					 				StkM+=cursorGroup.getInt(13); //總存貨金額
					 				Profit+=cursorGroup.getInt(11); //總毛利
					 				if (TM30>0)	{Profits=Math.round(Profit*100/TM30);} //總毛利率
					 				else {Profits=0;}
					 				mAdapter.mList.add(data);
					 				
									cursorGroup.moveToNext();
							}
						}
							cursorGroup.close();
					}
		} else if (mGroupMode!=GroupMode.TOP3 &&  (mGroupMode==GroupMode.TOP2 || mMode==KeySet.SearchMode.BATCH)){ //暢銷品  留貨區
					bufCategory=bufCategory.delete(0, bufCategory.toString().length());
					StringBuffer childSQL= new StringBuffer();
					//找出期間 所有進銷
					//"select distinct GOODSNO from qitems WHERE "
					bufCategory.append("select GOODSNO,GOODSNAME,")
					.append(" sum(UNIT30+UNIT40) as SUM30,round(sum(SUBPRICE)) as SUNSUB, round(sum(ACOST)) as SUMCOST ") 	//
					.append(",max(COLORS) ,max(SIZES),max(UNIT1),max(PIC) ");
					
					childSQL.append("select DISTINCT GOODSNO");
					if (mMode==KeySet.SearchMode.BATCH){
						bufCategory.append(" from qitems where BATCH ='"+ batch+"'");
						childSQL.append(" from qitems where BATCH ='"+ batch+"'");
						
					} else {
						bufCategory.append(" from qitems where FORMDATE >= '").append(dbStartDay).append("'")
						.append(" and FORMDATE <= '").append(dbEndDay).append("'");
						
						childSQL.append(" from qitems where FORMDATE >= '").append(dbStartDay).append("'")
						.append(" and FORMDATE <= '").append(dbEndDay).append("'");
						
					}
					bufCategory.append(SQLADD);
					childSQL.append(SQLADD);
					bufCategory.append(" and (QKIND ='30' or QKIND ='31' or QKIND ='40' or QKIND ='41' )");
					bufCategory.append("and ISCONFIRM='Y' ");
					//bufCategory.append("and (ISCONFIRM='Y' or (ISCONFIRM='O' or ISCONFIRM='R') or (ISCONFIRM='N' and ISCHECK='Y'))");

					childSQL.append(" and (QKIND ='30' or QKIND ='31' or QKIND ='40' or QKIND ='41' )");
					childSQL.append(" and ISCONFIRM='Y' ");
					//childSQL.append(" and (ISCONFIRM='Y' or (ISCONFIRM='O' or ISCONFIRM='R') or (ISCONFIRM='N' and ISCHECK='Y'))");

					bufCategory.append(" group by GOODSNO,GOODSNAME");
					
					//取消雲端判斷 言下之意 是只要是雲端版 就是拜訪雲端為主
				if  ((Utilis.haveInternet(QRep_01.this) && off_line==1) && mGroupMode==GroupMode.TOP3 ){
						StringBuffer bfstr = new StringBuffer();
						StringBuffer bfstrF = new StringBuffer();
						
							bfstr.append(Utilis.getIni(QRep_01.this, "SYS", "IMPORT", 2)).append(";");
							bfstrF.append("UID").append(";");
							if (nPart==1) bfstr.append(mDept).append(";"); else bfstr.append("").append(";"); 
							bfstrF.append("DEPTNO").append(";"); 
							bfstr.append(dbStartDay).append(";");
							bfstrF.append("STARTDAY").append(";");
							bfstr.append(dbEndDay).append(";");
							bfstrF.append("ENDDAY").append(";");
							bfstr.append(bufCategory.toString()).append(";");
							bfstrF.append("SQLADD").append(";");  
							bfstr.append(childSQL.toString()).append(";");
							bfstrF.append("SQLADDCHILD").append(";");  
							bfstr.append(""+nPart);
							bfstrF.append("ISPART"); 
							
							final String []fields=bfstr.toString().split(";");
							final String []fieldFs=bfstrF.toString().split(";");
							
						      myDialog = ProgressDialog.show(QRep_01.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
							  
						      new Thread()
						      { 
						        public void run()
						        { 
						          try
						          { 
										HttpPost httpRequest = new HttpPost(uriAPI2);
										// Post運作傳送變數必須用NameValuePair[]陣列儲存
										//Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI2);

										
										List<NameValuePair> params = new ArrayList<NameValuePair>();
										for(int x=0;x<fields.length;x++){
											params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
										}
										try {
											// 發出HTTP request(請求) 
											httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
											// 取得HTTP response(回傳) 
											HttpResponse httpResponse = new DefaultHttpClient()
													.execute(httpRequest);
											if (httpResponse.getStatusLine().getStatusCode() == 200)
											{
												// 取出回應字串
												String strResult = EntityUtils.toString(httpResponse	.getEntity());
												mHandlerQDR_12.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
											}
											
										} catch (Exception e)
										{
											e.printStackTrace();
										}

						          }
						          catch (Exception e)
						          {
						            e.printStackTrace();
						          }
						          finally
						          {
						            // 卸載所建立的myDialog物件。
						            myDialog.dismiss();
						          }
						        }
						      }.start(); 
				}else{	
					
	 				cursorGroup = db.rawQuery(bufCategory.toString(), null);
	 				
					if (cursorGroup != null) {
						if (cursorGroup.getCount() > 0) {
							cursorGroup.moveToFirst();
							for (int i = 0; i < cursorGroup.getCount(); i++) {  //就是每個主貨號
										int IT30=cursorGroup.getInt(2); //本銷量
										int IM30=cursorGroup.getInt(3); //本銷額
										int IS30=cursorGroup.getInt(4);  //本銷成本
										
										StringBuffer bufTt = new StringBuffer();
										Cursor cst;
										bufTt=bufTt.delete(0, bufCategory.toString().length());
										bufTt.append("select QKIND,"); 
										if (nPart==0){
											bufTt.append(" sum(UNIT10),sum(UNIT30),sum(UNIT40),round(sum(SUBPRICE)),round(sum(ACOST)),USER,DEPTNO "); 	//總進銷
										}else {
											bufTt.append(" sum(UNIT20),sum(UNIT30),sum(UNIT40),round(sum(SUBPRICE)),round(sum(ACOST)),USER,DEPTNO "); 	////總進銷
										}
										bufTt.append(" from qitems");
										bufTt.append(" where ");	
										bufTt.append(" GOODSNO='"+ cursorGroup.getString(0)+"'");
										bufTt.append(" and (ISCONFIRM='Y') ")
										.append(SQLADD)
										.append(" group by QKIND,USER,DEPTNO");
										
						 				cst = db.rawQuery(bufTt.toString(), null);
						 				//表示有銷貨紀錄
						 				RepData data = new RepData();
										data.iPic=cursorGroup.getString(8);  //圖片
										data.iFormdate=cursorGroup.getString(0); //主貨號 做為KEY 不顯示
										data.iGoods=cursorGroup.getString(0); //主貨號
										data.iName=cursorGroup.getString(1); //品名
										data.iCountry=cursorGroup.getString(5); //COLORS
										data.iNumber=cursorGroup.getString(6); //SIZES
										data.iUnit2=cursorGroup.getString(7); //COLORSNO
										
										T30=0; M30=0;S30=0;T10=0;M10=0;
										
										if (cst.getCount() > 0) {  //有各種QKIND
											cst.moveToFirst();
											for (int x=0;x<cst.getCount();x++){
								 				
												if (nPart==0 && cst.getInt(0)==10){

													T10=T10+cst.getInt(1);
													M10=M10+cst.getInt(5);
													
													TT10=TT10+cst.getInt(1);  //總進貨量
													TM10=TM10+cst.getInt(5); //總進貨額 因為這時的(1)為外幣進價
												}else if (nPart==1  && (cst.getInt(0)==20 || cst.getInt(0)==21)  && (cst.getString(6).equalsIgnoreCase(mDept)) ){

													T10=T10+cst.getInt(1);
													M10=M10+cst.getInt(5);
													
													TT10=TT10+cst.getInt(1);  //總進貨量
													TM10=TM10+cst.getInt(5); //總進貨額 因為這時的(1)為外幣進價
												
												}else if (nPart==1  && (cst.getInt(0)==21)  && (!cst.getString(6).equalsIgnoreCase(mDept)) ){													

												T10=T10-cst.getInt(1);
												M10=M10-cst.getInt(5);
												
												TT10=TT10-cst.getInt(1);  //總進貨量
												TM10=TM10-cst.getInt(5); //總進貨額 因為這時的(1)為外幣進價
												
												}	else if(nPart==0 || (nPart==1 && (cst.getString(7).equalsIgnoreCase(mDept)))){

													if (cst.getInt(0)==30 || cst.getInt(0)==31 || cst.getInt(0)==40 || cst.getInt(0)==41){
														T30=T30+cst.getInt(2)+cst.getInt(3); //銷量
														M30=M30+cst.getInt(4);//銷額
														S30=S30+cst.getInt(5);  //銷成本
														
														TS30=TS30+cst.getInt(5); //總銷貨成本
														TT30=TT30+cst.getInt(2)+cst.getInt(3);//總銷量
														TM30=TM30+cst.getInt(4); //總銷額
													}
												}
												
											cst.moveToNext();
										}
											cst.close();
									}
											data.iSort=M30;
											
											if (PSWD==0) {
													data.iMoney="總銷:"+T30+" /$:"+M30+"/毛:"+(M30-S30);
												if (mMode!=KeySet.SearchMode.BATCH){
													data.iCompany="本銷:"+IT30+" /$"+IM30+"/毛:"+(IM30-IS30);
												}else {
													data.iCompany="";
												}
											} else {
													data.iMoney="總銷:"+T30+" /$:"+M30;
												if (mMode!=KeySet.SearchMode.BATCH){
														data.iCompany="本銷:"+IT30+" /$"+IM30;
												}else {
													data.iCompany="";
												}
											}
							 				StkT=TT10-TT30;  //總存貨量
							 				StkM=TM10-TS30; //總存貨金額
							 				Profit=TM30-TM10; //總毛利
							 				if (TM30>0)	{Profits=Math.round(Profit*100/TM30);} //總毛利率
							 				else {Profits=0;}
											if (PSWD==0) {
												data.iImpo="總進:"+T10+" /$:"+M10+" 總存:"+(T10-T30);
											}else {
												data.iImpo="總進:"+T10+" 總存:"+(T10-T30);
											}
							 				if (mAdapter.mList.size()>0) {
							 					int fnd=0;
							 					for (int sort=0;sort<mAdapter.mList.size();sort++){
							 						RepData	dataS = (RepData)mAdapter.mList.get(sort) ;
							 					 
							 					 if (data.iSort>dataS.iSort) {
							 						mAdapter.mList.add(sort,data);
							 						fnd=1;
							 						break;
							 					 }
							 					}
							 					if (fnd==0) {
							 						mAdapter.mList.add(data);	
							 					}
							 				} else {  //第一筆沒得比,無條件寫入
							 				mAdapter.mList.add(data);
							 				}

									cursorGroup.moveToNext();
								}
							
						}
					}
	 				cursorGroup.close();
				}	
		} else if (mGroupMode==GroupMode.TOP3 || mGroupMode==GroupMode.TOP5){ //暢銷品  留貨區
			bufCategory=bufCategory.delete(0, bufCategory.toString().length());
			//找出期間 所有進銷
			bufCategory.append("select GOODSNO,GOODSNAME,")
			.append(" sum(UNIT30+UNIT40) as SUM30,round(sum(SUBPRICE)) as SUNSUB, sum(ACOST) as SUMCOST ") 	//
			.append(",max(COLORS) ,max(SIZES),max(UNIT1),PIC from qitems");
				bufCategory.append(" where FORMDATE >= '").append(dbStartDay).append("'")
				.append(" and FORMDATE <= '").append(dbEndDay).append("'");
				bufCategory.append(" and (QKIND ='30' or QKIND ='31' or QKIND ='40' or QKIND ='41' )");
				bufCategory.append(" and (ISCONFIRM='O' or (ISCONFIRM='N' and ISCHECK='Y'))");
				bufCategory.append(SQLADD);
				//總倉有選擇 全部門市或總倉 的功能
				bufCategory.append(" group by GOODSNO,GOODSNAME,PIC");
				if  (Utilis.haveInternet(QRep_01.this) && off_line==1 && mGroupMode==GroupMode.TOP3){
					StringBuffer bfstr = new StringBuffer();
					StringBuffer bfstrF = new StringBuffer();
					
						bfstr.append(Utilis.getIni(QRep_01.this, "SYS", "IMPORT", 2)).append(";");
						bfstrF.append("UID").append(";");
						
						if (nPart==1) bfstr.append(mDept).append(";"); else bfstr.append("").append(";"); 
						bfstrF.append("DEPTNO").append(";"); 
						
						bfstr.append(dbStartDay).append(";");
						bfstrF.append("STARTDAY").append(";");
						bfstr.append(dbEndDay).append(";");
						bfstrF.append("ENDDAY").append(";");
						bfstr.append(bufCategory.toString()).append(";");
						bfstrF.append("SQLADD").append(";");  

						if (mMode==KeySet.SearchMode.BATCH) bfstr.append(batch).append(";");
						else bfstr.append("");
						bfstrF.append("BATCH"); 
						
						final String []fields=bfstr.toString().split(";");
						final String []fieldFs=bfstrF.toString().split(";");
						
					      myDialog = ProgressDialog.show(QRep_01.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
						  
					      new Thread()
					      { 
					        public void run()
					        { 
					          try
					          { 
									HttpPost httpRequest = new HttpPost(uriAPI3);
									// Post運作傳送變數必須用NameValuePair[]陣列儲存
									//Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI1);

									
									List<NameValuePair> params = new ArrayList<NameValuePair>();
									for(int x=0;x<fields.length;x++){
										params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
									}
									try {
										// 發出HTTP request(請求) 
										httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
										// 取得HTTP response(回傳) 
										HttpResponse httpResponse = new DefaultHttpClient()
												.execute(httpRequest);
										if (httpResponse.getStatusLine().getStatusCode() == 200)
										{
											// 取出回應字串
											String strResult = EntityUtils.toString(httpResponse	.getEntity());
											mHandlerQDR_13.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
										}
										
									} catch (Exception e)
									{
										e.printStackTrace();
									}

					          }
					          catch (Exception e)
					          {
					            e.printStackTrace();
					          }
					          finally
					          {
					            // 卸載所建立的myDialog物件。
					            myDialog.dismiss();
					          }
					        }
					      }.start(); 
				}else{	
				
						cursorGroup = db.rawQuery(bufCategory.toString(), null);
						
					if (cursorGroup != null) {
						if (cursorGroup.getCount() > 0) {
							cursorGroup.moveToFirst();
							for (int i = 0; i < cursorGroup.getCount(); i++) {  //就是每個主貨號
										int IT30=cursorGroup.getInt(2); //本銷量
										int IM30=cursorGroup.getInt(3); //本銷額
										int IS30=cursorGroup.getInt(4);  //本銷成本
										
										StringBuffer bufTt = new StringBuffer();
						 				RepData data = new RepData();
										data.iPic=cursorGroup.getString(8);  //圖片
										data.iFormdate=cursorGroup.getString(0); //主貨號 做為KEY 不顯示
										data.iGoods=cursorGroup.getString(0); //主貨號
										data.iName=cursorGroup.getString(1); //品名
										data.iCountry=cursorGroup.getString(5); //COLORS
										data.iNumber=cursorGroup.getString(6); //SIZES
										data.iUnit2=cursorGroup.getString(7); //COLORSNO
										
										T30=0; M30=0;S30=0;T10=0;M10=0;
										
											data.iSort=M30;
											data.iMoney="";
											data.iCompany="本訂:"+IT30;
											//data.iCompany="本訂:"+IT30+" /$"+IM30+"/毛:"+(IM30-IS30);
											data.iImpo="";
							 				mAdapter.mList.add(data);
		
									cursorGroup.moveToNext();
								}
						}
					}
					cursorGroup.close();
			}
				
		}else{//TOP4
			
			bufCategory=bufCategory.delete(0, bufCategory.toString().length());
			bufCategory.append("SELECT  qitems.SUPPLY, qfact.FACTNAME,qitems.GOODSNOS, qitems.GOODSNAME,qitems.PIC,");
			bufCategory.append("qitems.P0  ,qitems.COLORS,qitems.SIZES,qitems.UNIT2,sum( qitems.UNIT10) ,round( max(qitems.P1)*sum(qitems.UNIT10)),");
			bufCategory.append("sum(qitems.UNITPRICE*qitems.UNIT30) ,sum( qitems.UNIT30),");
			bufCategory.append("sum( qitems.UNIT10)-sum( qitems.UNIT30), round(sum( qitems.UNIT30)/ sum( qitems.UNIT10)*100)");
			bufCategory.append(" FROM qitems left join qfact on qitems.SUPPLY=qfact.FACTNO WHERE qitems.GOODSNOS");
			bufCategory.append(" in(select DISTINCT GOODSNOS from qitems where FORMDATE>='"+dbStartDay+"' and FORMDATE<='"+dbEndDay+"'  and UNIT10>0 )");
			bufCategory.append(SQLADD);
			bufCategory.append(" group by  qitems.SUPPLY, qitems.GOODSNOS, qitems.GOODSNAME,qitems.P0,qitems.PIC");
			bufCategory.append(" having sum( qitems.UNIT10)-sum( qitems.UNIT30)<10 and");
			bufCategory.append(" sum( qitems.UNIT30)>10 and sum( qitems.UNIT10)>10 and");
			bufCategory.append("  sum( qitems.UNIT30) / sum( qitems.UNIT10)>=0.5 ");
			bufCategory.append(" order by qitems.SUPPLY,GOODSNOS, sum( qitems.UNIT30) desc");
			int T=0;

					cursorGroup = db.rawQuery(bufCategory.toString(), null);
					//表示有銷貨紀錄
				if (cursorGroup.getCount() > 0) {
					while (cursorGroup.moveToNext()){
					RepData data = new RepData();
					
					data.iPic=cursorGroup.getString(4);  //圖片
					
					data.iFormdate=cursorGroup.getString(2).substring(0,cursorGroup.getString(2).indexOf("-")); //主貨號 做為KEY 不顯示
					data.iGoods=cursorGroup.getString(2);
					data.iName=cursorGroup.getString(0)+"/"+cursorGroup.getString(1);
					data.iCountry=cursorGroup.getString(3)+"("+cursorGroup.getString(5)+")"; //色組
					data.iNumber=cursorGroup.getString(6)+"/"+cursorGroup.getString(7); //尺組
					data.iUnit2=cursorGroup.getString(8);//色NO組
					
					bufCategory=bufCategory.delete(0, bufCategory.toString().length());
					
					//可以條件式的判讀取 資料
					//SUM (CASE WHEN period BETWEEN 1 AND 3 THEN sales_amount ELSE 0 END) AS '1st Qtr',
					bufCategory.append("select sum(UNIT10),sum(UNIT30),sum(UNIT40) from qitems where GOODSNOS='"+data.iGoods+"' and (ISCONFIRM='Y' or (ISCONFIRM='O' or ISCONFIRM='R') or (ISCONFIRM='N' and ISCHECK='Y'))");
					Cursor cst=db.rawQuery(bufCategory.toString(), null);
					if (cst.getCount()>0){
						cst.moveToFirst();
						data.iImpo="總進:"+cst.getInt(0)+"/"+"本進:"+cursorGroup.getInt(9)+"/"+cursorGroup.getDouble(10);
						data.iMoney="總銷:"+(cst.getInt(1)+cst.getInt(2))+"/"+"本銷:"+cursorGroup.getInt(12)+"/"+cursorGroup.getDouble(11);
						data.iCompany="尚存:"+(cst.getInt(0)-(cst.getInt(1)+cst.getInt(2)))+"/銷率:";
						if (cst.getInt(0)>0) data.iCompany=data.iCompany+Math.round((cst.getDouble(1)+cst.getDouble(2))/cst.getDouble(0)*100)+"%";
						T+=1;
						data.iSort=T;
						mAdapter.mList.add(data);	
						TT10=TT10+cst.getInt(0);
						TM10=TM10+cursorGroup.getInt(10);
						TT30=TT30+cst.getInt(1)+cst.getInt(2);
						TM30=TM30+cursorGroup.getInt(11);
					}else{
						data.iImpo="本進:"+cursorGroup.getInt(9)+"/"+cursorGroup.getDouble(10);
						data.iMoney="本銷:"+cursorGroup.getInt(12)+"/"+cursorGroup.getDouble(11);
						data.iCompany="尚存:"+cursorGroup.getString(13)+"/銷率:"+cursorGroup.getString(14)+"%";
						T+=1;
						data.iSort=T;
						mAdapter.mList.add(data);	
						TT10=TT10+cursorGroup.getInt(9);
						TM10=TM10-cursorGroup.getInt(10);
						TT30=TT30+cursorGroup.getInt(12);
						TM30=TM30-cursorGroup.getInt(11);
					}
					cst.close();
	 				StkT=TT10-TT30;  //總存貨量
	 				StkM=TM10-TT30; //總存貨金額
					}
					cursorGroup.close();
				}			
						
		}
 				((TextView)findViewById(R.id.text_tot)).setText("T:"+StkT); 				
 				((TextView)findViewById(R.id.text_t10)).setText("T:"+TT10); 				
 				((TextView)findViewById(R.id.text_t30)).setText("T:"+TT30);
 				if (PSWD==0){
	 				((TextView)findViewById(R.id.text_mtot)).setText("$:"+StkM);
	 				((TextView)findViewById(R.id.text_r10)).setText("$:"+(TM30-TM10));
	 				((TextView)findViewById(R.id.text_m10)).setText("$:"+TM10);
	 				((TextView)findViewById(R.id.text_m30)).setText("$:"+TM30);
	 				((TextView)findViewById(R.id.text_r30)).setText("$:"+Profit);
	 				((TextView)findViewById(R.id.text_rp0)).setText("%:"+Profits);
 				}else {
	 				((TextView)findViewById(R.id.text_mtot)).setText("xxxxxx");
	 				((TextView)findViewById(R.id.text_r10)).setText("xxxxxx");
	 				((TextView)findViewById(R.id.text_m10)).setText("xxxxxx");
	 				((TextView)findViewById(R.id.text_m30)).setText("xxxxxx");
	 				((TextView)findViewById(R.id.text_r30)).setText("xxxxxx");
	 				((TextView)findViewById(R.id.text_rp0)).setText("xxxxxx");
 				}
 				db.close();
 				db = null;
			
		}


		
		
	
	class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QRep_01.this);
			switch (id) {
				case R.id.btn_exit:
				{
					finish();
					break;
				}
				case R.id.btn_btn0:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.DAY;
					chkMode();
					break;
				}
				case R.id.btn_btn1:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.WEEK;
					chkMode();
					break;
				}
				case R.id.btn_btn2:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.MONTH;
					chkMode();
					break;
				}
				case R.id.btn_btn3:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.SEASON;
					chkMode();
					break;
				}
				case R.id.btn_btn4:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.BATCH;
					chkMode();
					break;
				}

				
				case R.id.btn_prev_date:  //當按了上一??
				{
					switch(mMode){
						case KeySet.SearchMode.DAY:  //就是7筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, -1);
							mEndDay = mStartDay;
							if ((mGroupMode!=GroupMode.TOP3 && mGroupMode!=GroupMode.TOP5) &&
								(WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 )){
									mStartDay=mLimitDay;
									mEndDay=mStartDay;
							}
			    			break;
			    		}
						case KeySet.SearchMode.MONTH:  //就是31筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, -1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
							if ((mGroupMode!=GroupMode.TOP3 && mGroupMode!=GroupMode.TOP5) &&
									(WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 )){
								mStartDay=mLimitDay;
								mEndDay=DateUtil.addDate(mStartDay, +30);
							}
			    			break;
			    		}
						case KeySet.SearchMode.WEEK:  //就是7筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, -7);
							mEndDay = DateUtil.addDate(mEndDay, -7);
							if ((mGroupMode!=GroupMode.TOP3 && mGroupMode!=GroupMode.TOP5) &&
									(WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 )){
								mStartDay=mLimitDay;
								mEndDay=DateUtil.addDate(mStartDay, +7);
							}
			    			break;
			    		}
						case KeySet.SearchMode.BATCH:  //銷貨單 (單頭+單身)
						{
				    		//應追加 上一批 的程式
							SQLiteDatabase db = Utilis.getDB(QRep_01.this);
							Cursor cursorAlbun = null;
							if(batch != null && batch.length() > 0){
								StringBuffer bufCategory = new StringBuffer();
									bufCategory.append("select distinct BATCH from qitems");
									bufCategory.append(" where BATCH<'" + batch+"'");
									bufCategory.append(SQLADD);
									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);
										}
									}
							}
							cursorAlbun.close();
							db.close();
							break;
						}
					}
					if ((mGroupMode!=GroupMode.TOP3 && mGroupMode!=GroupMode.TOP5) &&
							(WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 )){
						mStartDay=mLimitDay;
						mEndDay=DateUtil.addDate(mStartDay, +7);
					}
					getGroupData(QRep_01.this,mStartDay, mEndDay, null, null);
					mAdapter.notifyDataSetChanged();
					break;
				}
				case R.id.btn_next_date:
				{
					switch(mMode){
			    		case KeySet.SearchMode.DAY: //就是日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, 1);
							mEndDay = mStartDay;
			    			break;
			    		}
			    		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.BATCH:
						{
				    		//應追加 下一批 的程式
							SQLiteDatabase db = Utilis.getDB(QRep_01.this);
							Cursor cursorAlbun = null;
							if(batch != null && batch.length() > 0){
								StringBuffer bufCategory = new StringBuffer();
									bufCategory.append("select distinct BATCH from qitems");
									bufCategory.append(" where BATCH>'" + batch+"'");
									bufCategory.append(SQLADD);
									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);
										}
									}
							}
							cursorAlbun.close();
							db.close();
							break;
						}
					}

					getGroupData(QRep_01.this,mStartDay, mEndDay, null, null);
					mAdapter.notifyDataSetChanged();
					break;

				}
						
			    case R.id.btn_sort_top1: //到新品
			    	{
		    			resetButton(id);			    		
			    		mGroupMode = GroupMode.TOP1;
		    			getGroupData(QRep_01.this,mStartDay, mEndDay, null, null);
		    				mAdapter.notifyDataSetChanged();
		    				
			   			break;
			    		}
			    case R.id.btn_sort_top2:  //暢貨
			    		{
			    			resetButton(id);
			    			mGroupMode = GroupMode.TOP2;
			    			getGroupData(QRep_01.this,mStartDay, mEndDay, null, null);
			    				mAdapter.notifyDataSetChanged();
			    				
			    				break;
			    			}
			    case R.id.btn_sort_top3: //預購
			    		{
			    			resetButton(id);
			    			mGroupMode = GroupMode.TOP3;
			    			getGroupData(QRep_01.this,mStartDay, mEndDay, null, null);
			    				mAdapter.notifyDataSetChanged();
			    				
			    				break;
			    		}
			    case R.id.btn_sort_top4: //追加
			    		{
			    			resetButton(id);
			    			mGroupMode = GroupMode.TOP4;
			    			getGroupData(QRep_01.this,mStartDay, mEndDay, null, null);
			    			mAdapter.notifyDataSetChanged();
			    			
			    			break;
			    		}
					}
			setCondition();
		}
	}
	
	private void resetButton(int id){
		((Button)findViewById(R.id.btn_sort_top1)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_top3)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_top2)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_top4)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_yellow);
	}


	// 搜尋日期 Dialog
    private View makeDateDialog() {
    	View view = LayoutInflater.from(this).inflate(R.layout.search_date, null, false);
    	mYear1=Utilis.toInt(mStartDay.substring(0, 4));
    	mMonth1=Utilis.toInt(mStartDay.substring(5, 7));
    	mDay1=Utilis.toInt(mStartDay.substring(8, 10));
    	mYear2=Utilis.toInt(mEndDay.substring(0, 4));
    	mMonth2=Utilis.toInt(mEndDay.substring(5, 7));
    	mDay2=Utilis.toInt(mEndDay.substring(8, 10));
    	//Calendar c = Calendar.getInstance();
    	//c.set(Calendar.DAY_OF_MONTH, 1); // 關鍵
    	
		
		dp1 = (DatePicker)view.findViewById(R.id.dp1);
		dp1.init(mYear1, mMonth1 - 1, mDay1, new DatePicker.OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				mYear1 = year;
				mMonth1 = monthOfYear + 1;
				mDay1 = dayOfMonth;
			}
		});
		
		dp2 = (DatePicker)view.findViewById(R.id.dp2);
		dp2.init(mYear2, mMonth2 - 1, mDay2, new DatePicker.OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				mYear2 = year;
				mMonth2 = monthOfYear + 1;
				mDay2 = dayOfMonth;
			}
		});
		
		return view;
	}

    private void  makeF(SQLiteDatabase db,String mBATCH,int Total){
		for(int jx=0;jx<ColorSplit.length;jx++){
			for(int jy=0;jy<SizeSplit.length;jy++){
				detailData.mCountList=detailData.mCountList+ColNoSiz[jx][jy];
				if(jy<(SizeSplit.length-1)) detailData.mCountList=detailData.mCountList+",";
			}
			if(jx<(ColorSplit.length-1)) detailData.mCountList=detailData.mCountList+"，";
		}
		detailData.batch=mBATCH;
		detailData.nTotalCount=Total;
		 db.insert(TbName.QDETAIL, null, makeV(mBATCH));
    }
    
    private void makeE(){
		ColorSplit=detailData.mColorsNo.split("，");
		SizeSplit=detailData.mSizes.split(",");
		detailData.mCountList="";
		ColNoSiz= new String[ColorSplit.length][SizeSplit.length];
		for(int ix=0;ix<ColorSplit.length;ix++){
				for(int iy=0;iy<SizeSplit.length;iy++){
						ColNoSiz[ix][iy]="0";
				}		}
    }
    
    private ItemData makeD(SQLiteDatabase db,String Goods){
    	ItemData data;	
		String SQLdetail="select * from qdetail where GOODSNO='"+Goods+"' order by MID DESC LIMIT 1";
		Cursor csd=db.rawQuery(SQLdetail, null);
		if (csd.getCount()>0){
			csd.moveToFirst();
			data = DBUtil.CItem.parseData(csd, true);
		}else{
			data=new ItemData();
			Cursor cursor=db.rawQuery("select dsitinct * from qitems where GOODSNO='"+Goods+"' order by CREATEDATETIME DESC LIMIT 1", null);
			if (cursor.getCount()>0){
				cursor.moveToFirst();
				data.batch=((mStartDay.replaceAll("-", "")).substring(3)+mEndDay.replaceAll("-", "").substring(3));

 				data.nTR =30;
				data.supply = cursor.getString(cursor.getColumnIndex("SUPPLY"));
				data.nCountry = 0;
				data.sourceNo = cursor.getString(cursor.getColumnIndex("SOURCENO"));
				data.GoodsNo = cursor.getString(cursor.getColumnIndex("GOODSNO"));
				data.nGoodsType = cursor.getInt(cursor.getColumnIndex("GOODSTYPE"));
				data.goodsname = cursor.getString(cursor.getColumnIndex("GOODSNAME"));
				data.nUnit1 = cursor.getString(cursor.getColumnIndex("EMPID"));
				data.nUnit2 = cursor.getString(cursor.getColumnIndex("YEAR"));
				data.nUnit = cursor.getInt(cursor.getColumnIndex("UNIT"));
				data.batch = ((mStartDay.replaceAll("-", "")).substring(3)+mEndDay.replaceAll("-", "").substring(3));
				data.dBill = 0;
				data.dBillRate = cursor.getDouble(cursor.getColumnIndex("RATE"));
				data.dAddCost = 0;
				data.dP0 = cursor.getDouble(cursor.getColumnIndex("P0"));
				data.dP1 = cursor.getDouble(cursor.getColumnIndex("P1"));
				data.dP2 = cursor.getDouble(cursor.getColumnIndex("P2"));
				data.dP3 = cursor.getDouble(cursor.getColumnIndex("P3"));
				data.dP4 = cursor.getDouble(cursor.getColumnIndex("P4"));
				data.dP5 = cursor.getDouble(cursor.getColumnIndex("P5"));
				data.nSeason = cursor.getInt(cursor.getColumnIndex("SEASON"));
				data.time = cursor.getString(cursor.getColumnIndex("FORMDATE"));
				data.nState = cursor.getInt(cursor.getColumnIndex("STATE"));
				data.pic1 = cursor.getString(cursor.getColumnIndex("PIC"));
				data.pic2 = data.pic1.substring(data.pic1.lastIndexOf("/")+1);
				data.nQualityID = 0;
				data.nWashID = 0;
				data.nTotalCount = 1;
				data.nAccountId = 0;
				data.mColors = cursor.getString(cursor.getColumnIndex("COLORS"));
				data.mColorsNo = cursor.getString(cursor.getColumnIndex("UNIT2"));
				data.mCountList = "";
				data.mSizes = cursor.getString(cursor.getColumnIndex("SIZES"));
			}
		}
    	return data;
    }
    
    
    private ContentValues makeV(String batch){
		ContentValues value = new ContentValues();
		value.put("SUPPLY", detailData.supply);
		value.put("SOURCENO", detailData.sourceNo);
		value.put("GOODSNO", detailData.GoodsNo);
		value.put("GOODSTYPE", detailData.nGoodsType);
		value.put("GOODSNAME", detailData.goodsname);
		value.put("UNIT1", detailData.nUnit1);
		value.put("UNIT2", detailData.nUnit2);
		value.put("BILL",DateUtil.getSystemTime().substring(2,12));
		value.put("BILLRATE", detailData.dBillRate);
		value.put("ADDCOST", detailData.dAddCost);
		value.put("COUNTRY", detailData.nCountry);
		value.put("BATCH", batch);
		value.put("P0", detailData.dP0);
		value.put("P1", detailData.dP1);
		value.put("P2", detailData.dP2);
		value.put("P3", detailData.dP3);
		value.put("P4", detailData.dP4);
		value.put("P5",  detailData.dP5);
		value.put("PS", detailData.mPS);
		value.put("SEASON", detailData.nSeason);
		value.put("STATE", detailData.nState);
		value.put("PIC", detailData.pic1);
		value.put("PICTURE", detailData.pic2);
		value.put("WASH_ID", detailData.nWashID);
		value.put("QUALITY_ID", detailData.nQualityID);
		value.put("ACCOUNT", detailData.nAccountId);
		value.put("CREATEDATETIME", DateUtil.getCurrentDateDb());
		value.put("IMPO",detailData.nTotalCount);
		value.put("COLOR",detailData.mColors);
		value.put("COLORNO",detailData.mColorsNo);
		value.put("INLIST",detailData.mCountList);
		value.put("SIZE",detailData.mSizes);
		value.put("TR",30);
    	
    	return value; 
    }
    
    private void chkMode(){        
        switch(mMode){ //剛進入主程式的狀態,初始的模式
        
	    	case KeySet.SearchMode.DAY:
	    	{
	    		mStartDay = DateUtil.getCurrentDate();
	    		mEndDay = mStartDay;
	    		
		    	getGroupData(QRep_01.this, mStartDay, mEndDay, null, null);
				mAdapter.notifyDataSetChanged();        
		    	
	    		((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("上一日");
	    		setTitle(getString(R.string.app_name)+":[每日]"+mode_E[mGroupMode]);
	    		break;
    	}
	    	case KeySet.SearchMode.WEEK:
	    	{
	    		String day = Utilis.getWeekDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
	    		
		    	getGroupData(QRep_01.this, mStartDay, mEndDay, null, null);
				mAdapter.notifyDataSetChanged();        
		    	
	    		((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("上一週");
	    		setTitle(getString(R.string.app_name)+":[每週]"+mode_E[mGroupMode]);
	    		break;
	    	}
	    	case KeySet.SearchMode.MONTH:
	    	{
	    		String day = Utilis.getMonthDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
	    		
		    	getGroupData(QRep_01.this, mStartDay, mEndDay, null, null);
				mAdapter.notifyDataSetChanged();        
		    	
	    		((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("上個月");
	    		
	    		setTitle(getString(R.string.app_name)+":[每月]"+mode_E[mGroupMode]);
	    		break;
	    	}
	    	case KeySet.SearchMode.SEASON:  //自定日期範圍
	    	{
	    		final int nAccountId = getIntent().getIntExtra("accountid", 0);
	    		new AlertDialog.Builder(QRep_01.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;
						if ((mGroupMode!=GroupMode.TOP3 && mGroupMode!=GroupMode.TOP5) &&
								(WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 )){
							mStartDay=mLimitDay;
							mEndDay=DateUtil.addDate(mStartDay, +7);
						}
		            	mTextDuration.setText(getString(R.string.str_duration) + " : " + mStartDay + "~" + mEndDay);
		            	mTextDuration.setText( mStartDay + "~" + mEndDay);
		            	
		            	getGroupData(QRep_01.this, mStartDay, mEndDay, null, null);
		        		mAdapter.notifyDataSetChanged();        
		            	
		            	setTitle(getString(R.string.app_name)+":[日期範圍]"+mode_E[mGroupMode]);
		            	
		            }
		          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            }
		          }).show();
	    		break;
	    	}
	    	case KeySet.SearchMode.BATCH:  //批號
	    	{
	    		SQLiteDatabase db = Utilis.getDB(QRep_01.this);
				Cursor cursorAlbun = null;
				StringBuffer bufCategory = new StringBuffer();
				bufCategory.append("select distinct BATCH from qitems");
				bufCategory.append(" where BATCH> ' '");
				bufCategory.append(SQLADD);
				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);
					}
				}
				cursorAlbun.close();
				db.close();
				if ((mGroupMode!=GroupMode.TOP3 && mGroupMode!=GroupMode.TOP5) &&
						(WeiLa!=0 &&	DateUtil.compareTime(mStartDay, mLimitDay)<0 )){
					mStartDay=mLimitDay;
					mEndDay=DateUtil.addDate(mStartDay, +7);
				}
	    		getGroupData(QRep_01.this, mStartDay, mEndDay, null, null);
	    		mAdapter.notifyDataSetChanged();        
	    		
	    		((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("上一批");

	    		setTitle(getString(R.string.app_name)+":[依批號結算]"+mode_E[mGroupMode]);	    		
	    		break;
	    	}
	    	case KeySet.SearchMode.ORDER:  //自定日期範圍
	    	{
	    		new AlertDialog.Builder(QRep_01.this).setTitle("預購單 搜尋(起始、結束日期)")
				.setView(makeDateDialog())
				.setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            	String startDay = "" + mYear1 + "/" + Utilis.formatDate(mMonth1) + "/" + Utilis.formatDate(mDay1);
		            	String endDay = "" + mYear2 + "/" + Utilis.formatDate(mMonth2) + "/" + Utilis.formatDate(mDay2);
		            	
		            	mStartDay = startDay;
		            	mEndDay = endDay;
		            	mTextDuration.setText(getString(R.string.str_duration) + " : " + mStartDay + "~" + mEndDay);
		            	setTitle(getString(R.string.app_name)+":[日期範圍]"+mode_E[mGroupMode]);
		            	getGroupData(QRep_01.this, mStartDay, mEndDay, null, null);
		        		mAdapter.notifyDataSetChanged();        
		            }
		          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            }
		          }).show();
	    		break;
	    	}

        }

        setCondition();
    }

	private void makeTable(String kGoods,String kSplitColorNo,String kSplitColor,String kSplitSizes){
		
		//展開用的引用在庫存表
		String[] anames;	
		String[] anumber;
		String[] asizes;
		double[] attot;
	
		if(kSplitSizes != null && kSplitSizes.length() > 0
    		&& kSplitColorNo != null && kSplitColorNo.length() > 0
    		&& kSplitColor != null && kSplitColor.length() > 0){
			
			    	mArrayColorNumber.clear();
			    	mArrayColorNumber.removeAll(mArrayColorNumber);
			    	mArrayColorName.clear();
			    	mArrayColorName.removeAll(mArrayColorName);
			    	
		        	anumber = kSplitColorNo.split("，"); //取得各色號字串
		        	anames = kSplitColor.split("，");
		        	asizes = kSplitSizes.split(",");
		        	attot=new double[asizes.length*anumber.length];
			    	
			    	
			    	for(int i = 0; i < anumber.length; i++){ 
			    		mArrayColorNumber.add(anumber[i]); //從numbers字串陣列 存入 List_mArrayColorNumber
			    	}
			    	
			    	anames = kSplitColor.split("，");
			    	
			    	for(int i = 0; i < anames.length; i++){
			    		mArrayColorName.add(anames[i]);
			    	}
				
			    	//努力歸零 very important
			    	mLayoutRoot.removeAllViews(); //***************
					mSizeLink.clear();
					mCountRow.clear();	        		
					mCountCell.clear();
					
			    	mSizeLink.add("代碼"); // 顏色
			    	mSizeLink.add("顏色"); // 尺寸
			    	// 設定 Title 行 //使每個尺寸都有3格(進/銷/存)
			    	String ttot[] =new String[asizes.length*3*anumber.length] ; //進銷存統計用
			    	String ptot[] =new String[asizes.length*anumber.length] ;	//展開用
			    	for(int i = 0; i < asizes.length*3*anumber.length; i++){ttot[i]="0";}
			    	for(int i = 0; i < asizes.length*anumber.length; i++){ptot[i]="";}
			    	for(int i = 0; i < asizes.length; i++){
			    		mSizeLink.add(asizes[i]+"進");
			    		mSizeLink.add(asizes[i]+"銷(訂)");
			    		mSizeLink.add(asizes[i]+"存");
			    	}
			    	// 設定初始Row 列
			    	for(int i = 0; i <= mArrayColorName.size(); i++){
			    		// 設定Row會包含哪些 Key
			    		mCountRow.put(i, i * 100);
			    		for(int k = 0; k < mSizeLink.size(); k ++){ //s1,s2,s3,m1,m2,m3,l1,l2,l3,x1,x2,x3
			        		if( i == 0){
			        			mCountCell.put(k, mSizeLink.get(k)); //原先 i*100+k 沒有意義
			        		}
			        		else{ // 第二列以後
			        			if( k == 0){ // 新增號碼
			        					mCountCell.put(i * 100 + k, mArrayColorNumber.get(i - 1));
			        			} else {
			        					mCountCell.put(i * 100 + k, mArrayColorName.get(i - 1)); 
			        			}
			
			        		}			
			    		}
			    	}
					try{
				        SQLiteDatabase db = Utilis.getDB(this);		
						Cursor cs = null;
						StringBuffer mySqlBuf = new StringBuffer();
						mySqlBuf.delete(0, mySqlBuf.toString().length()); //清空
						if (nPart==0){
							mySqlBuf.append("select GOODSNO,COLOR,SIZE,");
							mySqlBuf.append("sum(UNIT10) as SUM10,sum(UNIT20) as SUM20,sum(UNIT30) as SUM30,sum(UNIT40) as SUM40,sum(UNIT) as SUM1");
							mySqlBuf.append(" from qitems")
							.append(" where GOODSNO='" + kGoods+"' and (QKIND ='10' or QKIND ='20' or QKIND ='30' or QKIND ='40')")
							.append(" group by GOODSNO,COLOR,SIZE");
						//門市版需考量為 轉入或轉出 有正負的問題
							cs =null;
							cs = db.rawQuery(mySqlBuf.toString(), null);
//							Toast.makeText(this,"程式路過這裡" , Toast.LENGTH_SHORT).show();
							if (cs.getCount()>0){
								cs.moveToFirst();			
								for (int i=0;i<cs.getCount();i++){  //從第一筆--最後一筆讀取
										String acol=cs.getString(cs.getColumnIndex("COLOR"));
										String asiz=cs.getString(cs.getColumnIndex("SIZE"));
										
									for (int j=0;j<anumber.length;j++){
										if (acol.equalsIgnoreCase(anumber[j]))  { //顏色相符
					  						for (int k=0;k<asizes.length;k++){
						  						if (asiz.equalsIgnoreCase(asizes[k]))  { //尺寸相符  置入進銷存
					  								ttot[(j*asizes.length*3)+k*3]=""+Math.round(cs.getInt(cs.getColumnIndex("SUM10")));
						  							ttot[(j*asizes.length*3)+k*3+1]=""+Math.round((cs.getInt(cs.getColumnIndex("SUM30"))+cs.getInt(cs.getColumnIndex("SUM40"))-cs.getInt(cs.getColumnIndex("SUM1"))))+"("+cs.getInt(cs.getColumnIndex("SUM1"))+")";
					  								ttot[(j*asizes.length*3)+k*3+2]=""+Math.round((cs.getInt(cs.getColumnIndex("SUM10"))-(cs.getInt(cs.getColumnIndex("SUM20"))+cs.getInt(cs.getColumnIndex("SUM30"))+cs.getInt(cs.getColumnIndex("SUM40")))));
						  						}
					  						}
										}
									}
									cs.moveToNext();
								}
							}
						} else { //nPart==1 門市的進銷存
							mySqlBuf.append("select GOODSNO,COLOR,SIZE,USER,QKIND,");
							mySqlBuf.append("sum(UNIT20) as SUM20,sum(UNIT30) as SUM30,sum(UNIT40) as SUM40,sum(UNIT) as SUM1");
							mySqlBuf.append(" from qitems")
							.append(" where GOODSNO='" + kGoods+"'")
							.append(" group by GOODSNO,COLOR,SIZE,USER,QKIND");
							cs =null;
							cs = db.rawQuery(mySqlBuf.toString(), null);
							if (cs.getCount()>0){
								cs.moveToFirst();			
								for (int i=0;i<cs.getCount();i++){  //從第一筆--最後一筆讀取
										String acol=cs.getString(cs.getColumnIndex("COLOR"));
										String asiz=cs.getString(cs.getColumnIndex("SIZE"));
										
									for (int j=0;j<anumber.length;j++){
										if (acol.equalsIgnoreCase(anumber[j]))  { //顏色相符
					  						for (int k=0;k<asizes.length;k++){
						  						if (asiz.equalsIgnoreCase(asizes[k]))  { //尺寸相符  置入進銷存
						  							if (cs.getString(4).equalsIgnoreCase("20") || (cs.getString(3).equalsIgnoreCase(mDept) && cs.getString(4).equalsIgnoreCase("21")) ) {  
						  								ttot[(j*asizes.length*3)+k*3]=""+(Utilis.toInt(ttot[(j*asizes.length*3)+k*3])+Math.round(cs.getInt(cs.getColumnIndex("SUM20"))));
						  								ttot[(j*asizes.length*3)+k*3+2]=""+(Utilis.toInt(ttot[(j*asizes.length*3)+k*3+2])+Math.round((cs.getInt(cs.getColumnIndex("SUM20")))));
						  							} else if (cs.getString(4).equalsIgnoreCase("21") && !cs.getString(3).equalsIgnoreCase(mDept)){
						  								ttot[(j*asizes.length*3)+k*3]=""+(Utilis.toInt(ttot[(j*asizes.length*3)+k*3])-Math.round(cs.getInt(cs.getColumnIndex("SUM20"))));
						  								ttot[(j*asizes.length*3)+k*3+2]=""+(Utilis.toInt(ttot[(j*asizes.length*3)+k*3+2])-Math.round((cs.getInt(cs.getColumnIndex("SUM20")))));						  							
					  								} else {
					  									
					  									int M300=0;
					  									int M11=0;
					  									int M30=0;  //銷貨時判斷原理nPart==0總公司只判讀30 40 門市只判讀 31 41
					  									if (nPart==0 && (cs.getString(4).equalsIgnoreCase("30") || cs.getString(4).equalsIgnoreCase("40"))) {
					  										M30=cs.getInt(cs.getColumnIndex("SUM30"))+cs.getInt(cs.getColumnIndex("SUM40"));
					  									}else  if (nPart==1 && (cs.getString(4).equalsIgnoreCase("31") || cs.getString(4).equalsIgnoreCase("41"))) {
					  										M30=cs.getInt(cs.getColumnIndex("SUM30"))+cs.getInt(cs.getColumnIndex("SUM40"));
					  									}
					  									
					  									int M1=cs.getInt(cs.getColumnIndex("SUM1"));
					  									ttot[(j*asizes.length*3)+k*3+2]=""+(Utilis.toInt(ttot[(j*asizes.length*3)+k*3+2])-M30);
					  									 //31 41 單 會牽扯到 銷貨(留貨)的問題 2個運算在同一欄位上 需分開運算
					  									if (ttot[(j*asizes.length*3)+k*3+1].indexOf("(")>-1) { //表有留貨的値在()之間
					  										M11=M1+Utilis.toInt(ttot[(j*asizes.length*3)+k*3+1].substring(ttot[(j*asizes.length*3)+k*3+1].indexOf("(")+1, ttot[(j*asizes.length*3)+k*3+1].indexOf(")")));
					  										try {
					  											M300=M30+Utilis.toInt(ttot[(j*asizes.length*3)+k*3+1].substring(0, ttot[(j*asizes.length*3)+k*3+1].indexOf("(")));
					  										}catch(Exception e){
					  											e.printStackTrace();
					  										}
					  									} else { //沒留貨
					  										M300 =M30+Utilis.toInt(ttot[(j*asizes.length*3)+k*3+1]);
					  									}
					  									
						  							ttot[(j*asizes.length*3)+k*3+1]=""+M300+"("+M11+")";
						  							
						  							}	
						  						}
					  						}
										}
									}
									cs.moveToNext();
								}
							}
							
						}
						db.close();
						cs.close();
						
			
						StringBuffer mCountList= new StringBuffer(); //所有件數表 5,5，3,3
						StringBuffer mInCountList= new StringBuffer(); //所有件數表 5,5，3,3
						
						for (int i=0;i<anumber.length;i++){
							for (int j=0;j<asizes.length;j++){
								mInCountList.append(""+Math.round(attot[((i*asizes.length)+j)]));
					  			mCountList.append(ttot[((i*asizes.length*3)+j*3)]).append(",")
					  			.append(ttot[((i*asizes.length*3)+j*3)+1]).append(",")
					  			.append(ttot[((i*asizes.length*3)+j*3)+2]);
					  		if  ( j<(asizes.length-1)) {
					  			mCountList.append(",");
					  			mInCountList.append(",");
					  			}
					  		
							}
							if (i<(anumber.length-1)){	
								mCountList.append("，"); 
								mInCountList.append("，");
								}
						}
			
						
			    	String[] numberLevel1 = mCountList.toString().split("，");
			    	for(int nRow = 1; nRow < mCountRow.size(); nRow++){
			    		String[] numberLevel2 = numberLevel1[nRow - 1].split(",");
			    		int nLevel2 = 0;
						int nCellKey = mCountRow.get(nRow);
						for(int i = 2 ; i < mSizeLink.size(); i++){
							if(nLevel2 < numberLevel2.length){
								mCountCell.put(nCellKey + i, numberLevel2[nLevel2]);
							}
							nLevel2++;
						}
					}
					
				}catch(Exception e){
					e.printStackTrace();
				}
					
					ArrayList<TableRow> table = new ArrayList<TableRow>();
				table.removeAll(table);
			
				for(int i = 0; i <= mArrayColorName.size(); i++){
					TableCell[] titles = new TableCell[mSizeLink.size()];
			
					for(int k = 0; k < titles.length; k++){
	        			if (k<=1) titles[k] = new TableCell((Wwidth/(tabless+1))-8,tableHeight,TableCell.STRING);
	        			else titles[k] = new TableCell((Wwidth/tabless)-8,tableHeight,TableCell.STRING);
					}
					table.add(new TableRow(titles));
				}
				
				TableRow tableRow = table.get(0);
				for(int i = 0; i <=mArrayColorName.size(); i ++){
					TableRowView row = new TableRowView(this, tableRow,0, i);
					mLayoutRoot.addView(row);
				}
		
		}
	}

	
	private void DisplayPart0(String GoodsNo,int qmtrio) {//總倉直接解析QITEMS
		if  (Utilis.haveInternet(QRep_01.this) && off_line==1){
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
			
				bfstr.append(Utilis.getIni(this, "SYS", "IMPORT", 2)).append(";");
				bfstrF.append("UID").append(";");
				bfstr.append(GoodsNo).append(";");
				bfstrF.append("GOODSNO").append(";");
				bfstr.append(deptStr[5]).append(";");
				bfstrF.append("PARTNO").append(";");  //總倉代號 名稱
				bfstr.append(deptStr[6]);
				bfstrF.append("PARTNA");
				
				final String []fields=bfstr.toString().split(";");
				final String []fieldFs=bfstrF.toString().split(";");
				
			      myDialog = ProgressDialog.show(this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
				  
			      new Thread()
			      { 
			        public void run()
			        { 
			          try
			          { 
							String uriAPI="http://"+Utilis.getIni(QRep_01.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(QRep_01.this, "SYS", "IMPORT", 2)+File.separator+"qmtrio.php";
							HttpPost httpRequest = new HttpPost(uriAPI);
							// Post運作傳送變數必須用NameValuePair[]陣列儲存
							//Log.i("DOWNLOAD_QRep_03_qmtrio","VISITint_"+uriAPI );
							
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							for(int x=0;x<fields.length;x++){
								params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
							}
							try {
								// 發出HTTP request(請求) 
								httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								// 取得HTTP response(回傳) 
								HttpResponse httpResponse = new DefaultHttpClient()
										.execute(httpRequest);
								// 若狀態碼為200 ok 
								if (httpResponse.getStatusLine().getStatusCode() == 200)
								{
									// 取出回應字串
									
									String strResult = EntityUtils.toString(httpResponse	.getEntity());
									mHandlerQm.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
									
								}
							} catch (Exception e)
							{
								e.printStackTrace();
							}

			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			            // 卸載所建立的myDialog物件。
			            myDialog.dismiss();
			          }
			        }
			      }.start(); /* 開始執行執行緒 */


		}else{//localhost	
	        SQLiteDatabase db = Utilis.getDB(this);		
			Cursor cs = null;
			if (GoodsNo.indexOf("-")>0) GoodsNo= GoodsNo.substring(0,GoodsNo.indexOf("-"));
			StringBuffer mySqlBuf = new StringBuffer();
			//總倉進貨各色尺寸件數,必然在各色尺寸俱全(畢竟為源起資料)貨品建檔
					mySqlBuf.append("select COLOR,SIZE,UNIT1,sum(UNIT10)")
					.append(" from qitems where GOODSNO='" + GoodsNo+"' and ISCONFIRM='Y'")
					.append(" group by COLOR,SIZE,UNIT1");
					cs = db.rawQuery(mySqlBuf.toString(), null);
					if (cs.getCount()>0){
						ColNoSizN=cs.getCount();
						ColNoSiz= new String[ColNoSizN][3];
						Otott=new int[deptN+1][ColNoSizN*6];  //預設各色尺寸及1進2出3銷4留5實6存
						for (int i=0;i<deptN+1;i++){
							for (int j=0;j<ColNoSizN*6;j++){
									Otott[i][j]=0;
							}
						}
							cs.moveToFirst();
						for (int x=0;x<ColNoSizN;x++){
							ColNoSiz[x][0]=cs.getString(0); //COLOR
							ColNoSiz[x][1]=cs.getString(2); //UNIT1_COLOR_NAME
							ColNoSiz[x][2]=cs.getString(1); //SIZE
							Otott[0][x*3]=cs.getInt(3); //進
							Otott[0][x*3+2]=Otott[0][x*3+2]+cs.getInt(3);
							Otott[0][ColNoSizN*3+x*3+2]=Otott[0][ColNoSizN*3+x*3+2]+cs.getInt(3);
							cs.moveToNext();
						}
					}
					
			mySqlBuf.delete(0, mySqlBuf.toString().length());
			//針對出貨單
			cs=null;
			mySqlBuf.append("select USER,COLOR,SIZE,sum(UNIT20)")
			.append(" from qitems where GOODSNO='" + GoodsNo+"' and ISCONFIRM='Y'")
			.append(" group by USER,COLOR,SIZE");
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				for (int x=0;x<cs.getCount();x++){
					for (int xi=0;xi<deptN;xi++){
						if (cs.getString(0).equalsIgnoreCase(DepNo[xi])){  //對上門市代號
							for (int xj=0;xj<ColNoSizN;xj++){						
							if(cs.getString(1).equalsIgnoreCase(ColNoSiz[xj][0]) && cs.getString(2).equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色
								if (cs.getString(0).equalsIgnoreCase(deptStr[5])){
									Otott[xi][ColNoSizN*3+xj*3]=Otott[xi][ColNoSizN*3+xj*3]+cs.getInt(3); //總倉出貨
									Otott[xi][xj*3+2]=Otott[xi][xj*3+2]-cs.getInt(3);
									Otott[xi][ColNoSizN*3+xj*3+2]=Otott[xi][ColNoSizN*3+xj*3+2]-cs.getInt(3);
									
								}else {
									Otott[xi][xj*3]=Otott[xi][xj*3]+cs.getInt(3); //門市出貨
									Otott[xi][xj*3+2]=Otott[xi][xj*3+2]+cs.getInt(3);
									Otott[xi][ColNoSizN*3+xj*3+2]=Otott[xi][ColNoSizN*3+xj*3+2]+cs.getInt(3);
								}
							}
						}
					}
				}
					cs.moveToNext();
				}
			}
			//接下來門市出貨 20 21 兩段 UNIT 20
			mySqlBuf.delete(0, mySqlBuf.toString().length());
			//針對總倉或門市轉出單 及 銷貨單 及 留貨單   (暫存單要扣除實,存)
			cs=null;
			mySqlBuf.append("select DEPTNO,COLOR,SIZE,sum(UNIT20),sum(UNIT30),sum(UNIT40),sum(UNIT)")
			.append(" from qitems where GOODSNO='" + GoodsNo+"' and (ISCONFIRM='Y' or (ISCONFIRM<>'Y' and ISCHECK<>'Y'))")
			.append(" group by DEPTNO,COLOR,SIZE");
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				for (int x=0;x<cs.getCount();x++){
					for (int xi=0;xi<deptN;xi++){
						if (cs.getString(0).equalsIgnoreCase(DepNo[xi])){  //對上門市代號
							for (int xj=0;xj<ColNoSizN;xj++){						
							if(cs.getString(1).equalsIgnoreCase(ColNoSiz[xj][0]) && cs.getString(2).equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色
								Otott[xi][ColNoSizN*3+xj*3]=Otott[xi][ColNoSizN*3+xj*3]+cs.getInt(3); //總倉出貨
								Otott[xi][xj*3+1]=Otott[xi][xj*3+1]+cs.getInt(4); //門市銷貨
								Otott[xi][xj*3+1]=Otott[xi][xj*3+1]+cs.getInt(5); //門市櫃員銷貨
								Otott[xi][ColNoSizN*3+xj*3+1]=Otott[xi][ColNoSizN*3+xj*3+1]+cs.getInt(6); //門市留貨
								Otott[xi][xj*3+2]=Otott[xi][xj*3+2]-cs.getInt(3)-cs.getInt(4)-cs.getInt(5);
								Otott[xi][ColNoSizN*3+xj*3+2]=Otott[xi][ColNoSizN*3+xj*3+2]-cs.getInt(3)-cs.getInt(4)-cs.getInt(5)-cs.getInt(6);
							}
						}
					}
				}
					cs.moveToNext();
				}
			}
			
			//還剩預購單未計入
			mySqlBuf.delete(0, mySqlBuf.toString().length());
			//針對預購 ISCHECK='Y' and ISCONFIRM<>'Y'
			cs=null;
			mySqlBuf.append("select DEPTNO,COLOR,SIZE,sum(UNIT30),sum(UNIT40)")
			.append(" from qitems where GOODSNO='" + GoodsNo+"' and ISCONFIRM<>'Y' and ISCHECK='Y'")
			.append(" group by DEPTNO,COLOR,SIZE");
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				for (int x=0;x<cs.getCount();x++){
					for (int xi=0;xi<deptN;xi++){
						if (cs.getString(0).equalsIgnoreCase(DepNo[xi])){  //對上門市代號
							for (int xj=0;xj<ColNoSizN;xj++){						
							if(cs.getString(1).equalsIgnoreCase(ColNoSiz[xj][0]) && cs.getString(2).equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色
								Otott[xi][ColNoSizN*3+xj*3+1]=Otott[xi][ColNoSizN*3+xj*3+1]+cs.getInt(3)+cs.getInt(4); //門市留貨
								Otott[xi][ColNoSizN*3+xj*3+2]=Otott[xi][ColNoSizN*3+xj*3+2]-cs.getInt(3)-cs.getInt(4);
							}
						}
					}
				}
					cs.moveToNext();
				}
			}
	//臨時
				
			db.close();
			
			//製作一個空的STRINGGRID _是個容器
	    	mLayoutRoot.removeAllViews(); //***************
			mSizeLink.clear();
			mSizeLink1.clear();		
			mCountRow.clear();	        		
			mCountCell.clear();
			
	    	mSizeLink.add("顏色"); // 顏色
	    	mSizeLink.add("尺寸"); // 尺寸
	    	mSizeLink1.add("NO"); // 顏色
	    	mSizeLink1.add("門市"); // 尺寸

	    	// 設定 Title 行 //使每個顏色尺寸都有3格(進/銷/存)
	    	for(int i = 0; i < ColNoSizN; i++){
	    		mSizeLink1.add("進/出"); 
	    		mSizeLink1.add("銷/(訂)");
	    		mSizeLink1.add("實(存)");
	    		for(int j = 0; j < 3; j++){
	    		mSizeLink.add(ColNoSiz[i][j]);
	    		}
	    	}
	    	// 以下完成所有TABLE表的nCountCell裝填
	    	for(int i = 0; i <= (deptN+1); i++){ //i縱向 門市的總量+上2行
	    		// 設定Row會包含哪些 Key
	    		mCountRow.put(i, i * 200);
	    		for(int k = 0; k < mSizeLink.size(); k ++){ //k橫向
	        		if( i == 0){
	        			mCountCell.put(k, mSizeLink.get(k)); 
	        		} else if (i==1){
	        			mCountCell.put(i*200+k, mSizeLink1.get(k));
	        		} else{ // 第三列以後
	        			if( k == 0){ // 增門市代號
	       					mCountCell.put(i * 200 + k, DepNo[i- 2]);
	        			} else if (k==1){ //增門市名稱
	    					mCountCell.put(i * 200 + k, DepNa[i- 2]);
	        			} else {
	        					mCountCell.put(i * 200 + k, ""+Otott[i-2][k-2]+"("+Otott[i-2][mSizeLink.size()-2+k-2]+")"); //廠商進貨/門市出貨
	        			}
	        		}			
	    		}
	    	}
			if (mCountCell.size()>0){
				ArrayList<TableRow> table = new ArrayList<TableRow>();
				table.removeAll(table);
			
				for(int i = 0; i <= (deptN+1); i++){  //縱向一一
					TableCell[] titles = new TableCell[ColNoSizN*3+2]; //橫向一一
			
					for(int k = 0; k < titles.length; k++){
						titles[k] = new TableCell((Wwidth/tabless)-8,tableHeight,TableCell.STRING);
					}
					table.add(new TableRow(titles));
				}
				
				TableRow tableRow = table.get(0);
				for(int i = 0; i <=(deptN+1); i ++){
					TableRowView row = new  TableRowView(QRep_01.this, tableRow,1, i);
					mLayoutRoot.addView(row);
				}
			}
	    	
	    	
		}
	}
   	
public class TableRowView extends LinearLayout {  
    public TableRowView(Context context, TableRow tableRow,int imode, int position) {  
        super(context);  
        this.setOrientation(LinearLayout.HORIZONTAL);
        String colStr="01";
        for (int i = 0; i < tableRow.getSize(); i++) { 
            TableCell tableCell = tableRow.getCellValue(i);  
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(  
                    tableCell.width, tableCell.height);  
            layoutParams.setMargins(0, 0, 1, 1);  
            TextView textCell = new TextView(context);  
                textCell.setLines(1);  
                textCell.setGravity(Gravity.CENTER);  
                textCell.setBackgroundColor(Color.WHITE);
                if(mCountRow.containsKey(position) == true){
                	int key = mCountRow.get(position);  //keep
                	if( mCountCell.containsKey(key + i)){
                		textCell.setText(String.valueOf(mCountCell.get(key + i))); //keep
                	}else{
                		textCell.setText("X");
                	}
                }else{
                	textCell.setText("X");
                }
                textCell.setId(position * 200 + i);
                textCell.setTextColor(Color.BLACK);
                if(position >=1 && i >= 2){
                	if ((i+2) %3==1){
                	textCell.setBackgroundResource(R.drawable.keypad_yellow);
                	} else if((i+2) %3==2) {
                    	textCell.setBackgroundResource(R.drawable.keypad_green);                    		
                	} else if((i+2) %3==0) {
                    	textCell.setBackgroundResource(R.drawable.keypad_blue2);                    		
                	}
                	
                }else  if(position > 0 && i ==0 && imode==0){  //
                	String colorN=DBUtil.ColorGetTxt(QRep_01.this,textCell.getText().toString());
                	String [] colors=colorN.split(";");
                	textCell.setBackgroundColor(Utilis.toInt(colors[2]));
                }else  if(position == 0 && imode==1 && i>1 ){  //
                	String colorN=DBUtil.ColorGetTxt(QRep_01.this,textCell.getText().toString());
                	String [] colors=colorN.split(";");
                	if (((i+1) %3)==0){	
                		colStr=textCell.getText().toString();
                		colorN=DBUtil.ColorGetTxt(QRep_01.this,textCell.getText().toString());
                		colors=colorN.split(";");
                	}
               		if (((i+1) %3)==2){
               			textCell.setBackgroundResource(R.drawable.keypad_blue2);
               		}else{	
                		textCell.setBackgroundColor(Utilis.toInt(colors[2]));
               		}
                } else {
                	textCell.setBackgroundColor(Color.rgb(208, 208, 208));
                }
                
                addView(textCell, layoutParams);
                
        }  
        this.setBackgroundColor(Color.BLACK);
    }  
}
    
	private String ColorGetName(Context context,String key){
		String ColorName="混色";
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cs = null;					
		StringBuffer mySqlBuf = new StringBuffer();
			mySqlBuf.append("select distinct NO,TXT from qc_color where NO='"+key+"'");
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				ColorName=cs.getString(1);
			}
			db.close();
			cs.close();
		return ColorName;	
	}
    
	@SuppressLint("HandlerLeak")
	Handler mHandlerQm = new Handler()
	{
		@Override
		public  void handleMessage(Message msg)
		{
			//傳回的//upup_1-30_系統時間
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
				if (Hresult != null ){
					//Log.i("DOWNLOAD_QRep_03_qmtrio","Hresult="+Hresult );
					if (Hresult.indexOf("\r\n")>2){
				    	mLayoutRoot.removeAllViews(); //***************
						mCountRow.clear();	        		
						mCountCell.clear();
						String Lines [] = Hresult.split("\r\n");
						for (int xx=0;xx<Lines.length;xx++){
				  		mCountRow.put(xx, xx * 200);
							String[] data= Lines [xx].split(",");
							ColNoSizN=(data.length-2)/3;
							for (int jj=0;jj<data.length;jj++){
							mCountCell.put(xx * 200 + jj, data[jj]);
							
							}	
						}
						if (mCountCell.size()>0){
							ArrayList<TableRow> table = new ArrayList<TableRow>();
							table.removeAll(table);
						
							for(int i = 0; i <= (deptN+1); i++){  //縱向一一
								TableCell[] titles = new TableCell[ColNoSizN*3+2]; //橫向一一
						
								for(int k = 0; k < titles.length; k++){
									titles[k] = new TableCell((Wwidth/tabless)-8,tableHeight,TableCell.STRING);
								}
								table.add(new TableRow(titles));
							}
							
							TableRow tableRow = table.get(0);
							for(int i = 0; i <=(deptN+1); i ++){
								TableRowView row = new  TableRowView(QRep_01.this, tableRow,1, i);
								mLayoutRoot.addView(row);
							}
						}
					}
				}
			}
		}
	};

	Handler mHandlerQDR_11 = new Handler()
	{
		@Override
		public  void handleMessage(Message msg)
		{
			//傳回的//upup_1-30_系統時間
			
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
				if (Hresult != null ){
					if (Hresult.indexOf("SSSS\r\n")>2){

						if (mAdapter.mList != null) {
							mAdapter.mList.clear();
						}
						
						Hresult=	Hresult.substring(Hresult.indexOf("rep01;")+6);
						
						Log.i("DOWNLOAD_11",Hresult );
						
						String LineH [] = Hresult.substring(0, Hresult.length()-6).split(";SSSS\r\n");
						
						for (int xx=0;xx<LineH.length;xx++){

							String Lineshh[] =LineH[xx].split(";");

							RepData data = new RepData();
							
							if (Lineshh[4]!=null && Lineshh[4].length()>10 && Lineshh[4].indexOf("20123")>0){
								data.iPic=Lineshh[4].replace(Lineshh[4].substring(0,Lineshh[4].indexOf("20123/")), myPath);  //圖片
							}else data.iPic=defPic;
							data.iFormdate=Lineshh[0]; //主貨號 做為KEY 不顯示
							data.iGoods=Lineshh[0]; //主貨號
							data.iName=Lineshh[1]; //品名
							data.iCountry=Lineshh[2];
							data.iNumber=Lineshh[3];
							data.iUnit2=Lineshh[5];
							if (PSWD==0) {
								data.iImpo="進:"+Lineshh[6]+"/$:"+Lineshh[7]+" 存:"+Lineshh[8];									
								data.iCompany="毛:"+Lineshh[11]+" "+Lineshh[12]+"%";								
							}else {
								data.iImpo="進:"+Lineshh[6]+" 存:"+Lineshh[8];								
									data.iCompany="";
							}
							data.iMoney="銷:"+Lineshh[9]+" /$:"+Lineshh[10];
										
										TS30+=Utilis.toInt(Lineshh[12]); //總銷貨成本
										TT30+=Utilis.toInt(Lineshh[9]);//總銷量
										TM30+=Utilis.toInt(Lineshh[10]); //總銷額
							
							data.iSort=Utilis.toInt(Lineshh[9]);
							TT10+=Utilis.toInt(Lineshh[6]);
			 				StkT+=Utilis.toInt(Lineshh[8]);  //總存貨量
			 				StkM+=Utilis.toInt(Lineshh[13]); //總存貨金額
			 				Profit+=Utilis.toInt(Lineshh[11]); //總毛利
			 				if (TM30>0)	{Profits=Math.round(Profit*100/TM30);} //總毛利率
			 				else {Profits=0;}
			 				
			 				if (mAdapter.mList.size()>0) {
			 					int fnd=0;
			 					for (int sort=0;sort<mAdapter.mList.size();sort++){
			 						RepData	dataS = (RepData)mAdapter.mList.get(sort) ;
			 					 
			 					 if (data.iSort>dataS.iSort) {
			 						mAdapter.mList.add(sort,data);
			 						fnd=1;
			 						break;
			 					 }
			 					}
			 					if (fnd==0) {
			 						mAdapter.mList.add(data);	
			 					}
			 				} else {  //第一筆沒得比,無條件寫入
			 				mAdapter.mList.add(data);
			 				}
							
						}
						mAdapter.notifyDataSetChanged();
						
		 				((TextView)findViewById(R.id.text_tot)).setText("T:"+StkT); 				
		 				((TextView)findViewById(R.id.text_t10)).setText("T:"+TT10); 				
		 				((TextView)findViewById(R.id.text_t30)).setText("T:"+TT30);
		 				if (PSWD==0){ 				
			 				((TextView)findViewById(R.id.text_mtot)).setText("$:"+StkM);
			 				((TextView)findViewById(R.id.text_r10)).setText("$:"+(TM30-TM10));
			 				((TextView)findViewById(R.id.text_m10)).setText("$:"+TM10);
			 				((TextView)findViewById(R.id.text_m30)).setText("$:"+TM30);
			 				((TextView)findViewById(R.id.text_r30)).setText("$:"+Profit);
			 				((TextView)findViewById(R.id.text_rp0)).setText("%:"+Profits);
		 				}else {
			 				((TextView)findViewById(R.id.text_mtot)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_r10)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_m10)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_m30)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_r30)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_rp0)).setText("xxxxxx");
		 				}
							
						
				}
			}
		}
	}
	};
	
	Handler mHandlerQDR_12 = new Handler()
	{
		@Override
		public  void handleMessage(Message msg)
		{
			//傳回的//upup_1-30_系統時間
			
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
				if (Hresult != null ){
					if (Hresult.indexOf("SSSS\r\n")>2){

						if (mAdapter.mList != null) {
							mAdapter.mList.clear();
						}
						
						Hresult=	Hresult.substring(Hresult.indexOf("rep01;")+6);
						
						//Log.i("DOWNLOAD_11",Hresult );
						
						String LineH [] = Hresult.substring(0, Hresult.length()-6).split(";SSSS\r\n");
						
						for (int xx=0;xx<LineH.length;xx++){

							String Lineshh[] =LineH[xx].split(";");

							RepData data = new RepData();
							
							int IT30=Utilis.toInt(Lineshh[2]); //本銷量
							int IM30=Utilis.toInt(Lineshh[3]); //本銷額
							int IS30=Utilis.toInt(Lineshh[4]);  //本銷成本
							
							if (Lineshh[8]!=null && Lineshh[8].length()>10 && Lineshh[8].indexOf("20123")>0){
								data.iPic=Lineshh[8].replace(Lineshh[8].substring(0,Lineshh[8].indexOf("20123/") ), myPath);  //圖片
							}else data.iPic=defPic;
							data.iFormdate=Lineshh[0]; //主貨號 做為KEY 不顯示
							data.iGoods=Lineshh[0]; //主貨號
							data.iName=Lineshh[1]; //品名
							data.iCountry=Lineshh[5]; //COLORS
							data.iNumber=Lineshh[6]; //SIZES
							data.iUnit2=Lineshh[7]; //COLORSNO
							
							T10=Utilis.toInt(Lineshh[9]);
							TT10+=T10;
							M10=Utilis.toInt(Lineshh[10]);
							TT30+=M10;
							T30=Utilis.toInt(Lineshh[11]);
							TT30+=T30;
							M30=Utilis.toInt(Lineshh[12]);
							TM30+=M30;
							S30=Utilis.toInt(Lineshh[13]);
							TS30+=S30;
							
								data.iSort=M30;
								
								if (PSWD==0) {
										data.iMoney="總銷:"+T30+" /$:"+M30+"/毛:"+(M30-S30);
									if (mMode!=KeySet.SearchMode.BATCH){
										data.iCompany="本銷:"+IT30+" /$"+IM30+"/毛:"+(IM30-IS30);
									}else {
										data.iCompany="";
									}
								} else {
										data.iMoney="總銷:"+T30+" /$:"+M30;
									if (mMode!=KeySet.SearchMode.BATCH){
											data.iCompany="本銷:"+IT30+" /$"+IM30;
									}else {
										data.iCompany="";
									}
								}
				 				StkT=TT10-TT30;  //總存貨量
				 				StkM=TT30-TS30; //總存貨金額
				 				Profit=TM30-TM10; //總毛利
				 				if (TM30>0)	{Profits=Math.round(Profit*100/TM30);} //總毛利率
				 				else {Profits=0;}
								if (PSWD==0) {
									data.iImpo="總進:"+T10+" /$:"+M10+" 總存:"+(T10-T30);
								}else {
									data.iImpo="總進:"+T10+" 總存:"+(T10-T30);
								}
				 				if (mAdapter.mList.size()>0) {
				 					int fnd=0;
				 					for (int sort=0;sort<mAdapter.mList.size();sort++){
				 						RepData	dataS = (RepData)mAdapter.mList.get(sort) ;
				 					 
				 					 if (data.iSort>dataS.iSort) {
				 						mAdapter.mList.add(sort,data);
				 						fnd=1;
				 						break;
				 					 }
				 					}
				 					if (fnd==0) {
				 						mAdapter.mList.add(data);	
				 					}
				 				} else {  //第一筆沒得比,無條件寫入
				 				mAdapter.mList.add(data);
				 				}

						}
						mAdapter.notifyDataSetChanged();
						
		 				((TextView)findViewById(R.id.text_tot)).setText("T:"+StkT); 				
		 				((TextView)findViewById(R.id.text_t10)).setText("T:"+TT10); 				
		 				((TextView)findViewById(R.id.text_t30)).setText("T:"+TT30);
		 				if (PSWD==0){ 				
			 				((TextView)findViewById(R.id.text_mtot)).setText("$:"+StkM);
			 				((TextView)findViewById(R.id.text_r10)).setText("$:"+(TM30-TM10));
			 				((TextView)findViewById(R.id.text_m10)).setText("$:"+TM10);
			 				((TextView)findViewById(R.id.text_m30)).setText("$:"+TM30);
			 				((TextView)findViewById(R.id.text_r30)).setText("$:"+Profit);
			 				((TextView)findViewById(R.id.text_rp0)).setText("%:"+Profits);
		 				}else {
			 				((TextView)findViewById(R.id.text_mtot)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_r10)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_m10)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_m30)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_r30)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_rp0)).setText("xxxxxx");
		 				}
							
						
				}
			}
		}
	}
	};
	
	private void selectCountry(){
		Intent intent = new Intent();
		intent.setClass(QRep_01.this, CodeList.class);
		intent.putExtra("code_mode", CodeMode.COUNTRY);
		intent.putExtra("edit_mode", 1);
		QRep_01.this.startActivityForResult(intent, COUNTRY_CODE);
	}


	
	
	Handler mHandlerQDR_13 = new Handler()
	{
		@Override
		public  void handleMessage(Message msg)
		{
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
				if (Hresult != null ){
					if (Hresult.indexOf("SSSS\r\n")>2){

						if (mAdapter.mList != null) {
							mAdapter.mList.clear();
						}
						
						//Hresult=	Hresult.substring(Hresult.indexOf("rep01;")+6);
						
						Log.i("DOWNLOAD_13",Hresult );
						
						String LineH [] = Hresult.split("S\r\n");
						
						for (int xx=1;xx<LineH.length;xx++){
							String Lineshh[] =LineH[xx].split(";");

							RepData data = new RepData();
							
							int IT30=Utilis.toInt(Lineshh[2]); //本銷量
							int IM30=Utilis.toInt(Lineshh[3]); //本銷額
							int IS30=Utilis.toInt(Lineshh[4]);  //本銷成本

							if (Lineshh[8]!=null && Lineshh[8].length()>10 && Lineshh[8].indexOf("20123")>0){
								data.iPic=Lineshh[8].replace(Lineshh[8].substring(0,Lineshh[8].indexOf("20123/")), myPath);  //圖片
							}else data.iPic=defPic;
							
							data.iFormdate=Lineshh[0]; //主貨號 做為KEY 不顯示
							data.iGoods=Lineshh[0]; //主貨號
							data.iName=Lineshh[1]; //品名
							data.iCountry=Lineshh[5]; //COLORS
							data.iNumber=Lineshh[6]; //SIZES
							data.iUnit2=Lineshh[7]; //COLORSNO
							
							T30=0; M30=0;S30=0;T10=0;M10=0;
							
								data.iSort=M30;
								data.iMoney="";
								data.iCompany="本訂:"+IT30;
								data.iImpo="";
				 				mAdapter.mList.add(data);
						}
						mAdapter.notifyDataSetChanged();
						
		 				((TextView)findViewById(R.id.text_tot)).setText("T:"+StkT); 				
		 				((TextView)findViewById(R.id.text_t10)).setText("T:"+TT10); 				
		 				((TextView)findViewById(R.id.text_t30)).setText("T:"+TT30);
		 				if (PSWD==0){ 				
			 				((TextView)findViewById(R.id.text_mtot)).setText("$:"+StkM);
			 				((TextView)findViewById(R.id.text_r10)).setText("$:"+(TM30-TM10));
			 				((TextView)findViewById(R.id.text_m10)).setText("$:"+TM10);
			 				((TextView)findViewById(R.id.text_m30)).setText("$:"+TM30);
			 				((TextView)findViewById(R.id.text_r30)).setText("$:"+Profit);
			 				((TextView)findViewById(R.id.text_rp0)).setText("%:"+Profits);
		 				}else {
			 				((TextView)findViewById(R.id.text_mtot)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_r10)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_m10)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_m30)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_r30)).setText("xxxxxx");
			 				((TextView)findViewById(R.id.text_rp0)).setText("xxxxxx");
		 				}
							
						
				}
			}
		}
	}
	};
	

Handler mHandlerQDR_30 = new Handler()
{
	@Override
	public  void handleMessage(Message msg)
	{
	String Hresult=null;
	switch (msg.what)
	{
	// 顯示網路上抓取的資料
	case REFRESH_DATA:
	if (msg.obj instanceof String) 
		Hresult = (String) msg.obj;
	if (Hresult != null ){
		Log.i("DOWNLOAD_REP_01_30", Hresult);
		if (Hresult.indexOf("SSSS\r\n")>2){
			String LineH [] = Hresult.split("S\r\n");
			
		 if (LineH.length>1){
	        SQLiteDatabase db = Utilis.getDB(QRep_01.this);
	    	int mkqrGoods=Utilis.toInt(dataSend[3]);//0品名1備註
	    	
	    	albun_list = new ArrayList<HashMap<String, Object>>();
	    	
			StringBuffer isList = new StringBuffer();
			StringBuffer isList1 = new StringBuffer();
			StringBuffer isList2 = new StringBuffer();

			String Linesh1[] =LineH[1].split(";");
			String GoodsNOO=Linesh1[0];
			String GoodsN=Linesh1[0];
			String SupplyM="";
			String GoodsNo="";
			String GoodsM="";
			String GoodsPic="";
			int Toot=0;				
			int iP0=0;
			int ig=0;
			
			for (int xx=1;xx<LineH.length;xx++){
				//每一筆只要遇到貨號不一樣,就是要寫入
				String Lineshh[] =LineH[xx].split(";");
				GoodsN=Lineshh[0];
				
				if (!GoodsN.equalsIgnoreCase(GoodsNOO) || ig==9){
					HashMap<String, Object> mapn = new HashMap<String, Object>();
					
					Cursor csQdetail=db.rawQuery("select SOURCENO,GOODSNAME,SUPPLY,PIC,PS,P0 from QDETAIL where GOODSNO='"+GoodsNOO+"' order by MID DESC LIMIT 1", null);
					if (csQdetail.getCount()>0){
						csQdetail.moveToFirst();
						iP0=csQdetail.getInt(csQdetail.getColumnIndex("P0"));
						GoodsNo=GoodsNOO+"/"+csQdetail.getString(csQdetail.getColumnIndex("SOURCENO"));
						if (mkqrGoods==0)
							GoodsM=csQdetail.getString(csQdetail.getColumnIndex("GOODSNAME"));
						else
							GoodsM=csQdetail.getString(csQdetail.getColumnIndex("PS"));
						
						GoodsPic=csQdetail.getString(csQdetail.getColumnIndex("PIC"));
						SupplyM=csQdetail.getString(csQdetail.getColumnIndex("SUPPLY"));
					}else{
						iP0=99999;
						GoodsNo=GoodsNOO;
						GoodsM=GoodsNOO;
						GoodsPic=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/04.jpg";
					}
					if (SupplyM.length()>0){
						Cursor csf=db.rawQuery("select FACTNAME,MOBIL from qfact where FACTNO='"+SupplyM+"'", null);
							if (csf.getCount()>0){
								csf.moveToFirst();
								SupplyM=SupplyM+"/"+csf.getString(1);
							}
						csf.close();
					}
						csQdetail.close();
						
						mapn.put("eno",""+GoodsNo);
						mapn.put("ename",""+GoodsM);
						mapn.put("epics",""+GoodsPic);
						mapn.put("eprice",iP0+" x "+Toot+" 件");
						mapn.put("supply",""+SupplyM);
						mapn.put("ecolor",""+isList1.toString());
						mapn.put("esize",""+isList.toString());
						mapn.put("ebars",""+isList2.toString());				
						albun_list.add(mapn);
					//歸零
	                    isList.delete(0, isList.toString().length());
	                    isList1.delete(0, isList1.toString().length());
	                    isList2.delete(0, isList2.toString().length());
	                    
	                    Toot=0;
	                    iP0=0;
						ig=0;
				    	GoodsNOO=GoodsN;
					
				}
				
				SupplyM=Lineshh[1];
					if (ig%3==0)
						isList.append(Lineshh[3]+Lineshh[4]+"("+Lineshh[5]+")");
					else if (ig%3==1)
						isList1.append(Lineshh[3]+Lineshh[4]+"("+Lineshh[5]+")");
					else
						isList2.append(Lineshh[3]+Lineshh[4]+"("+Lineshh[5]+")");
					
					Toot=Toot+Utilis.toInt(Lineshh[5]);
					ig=ig+1;
			}
			
			if (ig%9!=0){
				Cursor csQdetail=db.rawQuery("select SOURCENO,GOODSNAME,SUPPLY,PIC,PS,P0 from QDETAIL where GOODSNO='"+GoodsNOO+"' order by MID DESC LIMIT 1", null);
				if (csQdetail.getCount()>0){
					csQdetail.moveToFirst();
					iP0=csQdetail.getInt(csQdetail.getColumnIndex("P0"));
					GoodsNo=GoodsNOO+"/"+csQdetail.getString(csQdetail.getColumnIndex("SOURCENO"));
					if (mkqrGoods==0)
						GoodsM=csQdetail.getString(csQdetail.getColumnIndex("GOODSNAME"));
					else
						GoodsM=csQdetail.getString(csQdetail.getColumnIndex("PS"));
					
					GoodsPic=csQdetail.getString(csQdetail.getColumnIndex("PIC"));
					SupplyM=csQdetail.getString(csQdetail.getColumnIndex("SUPPLY"));
				}else{
					iP0=99999;
					GoodsNo=GoodsNOO;
					GoodsM=GoodsNOO;
					GoodsPic=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/04.jpg";
					SupplyM="";
				}
				csQdetail.close();
				
				HashMap<String, Object> maps = new HashMap<String, Object>();
				maps.put("eno",""+GoodsNo);
				maps.put("ename",""+GoodsM);
				maps.put("epics",""+GoodsPic);
				maps.put("eprice",iP0+" x "+Toot+" 件");
				maps.put("supply",""+SupplyM);
				maps.put("ecolor",""+isList1.toString());
				maps.put("esize",""+isList.toString());
				maps.put("ebars",""+isList2.toString());				
				albun_list.add(maps);
			
			}
			
			db.close();
			if (albun_list.size()>0){
				//應該進行makeMkqr的程序
		  		FileOutputStream istream = null;
		  		ObjectOutputStream os = null;
		  		try {
		  			istream = new FileOutputStream(myAlbunList);
		  			os = new ObjectOutputStream(istream);
		              if (albun_list !=null && albun_list.size()>0)
		              { os.writeObject(albun_list); }
		      			os.close();
		      			istream.close();
							Bundle bundle = new Bundle();
		        			Intent intent = new Intent();
		        			bundle = new Bundle();
							bundle.putString("Mkqrs",myAlbunList+",ZZZ,"+isSupply+",123,"+mStartDay+","+mEndDay+","+orderMode);
		     			intent.setClass(QRep_01.this, Mkqr.class);
		     			intent.putExtras(bundle);
		     			startActivity(intent);
		  		} catch (Exception e) {

		  		}
			}
		 }else{
			Toast.makeText(QRep_01.this, "查不到相符的資料 !!", Toast.LENGTH_SHORT).show();
		 }
		}
		}
	}
	}
};
		

/**
 *  Menu 使用
 */

private static final int MENU_NORMAL = Menu.FIRST;
private static final int MENU_EACH = Menu.FIRST+1;
@Override
public boolean onCreateOptionsMenu(Menu menu){
	super.onCreateOptionsMenu(menu);
	menu.add(0, MENU_NORMAL, 0, "總倉(含門市)");
	menu.add(0, MENU_EACH, 1, "總倉(不含門市)");
	return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {			
	super.onOptionsItemSelected(item);
	switch (item.getItemId()) {
		case MENU_NORMAL:
		{
			SQLADD="";
			break;
		}
		case MENU_EACH:
		{
			SQLADD=" and DEPTNO='"+deptStr[0]+"' ";
			break;
		}
	}
	setCondition();
	getGroupData(QRep_01.this,mStartDay, mEndDay, null, null);				

	return true;
}


	
	
private class ReportAdapter extends BaseAdapter{
		
		private LayoutInflater mInflater;
		
		public LinkedList<RepData> mList = new LinkedList<RepData>();
		
		public ReportAdapter (Context context ){
		      mInflater = LayoutInflater.from(context);
		}

		public RepData getData(int Position){
			return mList.get(Position);
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

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

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_posh, null);
				holder = new ViewHolder();
				holder.imageItem = (ImageView)convertView.findViewById(R.id.img_ppic);
				holder.textGoodsNo = (TextView) convertView.findViewById(R.id.text_pgoodsno);
				holder.textImpo = (TextView) convertView.findViewById(R.id.text_pimpo);
				holder.textName = (TextView) convertView.findViewById(R.id.text_pname);
				holder.textMoney = (TextView) convertView.findViewById(R.id.text_pmoney);
				holder.textNumber = (TextView) convertView.findViewById(R.id.text_pnumber);
				holder.textCountry = (TextView) convertView.findViewById(R.id.text_pcountry);
				holder.textCompany = (TextView) convertView.findViewById(R.id.text_pcompany);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
			RepData data = mList.get(position);
			holder.imageItem.setImageBitmap(Utilis.getLimitBitmap(data.iPic, 80, 80));
			
			holder.textGoodsNo.setText(data.iGoods);
			
			holder.textName.setText(data.iName);
			holder.textCountry.setText(data.iCountry);
			holder.textCompany.setText(data.iCompany);
			holder.textMoney.setText(data.iMoney);
			holder.textNumber.setText(data.iNumber);
			holder.textImpo.setText(data.iImpo);			
			return convertView;
		}

		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textGoodsNo;
			TextView textImpo;
			TextView textName;
			TextView textMoney;
			TextView textCountry;
			TextView textNumber;
			TextView textCompany;
			
		}

	}
    
    
}
