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 com.cwbuyer.adapter.TableAdapter.TableCell;
import com.cwbuyer.adapter.TableAdapter.TableRow;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.ItemData;
import com.cwbuyer.format.PItemData;
import com.pwbuyer.main.R;
import com.cwbuyer.main.AIncome;
import com.cwbuyer.main.AIncomePc;
import com.cwbuyer.main.AItem;
import com.cwbuyer.main.APos;
import com.cwbuyer.main.APos.PItemKind;
import com.cwbuyer.main.QPosff;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
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.text.Editable;
import android.text.TextWatcher;
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.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

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

	private Gallery mGallery01;
	private ImageView mImage;
	private ImageButton mImgBtnSearch;
	private ImageButton mImgBtnRobk;
	private Button mBtnBrow; //展開色尺寸 //本單的流覽
	private Button mBtnNew; //建新品
	private Button mBtnDel;  //存檔後返回  //暢銷品流覽	
	private Button mBtnExit;  //返回貨單 
	private EditText mEdSearch;  //搜尋關鍵字
	private TextView mTextView01;	//貨號
	private TextView mTextView02;	//品名
	private TextView mTextView03;	//國別+定價
//	private Spinner spinColor;				//規範色盤
//	private Spinner spinSize;				//規範尺寸
	private TextView mTextView07; 		//單價
	private TextView mTextView08;		//折
	private TextView mTextView09;	//件數
	private TextView mTextView10;	//小計
	boolean bQHIS=false;
	int sQhis=0;
	private LinearLayout mLayoutRoot = null;
	private String [] DialogMenu={"追蹤","調整定價","補印條碼","網頁附圖編輯輸出","瀏覽附圖(分享LINE WeChat MAIL 雲端列印)","會員單一商品追蹤","預購留貨清單","返回"};	
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+	 File.separator + "CWBuyer"  ;
	private final String [] DISC  =Utilis.getIni(this, "QRP", "5X2QR",9).split("!&!");
	private final String[] backout =Utilis.getIni(this,"SYS","BACKOUT",9).split("!&!");
	
	private ArrayList<String> mArrayColorNumber = new ArrayList<String>();
	private ArrayList<String> mArrayColorName = new ArrayList<String>();
	
	LinkedList<String> mSizeLink = 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>();  // 尺寸欄資料

 	//5種狀態 0本單查詢1新增商品2編輯商品3暢銷品流覽(最好最近50款但有舊貨)4促銷品流覽(最差最久但有存貨50款)5最新商品(最後50款)參數設定
	String mTrade="5";
	String mDept="SOS";
	int pMode=1;	//0查詢 1新增 2編輯 單據目前的屬性,但會因G操作而改變
	int mMode=0; //0本單查詢 1.新增 2.編輯(指定商品) 3普4暢5促查
	int nKind=PItemKind.TR30; //預設為銷貨單  //外來將應用在廠商進貨 門市出貨 櫃員銷貨等
	String mKind=""+nKind;
	String Maxx=null;
	String aInput=null;
	int Source=0; //1 優先來源編號 02貨號
    int f123=0;  //0整數 1.小數點
	private final int RESULT_GALLERYO=5566; 		//GALLERY 
	int nUnit=0;
	int isUnit=0;
	int counts=0; 
	//保存商品原始資料,本區紀錄的目的是為了
	String fNo=null;  //單據編號 不可變  如果保持空白 代表永遠只能查詢(決不可以新增修改)	
	String mGoods=null;
	String mPics=null;
	String mTime=null;
	String mCountry=null;
	String mColor=null;  //單一顏色
	String mColorno=null;  //單一顏色
	String mySize=null; //單一尺寸
	double dDiscount=100;
	double dUnitprice=0;
	double dSubprice=0;
	double defDiscount=100;

	//供歷史價專用
	private double hisDiscount=100;
	private double hisUnitprice=0;
	private int nQhis=0; //標準價 =1.歷史價
	private double StdP0=0;
	private double StdP1=0;
	private String StdP5="";
	double units=0;
	double sumsubs=0;
	int nPart=0; //0總部 1分店
	int isIn = 0;  //0不存在該單 1存在
	int records = 0;
	int oposition = 0;
	String strRes = "";
	PItemData dataH;	
	//GalleryList專用的資料陣列
	private String[] Goods; //商品編號 
	private String[] Apicstr; //圖檔名稱
	private String[] Atime; //單價 
	private Bitmap reflactionBitmap; //提供畫布用
	
	//展開用的引用在庫存表
	private String mSplitSizes=null; //所有尺寸 L，XL
	private String mSplitColorNo=null; //顏色代號 01，02
	private String mSplitColor=null; //顏色 黑色，白色
	private String mSplitList=null; //異動的數字串
	private String[] anames;	
	private String[] anumber;
	private String[] asizes;
	private double[] attot;
	//原始的資料
		private double ounits=0; //原有的流覽商品   為了防範同一款號連續點閱 或重複點閱 影響異動 及有損資原
		private String oSplitList=null; //原有的數字串	
		private String oSplitList2=null; //進入brow前後有否異動
		private double oUnitprice=0; //原始的單價
		private double oDiscount=100; //原始的折數
	
	//狀態列:該會員姓名單號   [查詢中] [新增中] [編輯中] 
	
	private final int RESULT_INCOME = 1005;
	private final int RESULT_AITEM = 1200;
	
	int Wheight;
	int Wwidth;
	int tableHeight=30;
	int tabless=8;
	
	int modify=0;  //並未修改
	int localmodify=0;
	int change=1; //控制recount 手動自動update 7 8
	
	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.gallerysp);

		
		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);
		mBtnBrow=(Button) findViewById(R.id.btn_grybrow);		
		mBtnNew=(Button) findViewById(R.id.btn_newitem);		
		mBtnDel=(Button) findViewById(R.id.btn_grydel);
		mBtnExit=(Button) findViewById(R.id.btn_gryexit);
		
		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=600;
			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<=1200 && Wheight<=1920  ) {// HTC EVO 3D G_NOTE			
			mImage.getLayoutParams().width=550;
			mImage.getLayoutParams().height=800;
			mGallery01.getLayoutParams().height=250;
			tableHeight=60;
			tabless=8;
		} else  if (Wwidth<=1440 && Wheight<=2560  ) {// HTC EVO 3D G_NOTE			
			mImage.getLayoutParams().width=800;
			mImage.getLayoutParams().height=1200;
			mGallery01.getLayoutParams().height=300;
			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);
		mTextView07 = (TextView) findViewById(R.id.textViewg7);	//單價
		mTextView08 = (TextView) findViewById(R.id.textViewg8);	//折
		mTextView09 = (TextView) findViewById(R.id.textViewg9);	//件數
		mTextView10 = (TextView) findViewById(R.id.textViewg10);	//小計
		
    	mLayoutRoot = (LinearLayout)findViewById(R.id.root);
    	//[0]batch 關鍵字,可以是主貨號 明細貨號(編輯用)需搭配[4]mMode=2編輯
    	//[3]fNo單號 編輯時一定要指定
    	//[4] mKind nKind單別
    	//[5]mMode	//5種狀態 0本單查詢1新增商品2編輯商品3暢銷品流覽(最好最近50款但有舊貨)4促銷品流覽(最差最久但有存貨50款)5最新商品(最後50款)參數設定
    	//[6] Source  //0.優先判斷主貨號 1.優先判斷來源編號
    	
    	Bundle bundle = this.getIntent().getExtras();
		String fromW=bundle.getString("GalleryChild");
		String[] arrayW = fromW.split(",");
		String batch=arrayW[0]; //就是關鍵字
        nQhis = Utilis.toInt(arrayW[1]); //REC的指標
        sQhis=Utilis.toInt(backout[8]);
        dDiscount=Utilis.toDouble(arrayW[2]); //折數
       mTime=arrayW[8];
       // if (dDiscount<=0){dDiscount=100;}
        oDiscount=dDiscount;
        defDiscount=dDiscount;
        hisDiscount=dDiscount;
        fNo=arrayW[3]; //單號
        nKind=Utilis.toInt(arrayW[4]); //表示單別
        if (nKind<=0){nKind=PItemKind.TR30;} //如果非單據進來流覽時,預設為銷售 @@@有可能為31還要一段nPart
        mKind=""+nKind;
        //"UNIT"+mKind.substring(0,1)+"0" 件數
        //cs.getDouble(cs.getColumnIndex("P"+mTrade)) 該交易的單價
        mMode=Utilis.toInt(arrayW[5]); //表示0查詢(限某單) 1新增(不限某單) 2編輯(限單) 345所有商品查詢 6唯讀
        pMode=mMode;  //保存原來該單來的目的
        if (mMode==7 || mMode==8 || mMode==2 || mMode==3  || mMode==4) mMode=1;
        Source=Utilis.toInt(arrayW[6]);
        mDept=arrayW[7];  //指定門市

		//如果來自單據檔,先取得本單的資訊,否則都為345的查詢功能
        if (fNo.length()>0){
        	dataH=DBUtil.PItem.getData(GalleryViewP.this, fNo, mKind,true);
        	mTrade=""+dataH.nTrade;
        }
        if (!Utilis.getIni(this,"SYS","DEPT",1).equalsIgnoreCase(Utilis.getIni(this,"SYS","DEPT",6))) nPart=1;  //門市版
        
        if (Utilis.getIni(this,"SYS","SDB",7).equalsIgnoreCase("1")) f123=1; //需要小數位
        	
		if (QPosff.PSWD==1 && (nKind==10 || nKind==20 || nKind==21 )){
			mTextView03.setVisibility(View.INVISIBLE);	
			mTextView07.setVisibility(View.INVISIBLE);	//單價
			mTextView08.setVisibility(View.INVISIBLE);	//折
			mTextView10.setVisibility(View.INVISIBLE);	//小計
		}
		

        //初始必然執行
     	Maxx=Utilis.getIni(this,"HOST","MAXITEM",nKind/10);
		//Cursor cs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		
		if (pMode==2) {//編輯 限定單某商品,甚至帶入 顏色 尺寸(小範圍)
			//指的是 單筆編輯 @@@??? 無法
			mySqlBuf.append("select distinct GOODSNO,PIC,CREATEDATETIME from qitems")
			.append(" where FORMNO='"+fNo+"' and GOODSNO ='" + batch+"' and CREATEDATETIME='"+mTime+"' order by FORMDATE,CREATEDATETIME DESC LIMIT 1");

		}else if (pMode==0) {//pMode=0將該單所有商品流覽的功能
			mySqlBuf.append("select distinct GOODSNO,PIC,CREATEDATETIME from qitems")
			.append(" where FORMNO='"+fNo+"'");
			mySqlBuf.append(" and QKIND ='" + mKind+"'");			
			mySqlBuf.append(" order by GOODSNO ");
			
		}else if (pMode==1) {//在該單已輸入的關鍵字所有符合的商品
			mySqlBuf.append("select distinct GOODSNO,PIC,'0' from qitems");
			mySqlBuf.append(" where GOODSNO like  '%" + batch+"%'");
			mySqlBuf.append(" order by FORMDATE,CREATEDATETIME DESC LIMIT '"+Maxx+"'");  //最近交易的300筆

		}else if (pMode==3) {//來源編號
			mySqlBuf.append("select distinct GOODSNO,PIC,'0' from qitems");
			mySqlBuf.append(" where SOURCENO like '" + batch+"%'");
			mySqlBuf.append(" order by FORMDATE,CREATEDATETIME DESC LIMIT '"+Maxx+"'");  //最近交易的300筆
			pMode=2;
		}else if (pMode==6) {//pMode=6將該單所有商品流覽的功能,但是指限為讀
			mySqlBuf.append("select distinct GOODSNO,PIC,CREATEDATETIME from qitems")
			.append(" where FORMNO='"+fNo+"'");
			mySqlBuf.append(" and QKIND ='" + mKind+"'");			
			mySqlBuf.append(" order by GOODSNO ");  //最近交易的300筆
			mMode=0;
			
		}else if (pMode==7) {//在該單已輸入的關鍵字所有符合的商品
			mySqlBuf.append("select distinct GOODSNO,PIC,'0' from qitems");
			mySqlBuf.append(" where GOODSNAME like  '%" + batch+"%'");
			mySqlBuf.append(" order by FORMDATE,CREATEDATETIME DESC LIMIT '"+Maxx+"'");  //最近交易的300筆
			pMode=1; //因為這是由單據中帶來品名查詢特例
		}else if (pMode==8) {
			mySqlBuf.append("select distinct GOODSNO,PIC,'0' from qdetail");
			if (Source==0)
				mySqlBuf.append(" where GOODSNO ='" + batch+"'");
			else
				mySqlBuf.append(" where SOURCENO ='" + batch+"'");
				
			mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT 1");  //最近交易的300筆
			pMode=1; //因為這是由單據中帶來品名查詢特例
			
		}else if (pMode==5) {
			mySqlBuf.append("select distinct GOODSNO,PIC,'0' from qdetail");
			if (Source==0)
				mySqlBuf.append(" where GOODSNO like  '%" + batch+"%'");
			else
				mySqlBuf.append(" where SOURCENO like  '" + batch+"%'");

			mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT '"+Maxx+"'");  //最近交易的300筆
			pMode=1; //因為這是由單據中帶來品名查詢特例
			
		}else if (pMode==4) {//在Qdetail查到 SOURCENO
			mySqlBuf.append("select distinct GOODSNO,PIC,'0' from qdetail");
			mySqlBuf.append(" where GOODSNAME like  '%" + batch+"%'");
			mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT '"+Maxx+"'");  //最近交易的300筆
			pMode=1; //因為這是由單據中帶來品名查詢特例
		}else if (pMode==9) {
			mySqlBuf.append("select distinct GOODSNO,PIC,'0' from qdetail");
			mySqlBuf.append(" where PS like '%" + batch+"%'");
			mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT 300");  //最近交易的300筆
			pMode=1; //因為這是由單據中帶來品名查詢特例
			
		}	
		//@@@pMode==8 Qdetail 但是如何與下面銜接
        	SQLiteDatabase db = Utilis.getDB(this);
			Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
				if (cs.getCount() > 0) {
					//@@@Display(0);
					if (cs.getCount() >= Utilis.toInt(Maxx)) {
						Toast.makeText(GalleryViewP.this,"超過"+Maxx+"筆的部分無法顯示!請下次縮小範圍!" , Toast.LENGTH_SHORT).show();
			        	Intent intentS = new Intent();
			        	intentS.putExtra("GVP_modify",0);
			        	GalleryViewP.this.setResult(RESULT_OK,intentS);
			        	cs.close();
			        	db.close();
						finish();
					}else{
						updateListView(cs);
						Display(0,1);
					}
				}
				if (pMode!=0 && records==1)	visitAincome();
				
			cs.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
				Display(position,1);
				oposition=position;
				visitAincome();
			}
		});
		
		mGallery01.setOnItemLongClickListener(new OnItemLongClickListener(){

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				Utilis.runVibrate(GalleryViewP.this);
					Display(position,1);
					oposition=position;

				return true;
			}
		});

		mGallery01.setOnItemSelectedListener(new OnItemSelectedListener(){
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (arg2  != oposition){	
					Display(arg2,0);
					oposition=arg2;
					}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});		
		//製作一組畫面 多功能的
		//補印條碼/追蹤/返回該批號單
		mImage.setOnClickListener(new ImageView.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Utilis.runVibrate(GalleryViewP.this);
				if (QPosff.PSWD!=1) DialogMenu[7]="返回("+StdP1+StdP0+")";
				DialogUtilis.showDialog(GalleryViewP.this, "請選擇以下功能", -1,
						DialogMenu, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								switch (pos) {
									case 0: //商品追蹤
									{
										Intent intent = new Intent();
										intent.putExtra("QHis_kind", nKind);
										intent.putExtra("QHis_mode", 1);
										intent.putExtra("QHis_User","" );
										intent.putExtra("QHis_Goods",mGoods );
										intent.setClass(GalleryViewP.this, QHis.class);
										startActivity(intent);
										
									break;	
									}
									case 1: //調整價格
									{
										//影響 QITEMS 及 QDETAILS
										chgItems();
										break;	
									}
									case 2: //補印條碼
									{
										Intent intent = new Intent();
											intent.putExtra("mid", 0);
											intent.putExtra("batch", mGoods);									
											intent.putExtra("item_mode", 4); //3QDETAIL 4QITEMS
					 						intent.putExtra("cong", 1);
											intent.putExtra("unit", nUnit); //每手有幾段(童裝)
											intent.putExtra("size", mSplitSizes);
											intent.putExtra("colorno", mSplitColorNo);
											intent.putExtra("color", mSplitColor);
											intent.putExtra("countlist", mSplitList);
					 						intent.putExtra("mkind", mKind);
											intent.putExtra("unitprice", dUnitprice);
											intent.putExtra("discount", dDiscount);
											if (QPosff.isOnkey==1)
												intent.setClass(GalleryViewP.this, AIncomePc.class);
											else
												intent.setClass(GalleryViewP.this, AIncome.class);
											startActivity(intent);
										
									break;	
									}
									case 3: //網頁附圖
									{
										
											Bundle bundle = new Bundle();
											Intent intent = new Intent();
											bundle = new Bundle();
											bundle.putString("GalleryChild",mGoods+","+0+",0");
											intent.setClass(GalleryViewP.this, GalleryViewWeb.class);
											intent.putExtras(bundle);
											startActivity(intent);
										break;
									}
									case 4://瀏覽附圖
									{
											Bundle bundle = new Bundle();
											Intent intent = new Intent();
											bundle = new Bundle();
											bundle.putString("MkqrList",mGoods+","+0+",0");
											intent.setClass(GalleryViewP.this, MkqrList.class);
											intent.putExtras(bundle);
											startActivity(intent);
										break;
									}
									
									case 5: //單一會員商品追蹤
									{
										Intent intent = new Intent();
										intent.putExtra("QHis_kind", nKind);
										intent.putExtra("QHis_mode", 1);
										intent.putExtra("QHis_User",dataH.mUser );
										intent.putExtra("QHis_Goods",mGoods );
										intent.setClass(GalleryViewP.this, QHis.class);
										startActivity(intent);
										
									break;
									}	
									case 6: //預購留貨
									{
    										Intent intent = new Intent();
    					    				intent.putExtra("GalleryUser","");
    					    				intent.putExtra("GalleryGoods",mGoods);
    										String Dept=mDept;if (mDept.equalsIgnoreCase("SOS")) Dept=Utilis.getIni(GalleryViewP.this,"SYS","DEPT",1);
    					    				intent.putExtra("GalleryDept", Dept);
    					    				intent.putExtra("GalleryASK"," and GOODSNO='"+mGoods+"' ");
    					    				intent.putExtra("FormNo","");
    					    				intent.putExtra("GalleryQKIND",mKind);
    					    				intent.putExtra("GalleryMode",1);//0mUser 1mGoods 2KeepaToSale
    										intent.setClass(GalleryViewP.this, GalleryViewO.class);
											startActivityForResult(intent, RESULT_GALLERYO);
									break;	
									}
								}
							}
					});
			}
		});
		

