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.PItemData;
import com.cwbuyer.main.AIncome;
import com.cwbuyer.main.AIncomePc;
import com.cwbuyer.main.AItem;
import com.cwbuyer.main.AIncome.ChoiceMode;
import com.cwbuyer.main.AIncome.CountMode;
import com.cwbuyer.main.APos.PItemKind;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.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.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
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;

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

	private Gallery mGallery01;
	private ImageView mImage;
	private ImageButton mImgBtnSearch;
	private ImageButton mImgBtnRobk;
	private EditText mEdSearch;
	private TextView mTextView01;
	private TextView mTextView02;
	private TextView mTextView03;
	private TextView mTextView04;
	private TextView mTextView05;
	private EditText mInput;
	private TextView mEdAdord;
	private Button BtAdord;
	private Button BtAutoS;
	private Button BtSaveA;
	private Button BtSaveB;
	private String mBankn=Utilis.getIni(this,"SYS","DEPT",1)+Utilis.getIni(this,"SYS","DEPT",2);//門市代號+機號		
  	private LinearLayout lTableView = null;
	private LinearLayout mLayoutRoot = null;
	
	private int mChoiceMode = ChoiceMode.NORMAL;
	private int mAddValue = 0;
	private StringBuffer mBuf = new StringBuffer();
	
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+	 File.separator + "CWBuyer"  ;
	String uriAPI=null;

	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<Integer> mCountryIdList = new ArrayList<Integer>();
	private ArrayList<String> mTypeList = new ArrayList<String>();
	private ArrayList<Integer> mTypeIdList = new ArrayList<Integer>();
	
	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>();  // 行資料

	int nState=0;
    int locates =0;
	int nPart=0;
	int records = -1;
	int positions = 0;
	String mGoods="";
	private Bitmap reflactionBitmap; //提供畫布用
	int PSWD=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT",5));
	private int isOnkey=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT",8));

	int deptN=1;
	String [] DepNo;
	String [] DepNa;
	double [] DepLa;
	
	int Otot[][];  //本批號的訂量
	int Otott[][];	//全部訂量
	private int ColNoSizN=0;
	String [][] ColNoSiz;
	String[] menu_X={"追蹤","補印條碼","商品編輯","單筆傳送雲端","返回" };
	
	private final int RESULT_AITEM = 1200;
	private int mCountMode = CountMode.PLUS;
	
	String[] SizeLength; 
	String[] ColLength;
	String[] numberLevel1;
	String[] numberLevel2;
	String strRes = "";
	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 String[] anames;	
	private String[] anumber;
	private String[] asizes;
	private String[] acountlist;	
	
	int Wheight;
	int Wwidth;
	int tableHeight=80;
	int tabless=6;
	
	PItemData data = new PItemData(); //##格式化需考量內容增刪
	//For Cloud
	public ProgressDialog myDialog = null;
	protected static final int REFRESH_DATA = 0x00000001;
	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	
	Bundle bundle;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == RESULT_AITEM) {
			if (resultCode == RESULT_OK) {
				Display(positions);
			}	
		}				
	}

	/** 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.galleryvp);
		mGallery01 = (Gallery) findViewById(R.id.myGallery1);
		mImage = (ImageView) findViewById(R.id.imageView105);
		mImgBtnSearch = (ImageButton) findViewById(R.id.imageButton15);		
		mImgBtnRobk = (ImageButton) findViewById(R.id.imageButton16);
		mEdSearch =(EditText)findViewById(R.id.edSearch);
		
		mImage.getLayoutParams().width=(int) (Wwidth/2.5);
		mImage.getLayoutParams().height=(int) (Wheight/4);
		mGallery01.getLayoutParams().height=(int) (Wheight/7);
		if (Wwidth<=800) tabless=(int) (Wwidth/100)+2; else  tabless=(int) (Wwidth/140)+1;
		tableHeight=(int) (Wheight/22);
		
    	mTextView01 = (TextView) findViewById(R.id.textViewg1);
		mTextView02 = (TextView) findViewById(R.id.textViewg2);
		mTextView03 = (TextView) findViewById(R.id.textViewg3);
		mTextView04 = (TextView) findViewById(R.id.textViewg4);
		mTextView05 = (TextView) findViewById(R.id.textViewg5);
		mInput = (EditText) findViewById(R.id.ed_choiced);
		mEdAdord= (TextView) findViewById(R.id.ed_deptord);
		mEdAdord.setText(Utilis.getNadord(this));
		BtAdord= (Button) findViewById(R.id.deptord);
		BtAutoS= (Button) findViewById(R.id.auto_s);
		BtSaveA= (Button) findViewById(R.id.save_20);
		BtSaveB= (Button) findViewById(R.id.btn_bsave);

        ((Button)findViewById(R.id.btn_number_0)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_1)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_2)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_3)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_4)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_5)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_6)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_7)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_8)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_9)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_opreate_plus)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_choice_cell)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_choice_row)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_choice_all)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_choice_single)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_clean_number)).setOnClickListener(processListener);
		BtAdord.setOnClickListener(processListener);
		BtAutoS.setOnClickListener(processListener);
		BtSaveA.setOnClickListener(processListener);
		BtSaveB.setOnClickListener(processListener);
		
        lTableView = (LinearLayout)findViewById(R.id.tableview);
        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];
        locates = Utilis.valuesInt(arrayW[1]);
        nState=Utilis.valuesInt(arrayW[2]);
        //0依配貨表設計 1門市庫存分析表
        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 cs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		Cursor cs=db.rawQuery("select CUSTNO,CUSTNAME,GPSLA from qcust where TR='20' and  CUSTNO <>'"+Utilis.getIni(this,"SYS","DEPT",6)+"' order by CUSTNO",null);
		if (cs.getCount()>0){
			deptN=cs.getCount()+1;
			DepNo=new String[deptN];
			DepNa=new String[deptN];
			DepLa=new double[deptN+2];
			cs.moveToFirst();
			for (int i=0;i<cs.getCount();i++){
				DepNo[i+1]=cs.getString(0);
				DepNa[i+1]=cs.getString(1);
				DepLa[i+1]=cs.getDouble(2);//配比
				DepLa[deptN+1]+=cs.getDouble(2);//算出總比
				cs.moveToNext();
			}
		}else{
			deptN=1;
			DepNo=new String[deptN];
			DepNa=new String[deptN];
		}
		cs.close();
		DepNo[0]=Utilis.getIni(this,"SYS","DEPT",6);
		DepNa[0]=Utilis.getIni(this,"SYS","DEPT",7);
		Cursor cs1=db.rawQuery("select CUSTNO,CUSTNAME,GPSLA from qcust where TR='20' and  CUSTNO ='"+Utilis.getIni(this,"SYS","DEPT",6)+"'",null);
		if (cs1.getCount()>0){
			cs1.moveToFirst();
			DepLa[0]=cs1.getDouble(2);//配比
			DepLa[deptN+1]+=cs1.getDouble(2);//算出總比
		}else{
			DepLa[0]=0;//配比
		}
		cs1.close();
		if (DepLa[deptN+1]<=0) DepLa[deptN+1]=1;
		
		Toast.makeText(GalleryViewVP.this,"DepLaT="+DepLa[deptN+1]+"DepLaA="+DepLa[1] , Toast.LENGTH_SHORT).show();							
		if (locates==1){//來自採購單
			mySqlBuf.append("select MID,PIC,GOODSNO,BATCH from qdetail");
			mySqlBuf.append(" where BATCH='" + batch+"'");
			mySqlBuf.append(" order by BATCH desc");
			Cursor cs2 = db.rawQuery(mySqlBuf.toString(), null);
	
			if (cs2.getCount() > 0) {
				updateListView(cs2);
				Display(0);
				if (cs2.getCount() >= 300) {
					Toast.makeText(GalleryViewVP.this,"超過300筆的部分無法顯示!請下次縮小範圍!" , Toast.LENGTH_SHORT).show();							
				}
			} else {
				db.close();
				finish();
			}
			cs2.close();
		}else{//來自廠商進貨單
			//mySqlBuf.append("select distinct B.MID,B.PIC,A.GOODSNO,B.BATCH from qitems A left join qdetail B on (A.GOODSNO=B.GOODSNO)");
			//mySqlBuf.append(" where A.FORMNO='"+batch+"'");
			//mySqlBuf.append(" order by A.CREATEDATETIME desc");
			//cs1 = db.rawQuery(mySqlBuf.toString(),null);
			cs1 = db.rawQuery("select distinct MID,PIC,BATCH,GOODSNO from qdetail where GOODSNO in (select GOODSNO from qitems where FORMNO='"+batch+"') order by BATCH desc", null);
				if (cs1.getCount() > 0) {
					updateListView(cs1);
					Display(0);
					if (cs1.getCount() >= 300) {
						Toast.makeText(GalleryViewVP.this,"超過300筆的部分無法顯示!請下次縮小範圍!" , Toast.LENGTH_SHORT).show();							
					}
				}
			cs1.close();	
		}
		db.close();
	
		/* 設定一個itemclickListener事件 */
		mGallery01.setOnItemClickListener(new Gallery.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long ids) {
				// TODO Auto-generated method stub
				if (positions != position){
					SAVEDATA(mEdAdord.getText().toString(),0);
					Display(position);
				}
				positions = position;
			}
		});

