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 com.pwbuyer.main.R;
import com.cwbuyer.adapter.TableAdapter.TableCell;
import com.cwbuyer.adapter.TableAdapter.TableRow;
import com.cwbuyer.format.PItemData;
import com.cwbuyer.main.AIncome.ChoiceMode;
import com.cwbuyer.main.AIncome.CountMode;
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.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.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({ "UseSparseArrays", "DefaultLocale" })
@SuppressWarnings("deprecation")
public class GalleryViewV extends Activity {

	private Gallery mGallery01;
	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 Button BtMakeX2;
	private Button BtMakeXS;
	private Button BtMake0;
	private Button BtMakePlus;
  	private LinearLayout lTableView = null;
	private LinearLayout mLayoutRoot = null;
	
	private int mChoiceMode = ChoiceMode.NORMAL;
	private int mAddValue = 0;
	private StringBuffer mBuf = new StringBuffer();
	private int modify=0;
	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 nTopK=0;
	String	SerchKW="";
    String[] SerchK={"","GOODSNO","DEPTNO","GOODSTYPE","SUPPLY"};

    boolean AllOrSing=true;
    int locates =0;
	int nPart=0;
	int records = -1;
	int positions = 0;
	String mGoods="";
	private String[] deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");
	int PSWD=Utilis.toInt(deptStr[4]);

	int deptN=1;
	String [] DepNo;
	String [] DepNa;
	double [] DepLa;
	
	int Otot[][];  //本批號的訂量
	int Otott[][];	//全部訂量
	private int ColNoSizN=0;
	String [][] ColNoSiz;
	
	private int mCountMode = CountMode.PLUS;
	
	String[] SizeLength; 
	String[] ColLength;
	String[] numberLevel1;
	String[] numberLevel2;
	String strRes = "";
	String aInput=null;
	private String[] Apicstr; //圖檔名稱
	private String[] GoodsNo; //商品編號
	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;