//查詢 優先順序為 1.貨號 2.品名 3.類別 limit 300為最大值否則請縮小範圍		
		mImgBtnSearch.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (pMode<=2) {
					if (mEdSearch.getText().toString().length()>0){
							aInput=mEdSearch.getText().toString().toUpperCase();
						searched();
					}
				}	
			}
		});
		
//回復
		mImgBtnRobk.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//回復原始
				roback();
			}
		});
		
		mBtnDel.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//存入後返回單據 下面mMode chkMode()可以去掉
			if (pMode<=2) {				
				if (isIn==1)  { //表示有內容,就是要將該單同依商品先刪除
					SQLiteDatabase db = Utilis.getDB(GalleryViewP.this);					
					String[] args = {fNo,mKind,mGoods,mTime};
					db.delete(TbName.QITEMS, "FORMNO=? and QKIND=? and GOODSNO=? and CREATEDATETIME=?", args);
					db.close();
					modify=1;
					dDiscount=oDiscount;
					dUnitprice=oUnitprice;
					mSplitList=oSplitList;
					units=ounits=0;
					change=0;
					mTextView07.setText(""+dUnitprice);				
					mTextView08.setText(""+dDiscount);
					mTextView09.setText(""+units);
					mMode=1;
					Display(oposition,1);
					//reCount();					
					chkMode();
					
				}
				
//				mMode=0;
//				chkMode();
			}	
			}
		});
		

		mBtnNew.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Utilis.runVibrate(GalleryViewP.this);
				Intent intent = new Intent();
				intent.setClass(GalleryViewP.this,AItem.class);
				intent.putExtra("item_mode", AItem.ItemMode.ADD);
				intent.putExtra("item_mid", 0);
				if (Source==0)
					intent.putExtra("item_from", 2);
				else
					intent.putExtra("item_from", 3);
				//0.ManagerItem 1.GalleryView 2.GalleryViewP Goodsno 3.GalleryViewP Sourceno
				startActivityForResult(intent, RESULT_AITEM);
			}
		});

		mBtnBrow.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Display(oposition,1);
				visitAincome();
			}
		});
		
		mBtnExit.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mMode==2 ) {
					change=0;
					dDiscount=oDiscount;		mTextView08.setText(""+dDiscount);
					dUnitprice=oUnitprice;		mTextView07.setText(""+dUnitprice);
					mSplitList=oSplitList;
					units=ounits;		mTextView09.setText(""+units);
					//reCount();					
					mMode=1;
					chkMode();
				}else {	
		        	Intent intentS = new Intent();
		        	intentS.putExtra("GVP_modify",modify);
		        	GalleryViewP.this.setResult(RESULT_OK,intentS);
		        	finish();
				}
			}
		});
		
		
    	((TextView) findViewById(R.id.textViewg7)).addTextChangedListener(watcherPrice);
    	((TextView) findViewById(R.id.textViewg8)).addTextChangedListener(watcherPrice);
 
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){
				aInput=mEdSearch.getText().toString().toUpperCase();
				searched();
				return true;
			}else if (keyCode==KeyEvent.KEYCODE_ENTER){
				mEdSearch.requestFocus();
				return true;
			}
		}
		return false;
	}
	
});