//查詢 優先順序為 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;
			}
			
		});
		//補印條碼/追蹤/返回該批號單
		mImage.setOnClickListener(new ImageView.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Utilis.runVibrate(GalleryViewVP.this);
				DialogUtilis.showDialog(GalleryViewVP.this, "請選擇以下功能", -1,
						menu_X, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								switch (pos) {
									case 0: //商品追蹤
									{
										mGoods=GoodsNo[positions];
										Intent intent = new Intent();
										intent.putExtra("QHis_kind", PItemKind.TR10);
										intent.putExtra("QHis_mode", 1);
										intent.putExtra("QHis_User","" );
										intent.putExtra("QHis_Goods",mGoods );
										intent.setClass(GalleryViewVP.this, QHis.class);
										startActivity(intent);
										
									break;	
									}
									case 1: //補印條碼
									{
											SQLiteDatabase db = Utilis.getDB(GalleryViewVP.this);
											Cursor cs=db.rawQuery("select * from qdetail where MID='"+Amid[positions]+"'", null);
											if (cs.getCount()>0){
												cs.moveToFirst();
												Intent intent = new Intent();
												intent.putExtra("mid", Amid[positions]);
												intent.putExtra("batch", cs.getString(cs.getColumnIndex("GOODSNO")));
												intent.putExtra("item_mode", 3); // 3QDETAIL 4QITEMS
												intent.putExtra("cong", 0);
												intent.putExtra("unit", cs.getString(cs.getColumnIndex("UNIT"))); //每手有幾段(童裝)
												intent.putExtra("size", cs.getString(cs.getColumnIndex("SIZE")));
												intent.putExtra("colorno", cs.getString(cs.getColumnIndex("COLORNO")));
												intent.putExtra("color", cs.getString(cs.getColumnIndex("COLOR")));
												intent.putExtra("countlist", cs.getString(cs.getColumnIndex("INLIST")));
						 						intent.putExtra("mkind", "10");
												intent.putExtra("unitprice", cs.getString(cs.getColumnIndex("P0")));
												intent.putExtra("discount", 100.0);
												if (isOnkey==1)
													intent.setClass(GalleryViewVP.this, AIncomePc.class);
												else
													intent.setClass(GalleryViewVP.this, AIncome.class);

												startActivity(intent);
											}
										
											db.close();
											cs.close();
									break;	
									}
									case 2:  //商品編輯
									{
										if (PSWD==0){//只有採購+權限
											Utilis.runVibrate(GalleryViewVP.this);
											Intent intent = new Intent();
											intent.setClass(GalleryViewVP.this,AItem.class);
											intent.putExtra("item_mode", AItem.ItemMode.EDIT);
											intent.putExtra("item_mid", Utilis.toInt(Amid[positions]));
											intent.putExtra("item_from", 1);//0.ManagerItem 1.GalleryView
											startActivityForResult(intent, RESULT_AITEM);
										}
									break;
									}
									case 3:  //單筆匯出雲端
									{
											Intent intent = new Intent();
											intent.setClass(GalleryViewVP.this,MakeTransDetail.class);
											intent.putExtra("make_batch",Abatch[positions]);
											intent.putExtra("make_mode",0);
											intent.putExtra("make_kind",0);
											intent.putExtra("make_01",1);
											intent.putExtra("make_user",GoodsNo[positions]);
											startActivity(intent);
									break;
									}
								}
							}
					});
			}
		});

		mImgBtnRobk.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//@@@保留給以批號拉出
				//	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+"/0916961962.png");}
		}
		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){
        SQLiteDatabase db = Utilis.getDB(this);
        StringBuffer mySqlBuf = new StringBuffer();
 		mySqlBuf.append("select MID,PIC,GOODSNO,BATCH from qdetail");
 		mySqlBuf.append(" where GOODSNO  like '%" + mEdS+ "%' order by MID desc LIMIT 300" );

		Cursor cs = null;
		int catched = 0;
		cs = db.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){
			catched=1;
		}
		if (catched==0) {
	        mySqlBuf.delete(0, mySqlBuf.toString().length());
	 		mySqlBuf.append("select MID,PIC,GOODSNO,BATCH from qdetail");
	 		mySqlBuf.append(" where GOODSNAME  like '%" + mEdS + "%' order by MID desc LIMIT 300" );
			cs = null;
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				catched=1;
			}	
		} 
		if (catched==0) {
	        mySqlBuf.delete(0, mySqlBuf.toString().length());
	 		mySqlBuf.append("select MID,PIC,GOODSNO,BATCH from qdetail");
	 		mySqlBuf.append(" where SUPPLY  like '%" + mEdS + "%' order by MID desc LIMIT 300" );
			cs = null;
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				catched=1;
			}	
		} 
		if(catched<=0){
			Toast.makeText(GalleryViewVP.this,"查無此商品!" , Toast.LENGTH_SHORT).show();							
		}else {
			updateListView(cs);
			Display(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的寬高 */
			 if ((Wwidth<=580 && Wheight<=1000  ) ||  (Wwidth<=800 && Wheight<=1280  )) {// GI9000
				//200 230 100
				i.setLayoutParams(new Gallery.LayoutParams(100, 120));
			}else {
				i.setLayoutParams(new Gallery.LayoutParams(200, 240));				
//				i.setLayoutParams(new Gallery.LayoutParams(100, 120));				
				}
			/* 設定Gallery背景圖 */
			i.setBackgroundResource(mGalleryItemBackground);
			/* 傳回imageView物件 */
			return i;
		}
	}
	
	
	private void updateListView(Cursor cs) {

		int record = -1;
		String PAYD="XXXX";
		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 ((PAYD.indexOf("'"+cs.getString(cs.getColumnIndex("GOODSNO"))+"'"))<0){
					record++;
					Amid[record] = cs.getString(cs.getColumnIndex("MID"));
					Apicstr[record] = cs.getString(cs.getColumnIndex("PIC"));				
					GoodsNo[record] = cs.getString(cs.getColumnIndex("GOODSNO"));
					Abatch[record] = cs.getString(cs.getColumnIndex("BATCH"));
					PAYD=PAYD+"'"+GoodsNo[record]+"'";
				}
			}

		}

		records = record+1;

		if (records>=0) {		
		/* 新增一ImageAdapter並設定給Gallery物件 */
		mGallery01.setAdapter(new ImageAdapter(this, ChkPic()));		
		}

	}

	private void updateListViewOrd(ProcessKeypadInput processKeypadInput,String StrOrd) {

		int record = -1;

		SQLiteDatabase dbs = Utilis.getDB(GalleryViewVP.this);
		Cursor csi = dbs.rawQuery("select distinct GOODSNO,EMPNAME from QITEMS where EMPNAME='"+StrOrd+"' order by GOODSNO", null);
		
		Amid = new String[csi.getCount()];
		Apicstr = new String[csi.getCount()];
		GoodsNo = new String[csi.getCount()];
		Abatch = new String[csi.getCount()];
		
				if(csi.getCount() > 0){
					csi.moveToFirst();
					for(int i = 0; i < csi.getCount(); i++){
						String goods=csi.getString(0);
						Cursor cs=dbs.rawQuery("select MID,GOODSNO,PIC,BATCH from QDETAIL where GOODSNO='"+goods+"'order by MID desc LIMIT 1", null);
						if (cs.getCount() > 0) {
							cs.moveToFirst();
							record++;
							Amid[record] = cs.getString(0);
							Apicstr[record] = cs.getString(2);				
							GoodsNo[record] = cs.getString(1);
							Abatch[record] = cs.getString(3);
						}
						cs.close();
						csi.moveToNext();
					}
				}
		csi.close();		
		records = record+1;
		if (records>=0) {		
		mGallery01.setAdapter(new ImageAdapter(this, ChkPic()));		
		}
		dbs.close();
	}
	
