package com.cwbuyer.lib;

import java.io.File;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

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 com.pwbuyer.main.R;
import com.cwbuyer.adapter.TableAdapter.TableCell;
import com.cwbuyer.adapter.TableAdapter.TableRow;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.ItemData;
import com.cwbuyer.main.AIncome.ChoiceMode;
import com.cwbuyer.main.APos.PItemKind;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

@SuppressLint({ "UseSparseArrays", "DefaultLocale", "HandlerLeak" })
@SuppressWarnings("deprecation")
public class GalleryViewS extends Activity {

	private Gallery mGallery01;
	private ImageButton mImgBtnSearch;
	private ImageButton mImgBtnRobk;
	private Button mBtnCor1;
	private Button mBtnCor2;
	private Button mBtnCor3;
	private Button mBtnCor4;
	private Button mBtnCor5;
	private Button mBtnCor6;
	private Button mBtnCor7;
	private Button mBtnCor8;
	private Button mBtnCor9;
	private Button mBtnCor10;
	private Button mBtnCor11;
	private Button mBtnCor12;
	private Button mBtnCor13;
	private Button mBtnCor14;
	private Button mBtnCor15;
	private Button mBtnCor16;
	private Button mBtnCor17;
	private Button mBtnCor18;
	private Button mBtnCor19;
	private Button mBtnCor20;
	private EditText mEdSearch;
	private TextView mTextView01;
	private TextView mTextView07;
	private TextView mTextView08;
	private TextView mTextView20;
	private TextView mTextView21;
	private TextView mTextView22;
  	private LinearLayout lTableView = null;
	private LinearLayout mLayoutRoot = null;
	
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + "CWBuyer"+ File.separator + "PARA" + File.separator + "04.jpg";
	private String uriAPI=null;
	public ItemData iData;	

	private ArrayList<String> mArrayColorNumber = new ArrayList<String>();
	private ArrayList<String> mArrayColorName = new ArrayList<String>();
	
	private LinkedList<String> mSizeLink = new LinkedList<String>();
	private LinkedList<String> mSizeLink1 = new LinkedList<String>();	
	
	@SuppressLint("UseSparseArrays")
	private HashMap<Integer,Integer> mCountRow = new HashMap<Integer,Integer>(); // 列資料
	private HashMap<Integer,String> mCountCell = new HashMap<Integer,String>();  // 行資料

	private int nState=0;
	private int nPart=0;
	private int records = 0;
	private int positions = 0;
	private String mGoods="";
	private int PSWD=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT",5));

	private int deptN=1;
	private String [] DepNo;
	private String [] DepNa;
	private int [][] xMode={{0,1,2},{2,0,1},{0,2,1},{1,2,0}};
	private int mMode=0;//0原型1存進銷2進存銷3銷存進
	private String[] modeName={"進-銷-存","存-進-銷","進-存-銷","銷-進-存"};
	private String[] modeName2={"NO","顏色","尺寸"};
	private String mDept=Utilis.getIni(this,"SYS","DEPT",1);
	private String Lines [];//作為運算位移時的基本資料
	private int LocX = 0;//左右移動起始點 +-2
	private int LocY = 0;//上下移動起始點+-12
	private int Otot[][];  //本批號的訂量
	private int Otott[][];	//全部訂量
	private int ColNoSizN=0;
	private String [][] ColNoSiz;
	private String[] menu_X={"追蹤","切換庫存分析","網頁附圖編輯輸出","預購留貨清單","放大","返回"};
	private int btnSet []=new int [21];	
	private String btnNM []=new String [21];
	private String[] numberLevel1;
	private String[] numberLevel2;
	private String aInput=null;
	private String batch=null;
	private String[] Amid; //商品ID MID	
	private String[] Apicstr; //圖檔名稱
	private String[] GoodsNo; //商品編號
	private String[] Abatch;
	private String mSplitSizes; //所有尺寸 L，XL
	private String mSplitColorNo; //顏色代號 01，02
	private String mSplitColor; //顏色 黑色，白色
	private String mCountList; //所有件數表 5,5，3,3
	private int Wheight;
	private int Wwidth;
	private int tableHeight=30;
	private int tabless=10;
	private int mChoiceMode = ChoiceMode.ALL;
	
	//For Cloud
	public ProgressDialog myDialog = null;
	protected static final int REFRESH_DATA = 0x00000001;
	private int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Wwidth = dm.widthPixels;
        Wheight = dm.heightPixels;
		
		setContentView(R.layout.galleryps);
		mGallery01 = (Gallery) findViewById(R.id.myGallery1s);
		mImgBtnSearch = (ImageButton) findViewById(R.id.imageButton15s);		
		mImgBtnRobk = (ImageButton) findViewById(R.id.imageButton16s);
		mEdSearch =(EditText)findViewById(R.id.edSearchs);
		
		mGallery01.getLayoutParams().height=222;
		tabless=10;
		tableHeight=(int)(Wheight/26);
		if (Wwidth<=800) tabless=(int)(Wwidth/100)+2; else tabless=(int)(Wwidth/140)+1;

    	mTextView01 = (TextView) findViewById(R.id.textViewg1s);
		mTextView07 = (TextView) findViewById(R.id.textViewg7s);
		mTextView08 = (TextView) findViewById(R.id.textViewg8s);
    	mTextView20 = (TextView) findViewById(R.id.textViewg20s);
    	mTextView21 = (TextView) findViewById(R.id.textViewg21s);
    	mTextView22 = (TextView) findViewById(R.id.textViewg22s);
		
		mBtnCor1=(Button) findViewById(R.id.btn_col_top1);
		mBtnCor2=(Button) findViewById(R.id.btn_col_top2);
		mBtnCor3=(Button) findViewById(R.id.btn_col_top3);
		mBtnCor4=(Button) findViewById(R.id.btn_col_top4);
		mBtnCor5=(Button) findViewById(R.id.btn_col_top5);
		mBtnCor6=(Button) findViewById(R.id.btn_col_top6);
		mBtnCor7=(Button) findViewById(R.id.btn_col_top7);
		mBtnCor8=(Button) findViewById(R.id.btn_col_top8);
		mBtnCor9=(Button) findViewById(R.id.btn_col_top9);
		mBtnCor10=(Button) findViewById(R.id.btn_col_top10);
		mBtnCor11=(Button) findViewById(R.id.btn_col_top11);
		mBtnCor12=(Button) findViewById(R.id.btn_col_top12);
		mBtnCor13=(Button) findViewById(R.id.btn_col_top13);
		mBtnCor14=(Button) findViewById(R.id.btn_col_top14);
		mBtnCor15=(Button) findViewById(R.id.btn_col_top15);
		mBtnCor16=(Button) findViewById(R.id.btn_col_top16);
		mBtnCor17=(Button) findViewById(R.id.btn_col_top17);
		mBtnCor18=(Button) findViewById(R.id.btn_col_top18);
		mBtnCor19=(Button) findViewById(R.id.btn_col_top19);
		mBtnCor20=(Button) findViewById(R.id.btn_col_top20);