mEdSearch.setOnFocusChangeListener(new View.OnFocusChangeListener(){
	  public void onFocusChange(View view, boolean hasFocus){
	    if(hasFocus){
			mEdSearch.getSelectionStart();
	    }
	  }
	});

mBtnBrow.setOnFocusChangeListener(new View.OnFocusChangeListener(){
	  public void onFocusChange(View view, boolean hasFocus){
	    if(hasFocus){
			mEdSearch.requestFocus();
	    } else {
	    }
	  }
	});


}		//end_program
	
private void visitAincome(){
	if (mSplitColorNo.indexOf("，")<0 && mSplitSizes.indexOf(",")<0)	{
		chkItems();

	}else{
		oSplitList2=mSplitList; //以檢測INCOME前後是否異動
		oUnitprice=dUnitprice;
		oDiscount=dDiscount;
		Intent  intent = new Intent();
		
		intent.putExtra("mid", 0);
		intent.putExtra("batch", mGoods);
		intent.putExtra("item_mode", 2); // 專為GalleryViewP打造使BTN_色寸不顯示 
		intent.putExtra("cong", 1);
		intent.putExtra("unit", nUnit); //每手有幾段(童裝)
		intent.putExtra("size", mSplitSizes);
		intent.putExtra("colorno", mSplitColorNo);
		intent.putExtra("color", mSplitColor);
		intent.putExtra("countlist", mSplitList);
		intent.putExtra("mkind", mKind);
		intent.putExtra("unitprice", dUnitprice);
		intent.putExtra("discount", dDiscount);
		if (QPosff.isOnkey==1)
			intent.setClass(GalleryViewP.this, AIncomePc.class);
		else
			intent.setClass(GalleryViewP.this, AIncome.class);
		
		startActivityForResult(intent, RESULT_INCOME);
	}	
}