//事先整理出產地國別	
	public void getCountryData(Context context){
		if(mCountryIdList != null){
			mCountryIdList.clear();
		}
		if(mCountryList != null){
			mCountryList.clear();
		}
		SQLiteDatabase dbs = Utilis.getDB(context);
		Cursor cursor = dbs.rawQuery("select NAME,_ID from qc_country order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));						
						String name = cursor.getString(cursor.getColumnIndex("NAME"));
						mCountryIdList.add(id);
						mCountryList.add(name);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
			}
		}
		cursor.close();
		dbs.close();
	}
	
	// 取得類別資料
	public void getTypeData(Context context){
		if(mTypeList != null){
			mTypeList.clear();
		}
		if(mTypeIdList != null){
			mTypeIdList.clear();
		}
		SQLiteDatabase dbs = Utilis.getDB(context);
		Cursor cursor = dbs.rawQuery("select GOODTYPE,_ID from qc_type order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						String name = cursor.getString(cursor.getColumnIndex("GOODTYPE"));
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						mTypeList.add(name);
						mTypeIdList.add(id);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
			}
		}
		dbs.close();
		cursor.close();
	}
	
	
	private void Display(int positionid) {
		int position = positionid;

        SQLiteDatabase db = Utilis.getDB(this);		
		StringBuffer mySqlBuf = new StringBuffer();
		mGoods=GoodsNo[position];
		mySqlBuf.append("select distinct GOODSNO,GOODSNAME,")
		.append("BATCH,SUPPLY,SOURCENO,P0,P1,P2,P3,P4,P5,COLORNO,COLOR,SIZE,INLIST")
		.append(" from qdetail where GOODSNO='" + mGoods+"' and BATCH='" + Abatch[position]+"' order by MID desc limit 1");
		Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
		//@@@加入本次採購量 需分計各色尺寸件數 以備顯示 採購量
		if (cs.getCount()>0){//一定存在
			cs.moveToFirst();
				mTextView01.setText(cs.getString(cs.getColumnIndex("GOODSNO"))+"/"+cs.getString(cs.getColumnIndex("GOODSNAME")));		
				mTextView02.setText(cs.getString(cs.getColumnIndex("BATCH")));
        		mTextView03.setText(cs.getString(cs.getColumnIndex("P0"))+cs.getString(cs.getColumnIndex("P1")));
				mTextView04.setText(cs.getString(cs.getColumnIndex("P2"))+cs.getString(cs.getColumnIndex("P3")));
				mTextView05.setText(cs.getString(cs.getColumnIndex("P4"))+cs.getString(cs.getColumnIndex("P5")));
				mSplitSizes=	cs.getString(cs.getColumnIndex("SIZE"));
				mSplitColor=cs.getString(cs.getColumnIndex("COLOR"));
				mSplitColorNo=cs.getString(cs.getColumnIndex("COLORNO"));
				mCountList=cs.getString(cs.getColumnIndex("INLIST"));
	        	anumber = mSplitColorNo.split("，"); //取得各色號字串
	        	anames = mSplitColor.split("，");
	        	asizes = mSplitSizes.split(",");
	        	acountlist = mCountList.split("，");
	        	ColNoSizN=anumber.length*asizes.length;				
	        	ColNoSiz= new String[ColNoSizN][3];
	        	Otott=new int[deptN+1][ColNoSizN*7]; 
				for (int i=0;i<deptN+1;i++){
					for (int j=0;j<ColNoSizN*7;j++){
							Otott[i][j]=0;
					}
				}
				
				int z=-1;
				for (int x=0;x<anumber.length;x++){
					String acnt[]=acountlist[x].split(",");
					for (int y=0;y<asizes.length;y++){
						z+=1; //0-5
					ColNoSiz[z][0]=anumber[x]; //COLOR
					ColNoSiz[z][1]=anames[x]; //UNIT1_COLOR_NAME
					ColNoSiz[z][2]=asizes[y]; //SIZE
					Otott[0][z*3]=Utilis.toInt(acnt[y]); //訂(存)
					}		        	
				}		        	

				mySqlBuf.delete(0, mySqlBuf.toString().length());
				//針對出貨單
				Cursor css=null;
				mySqlBuf.append("select USER,COLOR,SIZE,sum(UNIT20)")
				.append(" from qitems where GOODSNO='" + mGoods+"' and EMPNAME='"+mEdAdord.getText().toString()+"'")
				.append(" group by USER,COLOR,SIZE");
				css = db.rawQuery(mySqlBuf.toString(), null);
				if (css.getCount()>0){
					while (css.moveToNext()){
						for (int xi=0;xi<deptN;xi++){ //配貨中的出貨單,取回
							if (css.getString(0).equalsIgnoreCase(DepNo[xi])){  //對上門市代號
								for (int xj=0;xj<ColNoSizN;xj++){						
									if(css.getString(1).equalsIgnoreCase(ColNoSiz[xj][0]) && css.getString(2).equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色
											//配貨中的出貨單,存在原始記錄等待比對
											Otott[xi][ColNoSizN*6+xj]=Otott[xi][ColNoSizN*6+xj]+css.getInt(3);
											//也要存入正確陣列的[配貨欄位]
											Otott[xi][xj*3+2]=Otott[xi][xj*3+2]+css.getInt(3);
											//初始一定一模一樣 總倉已配量也要維護
											Otott[0][xj*3+2]=Otott[0][xj*3+2]+css.getInt(3);
									}
								}
							}
						}
					}
				}
				css.close();
		}
		
		Bitmap bm = Utilis.getLimitBitmap(Apicstr[position], 200,200);
		if (bm!=null){	
			reflactionBitmap = createReflectionBitmap(bm);
			mImage.setImageBitmap(reflactionBitmap);
			AnimationSet animation = new AnimationSet(true);
			animation.addAnimation(new AlphaAnimation(0.0F, 1.0F));
			animation.addAnimation(new TranslateAnimation(30, 0, 10, 0));
			animation.setDuration(1000);
			mImage.startAnimation(animation);
		}

		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(GalleryViewVP.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(GalleryViewVP.this, "SYS", "IMPORT", 2)+File.separator+"qmtrio.php";
							HttpPost httpRequest = new HttpPost(uriAPI);
							// Post運作傳送變數必須用NameValuePair[]陣列儲存
							
							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){
					//將Qdetail訂貨量 放入
				mySqlBuf.delete(0, mySqlBuf.toString().length());
				//總倉進貨各色尺寸件數,必然在各色尺寸俱全(畢竟為源起資料)貨品建檔
				mySqlBuf.append("select COLOR,SIZE,UNIT1,sum(UNIT10)")
				.append(" from qitems where GOODSNO='" + mGoods+"' and ISCONFIRM='Y'")
				.append(" group by COLOR,SIZE,UNIT1");
				Cursor cs1 = db.rawQuery(mySqlBuf.toString(), null);
				if (cs1.getCount()>0){
					while (cs1.moveToNext()){
						for (int xj=0;xj<ColNoSizN;xj++){						
							if(cs1.getString(0).equalsIgnoreCase(ColNoSiz[xj][0]) && cs1.getString(1).equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色
									Otott[0][ColNoSizN*3+xj*3]=Otott[0][ColNoSizN*3+xj*3]+cs1.getInt(3); //進貨(累積存貨)
							}
						}
					}
				}
				cs1.close();
		mySqlBuf.delete(0, mySqlBuf.toString().length());
		//針對出貨單
		mySqlBuf.append("select USER,DEPTNO,COLOR,SIZE,sum(UNIT20)")
		.append(" from qitems where GOODSNO='" + mGoods+"' and ISCONFIRM='Y'")
		.append(" group by USER,DEPTNO,COLOR,SIZE");
		Cursor cs2 = db.rawQuery(mySqlBuf.toString(), null);
		if (cs2.getCount()>0){
			while (cs2.moveToNext()){
				for (int xi=0;xi<deptN;xi++){ //xi  0總倉(也會有交易) 1門市 2....
					if (cs2.getString(0).equalsIgnoreCase(DepNo[xi])){  //對上門市代號
						for (int xj=0;xj<ColNoSizN;xj++){						
							if(cs2.getString(2).equalsIgnoreCase(ColNoSiz[xj][0]) && cs2.getString(3).equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色
								//門市進貨累計
								Otott[xi][ColNoSizN*3+xj*3]=Otott[xi][ColNoSizN*3+xj*3]+cs2.getInt(4);
								if (!cs2.getString(0).equalsIgnoreCase(Utilis.getIni(this,"SYS","DEPT",6))){
									//門市存貨&進貨累計
									Otott[xi][xj*3]=Otott[xi][+xj*3]+cs2.getInt(4);
								}
							}
						}
					}
				}
			}
		}
		cs2.close();
		//接下來門市出貨 20 21 兩段 UNIT 20
		mySqlBuf.delete(0, mySqlBuf.toString().length());
		//針對總倉或門市轉出單 及 銷貨單 及 留貨單   (暫存單要扣除實,存)
		mySqlBuf.append("select DEPTNO,COLOR,SIZE,sum(UNIT20),sum(UNIT30),sum(UNIT40)")
		.append(" from qitems where GOODSNO='" + mGoods+"' and (ISCONFIRM='Y' or ISCONFIRM='R')")
		.append(" group by DEPTNO,COLOR,SIZE");
		Cursor cs3 = db.rawQuery(mySqlBuf.toString(), null);
		if (cs3.getCount()>0){
			while (cs3.moveToNext()){
				for (int xi=0;xi<deptN;xi++){
					if (cs3.getString(0).equalsIgnoreCase(DepNo[xi])){  //對上門市代號
						for (int xj=0;xj<ColNoSizN;xj++){						
							if(cs3.getString(1).equalsIgnoreCase(ColNoSiz[xj][0]) && cs3.getString(2).equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色
								Otott[xi][xj*3+1]=Otott[xi][xj*3+1]+cs3.getInt(4)+cs3.getInt(5); //所有銷貨櫃員
								Otott[xi][ColNoSizN*3+xj*3]=Otott[xi][ColNoSizN*3+xj*3]-cs3.getInt(3)-cs3.getInt(4)-cs3.getInt(5);
							}
						}
					}
				}
			}
		}
		cs3.close();
		//還剩預購單未計入
		mySqlBuf.delete(0, mySqlBuf.toString().length());
		//針對預購 ISCHECK='Y' and ISCONFIRM<>'Y'
		mySqlBuf.append("select DEPTNO,COLOR,SIZE,sum(UNIT30),sum(UNIT40)")
		.append(" from qitems where GOODSNO='" + mGoods+"' and (ISCONFIRM<>'R' and ISCHECK='Y')")
		.append(" group by DEPTNO,COLOR,SIZE");
		Cursor cs4 = db.rawQuery(mySqlBuf.toString(), null);
		if (cs4.getCount()>0){
			while (cs4.moveToNext()){
				for (int xi=0;xi<deptN;xi++){
					if (cs4.getString(0).equalsIgnoreCase(DepNo[xi])){  //對上門市代號
						for (int xj=0;xj<ColNoSizN;xj++){						
							if(cs4.getString(1).equalsIgnoreCase(ColNoSiz[xj][0]) && cs4.getString(2).equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色
								Otott[xi][ColNoSizN*3+xj*3+1]=Otott[xi][ColNoSizN*3+xj*3+1]+cs4.getInt(3)+cs4.getInt(4); //門市預購
								Otott[xi][ColNoSizN*3+xj*3]=Otott[xi][ColNoSizN*3+xj*3]-cs4.getInt(3)-cs4.getInt(4); //門市預購扣除存貨
							}
						}
					}
				}
			}
		}
		cs4.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 {
        				if ((k%3)==1 )
        					mCountCell.put(i * 200 + k,""+Otott[i-2][k-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(this, tableRow,1, i);
				mLayoutRoot.addView(row);
			}
		}
		}
	db.close();
	cs.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 ){
				if (Hresult.indexOf("\r\n")>2){
					String Lines [] = Hresult.split("\r\n");
					String[] data;
					String[] dataH= Lines [0].split(",");
					//避開台頭0.1 的2筆
					for (int xx=2;xx<Lines.length;xx++){
						data= Lines [xx].split(",");
						for (int xi=0;xi<deptN;xi++){
							if (data[0].equalsIgnoreCase(DepNo[xi])){  //對上門市代號
								for (int jj=2;jj<dataH.length;jj+=3){ //第一組色號起迴圈
									for (int xj=0;xj<ColNoSizN;xj++){//檢查顏色/尺寸絕對位址
										if(dataH[jj].equalsIgnoreCase(ColNoSiz[xj][0]) && dataH[jj+2].equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色尺寸
											//應取得 進(訂) 銷(訂) 實(存)
											//改存為 進(存) 銷(訂) 配貨 
											//[[實]](存)
											int Value=Utilis.toInt(data[jj+2].substring(0,data[jj+2].indexOf("(")));
											Otott[xi][ColNoSizN*3+xj*3]=Otott[xi][ColNoSizN*3+xj*3]+Value; //進[[(存)]]
											if (xi!=0){//非總倉	//[進]-[出]
												Value=Utilis.toInt(data[jj].substring(0,data[jj].indexOf("(")))-Utilis.toInt(data[jj].substring(data[jj].indexOf("(")+1,data[jj].indexOf(")")));
												Otott[xi][xj*3]=Otott[xi][xj*3]+Value; //[[進]](存)
											}
											//銷
											Value=Utilis.toInt(data[jj+1].substring(0,data[jj+1].indexOf("(")));
											Otott[xi][xj*3+1]=Otott[xi][xj*3+1]+Value; //銷
											//訂
											Value=Utilis.toInt(data[jj+1].substring(data[jj+1].indexOf("(")+1,data[jj+1].indexOf(")")));
											Otott[xi][ColNoSizN*3+xj*3+1]=Otott[xi][ColNoSizN*3+xj*3+1]+Value;
										}
									}
								}
							}
						}
					}
				}
			}
		}
    	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 {
        				if ((k%3)==1 )
        					mCountCell.put(i * 200 + k,""+Otott[i-2][k-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(GalleryViewVP.this, tableRow,1, i);
				mLayoutRoot.addView(row);
			}
		}
		
	}
};

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