		((Button) findViewById(R.id.btn_col_all)).setOnClickListener(new MainClick());
		mBtnCor1.setOnClickListener(new MainClick());//存進銷
		mBtnCor2.setOnClickListener(new MainClick());//進存銷
		mBtnCor3.setOnClickListener(new MainClick());//銷存進
		
		mBtnCor4.setOnClickListener(new MainClick());
		mBtnCor5.setOnClickListener(new MainClick());
		mBtnCor6.setOnClickListener(new MainClick());
		mBtnCor7.setOnClickListener(new MainClick());
		mBtnCor8.setOnClickListener(new MainClick());
		mBtnCor9.setOnClickListener(new MainClick());
		mBtnCor10.setOnClickListener(new MainClick());
		mBtnCor11.setOnClickListener(new MainClick());
		mBtnCor12.setOnClickListener(new MainClick());
		mBtnCor13.setOnClickListener(new MainClick());
		mBtnCor14.setOnClickListener(new MainClick());
		mBtnCor15.setOnClickListener(new MainClick());
		mBtnCor16.setOnClickListener(new MainClick());
		mBtnCor17.setOnClickListener(new MainClick());
		mBtnCor18.setOnClickListener(new MainClick());
		mBtnCor19.setOnClickListener(new MainClick());
		mBtnCor20.setOnClickListener(new MainClick());
		
        lTableView = (LinearLayout)findViewById(R.id.tableviews);
        lTableView.setVisibility(View.VISIBLE);	  		
    	mLayoutRoot = (LinearLayout)findViewById(R.id.root);
    	Bundle bundle = this.getIntent().getExtras();
		String fromW=bundle.getString("GalleryChild");
		String[] arrayW = fromW.split(";");
		batch=arrayW[0];
        int locates = Utilis.valuesInt(arrayW[1]);
        nState=Utilis.valuesInt(arrayW[2]); //0依採購商品原始設計 1多門市庫存分析表(只在總倉啟用)  (沒用保留 2在各門市啟用)
        if (!Utilis.getIni(this,"SYS","DEPT",1).equalsIgnoreCase(Utilis.getIni(this,"SYS","DEPT",6))) nPart=1;  //門市版
        
		//getTypeData(this);
		//getCountryData(this);
        
        SQLiteDatabase db = Utilis.getDB(this);
		Cursor cs1;
		StringBuffer mySqlBuf = new StringBuffer();
	if (locates==1){//來自採購單	
		mySqlBuf.append("select MID,PIC,GOODSNO,BATCH from qdetail");
		mySqlBuf.append(" where BATCH ='"+batch+"'");
		mySqlBuf.append(" order by MID desc");
		cs1 = db.rawQuery(mySqlBuf.toString(), null);

				if (cs1.getCount() > 0) {
					updateListView(cs1);
					DisplayPart0(0);
					if (cs1.getCount() >= 300) {
						Toast.makeText(GalleryViewS.this,"超過300筆的部分無法顯示!請下次縮小範圍!" , Toast.LENGTH_SHORT).show();							
					}
				}
	}else {//交易明細搜尋貨號
		//多門市庫存分析表 @@@還要分總倉 OR 門市倉
		//String [] serch0=batch.split(",");
		mySqlBuf.append("select MID,PIC,GOODSNO,BATCH from qdetail");
		mySqlBuf.append(" where GOODSNO in ("+batch+")");
		mySqlBuf.append(" order by MID desc");
		
		cs1 = db.rawQuery(mySqlBuf.toString(),null);

			if (cs1.getCount() > 0) {
				updateListView(cs1);
				DisplayPart0(0);
				if (cs1.getCount() >= 300) {
					Toast.makeText(GalleryViewS.this,"超過300筆的部分無法顯示!請下次縮小範圍!" , Toast.LENGTH_SHORT).show();							
				}
			}
	}			
	cs1.close();
	db.close();
	

		mGallery01.setOnItemClickListener(new Gallery.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long ids) {
				// TODO Auto-generated method stub
				positions = position;
				if (nState==0){
					Display(positions);
				}else {
					DisplayPart0(positions);
				}
			}
		});

//menu_X={"追蹤","切換庫存分析","網頁附圖編輯輸出","預購留貨清單","返回" };
		mGallery01.setOnItemLongClickListener(new OnItemLongClickListener(){
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				Utilis.runVibrate(GalleryViewS.this);
				positions = position;
				DialogUtilis.showDialog(GalleryViewS.this, "請選擇以下功能", -1,
				menu_X, new IDialog() {
				@Override
				public void onDialogFinish(int pos, String choice) {
					
					Intent intent = new Intent();
				switch (pos) {
					case 0: //商品追蹤
					
					mGoods=GoodsNo[positions];
					intent.putExtra("QHis_kind", PItemKind.TR30);
					intent.putExtra("QHis_mode", 1);
					intent.putExtra("QHis_User","" );
					intent.putExtra("QHis_Goods",mGoods );
					intent.setClass(GalleryViewS.this, QHis.class);
					startActivity(intent);
						
					break;	
					
					case 1: //切換庫存分析
					
					if (nState==0){
						nState=1;
						DisplayPart0(positions);
					}else {
						nState=0;
						Display(positions);
					}
					break;	
					
					case 2: //網頁附圖GalleryViewWeb
					
					if (nState==0){
						Bundle bundle = new Bundle();
						bundle = new Bundle();
						bundle.putString("GalleryChild",GoodsNo[positions]+","+0+",0");
						intent.setClass(GalleryViewS.this, GalleryViewWeb.class);
						intent.putExtras(bundle);
						startActivity(intent);
					}
					break;
					
					case 3:
					{
	    				intent.putExtra("GalleryUser","");
	    				intent.putExtra("GalleryGoods",GoodsNo[positions]);
						intent.putExtra("GalleryDept",Utilis.getIni(GalleryViewS.this,"SYS","DEPT",1));    					    				
	    				intent.putExtra("GalleryASK"," and GOODSNO='"+GoodsNo[positions]+"' ");
	    				intent.putExtra("FormNo","");
	    				if (nPart==0)
	    				intent.putExtra("GalleryQKIND","30");
	    				else
	    				intent.putExtra("GalleryQKIND","31");
	    				
	    				intent.putExtra("GalleryMode",1);//0mUser 1mGoods 2KeepaToSale
						intent.setClass(GalleryViewS.this, GalleryViewO.class);
						startActivity(intent);
					break;
					}
					
					case 4:
						try{
							intent = new Intent();
							intent.setClass(GalleryViewS.this,Show_imagebig.class);
							intent.putExtra("image", Apicstr[positions]);
							startActivity(intent);
						}catch(Exception e){
							e.printStackTrace();
						}finally{
						}
						
					break;
				}
			}
			});

				return true;
			}
		});
		
//查詢 優先順序為 1.貨號 2.品名 3.類別 limit 300為最大值否則請縮小範圍		
		mImgBtnSearch.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mEdSearch!=null && mEdSearch.length()>0){
				aInput=mEdSearch.getText().toString().toUpperCase();
				searched(aInput);
				}
			}
		});
		
		mEdSearch.setOnKeyListener(new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
			//監視鍵盤按鍵
			if(event.getAction()== KeyEvent.ACTION_DOWN){ 
					if  (keyCode==KeyEvent.KEYCODE_ENTER && mEdSearch.getText().toString().length()>0){
						if (mEdSearch!=null && mEdSearch.length()>0){
						aInput=mEdSearch.getText().toString().toUpperCase();
						searched(aInput);
						return true;
						}
					}
			}
			return false;
			}
			
		});

		