private void savedata(){	
	if (pMode<=2 || pMode==8) {

		if 	(!oSplitList.equalsIgnoreCase(mSplitList) || oDiscount!=dDiscount || oUnitprice!=dUnitprice){
			if (fNo.length()>0){ //表示有單據存在,且已取得dataH
				
			SQLiteDatabase db = Utilis.getDB(GalleryViewP.this);
			
			StringBuffer mySqlBuf = new StringBuffer();
			ContentValues value = new ContentValues();
			APos.upDBH(GalleryViewP.this,2,fNo,value,dataH);
			//@@@為何要再寫入一次QHEAD
				//取得商品基本資訊

			mySqlBuf.append("select  * from "+TbName.QDETAIL);
			mySqlBuf.append(" where GOODSNO='"+mGoods+"'");
			mySqlBuf.append(" order by CREATEDATETIME DESC LIMIT 1");
			Cursor cursor = db.rawQuery(mySqlBuf.toString(), null);
			if (cursor.getCount()>0){ //有此貨號存在
				cursor.moveToFirst();
				ItemData dataI;
				dataI=DBUtil.CItem.parseData(cursor, true);
				value.put("ID",dataI.nState);
				value.put("QKIND",mKind);
				value.put("SUPPLY",dataI.supply);
				value.put("SOURCENO",dataI.sourceNo);
				value.put("GOODSNO",mGoods);
				
				Cursor csT=db.rawQuery("select GOODTYPE from qc_type where `_ID`="+dataI.nGoodsType, null);
				if (csT.getCount()>0){
					csT.moveToFirst();
					value.put("GOODSTYPE",csT.getString(0));
				}else{
					value.put("GOODSTYPE",dataI.nGoodsType);	
				}
				csT.close();
				
				value.put("GOODSNAME",dataI.goodsname);
				value.put("DISCOUNT",dDiscount );
				value.put("P1",dataI.dP1);
				value.put("P2",dataI.dP2);
				value.put("P3",dataI.dP3);
				value.put("P4",dataI.dP4);
				value.put("P5",dataI.dP5);
				value.put("ORDDATE",dataI.nUnit);
				value.put("RATE",dataI.dBillRate);		
				value.put("PIC",dataI.pic1);
				value.put("SEASON",dataI.nSeason);
				value.put("BATCH",dataI.batch);
				Cursor csC=db.rawQuery("select NAME from qc_country where _ID="+dataI.nCountry, null);
				if (csC.getCount()>0){
					csC.moveToFirst();
					value.put("COUNTRY",csC.getString(0));
				}else{
					value.put("COUNTRY",dataI.nCountry);	
				}
				csC.close();
				value.put("YEAR",dataI.nUnit2);
				StdP0=dataI.dP0;
				StdP1=dataI.dP1;
			
			}else{
				mySqlBuf.delete(0, mySqlBuf.toString().length());
				mySqlBuf.append("select  * from "+TbName.QITEMS);
				mySqlBuf.append(" where GOODSNO='"+mGoods+"'");
				//if (mTime.length()>1)	mySqlBuf.append(" and CREATEDATETIME='"+mTime+"'");
				mySqlBuf.append(" order by FORMDATE,CREATEDATETIME DESC LIMIT 1");
				Cursor cursor1 = db.rawQuery(mySqlBuf.toString(), null);
				
				if (cursor1.getCount()>0){ //有此貨號存在
					cursor1.moveToFirst();
					PItemData dataI;
					dataI=DBUtil.PItem.parseData(cursor1);
					
						//已在初始時取得dataH,upDBH填充了ITEMS中的HEAD相同欄位,放在value
						value.put("ID",dataI.nID);
							value.put("QKIND",mKind);
							value.put("SUPPLY",dataI.mSupply);
							value.put("SOURCENO",dataI.mSourceNo);
							value.put("GOODSNO",mGoods);
							value.put("GOODSTYPE",dataI.mGoodsType);
							value.put("GOODSNAME",dataI.mGoodsName);
							value.put("DISCOUNT",dDiscount );
							value.put("P1",dataI.dP1);
							value.put("P2",dataI.dP2);
							value.put("P3",dataI.dP3);
							value.put("P4",dataI.dP4);
							value.put("P5",dataI.dP5);
							value.put("ORDDATE",dataI.mOrddate);
							value.put("RATE",dataI.dRate);		
							value.put("PIC",dataI.mPic);
							value.put("SEASON",dataI.nSeason);
							value.put("BATCH",dataI.mBatch);
							value.put("COUNTRY",dataI.mCountry);
							value.put("YEAR",dataI.mYear);
							StdP0=dataI.dP0;
							StdP1=dataI.dP1;
					
				}
				cursor1.close();
			}
			if (isIn==1)  { //表示有內容,就是要將該單同依商品先刪除
				String[] args = {fNo,mKind.substring(0,1)+"%",mGoods,mTime};
				db.delete(TbName.QITEMS, "FORMNO=? and QKIND LIKE ? and GOODSNO=? and CREATEDATETIME=? ", args);
				
				value.remove("CREATEDATETIME");
				value.put("CREATEDATETIME", mTime);
			}
			
			cursor.close();
			
			anames = mSplitColor.split("，");								
			anumber = mSplitColorNo.split("，");
			asizes = mSplitSizes.split(",");
			value.put("UNIT2", mSplitColorNo);
			value.put("COLORS",mSplitColor);
			value.put("SIZES",mSplitSizes);
			
			ContentValues valueSTD =value;		
			
			String[] listh =mSplitList.split("，");
				for (int i=0;i<anames.length;i++){
					value=valueSTD;
					value.put("COLOR",anumber[i]);
					value.put("UNIT1",anames[i]);
					String [] listi =listh[i].split(",");
					for (int j=0;j<asizes.length;j++){
						if (Utilis.toInt(listi[j])!=0){ //表示該顏色尺寸有數量
							value.put("GOODSNOS",mGoods+"-"+anumber[i]+"-"+asizes[j]);
							value.put("SIZE",asizes[j]);
							value.put("ACOST",Utilis.dedb (Utilis.toInt(listi[j])*StdP1,3));
							value.put("UNIT10", 0);value.put("UNIT20", 0);value.put("UNIT30", 0);value.put("UNIT40", 0);
							value.remove("UNIT"+mKind.substring(0,1)+"0");
							if ((dataH.mIscheck !=null && dataH.mIscheck.equalsIgnoreCase("Y")) && (mKind.equalsIgnoreCase("30") || mKind.equalsIgnoreCase("31")) ) 
								value.put("UNIT",Utilis.toInt(listi[j]));
							else value.put("UNIT",0);
							
							value.put("UNIT"+mKind.substring(0,1)+"0",Utilis.toInt(listi[j]));
							value.put("UNITPRICE",dUnitprice);
							value.put("P0",StdP0);
							
							if (f123==0) value.put("SUBPRICE",Math.round(Utilis.toInt(listi[j])*dUnitprice*dDiscount/100));
							else value.put("SUBPRICE",Utilis.dedb (Utilis.toInt(listi[j])*dUnitprice*dDiscount/100, 2));
							
							String mPS="";
							if (bQHIS && listi[j].indexOf("-")<0) mPS="追";
							else if (listi[j].indexOf("-")>=0) mPS="退";
							if (dDiscount<100 && dDiscount>0) mPS=mPS+(int)dDiscount;
							value.put("PS",mPS);
							if (nKind!=10){
								String stkAt=DBUtil.getStk(this, db, nKind, dataH.mDeptno, dataH.mUser, mGoods+"-"+anumber[i]+"-"+asizes[j],Utilis.toInt(listi[j]));
								value.put("FINEDATE",stkAt);
								if (stkAt.indexOf("庫存不足")>0)
									Toast.makeText(GalleryViewP.this,stkAt , Toast.LENGTH_SHORT).show();
							}else{
								value.put("FINEDATE","");
							}
							db.insert(TbName.QITEMS, null, value);
						}
					}
				}
			valueSTD.clear();				
			value.clear();
			db.close();
			oSplitList = mSplitList;				
			}
			mMode=1;  //既然前面可以前進到此
			chkMode();
			Display(oposition,1);
			mEdSearch.requestFocus();
			mEdSearch.setText("");
			roback();
			PosUtilis.reCountHead(GalleryViewP.this,fNo,"",mKind,f123);
		}
	}	
}	
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	
	        	Intent intentS = new Intent();
	        	intentS.putExtra("GVP_modify",modify);
	        	GalleryViewP.this.setResult(RESULT_OK,intentS);
	        	finish();
          return true;
        }else{
        	
          return super.onKeyDown(keyCode, event);
        }
    }
	
 	
	private TextWatcher watcherPrice = new TextWatcher(){  
        @Override  
        public void afterTextChanged(Editable s) {  
        }  
        @Override  
        public void beforeTextChanged(CharSequence s, int start, int count,  
                int after) {  
        }  
        @Override  
        public void onTextChanged(CharSequence s, int start, int before,  
                int count) {
        		//Toast.makeText(GalleryViewP.this,"789啟動異動重運算!" , Toast.LENGTH_SHORT).show();
        	  	reCount();
        }  
    };
	
    private void reCount(){
		//只要有異動,就要維護
    	if (change==1) {
    		dUnitprice=Utilis.toDouble(mTextView07.getText().toString()); 								
			dDiscount=Utilis.toDouble(mTextView08.getText().toString());
    	}
    		change=1;
			if (f123==0) dSubprice=Math.round(dUnitprice*dDiscount*units/100);
			else dSubprice=Utilis.dedb (dUnitprice*dDiscount*units/100, 2 );
			mTextView10.setText(""+dSubprice);
		if (dDiscount != oDiscount || dUnitprice != oUnitprice || mSplitList !=oSplitList) {
			//表示異動了本筆資料 需關掉或啟動 BTNS
			mMode=2;  //控制重要的判斷
			modify=1;
			chkMode();
		}else {
			mMode=1;  //控制重要的判斷
			chkMode();
		}
								
	}

