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.Locale;
import java.util.Set;

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;
import com.cwbuyer.main.AIncomePc;
import com.cwbuyer.main.AItem;
import com.cwbuyer.main.APos.PItemKind;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.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.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
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({ "UseSparseArrays", "InflateParams" })
@SuppressWarnings("deprecation")
public class GalleryView 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 TextView mTextView06;
	private TextView mTextView07;
	private TextView mTextView08;
	private TextView mTextView09;
	private TextView mTextView10;
	private TextView mTextView11;
	
  	private LinearLayout lTableView = null;
	private LinearLayout mLayoutRoot = null;
	
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+	 File.separator + "CWBuyer"  ;
	String uriAPI=null;
	public ItemData iData;	

	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>();
	
	private ArrayList<String> mArrayColorNumber = new ArrayList<String>();
	private ArrayList<String> mArrayColorName = new ArrayList<String>();
	
	LinkedList<String> mSizeLink = new LinkedList<String>();
	LinkedList<String> mSizeLink1 = new LinkedList<String>();	
	LinkedList<String> mColorLink = new LinkedList<String>();
	
	HashMap<Integer,Integer> mCountRow = new HashMap<Integer,Integer>(); // 列資料
	HashMap<Integer,String> mCountCell = new HashMap<Integer,String>();  // 行資料

	int nState=0;
	int nPart=0;
	int version = 1;
	int records = 0;
	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 isPass=5;
	int deptN=1;
	String [] DepNo;
	String [] DepNa;
	String mDept=Utilis.getIni(this,"SYS","DEPT",1);
	private int [][] Oinlist;
	private String msFno ="";
	private String msFdate=DateUtil.getCurrentDateDb(); //預設取得單子的日期
	private int isNew=0;
	
	int Otot[][];  //本批號的訂量
	int Otott[][];	//全部訂量
	String [][] ColNoSiz;
	String[] menu_Z={"追蹤","補印條碼","切換庫存分析","商品編輯","(輸出)單筆傳送雲端","調整定價","網頁附圖編輯輸出","瀏覽附圖(分享LINE WeChat MAIL 雲端列印)","預購留貨清單","快速編圖ZZZ","返回" };
	String[] menu_X={"追蹤","補印條碼","切換庫存分析","商品編輯","(輸出)單筆傳送雲端","調整定價","網頁附圖編輯輸出","瀏覽附圖(分享LINE WeChat MAIL 雲端列印)","預購留貨清單","快速編圖ZZZ","返回" };
	String[] menu_Y={"追蹤","----------","切換庫存分析","--------","--------","返回" };
	
	private final int RESULT_AITEM = 1200;
	private final int RESULT_AINCOME = 1201;
	
	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
	int Wheight;
	int Wwidth;
	int tableHeight=30;
	int tabless=6;
	
	//For Cloud
	public ProgressDialog myDialog = null;
	protected static final int REFRESH_DATA = 0x00000001;
	private final int RESULT_GALLERYO=5566; 		//GALLERY 
	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);
			}
		}else if (requestCode == RESULT_GALLERYO) {
			DBCloud.aa0_aa1_auto_HI(this,30);
		}else if (requestCode == RESULT_AINCOME) {
			if (resultCode == RESULT_OK) {
				int total = data.getIntExtra("item_impo", 0);
				// 需避免資料下次傳過去
				String TSIZE = data.getStringExtra("item_size");
				String TCOLOR = data.getStringExtra("item_color");
				String TCOLORNO = data.getStringExtra("item_colorno");
				String TINLIST = data.getStringExtra("item_countlist");
				String [] InListC=TINLIST.split("，");
				String[] Asize=TSIZE.split(","); 
				String[] Acolor=TCOLOR.split("，");
				String[] Acolorno=TCOLORNO.split("，");
				int [][] aList=new int [Acolorno.length][Asize.length];
				int isSame=1;
				for (int xx=0;xx<Acolorno.length;xx++){
					String[] Inlist=InListC[xx].split(",");
					for (int xy=0;xy<Asize.length;xy++){
						aList[xx][xy]=Utilis.toInt(Inlist[xy]);
						if (Oinlist[xx][xy]!=aList[xx][xy]) isSame=0;
					}
				}//已上取得各色尺寸的訂單件數
				if (isNew==1 && total ==0){;}else{
					SQLiteDatabase db = Utilis.getDB(this);
					if (isNew==1 && total !=0){
						msFdate=DateUtil.getCurrentDateDb();
						msFno = Utilis.getNFormno(this,"1");
					}
					if (isNew==0 && isSame==0) db.execSQL("delete from qitems where FORMNO='"+msFno+"' and GOODSNO='"+iData.GoodsNo+"'");
					int Atot=0;
					double Asum=0;
					Cursor cs;
							cs=db.rawQuery("select * from qdetail where BATCH='"+iData.batch+"' and GOODSNO='"+iData.GoodsNo+"'",null);
						if (cs.getCount()>0){
							cs.moveToFirst();
							iData = DBUtil.CItem.parseData(cs, false);
							if (total!=0){
							for (int ji=0;ji<Acolorno.length;ji++){ //逐一讀取顏色代號,顏色名稱
								for (int jk=0;jk<Asize.length;jk++) { //逐一讀取尺寸
									ContentValues value = new ContentValues();
									value.put("TR", "10");
									value.put("ID","10");										
									value.put("QKIND","10" );
									value.put("HANDNO",iData.batch);
									value.put("GOODSNO",iData.GoodsNo);
									value.put("SOURCENO",iData.sourceNo);
									value.put("GOODSNOS",iData.GoodsNo+"-"+Acolorno[ji]+"-"+Asize[jk]);
									//GOODSTYPE須先換回文字
									int gtype = iData.nGoodsType;  //代號需轉換為文字
						        	int index = mTypeIdList.indexOf(gtype);
						        	if(index >= 0){	value.put("GOODSTYPE",mTypeList.get(index));	}
						        	else {
						        		value.put("GOODSTYPE",String.valueOf(iData.nGoodsType));
						        	}																			
									value.put("GOODSNAME",iData.goodsname);
									value.put("COLORS",TCOLOR);
									value.put("SIZES",TSIZE);//去掉前後雙引號
									value.put("COLOR",Acolorno[ji]);
									value.put("SIZE",Asize[jk]);
									value.put("UNIT1",Acolor[ji]);
									value.put("UNIT2",TCOLORNO);
									value.put("UNIT10",aList[ji][jk]);
									value.put("UNIT20",0);
									value.put("UNIT30",0);
									value.put("UNIT40",0);
									value.put("SUPPLY",iData.supply);
									value.put("USER",iData.supply);
									value.put("BATCH",iData.batch);
									value.put("FORMNO",msFno);  
									value.put("RATE",iData.dBillRate);
									value.put("P0",iData.dP0);
									value.put("P1",iData.dP1);
									value.put("P2",iData.dP2);
									value.put("P3",iData.dP3);
									value.put("P4",iData.dP4);
									value.put("P5",iData.dP5);
									value.put("PIC",iData.pic1);
									value.put("SEASON",iData.nSeason);
									int gcountry = iData.nCountry;  //代號需轉換為文字
						        	int cindex = mCountryIdList.indexOf(gcountry);
						        	if(cindex >= 0){	value.put("COUNTRY",mCountryList.get(cindex));}
						        	else {
						        		value.put("COUNTRY",iData.country);
						        	}																			
									value.put("EMPID",iData.nUnit1); //櫃員統計要用 EMPNAME
									value.put("YEAR",iData.nUnit2);
									value.put("CREATEDATETIME",DateUtil.getSystemTime().substring(2,12)); 
									value.put("FORMDATE",msFdate);
									value.put("DISCOUNT",100.0); //預設為100.0折數
									value.put("UNITPRICE",iData.dP0);
									value.put("TRADETYPE","0"); //外幣
									
									value.put("ACOST",iData.dP0*aList[ji][jk]);
									value.put("SUBPRICE",iData.dP0*aList[ji][jk]);
									value.put("RATEPRICE",iData.dP0*aList[ji][jk]);
									value.put("ISCONFIRM","N");
									value.put("ISCHECK","N");
									value.put("DEPTNO",Utilis.getIni(this,"SYS","DEPT",1));
									db.insert(TbName.QITEMS, null, value);
//									long result = db.insert(TbName.QITEMS, null, value);
									//完成了QITEMS存檔後
								}
							}	
						}	
					}
						cs.close();
							//製作QHEAD
							//先求出 qitems _total's
							Cursor cs1=db.rawQuery("select sum(UNIT10),sum(SUBPRICE) from qitems where FORMNO='"+msFno+"' and QKIND='10'",null);
							if (cs1.getCount()>0){
								cs1.moveToFirst();
								Atot=cs1.getInt(0);
								Asum=cs1.getDouble(1);
							}
							cs1.close();
							ContentValues value = new ContentValues();
							value.put("TR", "10");
							value.put("ID","10");										
							value.put("QKIND","10" );
							value.put("HANDNO","+"+Atot);
							//GOODSTYPE須先換回文字
							value.put("USER",iData.supply);
							value.put("FORMNO",msFno);  
							value.put("CREATEDATETIME",DateUtil.getSystemTime().substring(2,12));
							value.put("FORMDATE",msFdate);
							value.put("TRADETYPE","0"); //外幣			
							value.put("EMPID",iData.nUnit1);
							value.put("EMPNAME",iData.batch);
							value.put("BILLRATE",iData.dBillRate);
							value.put("USER",iData.supply);
							value.put("DEPTNO",Utilis.getIni(this,"SYS","DEPT",1));
							value.put("ATOT",Atot);
							value.put("ASUM",Asum);
							value.put("BSUM",Asum);
							value.put("CASH",0);
							value.put("CARD",0);
							value.put("ORDCASH",0);
							value.put("ORDCARD",0);
							value.put("DISMONEY",0);
							value.put("TURESUM",Asum);
							value.put("COSTS",Asum);
							value.put("ISCONFIRM","N");
							value.put("ISCHECK","N");
							if (isNew==1){ //INSERT
								db.insert(TbName.QHEAD, null, value);
							}else{ //update
								String[] args = {msFno,"10"};
								db.update(TbName.QHEAD, value,"FORMNO=? and QKIND=?", args);
							}
							db.close();
							Display(positions);
				}
			}

		}				
				// 需避免資料下次傳過去