	/** 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.galleryv);
		mGallery01 = (Gallery) findViewById(R.id.myGallery1);
		mImgBtnSearch = (ImageButton) findViewById(R.id.imageButton15);		
		mImgBtnRobk = (ImageButton) findViewById(R.id.imageButton16);
		mEdSearch =(EditText)findViewById(R.id.edSearch);
		
		//mGallery01.getLayoutParams().height=(int) (Wheight/7);
		mGallery01.getLayoutParams().height=(int) (Wheight/10);
		//if (Wwidth<=800) tabless=(int) (Wwidth/100)+2; else  tabless=(int) (Wwidth/140)+1;
		if (Wwidth<=800) tabless=(int) (Wwidth/100)+6; else  tabless=(int) (Wwidth/140)+5;
		//tableHeight=(int) (Wheight/22);
		tableHeight=(int) (Wheight/33);
		
    	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);
		BtMakeXS= (Button) findViewById(R.id.makexs);
		BtMake0= (Button) findViewById(R.id.make0);
		BtMakeX2= (Button) findViewById(R.id.makex2);
		BtMakePlus= (Button) findViewById(R.id.makeplus);

        ((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);
		BtMakeXS.setOnClickListener(processListener);
		BtMake0.setOnClickListener(processListener);
		BtMakeX2.setOnClickListener(processListener);
		BtMakePlus.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(";");
		SerchKW=arrayW[0];
        locates = Utilis.valuesInt(arrayW[1]);
        nTopK=Utilis.valuesInt(arrayW[2]);
        //1GOODSNO 2DEPTNO 3GOODSTYPE 4SUPPLY
        
        if (!deptStr[0].equalsIgnoreCase(deptStr[5])) nPart=1;  //門市版
        
		getTypeData(this);
		getCountryData(this);
        
        SQLiteDatabase db = Utilis.getDB(this);
		//Cursor cs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		//僅限zadord既存的門市範圍
		String DeptSQL="select CUSTNO,CUSTNAME,GPSLA from qcust where TR='20' and  CUSTNO <>'"+deptStr[5]+"' and CUSTNO in (select distinct DEPTNO from zadord) order by CUSTNO";
		if (nTopK==2) DeptSQL="select CUSTNO,CUSTNAME,GPSLA from qcust where TR='20' and  CUSTNO <>'"+deptStr[5]+"' and CUSTNO='"+SerchKW+"' "; 
			//針對單一門市配貨
			
		Cursor cs=db.rawQuery(DeptSQL,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]=deptStr[5];
		DepNa[0]=deptStr[6];
		Cursor cs1=db.rawQuery("select CUSTNO,CUSTNAME,GPSLA from qcust where TR='20' and  CUSTNO ='"+deptStr[5]+"'",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;
		
		//來自zadord
			mySqlBuf.append("select sum(UNIT33),sum(UNIT34), GOODSNO,PIC from zadord");
			if (nTopK>0) mySqlBuf.append(" where "+SerchK[nTopK]+"='"+SerchKW+"'");
			if (AllOrSing==false)  mySqlBuf.append(" and UNITEDIT<>0");
			mySqlBuf.append(" group by GOODSNO,PIC having sum(UNIT33)>0 order by sum(UNIT33) desc");
			Cursor cs2 = db.rawQuery(mySqlBuf.toString(), null);
			if (cs2.getCount() > 0) {
				updateListView(cs2);
				Display(0);
			} else {
				db.close();
	        	Intent intentS = new Intent();
	        	intentS.putExtra("GVP_modify",modify);
	        	GalleryViewV.this.setResult(RESULT_OK,intentS);
				finish();
			}
			cs2.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){
					SaveZord("");
					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;
			}
			
		});

		mImgBtnRobk.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//@@@保留給以批號拉出
				if (AllOrSing==true)
					AllOrSing=false;
				else AllOrSing=true;
		        StringBuffer mySqlBuf = new StringBuffer();
		        SQLiteDatabase db = Utilis.getDB(GalleryViewV.this);
				
				mySqlBuf.append("select sum(UNIT33),sum(UNIT34), GOODSNO,PIC from zadord");
				if (nTopK>0) mySqlBuf.append(" where "+SerchK[nTopK]+"='"+SerchKW+"'");
				if (AllOrSing==false){
					if (mySqlBuf.toString().indexOf("where")>0)
						mySqlBuf.append(" and UNITEDIT<>0");
					else
						mySqlBuf.append(" where UNITEDIT<>0");
				}
				mySqlBuf.append(" group by GOODSNO,PIC having sum(UNIT33)>0 order by sum(UNIT33) desc");
				//未來參用 倉存>?? 條件
				//mySqlBuf.append(" group by GOODSNO,PIC having sum(UNIT33)>0 and (sum(UNIT10)-sum(UNIT34)-sum(DSTK))>0 order by sum(UNIT33) desc");
				Cursor cs2 = db.rawQuery(mySqlBuf.toString(), null);
				if (cs2.getCount() > 0) {
					updateListView(cs2);
					Display(0);
				}
				cs2.close();
			db.close();
			}
		});
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
			SaveZord("");
        	Intent intentS = new Intent();
        	intentS.putExtra("GVP_modify",modify);
        	GalleryViewV.this.setResult(RESULT_OK,intentS);
			finish();
        }
        return true;
	}

	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 sum(UNIT33),sum(UNIT34),GOODSNO,PIC from zadord");
 		mySqlBuf.append(" where GOODSNO  like '%" + mEdS+ "%'");
 		if (nTopK>1)  mySqlBuf.append(" and "+SerchK[nTopK]+"='"+SerchKW+"'");
		if (AllOrSing==false) mySqlBuf.append(" and UNITEDIT<>0");

 		mySqlBuf.append( " group by GOODSNO,PIC order by sum(UNIT33) desc" );

		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 sum(UNIT33),sum(UNIT34),GOODSNO,PIC from zadord");
	 		mySqlBuf.append(" where GOODSNAME  like '%" + mEdS + "%'");
	 		if (nTopK>0)  mySqlBuf.append(" and "+SerchK[nTopK]+"='"+SerchKW+"'");
			if (AllOrSing==false)  mySqlBuf.append(" and UNITEDIT<>0");
	 		mySqlBuf.append(" group by GOODSNO,PIC order by sum(UNIT33) desc" );
			cs = null;
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				catched=1;
			}	
		} 
		if(catched<=0){
			Toast.makeText(GalleryViewV.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);
				Bitmap bm = Utilis.getLimitBitmap(lis.get(position).toString(), 60, 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(80, 100));
			}else {
				i.setLayoutParams(new Gallery.LayoutParams(160, 200));				
				}
			/* 設定Gallery背景圖 */
			i.setBackgroundResource(mGalleryItemBackground);
			/* 傳回imageView物件 */
			return i;
		}
	}
	
	
	private void updateListView(Cursor cs) {

		int record = -1;
		String PAYD="XXXX";
		if (cs.getCount() > 0) {
			Apicstr = new String[cs.getCount()];
			GoodsNo = new String[cs.getCount()];
			
//			cs.moveToFirst();
			while (cs.moveToNext()) {
				if ((PAYD.indexOf("'"+cs.getString(cs.getColumnIndex("GOODSNO"))+"'"))<0){
					record++;
					Apicstr[record] = cs.getString(cs.getColumnIndex("PIC"));				
					GoodsNo[record] = cs.getString(cs.getColumnIndex("GOODSNO"));
					PAYD=PAYD+"'"+GoodsNo[record]+"'";
				}
			}

		}

		records = record+1;

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

	
//事先整理出產地國別	
	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+"'  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 DEPTNO,GOODSNOS,SIZE,sum(DSTK),sum(UNIT21_20),sum(UNIT33),sum(UNIT34),sum(UNITEDIT)")
				.append(" from zadord where GOODSNO='" + mGoods+"'");
		 		if (nTopK>1)  mySqlBuf.append(" and "+SerchK[nTopK]+"='"+SerchKW+"'");
		 		mySqlBuf.append(" group by DEPTNO,GOODSNOS,SIZE");
				css = db.rawQuery(mySqlBuf.toString(), null);
				if (css.getCount()>0){
					while (css.moveToNext()){
						String ColorNo=css.getString(1).substring(css.getString(1).indexOf("-")+1,css.getString(1).lastIndexOf("-"));
						for (int xi=0;xi<deptN;xi++){ //配貨中的出貨單,取回
							if (css.getString(0).equalsIgnoreCase(DepNo[xi])){  //對上門市代號
								for (int xj=0;xj<ColNoSizN;xj++){
									//3sum(DSTK),4sum(UNIT21_20),5sum(UNIT33),6sum(UNIT34),7sum(UNITEDIT)
									if(ColorNo.equalsIgnoreCase(ColNoSiz[xj][0]) && css.getString(2).equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色
										if (!deptStr[5].equalsIgnoreCase(css.getString(0))){
											//只有門市擬配
											Otott[xi][ColNoSizN*6+xj]=Otott[xi][ColNoSizN*6+xj]+css.getInt(7);
											//配貨中的擬配UNITEDIT,存在原始記錄等待比對
											//也要存入正確陣列的[配貨欄位]
											Otott[xi][xj*3+2]=Otott[xi][xj*3+2]+css.getInt(7);
											//初始一定一模一樣 總倉已配量也要維護
											Otott[0][xj*3+2]=Otott[0][xj*3+2]+css.getInt(7);
											//Otott[0][i-2]=Otott[0][i-2]+value;
											//門市進存
											Otott[xi][xj*3]=Otott[xi][xj*3]+css.getInt(4); //進貨
											Otott[xi][ColNoSizN*3+xj*3]=Otott[xi][ColNoSizN*3+xj*3]+(css.getInt(3)); //進貨(累積存貨)
											//門市本(銷)
											Otott[xi][xj*3+1]=Otott[xi][xj*3+1]+css.getInt(5); //本銷
											Otott[xi][ColNoSizN*3+xj*3+1]=Otott[xi][ColNoSizN*3+xj*3+1]+(css.getInt(6)); //總銷
										}else{
											//總倉本(銷)
											Otott[xi][xj*3+1]=Otott[xi][xj*3+1]+css.getInt(5); //本銷
											Otott[xi][ColNoSizN*3+xj*3+1]=Otott[xi][ColNoSizN*3+xj*3+1]+(css.getInt(6)); //總銷
										}
									}
								}
							}
						}
					}
				}
				css.close();
		}
		
			if (cs.getCount()>0){
					//這裡取 總進貨 還要總倉存貨(UNIT10(總進)-(總銷)UNIT34-(店存)DSTK)
				mySqlBuf.delete(0, mySqlBuf.toString().length());
				//總倉進貨各色尺寸件數,必然在各色尺寸俱全(畢竟為源起資料)貨品建檔
				//不分門市算總量
				mySqlBuf.append("select GOODSNOS,SIZE,COLOR,sum(UNIT10),sum(UNIT34),sum(DSTK),sum(UNIT33)")
				.append(" from zadord where GOODSNO='" + mGoods+"'");
		 		mySqlBuf.append(" group by GOODSNOS,SIZE,COLOR");
				Cursor cs1 = db.rawQuery(mySqlBuf.toString(), null);
				if (cs1.getCount()>0){
					while (cs1.moveToNext()){
						String ColorNo=cs1.getString(0).substring(cs1.getString(0).indexOf("-")+1,cs1.getString(0).lastIndexOf("-"));
						for (int xj=0;xj<ColNoSizN;xj++){						
							if(ColorNo.equalsIgnoreCase(ColNoSiz[xj][0]) && cs1.getString(1).equalsIgnoreCase(ColNoSiz[xj][2])){  //對上顏色
									Otott[0][xj*3]=Otott[0][xj*3]+cs1.getInt(3); //進貨
									Otott[0][ColNoSizN*3+xj*3]=Otott[0][ColNoSizN*3+xj*3]+(cs1.getInt(3)-cs1.getInt(4)-cs1.getInt(5)); //進貨(累積存貨)
							}
						}
					}
				}
				cs1.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]);
	               			//if ((i==2) && k>3) mCountCell.put(i * 200 + k,""+Otott[0][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();
	}

   	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 SaveZord(String ordNo){
	    SQLiteDatabase db = Utilis.getDB(this);		
   		
   		for(int nRow = 3; nRow < mCountRow.size(); nRow++){
   			//視為每個門市,逐一檢視
   			int nCellKey = mCountRow.get(nRow);
   			int Loca=-1;
   			
   			//先檢查該門市該商品有無異動
   			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]){
   					//馬上執行 zadord  的UNITEDIT異動
   					String Deptno=mCountCell.get(nCellKey);
					String mColor=ColNoSiz[Loca][0];
					String mColorName=ColNoSiz[Loca][1];
					String mSize=ColNoSiz[Loca][2];
					String[] args = {Deptno,mGoods+"-"+mColor+"-"+mSize};
					ContentValues value = new ContentValues();
					value.put("UNITEDIT",valueN );
					int result = db.update("zadord", value,"DEPTNO=? and GOODSNOS=? and FDEPTNO='NEED' ", args);
					if (result==0){
						String SQLS="insert into zadord (DEPTNO,GOODSNO,GOODSNOS,GOODSNAME,GOODSTYPE,SUPPLY"+
								",COLOR,SIZE,COLORS,SIZES,PIC,AASTK,DSTK,UNIT10,UNIT21_20,UNIT33,UNIT34,FDEPTNO,UNITDEF,UNITEDIT) "+
								" select '"+Deptno+"',A.GOODSNO,'"+mGoods+"-"+mColor+"-"+mSize+"',A.GOODSNAME,A.GOODSTYPE,A.SUPPLY,A.COLOR,A.SIZE,A.COLORS,A.SIZES,A.PIC,"+
								"0,0,0,0,0,0,'NEED',0,"+valueN+" from zadord as A where GOODSNO='"+mGoods+"' order by '"+mGoods+"' limit 1";
						db.execSQL(SQLS);
						//表示異動失敗,不存在
						//需要產生新的資料
					}
					modify=1;
   				}
   			}
   		}
   		db.close();
   	}   	
   	
  	@SuppressWarnings("unused")
	private void SAVEDATA(int mode){
	    SQLiteDatabase db = Utilis.getDB(this);		
   		
   		for(int nRow = 3; nRow < mCountRow.size(); nRow++){
   			//視為每個門市,逐一檢視
   			int nCellKey = mCountRow.get(nRow);
   			int Loca=-1;

   			for(int i = 4 ; i < mSizeLink.size(); i+=3){
   				Loca+=1;//取得顏色尺寸件數
   				int valueN =Otott[nRow-2][i-2];
   				int valueO=valueN;
				//馬上執行 zadord  的UNITEDIT歸零
				String Deptno=mCountCell.get(nCellKey);
				String mColor=ColNoSiz[Loca][0];
				String mSize=ColNoSiz[Loca][2];
				String[] args = {Deptno,mGoods+"-"+mColor+"-"+mSize};
				ContentValues value = new ContentValues();
				if (mode==0){
					valueN=0;
				}else if (mode==1){
					if (valueN!=0)	valueN+=1;
				}else if (mode==2){
					valueN=valueN*2;
				}else if (mode==3){
	   				valueN =Otott[nRow-2][i-3];
				}
					value.put("UNITEDIT",valueN );
				
				if (valueN!=valueO){
					int result = db.update("zadord", value,"DEPTNO=? and GOODSNOS=? and FDEPTNO='NEED' ", args);
					modify=1;
				}
   			}
   		}
   		db.close();
		Display(positions);
   	}
   	
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(GalleryViewV.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(GalleryViewV.this,textCell.getText().toString());
                	String [] colors=colorN.split(";");
                	if (((i+1) %3)==0){	
                		colStr=textCell.getText().toString();
                		colorN=DBUtil.ColorGetTxt(GalleryViewV.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(GalleryViewV.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.makex2: //各配兩倍
			SAVEDATA(2);
			break;
			
		case R.id.make0: //配貨歸零
			SAVEDATA(0);
			break;
			
		case R.id.makexs: //依本銷配
			SAVEDATA(3);
			break;
			
		case R.id.makeplus://配各加一
			SAVEDATA(1);
			break;

		case R.id.btn_bsave: //暫存
			SAVEDATA(5);
			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();
			modify=1;
			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;
		}
	}
}

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

}