//切換庫存表
		mImgBtnRobk.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (nState==0){
					nState=1;
					DisplayPart0(positions);
				}else {
					nState=0;
					Display(positions);
				}
			}
		});
	}		
	
	private List<String> ChkPic() {
		/* 設定目前所在路徑 */
		List<String> it = new ArrayList<String>();
		/* 將所有檔案加入ArrayList中 */
		for (int i = 0; i < records; i++) {
			if (getImageFile(Apicstr[i]))
				it.add(Apicstr[i]);
			else {it.add(filepath);}
		}
		return it;
	}

	private boolean getImageFile(String fName) {
		boolean re;

		/* 取得副檔名 */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		/* 依附檔名的類型決定MimeType */
		if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			re = true;
		} else {
			re = false;
		}
		return re;
	}

	private void searched(String mEdS){
		//將鍵盤收起來
  		 InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
         m.hideSoftInputFromWindow(mEdSearch.getWindowToken(), 0);
         
         if (mEdS.substring(0, 1).equalsIgnoreCase("*")) mEdS=mEdS.substring(1);         
			
         SQLiteDatabase db = Utilis.getDB(this);
 		
        	Cursor cs = DBUtil.GVSQL(this,db,aInput,0,1,nState);
	  	
			if(cs.getCount()<=0){
				Toast.makeText(GalleryViewS.this,"查無此商品!" , Toast.LENGTH_SHORT).show();							
			}else {
				if(nState==0){
				updateListView(cs);
				Display(0);
				}else{
		  			updateListView(cs);
		  			DisplayPart0(0);
				}	
			}
			cs.close();
			db.close();	
	}
	
	/* 改寫BaseAdapter自訂一ImageAdapter class */
	public class ImageAdapter extends BaseAdapter {
		/* 宣告變數 */
		int mGalleryItemBackground;
		private Context mContext;
		private List<String> lis;

		/* ImageAdapter的建構子 */
		public ImageAdapter(Context c, List<String> li) {
			mContext = c;
			lis = li;
			/*
			 * 使用在res/values/attrs.xml中的<declare-styleable>定義 的Gallery屬性.
			 */
			TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
			/* 取得Gallery屬性的Index id */
			mGalleryItemBackground = a.getResourceId(
					R.styleable.Gallery_android_galleryItemBackground, 0);
			/* 讓物件的styleable屬性能夠反覆使用 */
			a.recycle();
		}

		/* 一定要覆寫的方法getCount,傳回圖片數目 */
		public int getCount() {
			return lis.size();
		}

		/* 一定要覆寫的方法getItem,傳回position */
		public Object getItem(int position) {
			return position;
		}

		/* 一定要覆寫的方法getItemId,傳回position */
		public long getItemId(int position) {
			return position;
		}

		/* 一定要覆寫的方法getView,傳回一View物件 */
		public View getView(int position, View convertView, ViewGroup parent) {
			/* 產生ImageView物件 */
			ImageView i = new ImageView(mContext);
			/* 設定圖片給imageView物件 */
//			Bitmap bm = BitmapFactory.decodeFile(lis.get(position).toString());
				Bitmap bm = Utilis.getLimitBitmap(lis.get(position).toString(), 80, 80);
				i.setImageBitmap(bm);

			/* 重新設定圖片的寬高 */
			i.setScaleType(ImageView.ScaleType.FIT_XY);
			/* 重新設定Layout的寬高 */
				i.setLayoutParams(new Gallery.LayoutParams(180, 220));				
			/* 設定Gallery背景圖 */
			i.setBackgroundResource(mGalleryItemBackground);
			/* 傳回imageView物件 */
			return i;
		}
	}
	
	
	private void updateListView(Cursor cs) {

		int record = 0;
		if (cs.getCount() > 0) {
			Amid = new String[cs.getCount()];
			Apicstr = new String[cs.getCount()];
			GoodsNo = new String[cs.getCount()];
			Abatch = new String[cs.getCount()];
			
//			cs.moveToFirst();
			while (cs.moveToNext()) {
				if (nState==0){
					Amid[record] = cs.getString(cs.getColumnIndex("MID"));
				}else {
					Amid[record] = cs.getString(cs.getColumnIndex("BATCH"));
				}
				Apicstr[record] = cs.getString(cs.getColumnIndex("PIC"));				
				GoodsNo[record] = cs.getString(cs.getColumnIndex("GOODSNO"));
				Abatch[record] = cs.getString(cs.getColumnIndex("BATCH"));
				record++;
			}

		}

		records = record;

		if (records>0) {		

		/* 新增一ImageAdapter並設定給Gallery物件 */
		mGallery01.setAdapter(new ImageAdapter(this, ChkPic()));		
		} else 
		{finish();}
		// if (dbHelper != null && dbHelper.getReadableDatabase().isOpen()) {
		// dbHelper.close(); }

	}
	
private void Display(int positionid) {
	int position = positionid;
	Otot=new int[30][30];  //預設30色 30尺寸
	for (int i=0;i<30;i++) for (int j=0;j<30;j++) Otot[i][j]=0;
    SQLiteDatabase db = Utilis.getDB(this);		
	Cursor cs = null;
	StringBuffer mySqlBuf = new StringBuffer();
	mGoods=GoodsNo[position];
	mySqlBuf.append("select GOODSNO,GOODSNAME,GOODSTYPE,COUNTRY,")
	.append("BATCH,SUPPLY,SOURCENO,P0,P1,P2,P3,P4,P5,COLORNO,COLOR,SIZE,INLIST,PS")
	.append(" from qdetail where GOODSNO='" + mGoods+"' and BATCH='" + Abatch[position]+"'");
	cs = db.rawQuery(mySqlBuf.toString(), null);
	if (cs.getCount()>0){
		cs.moveToFirst();
		for (int g=0;g<cs.getCount();g++) { 
				if (cs.isFirst()){
					mTextView01.setText("貨號."+cs.getString(cs.getColumnIndex("GOODSNO"))+"/"+cs.getString(cs.getColumnIndex("GOODSNAME")));
					mTextView07.setText("批號."+cs.getString(cs.getColumnIndex("BATCH"))+"/來源."+cs.getString(cs.getColumnIndex("SOURCENO"))+"PS."+cs.getString(cs.getColumnIndex("PS")));
					String ShowPr="中:"+cs.getString(cs.getColumnIndex("P2"))+"/批:"+cs.getString(cs.getColumnIndex("P3"))+"/網:"+cs.getString(cs.getColumnIndex("P4"))+"/零"+cs.getString(cs.getColumnIndex("P5"));
					if (PSWD!=1)ShowPr="("+cs.getString(cs.getColumnIndex("P0"))+cs.getString(cs.getColumnIndex("P1"))+")/"+ShowPr;
					mTextView08.setText(ShowPr);
				
		//新的一段處理顏色尺寸表-開始			
		//取得4組資料 色號 色名 尺寸表 數量表			
				}
				mSplitColor=cs.getString(cs.getColumnIndex("COLOR"));
//					String [] ColNa=mSplitColor.split("，");
				mSplitColorNo=cs.getString(cs.getColumnIndex("COLORNO"));
				String [] ColNo=mSplitColorNo.split("，");
				mSplitSizes=cs.getString(cs.getColumnIndex("SIZE"));
				String [] SizNo=mSplitSizes.split(",");
				mCountList=cs.getString(cs.getColumnIndex("INLIST"));

		  		try{ //算出本次的定單量
		        	for(int nRow = 0; nRow < ColNo.length; nRow++){
		        		numberLevel1=mCountList.split("，");
		    			for(int i = 0 ; i < SizNo.length; i++){
		    				numberLevel2=numberLevel1[nRow].split(",");
		    					Otot[nRow][i]=Utilis.toInt(numberLevel2[i]);
		    				}
		    			}
	    		}catch(Exception e){
	    			e.printStackTrace();
	    		}
		  		cs.moveToNext();
		}
		
		makeTable(mGoods,mSplitColorNo.toString(),mSplitColor.toString(),mSplitSizes.toString());			

	} //>0
	cs.close();
	db.close();
}
	