//---------------以上為應用在1&多欄位,又可觸動連動等運算------------------
	
	
	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+"/para/img_additem.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(){  //mMode(2)編輯狀態,不可執行 

	if (pMode<=2) {	
		SQLiteDatabase db = Utilis.getDB(this);
        //一致的搜尋規則
		Cursor cs = DBUtil.GVSQL(this,db,aInput,Source,0,0);
		
		if (cs.getCount()>0){
			updateListView(cs);
			Display(0,1);
		}else{
			Toast.makeText(GalleryViewP.this,"查無此商品!" , Toast.LENGTH_SHORT).show();
			mEdSearch.requestFocus();
		}
		
		if (records==1 && cs.getCount()==1){
			cs.moveToFirst();
			visitAincome();
		}
	cs.close();	
	db.close();
	}
	mEdSearch.setText("");
	}
	/* 改寫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
				i.setLayoutParams(new Gallery.LayoutParams(100, 120));
			}else {
				i.setLayoutParams(new Gallery.LayoutParams(200, 240));				
				}
			/* 設定Gallery背景圖 */
			i.setBackgroundResource(mGalleryItemBackground);
			/* 傳回imageView物件 */
			return i;
		}
	}
	
	private void updateListView(Cursor cs) {

		//以CREATEDATETIME 進行是否單內存在及價位
		int record = 0;
		if (cs.getCount() > 0) {
			Goods = new String[cs.getCount()];
			Apicstr = new String[cs.getCount()];
			Atime=new String[cs.getCount()];

			while (cs.moveToNext()) {
				Goods[record] = cs.getString(0);
				Apicstr[record] = cs.getString(1);
				Atime[record] = cs.getString(2);
				record++;
			}

		}

		records = record;

		if (records>0) {		
		mGallery01.setAdapter(new ImageAdapter(this, ChkPic()));		
		}

	}

	private void chkMode(){
		//未來有可能再加入其他的規則
		if (mMode==2){
			mBtnExit.setText("取消編輯");
		}else{
			mBtnExit.setText("返回單據");
		}
	}
	