//				mData.mSizes = data.getStringExtra("item_size");
	}

	
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		 isPass=AppUtil.isRegSucceed(this,1);
		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Wwidth = dm.widthPixels;
        Wheight = dm.heightPixels;
//		Wheight = this.getWindowManager().getDefaultDisplay().getHeight();
//		Wwidth = this.getWindowManager().getDefaultDisplay().getWidth();
		
		setContentView(R.layout.gallerys);
		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);

		if (Wwidth<=480 && Wheight<=800  ) {// GI9000
			mImage.getLayoutParams().width=270;
			mImage.getLayoutParams().height=350;
			mGallery01.getLayoutParams().height=120;
			
		} else  if (Wwidth<=600 && Wheight<=1000  ) {// HTC EVO 3D G_NOTE			
			mImage.getLayoutParams().width=330;
			mImage.getLayoutParams().height=450;
			mGallery01.getLayoutParams().height=120;
			tabless=8;
		} else  if (Wwidth<=576 && Wheight<=1024  ) {// HTC EVO 3D G_NOTE			
			mImage.getLayoutParams().width=400;
			mImage.getLayoutParams().height=500;
			mGallery01.getLayoutParams().height=120;
			tabless=8;
		} else  if (Wwidth<=600 && Wheight<=1018  ) {// HTC EVO 3D G_NOTE			
			mImage.getLayoutParams().width=400;
			mImage.getLayoutParams().height=500;
			mGallery01.getLayoutParams().height=120;
			tabless=8;
		} else  if (Wwidth<=800 && Wheight<=1000  ) {// ACER	_7.9"
			mImage.getLayoutParams().width=500;
			mImage.getLayoutParams().height=500;
			mGallery01.getLayoutParams().height=120;
			tableHeight=24;
			tabless=10;
		} else  if (Wwidth<=800 && Wheight<=1280  ) {// HTC EVO 3D G_NOTE			
			mImage.getLayoutParams().width=500;
			mImage.getLayoutParams().height=600;
			mGallery01.getLayoutParams().height=120;
			tableHeight=38;
			tabless=8;
		} else  if (Wwidth<=900 && Wheight<=1600  ) {// HTC EVO 3D G_NOTE			
			mImage.getLayoutParams().width=500;
			mImage.getLayoutParams().height=700;
			mGallery01.getLayoutParams().height=250;
			tableHeight=30;
			tabless=10;
//		} else  if (Wwidth<=1080 && Wheight<=1920  ) {// HTC EVO 3D G_NOTE			
		} else  if (Wwidth<=1200 && Wheight<=1920  ) {// HTC EVO 3D G_NOTE			
			mImage.getLayoutParams().width=550;
			mImage.getLayoutParams().height=800;
			mGallery01.getLayoutParams().height=250;
			tableHeight=60;
			tabless=6;
			
		} else  if (Wwidth<=1440 && Wheight<=2560  ) {// HTC EVO 3D G_NOTE			
			mImage.getLayoutParams().width=800;
			mImage.getLayoutParams().height=1200;
			mGallery01.getLayoutParams().height=250;
			tableHeight=100;
			tabless=10;

		} else {//平板 GTP3100 A10
			mImage.getLayoutParams().width=550;
			mImage.getLayoutParams().height=800;
			mGallery01.getLayoutParams().height=250;
			tableHeight=50;
			tabless=10;
		}
			

    	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);
		mTextView06 = (TextView) findViewById(R.id.textViewg6);
		mTextView07 = (TextView) findViewById(R.id.textViewg7);
		mTextView08 = (TextView) findViewById(R.id.textViewg8);
		mTextView09 = (TextView) findViewById(R.id.textViewg9);
		mTextView10 = (TextView) findViewById(R.id.textViewg10);
		mTextView11 = (TextView) findViewById(R.id.textViewg11);
		if (PSWD!=0) mTextView08.setVisibility(View.INVISIBLE);
		
        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];
        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 cs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		cs=db.rawQuery("select CUSTNO,CUSTNAME 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];
			cs.moveToFirst();
			for (int i=0;i<cs.getCount();i++){
				DepNo[i+1]=cs.getString(0);
				DepNa[i+1]=cs.getString(1);
				cs.moveToNext();
			}
		}else{
			deptN=1;
			DepNo=new String[deptN];
			DepNa=new String[deptN];
		}
		DepNo[0]=Utilis.getIni(this,"SYS","DEPT",6);
		DepNa[0]=Utilis.getIni(this,"SYS","DEPT",7);
		cs.close();
	if (nState==0){//採購明細依批號	
		mySqlBuf.append("select MID,PIC,GOODSNO,BATCH from qdetail");
		mySqlBuf.append(" where BATCH='" + batch+"'");
		mySqlBuf.append(" order by MID desc");
		Cursor cs1 = db.rawQuery(mySqlBuf.toString(), null);

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

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

		mGallery01.setOnItemClickListener(new Gallery.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long ids) {
				// TODO Auto-generated method stub
				if (nState==0){
					Display(position);
				}else {
					Display(position);
					DisplayPart0(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.isShown()){
//					mEdSearch.setVisibility(View.INVISIBLE);					
//				}else {
//					mEdSearch.setVisibility(View.VISIBLE);	
//				}
				if (mEdSearch!=null && mEdSearch.length()>0){
					Locale locale = Locale.ENGLISH;
				aInput=mEdSearch.getText().toString().toUpperCase(locale);
				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){
							Locale locale = Locale.ENGLISH;
						aInput=mEdSearch.getText().toString().toUpperCase(locale);
						searched(aInput);
						return true;
						}
					}
			}
			return false;
			}
			
		});

		//製作一組畫面 多功能的
		//補印條碼/追蹤/返回該批號單
		mImage.setOnClickListener(new ImageView.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (nState==0) menu_X=menu_Z; else menu_X=menu_Y;
				
				Utilis.runVibrate(GalleryView.this);
				DialogUtilis.showDialog(GalleryView.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(GalleryView.this, QHis.class);
										startActivity(intent);
										
									break;	
									}
									case 1: //補印條碼
									{
										if (nState==0){
											SQLiteDatabase db = Utilis.getDB(GalleryView.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", Utilis.toInt(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.getInt(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.getDouble(cs.getColumnIndex("P0")));
												intent.putExtra("discount", 100.0);
												if (isOnkey==1)
													intent.setClass(GalleryView.this, AIncomePc.class);
												else
													intent.setClass(GalleryView.this, AIncome.class);
												startActivity(intent);
												
												startActivity(intent);
											}
										
											db.close();
											cs.close();
										}else{
											Toast.makeText(GalleryView.this,"庫存分析不可以補印條碼,請切換回產品資訊!!" , Toast.LENGTH_SHORT).show();				
										}
									break;	
									}
									case 2: //切換庫存分析
									{
										if (nState==0){
											nState=1;
											DisplayPart0(positions);
										}else {
											nState=0;
											Display(positions);
										}
									break;	
									}
									case 3:  //商品編輯
									{
										if (isPass<6 && isPass!=3 && isPass!=4){
											if (nState==0 && PSWD!=1){//只有採購+權限
												Utilis.runVibrate(GalleryView.this);
												Intent intent = new Intent();
												intent.setClass(GalleryView.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);
											}
										}else {
												ProgressDialog mProgress = null;
											    mProgress = new ProgressDialog(GalleryView.this);
												mProgress.setCancelable(true);
												mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
												mProgress.setMessage("請檢查您的有效合約使用日期,如有疑問,請連繫CW:0933811753客服");			
												mProgress.show();
										}
									break;
									}
									case 4:  //make QIM
									{
										if (nState==0){//只有採購
											Intent intent = new Intent();
											intent.setClass(GalleryView.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;
									}
									case 5: //調整定價
									{
										mGoods=GoodsNo[positions];
										chgItems();
									break;
									}
									case 6: //
									{
										
										if (nState==0){
											Bundle bundle = new Bundle();
											Intent intent = new Intent();
											bundle = new Bundle();
											bundle.putString("GalleryChild",GoodsNo[positions]+","+0+",0");
											intent.setClass(GalleryView.this, GalleryViewWeb.class);
											intent.putExtras(bundle);
											startActivity(intent);
										}
										break;
									}
									case 7://
									{
										if (nState==0){
											Bundle bundle = new Bundle();
											Intent intent = new Intent();
											bundle = new Bundle();
											bundle.putString("MkqrList",GoodsNo[positions]+","+0+",0");
											intent.setClass(GalleryView.this, MkqrList.class);
											intent.putExtras(bundle);
											startActivity(intent);
										}
										break;
									}
									case 8:{
     										Intent intent = new Intent();
    					    				intent.putExtra("GalleryUser","");
    					    				intent.putExtra("GalleryGoods",GoodsNo[positions]);
    										intent.putExtra("GalleryDept",Utilis.getIni(GalleryView.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(GalleryView.this, GalleryViewO.class);
											startActivityForResult(intent, RESULT_GALLERYO);
										break;
									}
									case 9:{ //快速編圖
										//先拜訪ZZZ存在否
										//不存在時,再查詢最新的,複製到ZZZ
										//件數歸零
										//getData(mMid, null);
										SQLiteDatabase db = Utilis.getDB(GalleryView.this);
										Cursor cs=db.rawQuery("select GOODSNO from qdetail where BATCH='ZZZ' and GOODSNO='"+GoodsNo[positions]+"' order by MID DESC LIMIT 1",null);
										if (cs.getCount()==0){
											Cursor cs1=db.rawQuery("select MID from qdetail where GOODSNO='"+GoodsNo[positions]+"' order by MID DESC LIMIT 1",null);
											if (cs1.getCount()>0){
												cs1.moveToFirst();
												ItemData newData = DBUtil.CItem.getData(GalleryView.this, cs1.getInt(0), true);
												ContentValues value = new ContentValues();
												value.put("SUPPLY", newData.supply);
												value.put("SOURCENO", newData.sourceNo);
												value.put("GOODSNO", newData.GoodsNo);
												value.put("GOODSTYPE", newData.nGoodsType);
												value.put("GOODSNAME", newData.goodsname);
												value.put("UNIT1", newData.nUnit1);
												value.put("UNIT2", newData.nUnit2);
												value.put("BILL",newData.dBill);
												value.put("BILLRATE", newData.dBillRate);
												value.put("ADDCOST", newData.dAddCost);
												value.put("COUNTRY", newData.nCountry);
												value.put("BATCH", "ZZZ");
												value.put("P0", newData.dP0);
												value.put("P1", newData.dP1);
												value.put("P2", newData.dP2);
												value.put("P3", newData.dP3);
												value.put("P4", newData.dP4);
												value.put("P5", newData.dP5);
												value.put("CREATEDATETIME", DateUtil.getCurrentDateDb());
												value.put("PS", newData.mPS);
												value.put("SEASON", newData.nSeason);
												value.put("STATE", (newData.nState));
												value.put("UNIT",newData.nUnit);
												value.put("PIC",newData.pic1);
												value.put("PICTURE",newData.pic2);
												value.put("QUALITY_ID",newData.nQualityID);
												value.put("WASH_ID",newData.nWashID);
												value.put("IMPO",newData.nTotalCount);
												value.put("ACCOUNT",newData.nAccountId);
												value.put("COLOR",newData.mColors);
												value.put("COLORNO",newData.mColorsNo);
												value.put("SIZE",newData.mSizes);
												value.put("INLIST",newData.mCountList);
												 db.insert(TbName.QDETAIL, null, value);
											}
											cs1.close();
										}
										cs.close();
										db.close();
										break;
									}
								}
							}
					});
			}
		});
		
		
		