private void DisplayPart0(int positionid) {
		int position = positionid;

        SQLiteDatabase db = Utilis.getDB(this);		
		Cursor cs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		mGoods=GoodsNo[position];
		
		mySqlBuf.append("select GOODSNO,GOODSNAME,GOODSTYPE,COUNTRY,")
		.append("BATCH,SUPPLY,SOURCENO,P0,P1,P2,P3,P4,P5,COLORNO,COLOR,SIZE,INLIST,PS")
		.append(" from qdetail where GOODSNO='" + mGoods+"' and BATCH='" + Abatch[position]+"'");
		
		cs = db.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){
			cs.moveToFirst();
			mTextView01.setText("貨號."+cs.getString(cs.getColumnIndex("GOODSNO"))+"/"+cs.getString(cs.getColumnIndex("GOODSNAME")));
			mTextView07.setText("批號."+cs.getString(cs.getColumnIndex("BATCH"))+"/來源."+cs.getString(cs.getColumnIndex("SOURCENO"))+"/PS"+cs.getString(cs.getColumnIndex("PS")));
				String ShowPr="中:"+cs.getString(cs.getColumnIndex("P2"))+"/批:"+cs.getString(cs.getColumnIndex("P3"))+"/網:"+cs.getString(cs.getColumnIndex("P4"))+"/零"+cs.getString(cs.getColumnIndex("P5"));
				if (PSWD!=1)ShowPr="("+cs.getString(cs.getColumnIndex("P0"))+cs.getString(cs.getColumnIndex("P1"))+")/"+ShowPr;
			mTextView08.setText(ShowPr);
			//還是要一開始建立 雲端版 依門市順序要用到
			Cursor csc=db.rawQuery("SELECT distinct CUSTNO,CUSTNAME FROM `qcust` WHERE TR='20' and CUSTNO <>'"+Utilis.getIni(this,"SYS","DEPT",6)+"' and (CUSTNO in (select distinct USER FROM `qitems` where GOODSNO ='"+mGoods+"') or CUSTNO in (select distinct DEPTNO FROM `qitems` where GOODSNO ='"+mGoods+"')) order by CUSTNO",null);
			if (csc.getCount()>0){
				deptN=csc.getCount()+1;
				DepNo=new String[deptN];
				DepNa=new String[deptN];
				csc.moveToFirst();
				for (int i=0;i<csc.getCount();i++){
					DepNo[i+1]=csc.getString(0);
					DepNa[i+1]=csc.getString(1);
					csc.moveToNext();
				}
			}else{
				deptN=1;
				DepNo=new String[deptN];
				DepNa=new String[deptN];
			}
			DepNo[0]=Utilis.getIni(this,"SYS","DEPT",6);
			DepNa[0]=Utilis.getIni(this,"SYS","DEPT",7);
			csc.close();
		}
		if (Utilis.haveInternet(this) && of_line!=0){  //雲端&&網路OK
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
			
				bfstr.append(Utilis.getIni(this, "SYS", "IMPORT", 2)).append(";");
				bfstrF.append("UID").append(";");
				bfstr.append(mGoods).append(";");
				bfstrF.append("GOODSNO").append(";");
				bfstr.append(Utilis.getIni(this, "SYS", "DEPT", 6)).append(";");
				bfstrF.append("PARTNO").append(";");  //總倉代號 名稱
				bfstr.append(Utilis.getIni(this, "SYS", "DEPT", 7));
				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
			          { 
							uriAPI="http://"+Utilis.getIni(GalleryViewS.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(GalleryViewS.this, "SYS", "IMPORT", 2)+File.separator+"qmtrio.php";
							HttpPost httpRequest = new HttpPost(uriAPI);
							// Post運作傳送變數必須用NameValuePair[]陣列儲存
							Log.i("DOWNLOAD_GO", "呼叫執行緒PHP___"+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{
			
			if (cs.getCount()>0){
				mySqlBuf.delete(0, mySqlBuf.toString().length());
				//需要轉載CLOUD_VER QMTRIO.PHP
				//總倉進貨各色尺寸件數,必然在各色尺寸俱全(畢竟為源起資料)貨品建檔
				mySqlBuf.append("select COLOR,SIZE,UNIT1,sum(UNIT10)")
				.append(" from qitems where GOODSNO='" + mGoods+"'")
				.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='" + mGoods+"' 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(Utilis.getIni(this,"SYS","DEPT",6))){
								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='" + mGoods+"' and (ISCONFIRM='Y' or ISCHECK='Y')")
		.append(" from qitems where GOODSNO='" + mGoods+"' 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='" + mGoods+"' 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();
			}
		}
//臨時
			
		}
		
		//製作一個空的STRINGGRID _是個容器
    	mLayoutRoot.removeAllViews();
		mSizeLink.clear();
		mSizeLink1.clear();		
		mCountRow.clear();	        		
		mCountCell.clear();
		
		String data0="顏色,尺寸";
		String data1="NO,門市";
		
    	mSizeLink.add("顏色"); 	//顏色
    	mSizeLink.add("尺寸"); 	//尺寸
    	mSizeLink1.add("NO"); 	//門市代號
    	mSizeLink1.add("門市"); 	//門市名稱 

    	// 設定 Title 行 //使每個顏色尺寸都有3格(進/銷/存)
    	for(int i = 0; i < ColNoSizN; i++){
    		mSizeLink1.add("進/出"); 
    		mSizeLink1.add("銷/(訂)");
    		mSizeLink1.add("實(存)");
    		data1=data1+",進/出,銷/(訂),實(存)";
    		for(int j = 0; j < 3; j++){
    		mSizeLink.add(ColNoSiz[i][j]);
    		data0=data0+","+ColNoSiz[i][j];
    		}
    	}
    	// 以下完成所有TABLE表的nCountCell裝填
    	Lines =new String [deptN+2]; 
		Lines[0]=data0;
		Lines[1]=data1;
		
    	for(int i = 2; i <= (deptN+1); i++){ //i縱向 門市的總量+上2行
    		// 設定Row會包含哪些 Key
    		for(int k = 0; k < mSizeLink.size(); k ++){ //k橫向
        			if( k == 0){ // 增門市代號
       					data0=DepNo[i- 2];
        			} else if (k==1){ //增門市名稱
       					data0=data0+","+DepNa[i- 2];
        			} else {
       					data0=data0+","+Otott[i-2][k-2]+"("+Otott[i-2][mSizeLink.size()-2+k-2]+")";
        			}
    		}
    		Lines[i]=data0;    		
    	}
    	//以上 Lines[] 陣列 等同Cloud Qmtrio.php 所帶回的資資料
		LocX=0;LocY=0;mMode=0; //預設為 全部顯示
		for (int e=0;e<=20;e++) btnSet[e]=0;
		for (int e=0;e<=20;e++) btnNM[e]="";
		String[] btnM=Lines[0].split(",");
		//第0行 台頭
		int bg=3;String btnCol=btnM[3];
		//第一顏色btnCol是為了各色,只取一
		btnNM[0]=btnM[3];
		for (int e=6;e<btnM.length;e+=3){
			if (!btnM[e].equalsIgnoreCase(btnCol)){
				bg+=1;
				btnSet[bg]=(e/3)-1;
				btnNM[bg]=btnM[e];
				btnCol=btnM[e];
			}
		}
		reCount_btn();
		resetBottom(btnNM);
		makeCountCellTalbe();
		}
	cs.close();
	db.close();
	
}

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_5_qmtrio_Report===", ""+Hresult);						
				if (Hresult.indexOf("\r\n")>2){
			    	mLayoutRoot.removeAllViews();
					mCountRow.clear();	        		
					mCountCell.clear();
					//取得而須存著的 所以LOCAL端也要轉換 放在 Lines
					Lines = Hresult.split("\r\n");
						String btnNM []=new String [21];
							deptN=Lines.length-2;
							LocX=0;LocY=0;mMode=0; //預設為 全部顯示
						for (int e=0;e<=20;e++) btnSet[e]=0;
						for (int e=0;e<=20;e++) btnNM[e]="";
						String[] btnM=Lines[0].split(",");
						if (btnM.length>2){
							int bg=3;String btnCol=btnM[3];
							btnNM[0]=btnM[3];
							for (int e=6;e<btnM.length;e+=3){
								if (!btnM[e].equalsIgnoreCase(btnCol)){
									bg+=1;
									btnSet[bg]=(e/3)-1;
									btnNM[bg]=btnM[e];
									btnCol=btnM[e];
								}
							}
						reCount_btn();
						resetBottom(btnNM);
						makeCountCellTalbe();
					}else{
						((LinearLayout)findViewById(R.id.layout_color)).setVisibility(View.INVISIBLE);						
						Display(positions);
					}
				}
			}
		}
	}
};