//需顯示的欄位 1貨號 2品名 3售價 4產地 可編輯的(5色名 6尺寸 7單價 8折數 9件數 10小計
//因著單別不同 顯示欄位也不同
//@@如果該主貨商品在該單有多筆時,應以合計顯示,並關閉件數,只開放;單價;折選項	
	@SuppressWarnings("unused")
	private void Display(int positionid,int isListStk) {

		int position = positionid;  //可以讓畫面顯示另一個商品		
		oposition=position; //以檢測是否移動了G的ON
		ounits=units=0;
		dUnitprice=oUnitprice=0;
		hisDiscount=defDiscount;
		hisUnitprice=0;
		sumsubs=0;
		mGoods=Goods[position];
		mPics=Apicstr[position];
		mTime=Atime[position];
		//如果不為零 則視為單內商品
		//@@@不過 需再認證一次
		
		if (mPics==null || mPics.length()<=0) {
			mPics=filepath+"/para/img_additem.png";
		}else{
			File localFile = new File(mPics);
			if (!localFile.exists()){
				mPics=filepath+"/para/img_additem.png";
			}
		}
		
        SQLiteDatabase db = Utilis.getDB(this);		
		//Cursor cs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		int xChk=0;
		//先歸零
		mSplitSizes=""; //所有尺寸 L，XL
		mSplitColorNo=""; //顏色代號 01，02
		mSplitColor=""; //顏色 黑色，白色
		StdP0=0;StdP1=0;

			Cursor cst =db.rawQuery("select distinct COLORNO,COLOR,SIZE,UNIT,max(PS) from qdetail  where GOODSNO='" + mGoods+"'", null);
			if (cst.getCount()>0) {
				while (cst.moveToNext()){
					if (cst.getString(0).length()>mSplitColorNo.length()){
						mSplitColorNo=cst.getString(0);
						mSplitColor=cst.getString(1);
					}
					if (cst.getString(2).length()>mSplitSizes.length()) mSplitSizes=cst.getString(2);
					nUnit=cst.getInt(3);
					mCountry=cst.getString(4);
					xChk=1;
				}
			}
			cst.close();
		
		if (fNo.length()>0 && mMode<=2 ){//表示來自於單據,否則只能一般顯示
			
			//@@@關鍵在 同一GOODSNO 有可能因為單價折 不一致 而需分開顯示及編輯
			//若有兩種以上 則需 分開選擇確認
			mySqlBuf.delete(0, mySqlBuf.toString().length());
			mySqlBuf.append("select GOODSNO,GOODSNAME,COUNTRY,COLOR,SIZE,UNIT1,");
			mySqlBuf.append("UNITPRICE,P0,DISCOUNT,sum(SUBPRICE) as SUMSUB,");
			mySqlBuf.append("sum(UNIT"+mKind.substring(0, 1)+"0) as SUBUNIT ,CREATEDATETIME,P1");
			mySqlBuf.append(" from qitems  where GOODSNO='" + mGoods+"'  and FORMNO='"+fNo+"'");
			//if (mTime.length()>1)	mySqlBuf.append(" and CREATEDATETIME='"+mTime+"'");
			mySqlBuf.append(" and CREATEDATETIME='"+mTime+"'");
			mySqlBuf.append(" group by GOODSNO,GOODSNAME,COUNTRY,COLOR,SIZE,UNIT1,")
			.append("UNITPRICE,P0,DISCOUNT,CREATEDATETIME,P1");
			//一旦存在就一次完成所有需要的數據
			Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
		
			if (cs.getCount()>0){ //本單確實存在
				cs.moveToFirst();
						mMode=2;
						setTitle(mGoods+"編輯中!!");						
				isIn=1;  //表示本商品確定存在本單
				mTextView01.setText(cs.getString(cs.getColumnIndex("GOODSNO")));						
				mTextView02.setText(cs.getString(cs.getColumnIndex("GOODSNAME")));						
				dUnitprice=cs.getDouble(cs.getColumnIndex("UNITPRICE"));
				dDiscount=cs.getDouble(cs.getColumnIndex("DISCOUNT"));
				oUnitprice=dUnitprice;
				oDiscount=dDiscount;
				mTextView03.setText(cs.getString(cs.getColumnIndex("COUNTRY")));				
				StdP0=cs.getDouble(cs.getColumnIndex("P0"));				
				StdP1=cs.getDouble(cs.getColumnIndex("P1"));
	        	anumber = mSplitColorNo.split("，"); //取得各色號字串
	        	anames = mSplitColor.split("，");
	        	asizes = mSplitSizes.split(",");
	        	//即可得到3M 順序的陣列
	        	attot=new double[asizes.length*anumber.length];
	        	mTime=cs.getString(cs.getColumnIndex("CREATEDATETIME"));
	        	
				cs.moveToFirst();				
				for(int i=0;i<cs.getCount();i++){ //一一讀取每筆資料
					units=units+cs.getDouble(cs.getColumnIndex("SUBUNIT"));
					sumsubs=sumsubs+cs.getDouble(cs.getColumnIndex("SUMSUB"));
					
					for (int j=0;j<anumber.length;j++){
						for (int k=0;k<asizes.length;k++){
							if (anumber[j].equalsIgnoreCase(cs.getString(cs.getColumnIndex("COLOR")))){
								if (asizes[k].equalsIgnoreCase(cs.getString(cs.getColumnIndex("SIZE")))){
								attot[j*asizes.length+k]=attot[j*asizes.length+k]+cs.getDouble(cs.getColumnIndex("SUBUNIT"));
					}	}	}	}
					
					cs.moveToNext();
				}
		

			}else{	//一般查詢 單內不存在
				mMode=1;
				isIn=0; //確定本單不存在
				setTitle(mGoods+"新增中!!");				
			}
			cs.close();
		}else { //非來自單據	
		setTitle(mGoods+"流覽中!!");
			if (mMode==2){
			mMode=3;
			isIn=0;
			}
		}

	if (mMode!=2){//找尋歷史價
    	anumber = mSplitColorNo.split("，"); //取得各色號字串
    	anames = mSplitColor.split("，");
    	asizes = mSplitSizes.split(",");
    	attot=new double[asizes.length*anumber.length];
    	String qhisYear="";
    	int season=0;
    	//int aState=0;
    	
		mySqlBuf.delete(0, mySqlBuf.toString().length()); //清空
		mySqlBuf.append("select distinct GOODSNO,GOODSNAME,P0,P1,P2,P3,P4,P5,PS,");
		mySqlBuf.append("SEASON,UNIT2");
		mySqlBuf.append(" from qdetail");
		mySqlBuf.append(" where GOODSNO='" + mGoods+"' order by CREATEDATETIME DESC LIMIT 1");	
		Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){
			cs.moveToFirst();
			mTextView01.setText(mGoods);						
			mTextView02.setText(cs.getString(cs.getColumnIndex("GOODSNAME")));
			mCountry=cs.getString(cs.getColumnIndex("PS"));
			dDiscount=defDiscount;
			dUnitprice=cs.getDouble(cs.getColumnIndex("P"+mTrade));
			StdP0=cs.getDouble(cs.getColumnIndex("P0"));
			StdP1=cs.getDouble(cs.getColumnIndex("P1"));
			StdP5=cs.getString(cs.getColumnIndex("P5"));
			qhisYear=cs.getString(cs.getColumnIndex("UNIT2"));
			season=cs.getInt(cs.getColumnIndex("SEASON"));
		}else{
			mySqlBuf.delete(0, mySqlBuf.toString().length()); //清空
			mySqlBuf.append("select distinct GOODSNO,GOODSNAME,P0,P1,P2,P3,P4,P5,");
			mySqlBuf.append("SEASON,YEAR");
			mySqlBuf.append(" from qitems");
			mySqlBuf.append(" where GOODSNO='" + mGoods+"' order by FORMDATE,CREATEDATETIME DESC LIMIT 1");
			//可以思考 QDETAIL的直接拜訪,及最新資訊(依參數做優先考量)
			Cursor cs1 = db.rawQuery(mySqlBuf.toString(), null);
			if (cs1.getCount()>0){
				cs1.moveToFirst();
				mTextView01.setText(mGoods);						
				mTextView02.setText(cs1.getString(cs1.getColumnIndex("GOODSNAME")));						
				dUnitprice=cs1.getDouble(cs1.getColumnIndex("P"+mTrade));
				dDiscount=defDiscount;
				StdP0=cs1.getDouble(cs1.getColumnIndex("P0"));
				StdP1=cs1.getDouble(cs1.getColumnIndex("P1"));
				StdP5=cs1.getString(cs1.getColumnIndex("P5"));
				qhisYear=cs1.getString(cs1.getColumnIndex("YEAR"));
				season=cs1.getInt(cs1.getColumnIndex("SEASON"));
			}
			cs1.close();
		}
		cs.close();
			hisUnitprice=dUnitprice;
			hisDiscount=dDiscount;
			bQHIS=false;
			int checkP=0;
			if (mTextView02.getText().toString().indexOf("*")==0 && dDiscount>0)
				dDiscount=100;
			else {
				if (((sQhis==4 && dataH.nTrade==3) || (sQhis==5 && dataH.nTrade==5)) && nKind==31){
					bQHIS=Qhis(this,dataH.mUser,StdP5,qhisYear,season,1);
					if (bQHIS==true){
						dUnitprice=hisUnitprice;
						dDiscount=hisDiscount;
						checkP=1;
					}
				}
				if (checkP==0){//當對照表不存在時
					if (nQhis==1) //才有歷史價可言 
						bQHIS=Qhis(this,dataH.mUser,mGoods,qhisYear,season,0);
					 //確實找到OK
						if(nQhis==1 && bQHIS==true) {
						//單價折數比大小 決定 這次的價格
							dUnitprice=hisUnitprice;
							dDiscount=hisDiscount;
						}
				}	
				
			}
			mTextView03.setText(mCountry);				
			
    //區隔結束  是共同程式碼的開始    	
			
	}
				change=0;
				oUnitprice=dUnitprice;		mTextView07.setText(""+dUnitprice);
				oDiscount=dDiscount;		mTextView08.setText(""+dDiscount);				
				ounits=units;							mTextView09.setText(""+units);
				mTextView10.setText(""+sumsubs);
	if (isListStk>0){
	        if(mSplitSizes != null && mSplitSizes.length() > 0
	        		&& mSplitColorNo != null && mSplitColorNo.length() > 0
	        		&& mSplitColor != null && mSplitColor.length() > 0){
	        	
	        	mArrayColorNumber.clear();
	        	mArrayColorNumber.removeAll(mArrayColorNumber);
	        	mArrayColorName.clear();
	        	mArrayColorName.removeAll(mArrayColorName);
	        	
	        	for(int i = 0; i < anumber.length; i++){ 
	        		mArrayColorNumber.add(anumber[i]); //從numbers字串陣列 存入 List_mArrayColorNumber
	        	}
	        	String[] names = mSplitColor.split("，");
	        	for(int i = 0; i < names.length; i++){
	        		mArrayColorName.add(names[i]);
	        	}
    		
	        	//努力歸零 very important
	        	mLayoutRoot.removeAllViews(); //***************
        		mSizeLink.clear();
        		mCountRow.clear();	        		
        		mCountCell.clear();
        		
	        	mSizeLink.add("代碼"); // 顏色
	        	mSizeLink.add("顏色"); // 尺寸
	        	// 設定 Title 行 //使每個尺寸都有3格(進/銷/存)
	        	String ttot[] =new String[asizes.length*3*anumber.length] ; //進銷存統計用
	        	String ptot[] =new String[asizes.length*anumber.length] ;	//展開用
	        	for(int i = 0; i < asizes.length*3*anumber.length; i++){ttot[i]="";}
	        	for(int i = 0; i < asizes.length*anumber.length; i++){ptot[i]="";}
	        	for(int i = 0; i < asizes.length; i++){
	        		mSizeLink.add(asizes[i]+"進");
	        		mSizeLink.add(asizes[i]+"銷(訂)");
	        		mSizeLink.add(asizes[i]+"存");
	        	}
	        	// 設定初始Row 列
	        	for(int i = 0; i <= mArrayColorName.size(); i++){
	        		// 設定Row會包含哪些 Key
	        		mCountRow.put(i, i * 100);
	        		for(int k = 0; k < mSizeLink.size(); k ++){ //s1,s2,s3,m1,m2,m3,l1,l2,l3,x1,x2,x3
		        		if( i == 0){
		        			mCountCell.put(k, mSizeLink.get(k)); //原先 i*100+k 沒有意義
		        		}else{ // 第二列以後
		        			if( k == 0){ // 新增號碼
		        					mCountCell.put(i * 100 + k, mArrayColorNumber.get(i - 1));
		        			} else {
		        					mCountCell.put(i * 100 + k, mArrayColorName.get(i - 1)); 
		        			}

		        		}			
	        		}
	        	}
	        	
				try{
					mySqlBuf.delete(0, mySqlBuf.toString().length()); //清空
					if (nPart==0 && (mDept.equalsIgnoreCase("SOS") || mDept.equalsIgnoreCase("AA"))){
						mySqlBuf.append("select GOODSNO,COLOR,SIZE,");
						mySqlBuf.append("sum(UNIT10) as SUM10,sum(UNIT20) as SUM20,sum(UNIT30) as SUM30,sum(UNIT40) as SUM40,sum(UNIT) as SUM1");
						mySqlBuf.append(" from qitems");
						mySqlBuf.append(" where GOODSNO='" + mGoods+"' and (QKIND ='10' or QKIND ='20' or QKIND ='30' or QKIND ='40')");
						mySqlBuf.append(" group by GOODSNO,COLOR,SIZE");

						Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
						if (cs.getCount()>0){
							cs.moveToFirst();			
							for (int i=0;i<cs.getCount();i++){  //從第一筆--最後一筆讀取
									String acol=cs.getString(cs.getColumnIndex("COLOR"));
									String asiz=cs.getString(cs.getColumnIndex("SIZE"));
									
								for (int j=0;j<anumber.length;j++){
									if (acol.equalsIgnoreCase(anumber[j]))  { //顏色相符
				  						for (int k=0;k<asizes.length;k++){
					  						if (asiz.equalsIgnoreCase(asizes[k]))  { //尺寸相符  置入進銷存
				  								ttot[(j*asizes.length*3)+k*3]=""+Math.round(cs.getInt(cs.getColumnIndex("SUM10")));
					  							ttot[(j*asizes.length*3)+k*3+1]=""+Math.round((cs.getInt(cs.getColumnIndex("SUM30"))+cs.getInt(cs.getColumnIndex("SUM40"))-cs.getInt(cs.getColumnIndex("SUM1"))))+"("+cs.getInt(cs.getColumnIndex("SUM1"))+")";
				  								ttot[(j*asizes.length*3)+k*3+2]=""+Math.round((cs.getInt(cs.getColumnIndex("SUM10"))-(cs.getInt(cs.getColumnIndex("SUM20"))+cs.getInt(cs.getColumnIndex("SUM30"))+cs.getInt(cs.getColumnIndex("SUM40")))));
					  						}
				  						}
									}
								}
								cs.moveToNext();
							}
						}
						cs.close();
					} else { //nPart==1 門市的進銷存
						mySqlBuf.append("select GOODSNO,COLOR,SIZE,USER,QKIND,");
						mySqlBuf.append("sum(UNIT20) as SUM20,sum(UNIT30) as SUM30,sum(UNIT40) as SUM40,sum(UNIT) as SUM1");
						if (!mDept.equalsIgnoreCase("SOS") && !mDept.equalsIgnoreCase("AA")) {
							mySqlBuf.append(" from qitems where GOODSNO='" + mGoods+"' and (USER='"+mDept+"' or DEPTNO='"+mDept+"')");
						}else {
							mySqlBuf.append(" from qitems where GOODSNO='" + mGoods+"'");							
						}
						mySqlBuf.append(" group by GOODSNO,COLOR,SIZE,USER,QKIND");
						Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
						if (cs.getCount()>0){
							cs.moveToFirst();			
							for (int i=0;i<cs.getCount();i++){  //從第一筆--最後一筆讀取
									String acol=cs.getString(cs.getColumnIndex("COLOR"));
									String asiz=cs.getString(cs.getColumnIndex("SIZE"));
									
								for (int j=0;j<anumber.length;j++){
									if (acol.equalsIgnoreCase(anumber[j]))  { //顏色相符
				  						for (int k=0;k<asizes.length;k++){
					  						if (asiz.equalsIgnoreCase(asizes[k]))  { //尺寸相符  置入進銷存
					  							if (cs.getString(4).equalsIgnoreCase("20") || (cs.getString(3).equalsIgnoreCase(Utilis.getIni(GalleryViewP.this,"SYS","DEPT",1)) && cs.getString(4).equalsIgnoreCase("21")) ) {  
					  								ttot[(j*asizes.length*3)+k*3]=""+(Utilis.toInt(ttot[(j*asizes.length*3)+k*3])+Math.round(cs.getInt(cs.getColumnIndex("SUM20"))));
					  								ttot[(j*asizes.length*3)+k*3+2]=""+(Utilis.toInt(ttot[(j*asizes.length*3)+k*3+2])+Math.round((cs.getInt(cs.getColumnIndex("SUM20")))));
					  							} else if (cs.getString(4).equalsIgnoreCase("21") && !cs.getString(3).equalsIgnoreCase(Utilis.getIni(GalleryViewP.this,"SYS","DEPT",1))){
					  								ttot[(j*asizes.length*3)+k*3]=""+(Utilis.toInt(ttot[(j*asizes.length*3)+k*3])-Math.round(cs.getInt(cs.getColumnIndex("SUM20"))));
					  								ttot[(j*asizes.length*3)+k*3+2]=""+(Utilis.toInt(ttot[(j*asizes.length*3)+k*3+2])-Math.round((cs.getInt(cs.getColumnIndex("SUM20")))));						  							
				  								} else {
				  									
				  									int M300=0;
				  									int M11=0;
				  									int M30=0;  //銷貨時判斷原理nPart==0總公司只判讀30 40 門市只判讀 31 41
				  									if (nPart==0 && !mDept.equalsIgnoreCase("SOS") && !mDept.equalsIgnoreCase("AA") &&(cs.getString(4).equalsIgnoreCase("31") || cs.getString(4).equalsIgnoreCase("41"))) {
				  										M30=cs.getInt(cs.getColumnIndex("SUM30"))+cs.getInt(cs.getColumnIndex("SUM40"));
				  									}else  if (nPart==1 && (cs.getString(4).equalsIgnoreCase("31") || cs.getString(4).equalsIgnoreCase("41"))) {
				  										M30=cs.getInt(cs.getColumnIndex("SUM30"))+cs.getInt(cs.getColumnIndex("SUM40"));
				  									}
				  									int M1=cs.getInt(cs.getColumnIndex("SUM1"));
				  									ttot[(j*asizes.length*3)+k*3+2]=""+(Utilis.toInt(ttot[(j*asizes.length*3)+k*3+2])-M30);
				  									 //31 41 單 會牽扯到 銷貨(留貨)的問題 2個運算在同一欄位上 需分開運算
				  									if (ttot[(j*asizes.length*3)+k*3+1].indexOf("(")>-1) { //表有留貨的値在()之間
				  										M11=M1+Utilis.toInt(ttot[(j*asizes.length*3)+k*3+1].substring(ttot[(j*asizes.length*3)+k*3+1].indexOf("(")+1, ttot[(j*asizes.length*3)+k*3+1].indexOf(")")));
				  										try {
				  											M300=M30+Utilis.toInt(ttot[(j*asizes.length*3)+k*3+1].substring(0, ttot[(j*asizes.length*3)+k*3+1].indexOf("(")));
				  										}catch(Exception e){
				  											e.printStackTrace();
				  										}
				  									} else { //沒留貨
				  										M300 =M30+Utilis.toInt(ttot[(j*asizes.length*3)+k*3+1]);
				  									}
				  									
					  							ttot[(j*asizes.length*3)+k*3+1]=""+M300+"("+M11+")";
					  							
					  							}	
					  						}
				  						}
									}
								}
								cs.moveToNext();
							}
						}
						cs.close();
					}
//					db.close();
//					cs.close();

	  			StringBuffer mCountList= new StringBuffer(); //所有件數表 5,5，3,3
	  			StringBuffer mInCountList= new StringBuffer(); //所有件數表 5,5，3,3
	  			
	  			for (int i=0;i<anumber.length;i++){
	  				for (int j=0;j<asizes.length;j++){
	  					mInCountList.append(""+Math.round(attot[((i*asizes.length)+j)]));
  			  			mCountList.append(ttot[((i*asizes.length*3)+j*3)]).append(",")
  			  			.append(ttot[((i*asizes.length*3)+j*3)+1]).append(",")
  			  			.append(ttot[((i*asizes.length*3)+j*3)+2]);
  			  		if  ( j<(asizes.length-1)) {
  			  			mCountList.append(",");
  			  			mInCountList.append(",");
  			  			}
 			  		
  					}
	  				if (i<(anumber.length-1)){	
	  					mCountList.append("，"); 
	  					mInCountList.append("，");
	  					}
	  			}

	  			mSplitList=mInCountList.toString();
	  			oSplitList=mSplitList;
	  			
	        	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, i);
        		mLayoutRoot.addView(row);
        	}
       	 }  //判斷不為空白
	    
	}else{ //不顯示庫存
    	mLayoutRoot.removeAllViews(); //***************
		mSizeLink.clear();
		mCountRow.clear();	        		
		mCountCell.clear();
	}
		db.close();
			
			Bitmap bm = Utilis.getLimitBitmap(mPics, 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);
			}
			
	}
   	
	public class TableRowView extends LinearLayout {  
        public TableRowView(Context context, TableRow tableRow, int position) {  
            super(context);  
            this.setOrientation(LinearLayout.HORIZONTAL);  
            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);
                    	if( mCountCell.containsKey(key + i)){
                    		textCell.setText(String.valueOf(mCountCell.get(key + i)));
                    	}else{
                    		textCell.setText("X");
                    	}
                    }else{
                    	textCell.setText("X");
                    }
                    textCell.setId(position * 100 + 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){  //
                    	String colorN=DBUtil.ColorGetTxt(GalleryViewP.this,textCell.getText().toString());
                    	String [] colors=colorN.split(";");
                    	textCell.setBackgroundColor(Utilis.toInt(colors[2]));
                    } else {
                    	textCell.setBackgroundColor(Color.rgb(208, 208, 208));
                    }
                    
                    addView(textCell, layoutParams);
                    
            }  
            this.setBackgroundColor(Color.BLACK);
        }  
    }


	//QHIS 歷史價的重大功能
	
	public boolean Qhis(Context context,String user,String goodsno,String year,int season,int mode){
		//需取得 (單價)(折) mode=0原歷史價 mode=1對照表
		boolean YN=false;
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cs = null;					
		StringBuffer mySqlBuf = new StringBuffer();
		if (mode==0){
			mySqlBuf.append("select UNITPRICE,DISCOUNT,P0,GOODSNAME from qitems");
			mySqlBuf.append(" where GOODSNO = '" + goodsno+"'");
			
			if (user.indexOf("Z")==0 && nKind==31)//專櫃預設為實銷會員代號
				mySqlBuf.append(" and (USER= '"+user+"' or DEPTNO='"+user.substring(1)+"')");
			else
				mySqlBuf.append(" and USER= '"+user+"' and QKIND= '"+mKind+"'");
			
			mySqlBuf.append(" order by FORMDATE,CREATEDATETIME");  //取得最新一筆交易的歷史單價 折
			
			cs = db.rawQuery(mySqlBuf.toString(), null);
		
			if (cs.getCount()>0){ //找到唯一貨號後,檢查有否本單重覆的貨號
				cs.moveToLast();
				
				hisUnitprice=cs.getDouble(cs.getColumnIndex("UNITPRICE"));
					hisDiscount=cs.getDouble(cs.getColumnIndex("DISCOUNT"));
					StdP0=cs.getDouble(cs.getColumnIndex("P0"));
				YN=true;
			}
		}else{//對照表
			mySqlBuf.append("select APRI from qc_ppri where BPRI='"+goodsno+"' and YEAR='"+year+"' and SEASON='"+season+"'");
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){ //找到唯一貨號後,檢查有否本單重覆的貨號
				cs.moveToFirst();
				hisUnitprice=cs.getDouble(0);
				hisDiscount=100;
				YN=true;
			}	
			
		}
		db.close();	
		cs.close();
		return YN;
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
//@!		
		if(requestCode == RESULT_INCOME){
			if (resultCode == RESULT_OK) {

					units = data.getIntExtra("item_impo", 0);
					// 需避免資料下次傳過去,在QITEMS中沒有IMPO這個欄位,只有採購QDETAIL存在
					//這是由INCOME傳回給G的總件數
					mSplitSizes = data.getStringExtra("item_size");
					mSplitColor = data.getStringExtra("item_color");
					mSplitColorNo = data.getStringExtra("item_colorno");
					mSplitList = data.getStringExtra("item_countlist");
					dUnitprice= data.getDoubleExtra("unitprice",0);
					dDiscount= data.getDoubleExtra("discount",0);
					if (!oSplitList2.equalsIgnoreCase(mSplitList) || dDiscount!=oDiscount || dUnitprice!=oUnitprice) {  //因為也可能又改回來
						if (!oSplitList2.equalsIgnoreCase(mSplitList)) mTextView09.setText(""+units);
						if (dDiscount!=oDiscount) mTextView08.setText(""+dDiscount);
						if (dUnitprice!=oUnitprice) mTextView07.setText(""+dUnitprice);
						//reCount();
						modify=1;
						savedata();
					}
//				}
			}
		}else if(requestCode == RESULT_GALLERYO){
			if (resultCode == RESULT_OK) {
				if (data.getIntExtra("GVPO_modify",0)==1){
					modify=1;
					DBCloud.aa0_aa1_auto_HI(this,nKind);
				}
			}
			roback();
		}else if(requestCode == RESULT_AITEM){
			//如果建新品成功 是否直接帶入 編輯
			if (resultCode == RESULT_OK) {
				aInput=data.getStringExtra("item_batch");
				searched();
			}
		}
	}	

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