@SuppressWarnings("unused")
private void SAVEDATA(String ordNo,int mode){
/*
 常用的主貨號 顏色組 尺寸組 顏色編號組 
@@@應先全面檢查,是否有異動@@@
 參數應該是 (開始配貨)1正式單據存入 還是0(暫存)單存入
 0.先測試Otott[][]資料比對,若相符者,視為沒有異動
如有異動
1.採購單號 該會員有否出貨暫存單,並取得(出貨單號)及單頭既定資料
	並紀錄新單與否 如果為新單,建立單頭既定資料
2.依序讀取Otott[][]有異動者
先以mDeptOrd USER GOODSNO 搜尋 qitems 不存在時 INSERT
存在時UPDATE
3.只要有異動都需紀錄單號有異動,並直接維護recountHead
@@開始配貨,表示已從暫存單前進到正式單據
*/	
//mMode: 0 NN 1 YN
	
	
	for(int nRow = 3; nRow < mCountRow.size(); nRow++){
		//視為每個門市,逐一檢視
		int nCellKey = mCountRow.get(nRow);
		int Loca=-1;
		int isModify=0;
		int isModifyRow=0;
		
		//先檢查該門市該商品有無異動
		for(int i = 4 ; i < mSizeLink.size(); i+=3){
			Loca+=1;//取得顏色尺寸件數
			int valueN =Otott[nRow-2][i-2];
							
			if (valueN!=Otott[nRow-2][ColNoSizN*6+Loca]){
				isModifyRow=1;break;
			}
		}	
		
		if (isModifyRow==1){
		
				Loca=-1;
				int isExist=0;//預設為新單
				double Disc=100;
				String Deptno=mCountCell.get(nCellKey);
				//先確認該門市出貨單存在否,每個門市都要檢查 採購單號 門市代號 存在否
				int StepOk=1;
				
			    SQLiteDatabase db = Utilis.getDB(this);		
				Cursor cs = db.rawQuery("select * from QHEAD where USER='"+Deptno+"' and EMPNAME='"+mEdAdord.getText().toString()+"' and ISCONFIRM='N' and ISCHECK='N'", null);
				String Fields[]=new String [cs.getColumnCount()];
					if (cs.getCount()>0){
						cs.moveToFirst();
						for (int xx=0;xx<cs.getColumnCount();xx++)	Fields[xx]=cs.getString(xx);
						//取得單頭欄位	
						isExist=1;
					}else{isExist=0;
						//準備建立新單(這裡先不要建)  建立必要欄位
						Cursor csc = db.rawQuery("select CUSTNO,CUSTNAME,DISCOUNT,TRADETYPE from QCUST where CUSTNO='"+Deptno+"' and TR='20'", null);
						if (csc.getCount()>0){
							csc.moveToFirst();
							Fields[12]=csc.getString(0);//門市編號
							Fields[13]=csc.getString(1);//門市名稱
							Fields[14]=csc.getString(3);//交易方式
							Disc=csc.getDouble(2);//折數
							if (Disc<=1) Disc=100;
							Fields[1]="1004";
							Fields[2]="20";Fields[0]=Fields[2]; //TR QKIND
							Fields[3]=Utilis.getNFormno(this,Fields[2].substring(0,1));
							//Fields[4] 是件數"+合計"
							Fields[5]=DateUtil.getCurrentDateDb();//當日日期
							Fields[6]=DateUtil.getSystemTime().substring(2,14);//入檔時間
							Fields[7]="N";Fields[8]="N"; //暫存單
							Fields[10]="N20";//配貨預設櫃員代號
							Fields[11]=mEdAdord.getText().toString();
							Fields[15]=Utilis.getIni(this,"SYS","DEPT",6);
							for (int xx=16;xx<21;xx++) Fields[xx]="0";
							for (int xx=23;xx<29;xx++) Fields[xx]="0";
							Fields[21]="";Fields[22]="";
							Fields[29]="1";Fields[30]=mBankn;
							Fields[31]="0";Fields[33]="0";
							Fields[32]="";Fields[34]="";Fields[35]="";Fields[36]="";
						}else StepOk=0; //表示門市檔未建立完整
							csc.close();
						}			
				cs.close();
				
				if (StepOk==1){//到目前OK
						for(int i = 4 ; i < mSizeLink.size(); i+=3){
							Loca+=1;//取得顏色尺寸件數
							String mColor=ColNoSiz[Loca][0];
							String mColorName=ColNoSiz[Loca][1];
							String mSize=ColNoSiz[Loca][2];
							int valueN =Otott[nRow-2][i-2];
							String[] args = {Fields[3],mGoods+"-"+mColor+"-"+mSize};
							
							if (valueN!=Otott[nRow-2][ColNoSizN*6+Loca]){
								//表示有異動
								if (valueN==0 && isExist==1 ){
									//表示要刪除現有的QITEMS 至少有這張單號存在  條件:單號 貨品明細編號 次條件:USER  
									//db.execSQL("delete from qitems where FORMNO='"+Fields[3]+"' and GOODSNOS='"+(mGoods+"-"+mColor+"-"+mSize)+"'");
									db.delete(TbName.QITEMS, "FORMNO=? and GOODSNOS=?", args);
									isModify=1;
								}else{
								
									Cursor csg = db.rawQuery("select * from QDETAIL where GOODSNO='"+mGoods+"' order by MID desc LIMIT 1", null);
									
									if (csg.getCount()>0){//取得商品的 基本資料
										csg.moveToFirst();
										
										ContentValues value = new ContentValues();
										value.put("TR",Fields[0] );
										value.put("ID",Fields[1] );
										value.put("QKIND",Fields[2] );
										value.put("FORMNO",Fields[3] );
										value.put("HANDNO","+0");
										value.put("FORMDATE",Fields[5] );
										value.put("CREATEDATETIME",Fields[6] );
										value.put("ISCONFIRM",Fields[7] );
										value.put("ISCHECK",Fields[8] );
										//與QHEAD 差一欄
										value.put("EMPID",Fields[10] );
										value.put("EMPNAME",Fields[11] );
										value.put("USER",Fields[12] );
										value.put("USERNAME",Fields[13] );
										value.put("TRADETYPE",Fields[14] );
										value.put("DEPTNO",Fields[15] );
										value.put("GOODSNO",mGoods);
										value.put("GOODSNOS",mGoods+"-"+mColor+"-"+mSize);
										value.put("SOURCENO",csg.getString(csg.getColumnIndex("SOURCENO")));
										value.put("UNIT1",mColorName);
										value.put("UNIT2",csg.getString(csg.getColumnIndex("COLORNO")));
										value.put("UNIT",0);
										value.put("UNITPRICE",csg.getDouble(csg.getColumnIndex("P"+Fields[14])));
										value.put("DISCOUNT",Disc);//Double
										value.put("ACOST",""+valueN*csg.getInt(csg.getColumnIndex("P1")));
										value.put("RATE",1);
										value.put("RATEPRICE",0);
										value.put("REALSUM",0);
										value.put("SUBPRICE",valueN*Disc*csg.getDouble(csg.getColumnIndex("P"+Fields[14]))/100);
										value.put("P0",csg.getDouble(csg.getColumnIndex("P0")));
										value.put("P1",csg.getDouble(csg.getColumnIndex("P1")));
										value.put("P2",csg.getDouble(csg.getColumnIndex("P2")));
										value.put("P3",csg.getDouble(csg.getColumnIndex("P3")));
										value.put("P4",csg.getDouble(csg.getColumnIndex("P4")));
										value.put("P5",csg.getDouble(csg.getColumnIndex("P5")));
										value.put("COLOR",mColor);
										value.put("SIZE",mSize);
										value.put("ORDDATE","");
										value.put("FINEDATE","");
										value.put("BATCH",csg.getString(csg.getColumnIndex("BATCH")));
										value.put("SUPPLY",csg.getString(csg.getColumnIndex("SUPPLY")));
										int gtype = csg.getInt(csg.getColumnIndex("GOODSTYPE"));  //代號需轉換為文字
							        	int index = mTypeIdList.indexOf(gtype);
							        	if(index >= 0)
											value.put("GOODSTYPE",mTypeList.get(index));
							        	else {
							        		value.put("GOODSTYPE",csg.getString(csg.getColumnIndex("GOODSTYPE")));
							        	}
										value.put("GOODSNAME",csg.getString(csg.getColumnIndex("GOODSNAME")));
										value.put("COLORS",csg.getString(csg.getColumnIndex("COLOR")));
										value.put("SIZES",csg.getString(csg.getColumnIndex("SIZE")));
										value.put("UNIT10",0);
										value.put("UNIT20",valueN);
										value.put("UNIT30",0);
										value.put("UNIT40",0);
										value.put("PIC",csg.getString(csg.getColumnIndex("PIC")));
										value.put("PS","");
										value.put("SEASON",csg.getInt(csg.getColumnIndex("SEASON")));
										
										int gcountry= csg.getInt(csg.getColumnIndex("COUNTRY"));   //代號需轉換為文字
										int cindex = mCountryIdList.indexOf(gcountry);
										if(cindex>=0)
											value.put("COUNTRY",mCountryList.get(cindex));
										else 
											value.put("COUNTRY",csg.getString(csg.getColumnIndex("COUNTRY")));
										
										value.put("YEAR",csg.getString(csg.getColumnIndex("UNIT2")));
										
										 if (Otott[nRow-2][ColNoSizN*6+Loca]==0){//insert qitems
											long result = db.insert(TbName.QITEMS, null, value);
										}else{//update qitems
											long result = db.update(TbName.QITEMS, value,"FORMNO=? and GOODSNOS=?", args);
										}
										 isModify=1;
									} 
								 csg.close();
								}
								Otott[nRow-2][ColNoSizN*6+Loca]=valueN;								
							}
						}
						if (isModify>0){
							//recountHead
							StringBuffer mySqlBuf = new StringBuffer();
					//以上QHEAD完成維護,如下畫面 應收也要維護 ASUM 及 +件 -件				
		
								mySqlBuf.delete(0, mySqlBuf.toString().length());
								mySqlBuf.append("select sum(UNIT20) as UNITS");
								mySqlBuf.append(" from qitems where FORMNO ='" + Fields[3]+"'")
								.append(" and QKIND ='"+Fields[2]+"'");
								//if (myKind !=PItemKind.TR10) mySqlBuf.append(" and USER ='" + msCust+"'");
								//先算出的
								String mySql=mySqlBuf.toString();
								mySqlBuf.append("and UNIT20 >=0 ");
								
								Cursor cursory = db.rawQuery(mySqlBuf.toString(), null);									
								if (cursory.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
									cursory.moveToFirst();
									data.dInc=cursory.getInt(cursory.getColumnIndex("UNITS"));
								}else {
									data.dInc=0;
									}
								
								cursory.close();
								
								mySqlBuf.delete(0, mySqlBuf.toString().length());
								mySqlBuf.append(mySql); //共用片段
								
								mySqlBuf.append("and UNIT20 <0 ");
								
								Cursor cursorz = db.rawQuery(mySqlBuf.toString(), null);									
								if (cursorz.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
									cursorz.moveToFirst();
									data.dMic=cursorz.getInt(cursorz.getColumnIndex("UNITS"));				
								}else {
								data.dMic=0;
								}
								cursorz.close();
								
								double SUBP=0;
								
								mySqlBuf.delete(0, mySqlBuf.toString().length());
								mySqlBuf.append("select FORMNO,sum(UNIT20) as UNITS,sum(SUBPRICE) as SUBPRIS,");
								
								mySqlBuf.append("sum(ACOST) as ACOSTS from qitems")
								.append(" where FORMNO ='" +  Fields[3]+"'")
								.append(" and QKIND ='"+Fields[2]+"'");
								//if (myKind !=PItemKind.TR10) mySqlBuf.append(" and USER ='" + msCust+"'");
								mySqlBuf.append(" group by FORMNO" );
		
								Cursor cursorx = db.rawQuery(mySqlBuf.toString(), null);
								
								if (cursorx.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
									ContentValues value = new ContentValues();
									cursorx.moveToFirst();
		
									int PERS=Utilis.toInt(Utilis.getIni(this,"SYS", "SDB", 8));
									if (PERS==5){
										SUBP=Math.round(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS"))/10)*10;
									}else if (PERS==1){ //無條件捨去
										SUBP=Math.floor(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS"))/10)*10;
									}else if (PERS==9){ //無條件進入
										SUBP=Math.ceil(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS"))/10)*10;
									}else{ 
										SUBP=Math.round(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS")));
									}
									
									data.dAtot=cursorx.getDouble(cursorx.getColumnIndex("UNITS"));
									data.dCosts=Math.round(cursorx.getDouble(cursorx.getColumnIndex("ACOSTS")));
									if (data.dMic==0){
										data.mHandno="+"+data.dInc;
									}else {
										data.mHandno="+"+data.dInc+" "+data.dMic;
									}
									value.clear();
									
									value.put("TR",Fields[0] );
									value.put("ID",Fields[1] );
									value.put("QKIND",Fields[2] );
									value.put("FORMNO",Fields[3] );
									value.put("HANDNO",data.mHandno);
									value.put("FORMDATE",Fields[5] );
									value.put("CREATEDATETIME",Fields[6] );
									value.put("ISCONFIRM",Fields[7] );
									value.put("ISCHECK",Fields[8] );
									value.put("EMPID",Fields[10] );
									value.put("EMPNAME",Fields[11] );
									value.put("USER",Fields[12] );
									value.put("USERNAME",Fields[13] );
									value.put("TRADETYPE",Fields[14] );
									value.put("DEPTNO",Fields[15] );
									value.put("ORDCASH",Fields[16] );
									value.put("ORDCARD",Fields[17] );
									value.put("CASH",Fields[18] );
									value.put("CARD",Fields[19] );
									value.put("ATOT",Math.round(data.dAtot));
									value.put("ORDDATE",Fields[21] );
									value.put("FINEDATE",Fields[22] );
									value.put("ASUM",Math.round(SUBP));
									value.put("BSUM",Math.round(SUBP));
									value.put("BILLRATE",1 );
									value.put("COSTS",Math.round(data.dCosts));
									value.put("TURESUM",0 );
									value.put("DISMONEY",0 );
									value.put("BANKNO",Fields[29] );
									value.put("BANKNAME", mBankn);
									value.put("ATM",0 );
									value.put("ATMDATE","" );
									value.put("TRCASH",0 );
									value.put("PS","" );
									value.put("PS1","" );
									value.put("PS2","" );
		
									if (isExist==1){//更新QHEAD
										String[] args = {Fields[3],Fields[2],Fields[12]};
										long success = db.update(TbName.QHEAD, value,"FORMNO=? and QKIND LIKE ? and USER=?", args);
									} else {//insert
										long result = db.insert(TbName.QHEAD, null, value);
									}
							} else {  //讓單頭歸零,但是不離開
									db.execSQL("update qhead set TR='"+Fields[2]+"',ASUM=0,ATOT=0,COSTS=0,HANDNO='+0',ISCONFIRM='N',ISCHECK='N',FINEDATE='',ORDDATE='' where FORMNO='"+Fields[3]+"'");
							//會異動的有 HANDNO ASUM BSUM 
							}
							cursorx.close();			
						}
				}
				db.close();
		}
	}
	
	//nMode 1(開始配貨) 表示需寫入 ISCONFIRM='Y',ISCHECK='N'
	//完成所有單維護後 返回時,應結束
	
	if (mode==1){ 
		SQLiteDatabase db = Utilis.getDB(this);
	    
		db.execSQL("update qhead set TR='20',ISCONFIRM='Y',ISCHECK='N' where EMPNAME='"+mEdAdord.getText().toString()+"' and (ATOT>0)");
		db.execSQL("update qitems set TR='20',ISCONFIRM='Y',ISCHECK='N' where EMPNAME='"+mEdAdord.getText().toString()+"'");
		
		db.close();
		
		DBCloud.aa1_aa0_update_HI(this);
		
		finish();
	}
}
   	
public class TableRowView extends LinearLayout {  
    @SuppressWarnings("unused")
	public TableRowView(Context context, TableRow tableRow,int imode, int position) {  
        super(context);  
        this.setOrientation(LinearLayout.HORIZONTAL);
        String colStr="02";
        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) {
                		if(position >2) textCell.setOnClickListener(new Clickable(position,i));
                		if(position ==2){ 
                    		textCell.setBackgroundResource(R.drawable.keypad_green);
                    		textCell.setText("");
                    	}else{
                   		 	textCell.setBackgroundResource(R.drawable.keypad_blue2);
                    	}
                	}
                	
                }else  if(position > 0 && i ==0 && imode==0){  //
                	String colorN=DBUtil.ColorGetTxt(GalleryViewVP.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(GalleryViewVP.this,textCell.getText().toString());
                	String [] colors=colorN.split(";");
                	if (((i+1) %3)==0){	
                		colStr=textCell.getText().toString();
                		colorN=DBUtil.ColorGetTxt(GalleryViewVP.this,textCell.getText().toString());
                		colors=colorN.split(";");
                	}
               		if (((i+1) %3)==2){
               			textCell.setBackgroundResource(R.drawable.keypad_blue2);
               		}else{	
                		textCell.setBackgroundColor(Utilis.toInt(colors[2]));
               		}
                } else {
                	textCell.setBackgroundColor(Color.rgb(208, 208, 208));
                }
                
                addView(textCell, layoutParams);
                
        }  
        this.setBackgroundColor(Color.BLACK);
    }

}

class Clickable implements OnClickListener{
	private int mRow;
	private int mCell;
	Clickable(int row, int cell){
		mRow = row;
		mCell = cell;
	}
	@Override
	public void onClick(View v) {
		int id = v.getId();
		handleCount(id, mRow, mCell, mChoiceMode);
	}
}

private ProcessKeypadInput processListener = new ProcessKeypadInput();

class ProcessKeypadInput implements OnClickListener{
	@Override
	public void onClick(View v) {
		Utilis.runVibrate(GalleryViewVP.this);
		int id = v.getId();
		switch(id){
		case R.id.btn_number_0:
			processNumber("0");
			break;
		case R.id.btn_number_1:
			processNumber("1");
			break;
		case R.id.btn_number_2:
			processNumber("2");
			break;
		case R.id.btn_number_3:
			processNumber("3");
			break;
		case R.id.btn_number_4:
			processNumber("4");
			break;
		case R.id.btn_number_5:
			processNumber("5");
			break;
		case R.id.btn_number_6:
			processNumber("6");
			break;
		case R.id.btn_number_7:
			processNumber("7");
			break;
		case R.id.btn_number_8:
			processNumber("8");
			break;
		case R.id.btn_number_9:
			processNumber("9");
			break;
		case R.id.deptord: //顯示目前的配貨的清單
			if (nState==0){//批號->配貨單
				nState=1;
				updateListViewOrd(this,mEdAdord.getText().toString());
				if (records>=0)Display(0);

			}else{//配貨單->批號
				nState=0;
			    SQLiteDatabase db = Utilis.getDB(GalleryViewVP.this);
			    if (locates==1){
					Cursor cs = db.rawQuery("select MID,PIC,GOODSNO,BATCH from qdetail where BATCH='" + batch+"' order by MID desc", null);
					if (cs.getCount() > 0) {
						updateListView(cs);
						if (records>=0)Display(0);
					}
					cs.close();
			    }else{
					Cursor cs1 = db.rawQuery("select distinct MID,PIC,BATCH,GOODSNO from qdetail where GOODSNO in (select GOODSNO from qitems where FORMNO='"+batch+"') order by MID desc", null);
						if (cs1.getCount() > 0) {
							updateListView(cs1);
							if (records>=0)Display(0);
						}
					cs1.close();	
			    }
				db.close();
			}
			break;
		case R.id.auto_s: //自動配貨
			//一:取得各門市的配貨比二:算出本批採購量三:依如上均分
			onAutoAll();
			break;
		case R.id.btn_bsave: //暫存
			//一:取得各門市的配貨比二:算出本批採購量三:依如上均分
			SAVEDATA(mEdAdord.getText().toString(),0);
			break;
		case R.id.save_20: //開始配貨
			//不但要 檢查該筆商品是否已暫存
			SAVEDATA(mEdAdord.getText().toString(),1);
			//還要 使這次的配貨表 所有門市出貨單 都確認結帳
			
			break;
		case R.id.btn_opreate_plus:
			if(mCountMode == CountMode.PLUS){
				mCountMode = CountMode.NEGATIVE; // 負的
				((Button)findViewById(R.id.btn_opreate_plus)).setText("-");
				int value = Utilis.toInt(mBuf.toString());
				if(value > 0){
					mBuf.delete(0, mBuf.length());
					mBuf.append((0 - value));
				}
				mInput.setText(mBuf.toString());
			}else{
				mCountMode = CountMode.PLUS;	// 正的
				((Button)findViewById(R.id.btn_opreate_plus)).setText("+");
				try{
					int value = Utilis.toInt(mBuf.toString());
					if(value < 0){
						mBuf.delete(0, mBuf.length());
						mBuf.append((0 - value));
					}
					mInput.setText(mBuf.toString());
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			break;
		case R.id.btn_choice_cell:
			clearAllBackground();
			((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_count_focus);
			mChoiceMode = ChoiceMode.CELL;
			break;
		case R.id.btn_choice_row:
			clearAllBackground();
			((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_count_focus);
			mChoiceMode = ChoiceMode.ROW;
			break;
		case R.id.btn_choice_all:
			onSetAll();
			cleanNumber();
			break;
		case R.id.btn_choice_single:
			clearAllBackground();
			((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_count_focus);
			mChoiceMode = ChoiceMode.NORMAL;
			break;
		case R.id.btn_clean_number:
			cleanNumber();
			break;
		case R.id.btn_save_item:
			finish();
			break;
		}
	}
}

private void clearAllBackground(){
	((Button)findViewById(R.id.btn_choice_all)).setBackgroundResource(R.drawable.keypad_count2);
	((Button)findViewById(R.id.btn_choice_cell)).setBackgroundResource(R.drawable.keypad_count2);
	((Button)findViewById(R.id.btn_choice_row)).setBackgroundResource(R.drawable.keypad_count2);
	((Button)findViewById(R.id.btn_choice_single)).setBackgroundResource(R.drawable.keypad_count2);
}

public void processNumber(String number){
	if(mBuf.length() < 5){
		if(mBuf.length() > 0 && mBuf.charAt(0) == '0'){
			mBuf.delete(0, 1);
		}
		mBuf.append(number);
		mInput.setText(mBuf.toString());
	}else{
	    Toast.makeText(this, "超過顯示位數", Toast.LENGTH_SHORT).show();
	}
}

public void cleanNumber(){
	int len = mBuf.length();
	if(len > 0){
		mBuf.delete(0, len);
	}
//	mBuf.append("0");
	mInput.setText("0");
}

private void onSetAll(){
	// 去掉頭兩個值
	int nCellKey =0;
	for(int i = 4 ; i < mSizeLink.size(); i+=3){Otott[0][i-2]=0;}
	mAddValue = Utilis.toInt(mBuf.toString());
	for(int nRow = 3; nRow < mCountRow.size(); nRow++){
		nCellKey = mCountRow.get(nRow);
		for(int i = 4 ; i < mSizeLink.size(); i+=3){

				int value = Utilis.toInt(mCountCell.get(nCellKey + i));
				value = mAddValue;
				mCountCell.remove(nCellKey + i);
				mCountCell.put(nCellKey + i, String.valueOf(value));
				Otott[nRow-2][i-2]=value;
				Otott[0][i-2]=Otott[0][i-2]+value;
				TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + i);
				view.setText("" + value);
		}
	}
	
	 nCellKey = mCountRow.get(2);
	for(int i = 4 ; i < mSizeLink.size(); i+=3){
			mCountCell.remove(nCellKey + i);
			mCountCell.put(nCellKey + i, String.valueOf(Otott[0][i-2]));
			TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + i);
			view.setText("" + Otott[0][i-2]);
	}
}

private void onAutoAll(){
	// 自動配貨
	int nCellKey =0;
	for(int i = 4 ; i < mSizeLink.size(); i+=3){Otott[0][i-2]=0;}
	for(int nRow = 3; nRow < mCountRow.size(); nRow++){
		nCellKey = mCountRow.get(nRow);
		for(int i = 4 ; i < mSizeLink.size(); i+=3){
				int value =Otott[nRow-2][mSizeLink.size()-2+i-3];
				mCountCell.remove(nCellKey + i);
				mCountCell.put(nCellKey + i, String.valueOf(value));
				Otott[nRow-2][i-2]=value;
				Otott[0][i-2]=Otott[0][i-2]+value;
				TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + i);
				view.setText("" + value);
		}
	}
	
/*
	for(int i = 4 ; i < mSizeLink.size(); i+=3){Otott[0][i-2]=0;}
	for(int nRow = 3; nRow < mCountRow.size(); nRow++){
		nCellKey = mCountRow.get(nRow);
		for(int i = 4 ; i < mSizeLink.size(); i+=3){
			int TotInv=Otott[0][i-4]; //本次總倉採購量
				int value =(int)(Math.round(TotInv*DepLa[nRow-2]/DepLa[deptN+1]));
				mCountCell.remove(nCellKey + i);
				mCountCell.put(nCellKey + i, String.valueOf(value));
				Otott[nRow-2][i-2]=value;
				Otott[0][i-2]=Otott[0][i-2]+value;
				TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + i);
				view.setText("" + value);
				//如果有餘數,而且總倉不配時,全交給第一家門市
				if ((nRow+1)==mCountRow.size() && TotInv !=Otott[0][i-2] && DepLa[nRow-2]==0 && DepLa[0]<=0){
					int nCellKey1 = mCountRow.get(3);
					value=Utilis.toInt(mCountCell.get(nCellKey1+i))+(TotInv-Otott[0][i-2]);
					Otott[1][i-2]=value;
					mCountCell.remove(nCellKey1 + i);
					mCountCell.put(nCellKey1 + i, String.valueOf(value));
					Otott[0][i-2]=TotInv;
					view = (TextView)mLayoutRoot.findViewById(nCellKey1 + i);
					view.setText("" + value);
				}
		}
	}
*/	
	
	 nCellKey = mCountRow.get(2);
	for(int i = 4 ; i < mSizeLink.size(); i+=3){
			mCountCell.remove(nCellKey + i);
			mCountCell.put(nCellKey + i, String.valueOf(Otott[0][i-2]));
			TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + i);
			view.setText("" + Otott[0][i-2]);
	}

}



private void handleCount(int id, int row, int cell, int mode){
	mAddValue = Utilis.toInt(mBuf.toString());
	if(mode == ChoiceMode.NORMAL){
		int nCellKey = mCountRow.get(row);
		int value = Utilis.toInt(mCountCell.get(nCellKey + cell));
		if (mAddValue!=0){
			value += mAddValue;
		}else {
			value = mAddValue;
		}
		mCountCell.remove(nCellKey + cell);
		mCountCell.put(nCellKey + cell, String.valueOf(value));
		TextView view = (TextView)mLayoutRoot.findViewById(id);
//		String strValue = view.toString();
		view.setText("" + value);
	}else if(mode == ChoiceMode.ROW){
		int nCellKey = mCountRow.get(row);
		// 去掉頭兩個值
		for(int i = 3 ; i < mSizeLink.size(); i++){
			if ((i%3)==1){
				int value = Utilis.toInt(mCountCell.get(nCellKey + i));
				value = mAddValue;
				mCountCell.remove(nCellKey + i);
				mCountCell.put(nCellKey + i, String.valueOf(value));
				TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + i);
				view.setText("" + value);
			}	
		}
		cleanNumber();
	}else if(mode == ChoiceMode.CELL){
		for(int nRow = 3; nRow < mCountRow.size(); nRow++){
			int nCellKey = mCountRow.get(nRow);
			int value = Utilis.toInt(mCountCell.get(nCellKey + cell));
				value = mAddValue;
			mCountCell.remove(nCellKey + cell);
			mCountCell.put(nCellKey + cell, String.valueOf(value));
			TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + cell);
			view.setText("" + value);
		}
		cleanNumber();
	}else if(mode == ChoiceMode.ALL){
		// 去掉頭兩個值
		for(int nRow = 3; nRow < mCountRow.size(); nRow++){
			int nCellKey = mCountRow.get(nRow);
			for(int i = 4 ; i < mSizeLink.size(); i+=3){
				//if ((i%3)==1){
					int value = Utilis.toInt(mCountCell.get(nCellKey + i));
					value = mAddValue;
					mCountCell.remove(nCellKey + i);
					mCountCell.put(nCellKey + i, String.valueOf(value));
					TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + i);
					view.setText("" + value);
				//}
			}
		}
		cleanNumber();
	}
	//無條件存入Ottot[][] 1-3 是配貨欄位

	for(int i = 4 ; i < mSizeLink.size(); i+=3){Otott[0][i-2]=0;}
	int nCellKey =0;
	for(int nRow = 3; nRow < mCountRow.size(); nRow++){
		 nCellKey = mCountRow.get(nRow);
		//總倉配貨欄小計
		for(int i = 4 ; i < mSizeLink.size(); i+=3){
				int value = Utilis.toInt(mCountCell.get(nCellKey + i));
				Otott[nRow-2][i-2]=value;
				Otott[0][i-2]=Otott[0][i-2]+value;
		}
	}
	
	 nCellKey = mCountRow.get(2);
	for(int i = 4 ; i < mSizeLink.size(); i+=3){
			mCountCell.remove(nCellKey + i);
			mCountCell.put(nCellKey + i, String.valueOf(Otott[0][i-2]));
			TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + i);
			view.setText("" + Otott[0][i-2]);
	}
}

	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();
	}

}