class MainClick implements OnClickListener {
	@Override
	public void onClick(View v) {
		int id = v.getId();
		Utilis.runVibrate(GalleryViewS.this);
		switch (id) {
		case R.id.btn_col_all:mMode=0;LocX=0;LocY=0;break;
		case R.id.btn_col_top1:mMode=1;LocX=0;LocY=0;break;
		case R.id.btn_col_top2:mMode=2;LocX=0;LocY=0;break;
		case R.id.btn_col_top3:mMode=3;LocX=0;LocY=0;break;
		case R.id.btn_col_top4:mMode=0;LocX=btnSet[0];break;
		case R.id.btn_col_top5:mMode=0;LocX=btnSet[1];break;
		case R.id.btn_col_top6:mMode=0;LocX=btnSet[2];break;
		case R.id.btn_col_top7:mMode=0;LocX=btnSet[3];break;
		case R.id.btn_col_top8:mMode=0;LocX=btnSet[4];break;
		case R.id.btn_col_top9:mMode=0;LocX=btnSet[5];break;
		case R.id.btn_col_top10:mMode=0;LocX=btnSet[6];break;
		case R.id.btn_col_top11:mMode=0;LocX=btnSet[7];break;
		case R.id.btn_col_top12:mMode=0;LocX=btnSet[8];break;
		case R.id.btn_col_top13:mMode=0;LocX=btnSet[9];break;
		case R.id.btn_col_top14:mMode=0;LocX=btnSet[10];break;
		case R.id.btn_col_top15:mMode=0;LocX=btnSet[11];break;
		case R.id.btn_col_top16:mMode=0;LocX=btnSet[12];break;
		case R.id.btn_col_top17:mMode=0;LocX=btnSet[13];break;
		case R.id.btn_col_top18:mMode=0;LocX=btnSet[14];break;
		case R.id.btn_col_top19:mMode=0;LocX=btnSet[15];break;
		case R.id.btn_col_top20:mMode=0;LocX=btnSet[16];break;
		}
		//Toast.makeText(GalleryViewS.this,"LocX2="+btnSet[1]+"  LocX3="+btnSet[2]+"  LocX4="+btnSet[3]+"  LocX5="+btnSet[4] , Toast.LENGTH_SHORT).show();							
    	mLayoutRoot.removeAllViews();
		mCountRow.clear();	        		
		mCountCell.clear();
		makeCountCellTalbe();
	}
}	