//回復 batch mid
		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+"/0916961962.png");}
		}
		return it;
	}

	private boolean getImageFile(String fName) {
		boolean re;

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

		/* 依附檔名的類型決定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(GalleryView.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的寬高 */
			 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 = 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(); }

	}

//事先整理出產地國別	
	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){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		dbs.close();
		dbs = null;
	}
	
	// 取得類別資料
	public void getTypeData(Context context){
		if(mTypeList != null){
			mTypeList.clear();
		}
		if(mTypeIdList != null){
			mTypeIdList.clear();
		}
		SQLiteDatabase dbs = Utilis.getDB(context);
		Cursor cursor = dbs.rawQuery("select GOODTYPE,_ID from qc_type order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						String name = cursor.getString(cursor.getColumnIndex("GOODTYPE"));
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						mTypeList.add(name);
						mTypeIdList.add(id);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		dbs.close();
		dbs = null;
	}
	
	
	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")));		
						mTextView02.setText(cs.getString(cs.getColumnIndex("GOODSNAME")));
						
						int gtype = cs.getInt(cs.getColumnIndex("GOODSTYPE"));  //代號需轉換為文字
				        	int index = mTypeIdList.indexOf(gtype);
				        	if(index >= 0){	mTextView03.setText(mTypeList.get(index));	}
				        	else {
				        		mTextView03.setText(cs.getString(cs.getColumnIndex("GOODSTYPE")));
				        	}
						
						int gcountry= cs.getInt(cs.getColumnIndex("COUNTRY"));   //代號需轉換為文字
							int cindex = mCountryIdList.indexOf(gcountry);
							if(cindex>=0){mTextView04.setText(mCountryList.get(cindex));}
							else {
								mTextView04.setText(cs.getString(cs.getColumnIndex("COUNTRY")));
							}
					
						mTextView05.setText(cs.getString(cs.getColumnIndex("BATCH")));
						mTextView06.setText(cs.getString(cs.getColumnIndex("SUPPLY")));		
						mTextView07.setText(cs.getString(cs.getColumnIndex("SOURCENO")));
						mTextView08.setText(""+cs.getString(cs.getColumnIndex("P1"))+""+cs.getString(cs.getColumnIndex("P0")));
						mTextView09.setText(""+cs.getString(cs.getColumnIndex("P2"))+""+cs.getString(cs.getColumnIndex("P3")));
						mTextView10.setText(""+cs.getString(cs.getColumnIndex("P4"))+""+cs.getString(cs.getColumnIndex("P5")));
						mTextView11.setText(cs.getString(cs.getColumnIndex("PS")));
					
			//新的一段處理顏色尺寸表-開始			
			//取得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();
			}
			
			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);
			}
			
			
			makeTable(mGoods,mSplitColorNo.toString(),mSplitColor.toString(),mSplitSizes.toString());			

		} //>0
		cs.close();
		db.close();
	}

	