private void roback(){
	
if (pMode<=2) {				
    SQLiteDatabase db = Utilis.getDB(GalleryViewP.this);
	Cursor cs = null;
	StringBuffer mySqlBuf = new StringBuffer();
	
	mySqlBuf.append("select distinct GOODSNO,PIC,CREATEDATETIME from qitems")
	.append(" where FORMNO='"+fNo+"'");
	mySqlBuf.append(" and QKIND ='" + mKind+"'");			
	mySqlBuf.append(" order by CREATEDATETIME DESC");  //最近交易的300筆
	cs = db.rawQuery(mySqlBuf.toString(), null);

	if (cs.getCount() > 0) {
			updateListView(cs);
			Display(0,1);
	}
	cs.close();
	db.close();	
}
mEdSearch.requestFocus();
mEdSearch.setText("");
}

private void chkItems(){
	LayoutInflater factory = LayoutInflater.from(this);
	final View v1 = factory.inflate(R.layout.fcount, null);
	final EditText edtCount = (EditText) v1.findViewById(R.id.edcount);
	final EditText edtUprice = (EditText) v1.findViewById(R.id.eduprice);
	final EditText edtDiscount = (EditText) v1.findViewById(R.id.ediscount);
	final ImageView edtPic = (ImageView) v1.findViewById(R.id.imageV1);
	final TextView dUnit = (TextView) v1.findViewById(R.id.TextView02);
	final Button BD1= (Button) v1.findViewById(R.id.btn_disc1);
	BD1.setText(DISC[0]);
	final Button BD2= (Button) v1.findViewById(R.id.btn_disc2);
	BD2.setText(DISC[1]);
	final Button BD3= (Button) v1.findViewById(R.id.btn_disc3);
	BD3.setText(DISC[2]);
	final Button BD4= (Button) v1.findViewById(R.id.btn_disc4);
	BD4.setText(DISC[3]);
	final Button BD5= (Button) v1.findViewById(R.id.btn_disc5);
	BD5.setText(DISC[4]);
	final Button BD6= (Button) v1.findViewById(R.id.btn_disc6);
	BD6.setText(DISC[5]);
	final Button BD7= (Button) v1.findViewById(R.id.btn_disc7);
	BD7.setText(DISC[6]);
	final Button BD8= (Button) v1.findViewById(R.id.btn_disc8);
	BD8.setText(DISC[7]);
	final Button BD9= (Button) v1.findViewById(R.id.btn_disc9);
	BD9.setText(DISC[8]);
	
 
	if (QPosff.PSWD==1 && (Utilis.getIni(this,"SYS","BACKOUT",9).split("!&!")[8].equalsIgnoreCase("2") || nKind==10 || nKind==20 || nKind==21 )){
		edtUprice.setVisibility(View.INVISIBLE);
		edtDiscount.setVisibility(View.INVISIBLE);
		BD1.setVisibility(View.INVISIBLE);
		BD2.setVisibility(View.INVISIBLE);
		BD3.setVisibility(View.INVISIBLE);
		BD4.setVisibility(View.INVISIBLE);
		BD5.setVisibility(View.INVISIBLE);
		BD6.setVisibility(View.INVISIBLE);
		BD7.setVisibility(View.INVISIBLE);
		BD8.setVisibility(View.INVISIBLE);
		BD9.setVisibility(View.INVISIBLE);
	}
	
	if (nUnit<=1) {nUnit=1;isUnit=0;} else isUnit=1;
    
	edtPic.setImageBitmap(reflactionBitmap);
	counts=Utilis.toInt(mSplitList);
	if (isUnit==1 && nUnit>1 && (counts % nUnit)==0){
		counts=counts/nUnit;
		dUnit.setText(""+nUnit+"段");
	}else{
		isUnit=0;
		 dUnit.setText("件");
	}
	edtCount.setText(""+counts);  //件數
	edtUprice.setText(""+dUnitprice);
	edtDiscount.setText(""+dDiscount);
	edtUprice.requestFocus();
	
	dUnit.setOnClickListener(new ImageView.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewP.this);
			double lCount=Utilis.toDouble(edtCount.getText().toString());
			if (isUnit==0 && nUnit>1 && (lCount % nUnit)==0){
				lCount=lCount/nUnit;
				edtCount.setText(""+lCount);
				dUnit.setText(""+nUnit+"段");
				isUnit=1;
			}else if(isUnit==1){
				lCount=lCount*nUnit;
				edtCount.setText(""+lCount);
				isUnit=0;
				 dUnit.setText("件");
			}else{
				isUnit=0;
				 dUnit.setText("件");
			}
			
		}
		});
	
	BD1.setOnClickListener(new ImageView.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewP.this);
			edtDiscount.setText(BD1.getText().toString());
		}
		});

	BD2.setOnClickListener(new ImageView.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewP.this);
			edtDiscount.setText(BD2.getText().toString());
		}
		});

	BD3.setOnClickListener(new ImageView.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewP.this);
			edtDiscount.setText(BD3.getText().toString());
		}
		});

	BD4.setOnClickListener(new ImageView.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewP.this);
			edtDiscount.setText(BD4.getText().toString());
		}
		});

	BD5.setOnClickListener(new ImageView.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewP.this);
			edtDiscount.setText(BD5.getText().toString());
		}
		});

	BD6.setOnClickListener(new ImageView.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewP.this);
			edtDiscount.setText(BD6.getText().toString());
		}
		});

	BD7.setOnClickListener(new ImageView.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewP.this);
			edtDiscount.setText(BD7.getText().toString());
		}
		});

	BD8.setOnClickListener(new ImageView.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewP.this);
			edtDiscount.setText(BD8.getText().toString());
		}
		});

	BD9.setOnClickListener(new ImageView.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewP.this);
			edtDiscount.setText(BD9.getText().toString());
		}
		});

	
	edtUprice.requestFocus();
	//edtPic.setImageBitmap(reflactionBitmap);
	  new AlertDialog.Builder(this).setTitle(mTextView01.getText().toString()+"/"+mTextView02.getText().toString()+"\n"+this.getString(R.string.detail_msg_fgalleryedu)).setView(v1).setNeutralButton("確認傳回", new DialogInterface.OnClickListener() {
	      public void onClick(DialogInterface dialog, int which) {
	    	  double nDisC=Utilis.toDouble(edtDiscount.getText().toString());
	    	  double nCount=Utilis.toDouble(edtCount.getText().toString());
	    	  double nPri=Utilis.toDouble(edtUprice.getText().toString());

	    	  if (isUnit!=0) nCount=nCount*nUnit;
	    	  
	    	  if (nDisC!=dDiscount || counts!=nCount || nPri!=dUnitprice)
	    	  {//Update Db
		    	  localmodify=1;
		    	  dDiscount=Utilis.toDouble(edtDiscount.getText().toString());
		    	  mSplitList=""+nCount;
		    	  dUnitprice=Utilis.toDouble(edtUprice.getText().toString());
				  modify=localmodify;
				  savedata();
	    	  }
	      }
	    }).setNegativeButton("放棄編輯", new DialogInterface.OnClickListener() {
		      public void onClick(DialogInterface dialog, int which) {
		      }
	    })
	    .show();
}
 	
private void chgItems(){
	SQLiteDatabase db = Utilis.getDB(GalleryViewP.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(GalleryViewP.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(oposition,1);
		    		 Toast.makeText(GalleryViewP.this,"貨號:"+mGoods+"_已修改單價成功!" , Toast.LENGTH_SHORT).show();
		    	  }
		      }
		    }).setNegativeButton("放棄編輯", new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int which) {

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