private void resetBottom(String btnnM[]){

	((LinearLayout)findViewById(R.id.layout_color)).setVisibility(View.VISIBLE);						
	mBtnCor4.setVisibility(View.VISIBLE);
	mBtnCor4.setText(btnnM[0]);
	
	if (btnSet[1]>0){
		mBtnCor5.setVisibility(View.VISIBLE);
		mBtnCor5.setText(btnnM[1]);
	}else mBtnCor5.setVisibility(View.GONE);
	
	if (btnSet[2]>0){
		mBtnCor6.setVisibility(View.VISIBLE);
		mBtnCor6.setText(btnnM[2]);
	}else mBtnCor6.setVisibility(View.GONE);
	
	if (btnSet[3]>0){
		mBtnCor7.setVisibility(View.VISIBLE);
		mBtnCor7.setText(btnnM[3]);
	}else mBtnCor7.setVisibility(View.GONE);
	
	if (btnSet[4]>0){
		mBtnCor8.setVisibility(View.VISIBLE);
		mBtnCor8.setText(btnnM[4]);
	}else mBtnCor8.setVisibility(View.GONE);
	
	if (btnSet[5]>0){
		mBtnCor9.setVisibility(View.VISIBLE);
		mBtnCor9.setText(btnnM[5]);
	}else mBtnCor9.setVisibility(View.GONE);
	
	if (btnSet[6]>0){
		mBtnCor10.setVisibility(View.VISIBLE);
		mBtnCor10.setText(btnnM[6]);
	}else mBtnCor10.setVisibility(View.GONE);
	
	if (btnSet[7]>0){
		mBtnCor11.setVisibility(View.VISIBLE);
		mBtnCor11.setText(btnnM[7]);
	}else mBtnCor11.setVisibility(View.GONE);
	
	if (btnSet[8]>0){
		mBtnCor12.setVisibility(View.VISIBLE);
		mBtnCor12.setText(btnnM[8]);
	}else mBtnCor12.setVisibility(View.GONE);
	
	if (btnSet[9]>0){
		mBtnCor13.setVisibility(View.VISIBLE);
		mBtnCor13.setText(btnnM[9]);
	}else mBtnCor13.setVisibility(View.GONE);
	
	if (btnSet[10]>0){
		mBtnCor14.setVisibility(View.VISIBLE);
		mBtnCor14.setText(btnnM[10]);
	}else mBtnCor14.setVisibility(View.GONE);
	
	if (btnSet[11]>0){
		mBtnCor15.setVisibility(View.VISIBLE);
		mBtnCor15.setText(btnnM[11]);
	}else mBtnCor15.setVisibility(View.GONE);
	
	if (btnSet[12]>0){
		mBtnCor16.setVisibility(View.VISIBLE);
		mBtnCor16.setText(btnnM[12]);
	}else mBtnCor16.setVisibility(View.GONE);
	
	if (btnSet[13]>0){
		mBtnCor17.setVisibility(View.VISIBLE);
		mBtnCor17.setText(btnnM[13]);
	}else mBtnCor17.setVisibility(View.GONE);
	
	if (btnSet[14]>0){
		mBtnCor18.setVisibility(View.VISIBLE);
		mBtnCor18.setText(btnnM[14]);
	}else mBtnCor18.setVisibility(View.GONE);
	
	if (btnSet[15]>0){
		mBtnCor19.setVisibility(View.VISIBLE);
		mBtnCor19.setText(btnnM[15]);
	}else mBtnCor19.setVisibility(View.GONE);
	
	if (btnSet[16]>0){
		mBtnCor20.setVisibility(View.VISIBLE);
		mBtnCor20.setText(btnnM[16]);
	}else mBtnCor20.setVisibility(View.GONE);
}

class Clickable implements OnLongClickListener{
	private int mRow;
	private int mCell;
	Clickable(int row, int cell){
		mRow = row;
		mCell = cell;
	}
	@Override
	public boolean onLongClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		handleCount(id, mRow, mCell, mChoiceMode);		
		return false;
	}
}

private void handleCount(int id, int row, int cell, int mode){

	Toast.makeText(GalleryViewS.this,"ID=="+id+"  row="+row+"  cell="+cell+"  mod=e"+mode , Toast.LENGTH_SHORT).show();							
	
}

private void reCount_btn(){
	
	String[] data= Lines [2].split(",");//總倉的數據
	int btn_tot10=0;
	int btn_tot20=0;
	int btn_tot30=0;
	int btn_tot30order=0;
	
	for(int e=2;e<data.length;e+=3){
		btn_tot10+=Utilis.toInt(data[e].substring(0,data[e].indexOf("(")));
		btn_tot20+=Utilis.toInt(data[e].substring(data[e].indexOf("(")+1,data[e].indexOf(")")));
	}
	for (int xx=2;xx<(Lines.length);xx++){
		data= Lines [xx].split(",");
		for (int e=3;e<data.length;e+=3){
			btn_tot30+=Utilis.toInt(data[e].substring(0,data[e].indexOf("(")));
			btn_tot30order+=Utilis.toInt(data[e].substring(data[e].indexOf("(")+1,data[e].indexOf(")")));
		}
	}
	
	mTextView20.setText("總進"+btn_tot10+" 總出:"+btn_tot20);
	mTextView21.setText("總銷"+btn_tot30+" 預購:"+btn_tot30order);
	mTextView22.setText("總存"+(btn_tot10-btn_tot30));
}