private void DisplayPart0(int positionid) {//總倉直接解析QITEMS
		int position = positionid;
		mGoods=GoodsNo[position];
		Bundle bundle = new Bundle();
		Intent intent = new Intent();
		bundle = new Bundle();
		bundle.putString("GalleryChild",batch+";1;1");
		intent.setClass(GalleryView.this, GalleryViewS.class);
		intent.putExtras(bundle);
		startActivity(intent);
		
}


   	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]);
			    	}
				
			    	//努力歸零 very important
			    	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 i = 0; i <=mArrayColorName.size(); i ++){
					TableRowView row = new TableRowView(this, tableRow,0, i);
					mLayoutRoot.addView(row);
				}
		
		}
	}


private void chgItems(){
SQLiteDatabase db = Utilis.getDB(GalleryView.this);

StringBuffer mySqlBuf = new StringBuffer();
Cursor cursor = null;
//@@@為何要再寫入一次QHEAD
	//取得商品基本資訊
mySqlBuf.append("select  P2,P3,P5 from "+TbName.QITEMS);
mySqlBuf.append(" where GOODSNO='"+mGoods+"'");
mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT 1");
cursor = db.rawQuery(mySqlBuf.toString(), null);

if (cursor.getCount()>0){ //有此貨號存在
		cursor.moveToFirst();
	LayoutInflater factory = LayoutInflater.from(this);
	final View v1 = factory.inflate(R.layout.fcount, null);
	final EditText edtP3 = (EditText) v1.findViewById(R.id.edcount);
	final EditText edtP2 = (EditText) v1.findViewById(R.id.eduprice);
	final EditText edtP5 = (EditText) v1.findViewById(R.id.ediscount);
	final ImageView edtPic = (ImageView) v1.findViewById(R.id.imageV1);

	//edtCount.setBackgroundDrawable(d)
	//TextView01  TextView
	((TextView) v1.findViewById(R.id.TextView01)).setText("中盤價");
	((TextView) v1.findViewById(R.id.TextView02)).setText("批發價");
	((TextView) v1.findViewById(R.id.TextView03)).setText("零售價");
	
	edtP2.setText(cursor.getString(0));
	edtP3.setText(cursor.getString(1));  //dUnitprice
	edtP5.setText(cursor.getString(2));
	edtP2.requestFocus();
	edtPic.setImageBitmap(reflactionBitmap);
	final double OP2=cursor.getDouble(0);
	final double OP3=cursor.getDouble(1);
	final double OP5=cursor.getDouble(2);
	
	  new AlertDialog.Builder(this).setTitle(mTextView01.getText().toString()+"/"+mTextView02.getText().toString()+"\n"+"調整單價如下").setView(v1).setNeutralButton("確認改價格", new DialogInterface.OnClickListener() {
	      public void onClick(DialogInterface dialog, int which) {

	    	  double NP2=Utilis.toDouble(edtP2.getText().toString());
	    	  double NP3=Utilis.toDouble(edtP3.getText().toString());
	    	  double NP5=Utilis.toDouble(edtP5.getText().toString());
	    	  if(OP2!=NP2 || OP3!=NP3 || OP5!= NP5 ){
    			SQLiteDatabase dbU = Utilis.getDB(GalleryView.this);
	    		 dbU.execSQL("UPDATE qitems set P2="+NP2+",P3="+NP3+",P5=" +NP5+" where GOODSNO='" +mGoods+"'" );
	    		 dbU.execSQL("UPDATE qdetail set P2="+NP2+",P3="+NP3+",P5=" +NP5+" where GOODSNO='" +mGoods+"'" );
	    		 dbU.close();
	    		 
	    		 Display(positions);
	    		 Toast.makeText(GalleryView.this,"貨號:"+mGoods+"_已修改單價成功!" , Toast.LENGTH_SHORT).show();
	    	  }
	      }
	    }).setNegativeButton("放棄編輯", new DialogInterface.OnClickListener() {
		      public void onClick(DialogInterface dialog, int which) {

		      }
	    })
	    .show();
}
	  db.close();
	  cursor.close();
}


   	
public class TableRowView extends LinearLayout {  
    @SuppressWarnings("unused")
	public TableRowView(Context context, TableRow tableRow,int imode, int position) {  
        super(context);  
        this.setOrientation(LinearLayout.HORIZONTAL);
        String colStr="01";
        for (int i = 0; i < tableRow.getSize(); i++) { 
            TableCell tableCell = tableRow.getCellValue(i);  
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(  
                    tableCell.width, tableCell.height);  
            layoutParams.setMargins(0, 0, 1, 1);  
            TextView textCell = new TextView(context);  
                textCell.setLines(1);  
                textCell.setGravity(Gravity.CENTER);  
                textCell.setBackgroundColor(Color.WHITE);
                if(mCountRow.containsKey(position) == true){
                	int key = mCountRow.get(position);  //keep
                	if( mCountCell.containsKey(key + i)){
                		textCell.setText(String.valueOf(mCountCell.get(key + i))); //keep
                	}else{
                		textCell.setText("X");
                	}
                }else{
                	textCell.setText("X");
                }
                textCell.setId(position * 200 + i);
                textCell.setTextColor(Color.BLACK);
                if(position >=1 && i >= 2){
                	if ((i+2) %3==1){
                	textCell.setBackgroundResource(R.drawable.keypad_yellow);
                	} else if((i+2) %3==2) {
                    	textCell.setBackgroundResource(R.drawable.keypad_green);                    		
                	} else if((i+2) %3==0) {
                    	textCell.setBackgroundResource(R.drawable.keypad_blue2);                    		
                	}
                	
                }else  if(position > 0 && i ==0 && imode==0){  //
                	String colorN=DBUtil.ColorGetTxt(GalleryView.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(GalleryView.this,textCell.getText().toString());
                	String [] colors=colorN.split(";");
                	if (((i+1) %3)==0){	
                		colStr=textCell.getText().toString();
                		colorN=DBUtil.ColorGetTxt(GalleryView.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);
    }

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

}