private void makeCountCellTalbe(){

	if (Lines.length>2 && mMode==0){
		for (int yy=0;yy<2;yy++){
			mCountRow.put(yy, yy * 200);
			String[] data= Lines [yy].split(",");
			//橫向一筆 拆成所有欄位陣列
			ColNoSizN=(data.length-2)/3;
			//ColNoSizN 是有幾個顏色
			mCountCell.put(yy * 200 , data[0]);
			mCountCell.put(yy * 200+1 , data[1]);
			for (int jj=LocX*3+2;jj<data.length;jj++)
				mCountCell.put(yy * 200 + jj-LocX*3, data[jj]);
		}
		
		for (int yy=LocY+2;yy<(Lines.length);yy++){
		//看來*200是為 整格行 預備了200個 mCountCell
		//所以極限是 幾個顏色*幾個尺寸不得超過200
			mCountRow.put(yy-LocY, (yy-LocY) * 200);
			String[] data= Lines [yy].split(",");
			//橫向一筆 拆成所有欄位陣列
			//ColNoSizN=(data.length-2)/3;
			//ColNoSizN 是有幾個顏色
			mCountCell.put((yy-LocY) * 200 , data[0]);
			mCountCell.put((yy-LocY) * 200+1 , data[1]);
			
			for (int jj=LocX*3+2;jj<data.length;jj++){
			//每一行的欄位總數
			if (jj>1 && ((Utilis.toInt(data[jj].substring(0,data[jj].indexOf("(")))==0) && (Utilis.toInt(data[jj].substring(data[jj].indexOf("(")+1,data[jj].indexOf(")")))==0)))
				mCountCell.put((yy-LocY) * 200 + jj-LocX*3, "");
			else	
				mCountCell.put((yy-LocY) * 200 + jj-LocX*3, data[jj]);
			//每一個欄位一一填滿資料
			}	
		}
		
		if (mCountCell.size()>0){
			ArrayList<TableRow> table = new ArrayList<TableRow>();
			table.removeAll(table);
			for(int yy = 0; yy <= (deptN-LocY+1); yy++){
				TableCell[] titles = new TableCell[(ColNoSizN-LocX)*3+2]; 
				for(int xx = 0; xx < titles.length; xx++){
					if (xx==1)
						titles[xx] = new TableCell((Wwidth/tabless)+60,tableHeight,TableCell.STRING);
					else	
						titles[xx] = new TableCell((Wwidth/tabless)-20,tableHeight,TableCell.STRING);
				}
				table.add(new TableRow(titles));
			}
			TableRow tableRow = table.get(0);
			for(int yy = 0; yy <=(deptN-LocY+1); yy ++){
				TableRowView row = new  TableRowView(GalleryViewS.this, tableRow,1, yy);
				mLayoutRoot.addView(row);
				//每十筆重製一個台頭
				if (yy%10==0 && yy>0){
				  int repeat=3;if (mMode==0) repeat=1; 
				  for (int y=0;y<=repeat;y++){
					row = new  TableRowView(GalleryViewS.this, tableRow,1, y);
					mLayoutRoot.addView(row);
				  }
				}
			}
		}
	}else if (Lines.length>=2){ //mMode==1,2,3
			String [][]dataA= new String [3][Lines [0].split(",").length+1];
			dataA[0]= Lines [0].split(",");
			dataA[1]= Lines [1].split(",");
			dataA[2]= Lines [2].split(",");
			//前三 含(台頭一)(台頭二)(台頭三:總倉數據)
			//橫向一筆 拆成所有欄位陣列
			ColNoSizN=(dataA[0].length-2)/3;
			//ColNoSizN 是有幾個顏色及尺寸的組合
			for (int xx=0;xx<=2;xx++){//共三個Line
				if (xx==0){
					for (int qs=0;qs<=2;qs++){//共三行
						mCountRow.put(qs, (qs) * 200);
						mCountCell.put((qs) * 200 ,modeName2[qs]);
						mCountCell.put((qs) * 200+1 ,modeName[mMode]);
						int writeIn=1;
						for (int sq=0;sq<=2;sq++){
							for (int jj=2+qs;jj<dataA[0].length;jj+=3){
								writeIn++;mCountCell.put(qs * 200 + writeIn, dataA[0][jj]);
							}
						}
					}
					
				}else{
					mCountRow.put(xx+2, (xx+2) * 200);
					mCountCell.put((xx+2) * 200 ,dataA[xx][0]);
					mCountCell.put((xx+2) * 200+1 ,dataA[xx][1]);
					int writeIn=1;
					for (int jj=xMode[mMode][0]+2;jj<dataA[xx].length;jj+=3){
						writeIn++;mCountCell.put((xx+2) * 200 + writeIn, dataA[xx][jj]);
					}
					for (int jj=xMode[mMode][1]+2;jj<dataA[xx].length;jj+=3){
						writeIn++;mCountCell.put((xx+2) * 200 + writeIn, dataA[xx][jj]);
					}
					for (int jj=xMode[mMode][2]+2;jj<dataA[xx].length;jj+=3){
						writeIn++;mCountCell.put((xx+2) * 200 + writeIn, dataA[xx][jj]);
					}
				}
			}
			//各門市一一存入
			for (int xx=2;xx<(Lines.length);xx++){
				//看來*200是為 整格行 預備了200個 mCountCell
				mCountRow.put(xx+2, (xx+2) * 200);
				String[] data= Lines [xx].split(",");
				//橫向一筆 拆成所有欄位陣列
				mCountCell.put((xx+2) * 200 , data[0]);
				mCountCell.put((xx+2) * 200+1 , data[1]);
				int writeIn=1;
				
				for (int jj=2+xMode[mMode][0];jj<data.length;jj+=3){
					//每一行的欄位總數
					writeIn+=1;
					if (jj>1 && ((Utilis.toInt(data[jj].substring(0,data[jj].indexOf("(")))==0) && (Utilis.toInt(data[jj].substring(data[jj].indexOf("(")+1,data[jj].indexOf(")")))==0)))
						mCountCell.put((xx+2) * 200 + writeIn, "");
					else	
						mCountCell.put((xx+2) * 200 + writeIn, data[jj]);
					//每一個欄位一一填滿資料
				}						
				for (int jj=2+xMode[mMode][1];jj<data.length;jj+=3){
					//每一行的欄位總數
					writeIn+=1;
					if (jj>1 && ((Utilis.toInt(data[jj].substring(0,data[jj].indexOf("(")))==0) && (Utilis.toInt(data[jj].substring(data[jj].indexOf("(")+1,data[jj].indexOf(")")))==0)))
						mCountCell.put((xx+2) * 200 + writeIn, "");
					else	
						mCountCell.put((xx+2) * 200 + writeIn, data[jj]);
					//每一個欄位一一填滿資料
				}
				for (int jj=2+xMode[mMode][2];jj<data.length;jj+=3){
					//每一行的欄位總數
					writeIn+=1;
					if (jj>1 && ((Utilis.toInt(data[jj].substring(0,data[jj].indexOf("(")))==0) && (Utilis.toInt(data[jj].substring(data[jj].indexOf("(")+1,data[jj].indexOf(")")))==0)))
						mCountCell.put((xx+2) * 200 + writeIn, "");
					else	
						mCountCell.put((xx+2) * 200 + writeIn, data[jj]);
					//每一個欄位一一填滿資料
				}	
			}
			if (mCountCell.size()>0){
				ArrayList<TableRow> table = new ArrayList<TableRow>();
				table.removeAll(table);
				for(int i = 0; i <= (deptN+2+1); i++){
					TableCell[] titles = new TableCell[ColNoSizN*3+2]; 
					for(int k = 0; k < titles.length; k++){
						if (k==1)
							titles[k] = new TableCell((Wwidth/tabless)+60,tableHeight,TableCell.STRING);
						else	
							titles[k] = new TableCell((Wwidth/tabless)-20,tableHeight,TableCell.STRING);
					}
					table.add(new TableRow(titles));
				}
				TableRow tableRow = table.get(0);
				for(int yy = 0; yy <=(deptN+2-LocY+1); yy ++){
					TableRowView row = new  TableRowView(GalleryViewS.this, tableRow,2, yy);
					mLayoutRoot.addView(row);
					//每十筆重製一個台頭
					if (yy%10==0 && yy>0){
					  int repeat=3;if (mMode==0) repeat=1; 
					  for (int y=0;y<=repeat;y++){
						row = new  TableRowView(GalleryViewS.this, tableRow,2, y);
						mLayoutRoot.addView(row);
					  }
					}
				}
			}
			
	}else{	
		((LinearLayout)findViewById(R.id.layout_color)).setVisibility(View.INVISIBLE);						
		Display(positions);
	}
}

public class TableRowView extends LinearLayout {  
    public TableRowView(Context context, TableRow tableRow,int imode, int position) {  
        super(context);  
        this.setOrientation(LinearLayout.HORIZONTAL);
        for (int xx = 0; xx < tableRow.getSize(); xx++) { 
            TableCell tableCell = tableRow.getCellValue(xx);  
            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 + xx)){
                		textCell.setText(String.valueOf(mCountCell.get(key + xx))); //keep
                	}else{
                		textCell.setText("X");
                	}
                }else{
                	textCell.setText("X");
                }
                textCell.setId(position * 200 + xx);
                textCell.setTextColor(Color.BLACK);
                if (imode!=2){
	                if(position >=1 && xx >= 2){
	                	//第一行起三色表
	                	if ((xx+2) %3==1){
	                		textCell.setBackgroundResource(R.drawable.keypad_yellow);
	                		if(position >=2) textCell.setOnLongClickListener(new Clickable(position,xx));	                	
	                	} else if((xx+2) %3==2) {
	                    	textCell.setBackgroundResource(R.drawable.keypad_green);                    		
	                    	if(position >=2) textCell.setOnLongClickListener(new Clickable(position,xx));
                    	} else if((xx+2) %3==0) {
	                    	textCell.setBackgroundResource(R.drawable.keypad_blue2);                    		
	                	}
	                	
	                }else  if(position > 0 && xx ==0 && imode==0){  //
	                	//總庫存表 左側色表
	                	String colorN=DBUtil.ColorGetTxt(GalleryViewS.this,textCell.getText().toString());
	                	String [] colors=colorN.split(";");
	                	textCell.setBackgroundColor(Utilis.toInt(colors[2]));
	                }else if(position == 0 && imode==1 && xx>1 ){  
	                	//各門市庫存表 第一行 色表
	                	String colorN=DBUtil.ColorGetTxt(GalleryViewS.this,textCell.getText().toString());
	                	String [] colors=colorN.split(";");
	                	textCell.setBackgroundColor(Utilis.toInt(colors[2]));
	               		if (((xx+1)%3)==2){//[存]
	               			textCell.setBackgroundResource(R.drawable.keypad_blue2);
	               		}else{	
	                		textCell.setBackgroundColor(Utilis.toInt(colors[2]));
	               		}
	                } else {
	                	textCell.setBackgroundColor(Color.rgb(208, 208, 208));
	                }
                }else{
	                if(position <=1 && xx >= 2){
	                	String colorN=DBUtil.ColorGetTxt(GalleryViewS.this,textCell.getText().toString());
	                	String [] colors=colorN.split(";");
	                	textCell.setBackgroundColor(Utilis.toInt(colors[2]));
	                }else if(position >2 && xx >=2){
	                	if(position >=3) 
	                	//庫存的黃色
	                	if ((mMode==1 && ((xx-2)-LocX*2)<ColNoSizN) || (mMode!=1 && (xx-2)>=ColNoSizN && (xx-2)<(ColNoSizN*2)))//存-進-銷
	                    	textCell.setBackgroundResource(R.drawable.keypad_blue2);                    		
	                	else if ((mMode!=3 && (xx-2)>=(ColNoSizN*2)) || (mMode==3 && (xx-2)<ColNoSizN)){//存-進-銷
	                		textCell.setBackgroundResource(R.drawable.keypad_green);
	                		textCell.setOnLongClickListener(new Clickable(position,xx));
	                	}else{
	                    	textCell.setBackgroundResource(R.drawable.keypad_yellow);
	                    	textCell.setOnLongClickListener(new Clickable(position,xx));	                    	
	                	}
	                	
	                } else	textCell.setBackgroundColor(Color.rgb(208, 208, 208));
	                
                }
                addView(textCell, layoutParams);
                //每9增列一個 門市代號
                //if ((xx-2)%9==0 && xx>10){
                 if (((xx-2)%8==0 && xx>2 && xx<11) ||((xx-1)%9==0 && xx>11)){
                    layoutParams = new LinearLayout.LayoutParams(tableCell.width+60, tableCell.height);  
                    layoutParams.setMargins(0, 0, 1, 1);  
                    TextView textCell0 = new TextView(context);  
                        textCell0.setLines(1);  
                        textCell0.setGravity(Gravity.CENTER);  
	                	textCell0.setBackgroundColor(Color.rgb(208, 208, 208));
	                    textCell0.setTextColor(Color.BLACK);
	                	textCell0.setText(String.valueOf(mCountCell.get(mCountRow.get(position)+1)));                	
	                    addView(textCell0, layoutParams);
                }
        }  
        this.setBackgroundColor(Color.BLACK);
    }

}
	
public int[] toInt(Set<Integer> set) {
    		int[] a = new int[set.size()];
    		int i = 0;
    		for (Integer val : set)
    			a[i++] = val;
    		return a;
}

private void makeTable(String kGoods,String kSplitColorNo,String kSplitColor,String kSplitSizes){
		
		//展開用的引用在庫存表
		String[] anames;	
		String[] anumber;
		String[] asizes;
	
		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(",");
			    	
			    	
			    	for(int i = 0; i < anumber.length; i++){ 
			    		mArrayColorNumber.add(anumber[i]); //從numbers字串陣列 存入 List_mArrayColorNumber
			    	}
			    	
			    	for(int i = 0; i < anames.length; i++){
			    		mArrayColorName.add(anames[i]);
			    	}
				
			    	mLayoutRoot.removeAllViews();
					mSizeLink.clear();
					mCountRow.clear();	        		
					mCountCell.clear();
					
			    	mSizeLink.add("代碼"); // 顏色
			    	mSizeLink.add("顏色"); // 尺寸
			    	// 設定 Title 行 //使每個尺寸都有3格(進/銷/存)
			    	int ttot[][] =new int[(anumber.length+1)*3][(asizes.length+1)*6] ; //進銷存統計用
			    	for(int i = 0; i < (asizes.length+1)*6;i++) for ( int j=0;j<(anumber.length+1)*3;j++){ttot[j][i]=0;}
			    	for(int i = 0; i < asizes.length; i++){
			    		if (nPart==0){
			    			mSizeLink.add(asizes[i]+"進(訂)");
			    		}else{
				    		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 * 200);
			    		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 * 200 + k, mArrayColorNumber.get(i - 1));
			        			} else {
			        					mCountCell.put(i * 200 + k, mArrayColorName.get(i - 1)); 
			        			}
			
			        		}			
			    		}
			    	}
			    	
			    	mCountList= PosUtilis.getQMtrioArray(this,kGoods,kSplitColorNo,kSplitColor,kSplitSizes,mDept,mCountList , nPart,0);
			    	
				try{
						
			    	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 yy = 0; yy <=mArrayColorName.size(); yy ++){
					TableRowView row = new TableRowView(this, tableRow,0, yy);
					mLayoutRoot.addView(row);
					//每十筆重製一個台頭
					if (yy%10==0 && yy>0){
					  int repeat=3;if (mMode==0) repeat=1; 
					  for (int y=0;y<=repeat;y++){
						row = new  TableRowView(GalleryViewS.this, tableRow,0, y);
						mLayoutRoot.addView(row);
					  }
					}
				}
		}
	}
	        
	public static Bitmap createReflectionBitmap(Bitmap src) {
		// 原始圖片與反射圖片的邊界
		int margin = 4;
		int width = src.getWidth();
		int height = src.getHeight();

		// 用來做上下顛倒的Matrix
		Matrix matrix = new Matrix();
		matrix.preScale(1.0f, -1.2f);

		// 以原始圖片下半部顛倒過來產生Bitmap
		Bitmap reflection;
		reflection = Bitmap.createBitmap(src, 0, height / 2, width, height / 2,
				matrix, true);
		// 產生原始圖片與反射圖片合體後的結果圖片Bitmap
		// 這時還是空的
		Bitmap result;
		result = Bitmap.createBitmap(width, height + height / 5,
				Config.ARGB_8888);
		// 使用畫布
		Canvas canvas;
		canvas = new Canvas(result);
		// 將原始圖片寫到結果圖片畫布上
		canvas.drawBitmap(src, 0, 0, null);
		// 將反射圖片寫到結果圖片畫布上
		canvas.drawBitmap(reflection, 0, height + margin, null);

		// 到這裡已經與反射圖片合體完成了
		// 接下來要做淡化處理
		Paint paint = new Paint();
		// 使用LinearGradient這個直線方向的漸層
		LinearGradient shader;
		// 製作漸入透明的漸層
		// 0x90ffffff(稍微透明) -> 0x00FFFFFF(完全透明)
		shader = new LinearGradient(0, height, 0, result.getHeight() + margin,
				0x80ffffff, 0x00ffffff, TileMode.CLAMP);
		// 因為繼承Shader類別，所以使用setShader設定給Paint。
		paint.setShader(shader);
		// 指定顏色轉換模式
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		// 描繪漸層
		canvas.drawRect(0, height, width, result.getHeight(), paint);

		return result;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
//		db.close();
	}

}
