package com.cwbuyer.main;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.code.CodeList;
import com.cwbuyer.code.CodeMode;
import com.cwbuyer.format.DefaultData;
import com.cwbuyer.format.EMode;
import com.cwbuyer.format.IDateDialog;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.ItemData;
import com.cwbuyer.lib.AccountUtil;
import com.cwbuyer.lib.AppUtil;
import com.cwbuyer.lib.AsyncImageFileLoader;
import com.cwbuyer.lib.AsyncImageFileLoader.ImageCallback;
import com.cwbuyer.lib.Calculator;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DBUtil;
import com.cwbuyer.lib.DateUtil;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.MakeTransDetail;
import com.cwbuyer.lib.Show_imagebig;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.main.APos.PItemMode;
import com.cwbuyer.main.ManageAccount.AccountData;
import com.pwbuyer.main.R;

// 採購商品
@SuppressLint({ "DefaultLocale", "HandlerLeak", "InflateParams" })
@SuppressWarnings("unused")
public class AItem extends Activity {

	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	private static final int VOICE_RECOGNITION_REQUEST_CODE_PS = 1235;

	private int mMode =ItemMode.ADD;
	private int mModeD =ItemMode.ADD;
	private int nWhere = 0; 
	//0.ManagerItem 1.GalleryView 2.GalleryViewP Goodsno 3.GalleryViewP Sourceno 
	private int rotationInDegrees=0;
	private final int APSWD = 1001;
	private final int ITEM_CATEGORY = 1002;
	private final int PRICING_CODE = 1003;
	private final int ELEEMENTS_CODE = 1004;
	private final int RESULT_INCOME = 1005;
	private final int COUNTRY_CODE = 1006;
	private final int TPICTURE = 1009;
	private final int TPICTUREP = 1109;
	private final int SELECT_PICTURE = 1010;
	private final int ASUPPLY = 1020;
	private final int SERCHGOODS = 1200;
	private  static int rotateN=0;

	private int bmW=270;
	private int bmH=360;
	private int bmWidth=bmW;
	private int bmHeight=360;
	private int mCountry = 0;
	private int mType = 0;
	private String[] beUNIT = new String[]{"0","1","2","3","4","5","6","7","8","9","10","11","12"};
	private String[] SysDb = Utilis.getIni(this,"SYS","SDB",9).split("!&!"); 
	private String[] DSend = Utilis.getIni(this,"SYS","DEPT_SEND",9).split("!&!"); 
	private double[] mPrice=new double[]{0,0,0,0,0,0,0};	
	private int mMid = 0;
	private String mFactPhone ="";
	private String mBatch ="";
	
	private String[] mSeason = new String[]{"春天","夏天","秋天","冬天","四季"};
	private int [] getYS={2017,0} ;	
	private String mUnit1 = Utilis.getIni(this,"SYS","DEPT",1)+Utilis.getIni(this,"SYS","DEPT",2);
	private int isOnkey=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT",8));
	private int isSendUp=Utilis.toInt(Utilis.getIni(this,"SYS","DATA_SEND",8));
	private int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	Bitmap mBitmap=null;
	private ItemData mData;

	private DefaultData mDefaultData = null; // 採購參數

	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<String> mCountryIcon = new ArrayList<String>();
	private ArrayList<String> mTypeList = new ArrayList<String>();
	private ArrayList<Integer> mTypeIdList = new ArrayList<Integer>();

	private LinkedList<AccountData> mAccountList = null;
	private String[] mAccount;

	private int mSpinnerAccount = 0; // 帳戶
	java.text.DecimalFormat myformat1 = new java.text.DecimalFormat("#.#");
	java.text.DecimalFormat myformat2 = new java.text.DecimalFormat("#.##");
	java.text.DecimalFormat myformat3 = new java.text.DecimalFormat("#.###");
	//formatter.applyPattern("0.00000");
	
	private static int nPicDegree =0;
	// DatePicker Use
	private int mStartYear = 0;
	private int mStartMonth = 0;
	private int mStartDay = 0;
	private int mADD=0;  //判斷是否為追加進一步處理圖檔不再因BATCH再產生一次
	private String mSearch="";
	int isPass=0;

	ImageView OutPhoto = null;
	ImageView OutPhotoP = null;
	Uri mImageCaptureUri = null;
	private String mImagePath = null;
	private String mImagePathP = null;

	public final  String SAVE_FOLDER = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ Utilis.getIni(this,"SYS","YEAR",7) + File.separator;

	public interface ItemMode {
		public int ADD = 0;
		public int EDIT = 1;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		String OutPhotoURI="";
		if (requestCode == RESULT_INCOME) {
			if (resultCode == RESULT_OK) {
				int total = data.getIntExtra("item_impo", 0);
				// 需避免資料下次傳過去
				mData.mSizes = data.getStringExtra("item_size");
				mData.mColors = data.getStringExtra("item_color");
				mData.mColorsNo = data.getStringExtra("item_colorno");
				mData.mCountList = data.getStringExtra("item_countlist");
				mData.nTotalCount = total;
			}
		}
		if (requestCode == COUNTRY_CODE) {
			if (resultCode == RESULT_OK) {
				String pid = data.getStringExtra("country_pic");
				int id = data.getIntExtra("country_id", 1);
				double rate = data.getDoubleExtra("country_rate", 0);
				try {
					((EditText) findViewById(R.id.edit_rate))
							.setText("" + rate);
					if (mCountry != id) { // 更換國家 就清除廠商資料
						((EditText) findViewById(R.id.edit_supply)).setText("");
					}
					mCountry = id;
					// Test Add
					mData.nCountry = mCountry;
					((ImageView) findViewById(R.id.img_country))
							.setImageDrawable(Utilis.getResourceImage(
									AItem.this, pid));
					refreshCost(0);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else if (requestCode == ASUPPLY) { // 廠商
			if (resultCode == RESULT_OK) {
				String factid = data.getStringExtra("qfact_key");
				mFactPhone = data.getStringExtra("fact_ph");
				if (factid != null && factid.length() > 0) {
					((EditText) findViewById(R.id.edit_supply)).setText(factid);
					((EditText) findViewById(R.id.edit_psf)).setText(mFactPhone);
				}
			}
		} else if (requestCode == PRICING_CODE) {
			if (resultCode == RESULT_OK) {
				double p0 = data.getDoubleExtra("p0", 0);
				double p2 = data.getDoubleExtra("p2", 0);
				double p3 = data.getDoubleExtra("p3", 0);
				double p4 = data.getDoubleExtra("p4", 0);
				double p5 = data.getDoubleExtra("p5", 0);
				mPrice[0]=p0;mPrice[1]=0;mPrice[2]=p2;mPrice[3]=p3;mPrice[4]=p4;mPrice[5]=p5;
				((EditText) findViewById(R.id.edit_inprice)).setText(myformat3.format(p0));
				((EditText) findViewById(R.id.edit_midprice)).setText(myformat2.format(p2));
				((EditText) findViewById(R.id.edit_wholeprice)).setText(myformat2.format(p3));
				((EditText) findViewById(R.id.edit_netprice)).setText(myformat2.format(p4));
				((EditText) findViewById(R.id.edit_retailprice)).setText(myformat2.format(p5));

				refreshCost(0);
			}
		} else if (requestCode == ELEEMENTS_CODE) {
			if (resultCode == RESULT_OK) {
				// String name = data.getStringExtra("category_name");
				int wid = data.getIntExtra("wash_id", 1);
				int qid = data.getIntExtra("quality_id", 1);
				try {
					mData.nWashID = wid;
					mData.nQualityID = qid;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else if (requestCode == ITEM_CATEGORY) {
			if (resultCode == RESULT_OK) {
				String name = data.getStringExtra("category_name");
				int id = data.getIntExtra("type_id", 1);
				double addcost = data.getDoubleExtra("type_addcost", 0); // 管銷
				try {
					mType = id;
					if (name != null && name.length() > 0) {
						((EditText) findViewById(R.id.edit_cate)).setText(name);
						
						if (((EditText) findViewById(R.id.edit_itemname)).getText().toString().length()==0 || mMid<=0)
						//表示如果品名空 才引入 商品類別
							((EditText) findViewById(R.id.edit_itemname)).setText(name);
						
						((EditText) findViewById(R.id.edit_addcost)).setText(""+ addcost);
						refreshCost(0);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else if ((requestCode == SELECT_PICTURE) && (resultCode == RESULT_OK)) // 相本
		{
            Uri selectedImageUri = data.getData();
            if (mImagePath==null || mImagePath.equalsIgnoreCase(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png")){
        		File folder = new File(SAVE_FOLDER + mBatch);
        		if (folder.exists() == false) folder.mkdirs();
            	mImagePath=SAVE_FOLDER + mBatch + File.separator+"mtr_"+ String.valueOf(DateUtil.getSystemTime())+ ".jpg";
            }
            String uriImagePath="";            
            Bitmap bitmap=null;
            bmWidth=bmW;bmHeight=bmH;
    	 	rotateN=0;

				if (selectedImageUri.toString().indexOf("content://") >= 0) 
					uriImagePath = Utilis.getRealPathFromURI(AItem.this, selectedImageUri);
				else 
					uriImagePath = selectedImageUri.getPath();
			
            	FileOutputStream fos = null;
            
            if (Build.VERSION.SDK_INT < 19) {
				 BitmapFactory.Options option = new BitmapFactory.Options();
			     option.inJustDecodeBounds = true;
			     BitmapFactory.decodeFile(uriImagePath, option);
			     
			     //長寬因比較而對調
					bmWidth=option.outWidth;
					bmHeight=option.outHeight;
			     if (option.outWidth>1000 ){
			    	 if (option.outWidth>option.outHeight){
			    	 bmWidth=bmH;bmHeight=bmW;
			    	 }else{
				    	 bmWidth=bmW;bmHeight=bmH;
			    	 }
			     }
                mBitmap = Utilis.getScaleBitmap(uriImagePath, bmWidth, bmHeight);
//				eventImgCrop(uri);             	
				
            }
            else
            {
                ParcelFileDescriptor parcelFileDescriptor;
                try {
                    parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
                    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                    bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
                    parcelFileDescriptor.close();

    				ByteArrayOutputStream stream = new ByteArrayOutputStream();
    				//bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// (0 - 100)压缩文件
    		        //FileOutputStream fos = null;
    				try {
    						fos = new FileOutputStream(mImagePath);
        					bitmap.compress(CompressFormat.JPEG, 100, fos);
    				} catch (FileNotFoundException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} finally {
    					fos.close();
    				}
    				//try {
    					 BitmapFactory.Options option = new BitmapFactory.Options();
    				     option.inJustDecodeBounds = true;
    				     BitmapFactory.decodeFile(mImagePath, option);
    				     //長寬因比較而對調
    					//bmWidth=option.outWidth;
    					//bmHeight=option.outHeight;
						Toast.makeText(AItem.this, "bmWidth="+option.outWidth+"__bmHeight="+option.outHeight, Toast.LENGTH_SHORT).show();
						
    				     if (option.outWidth>1000  ){
    				    	 if (option.outWidth>option.outHeight){
    				    	 bmWidth=bmW;bmHeight=bmH;
    				    	 	rotateN=1;
    				    	 }else{
    					    	 bmWidth=bmW;bmHeight=bmH;
     				    	 	rotateN=0;
    				    	 }
    				     }
    	                mBitmap = Utilis.getScaleBitmap(mImagePath, bmWidth, bmHeight);
    	                uriImagePath=mImagePath;
    				//} catch (IOException e) {
    					// TODO Auto-generated catch block
    				//	e.printStackTrace();
    				//}
                    
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
            
			try {
				ExifInterface exif = new ExifInterface(uriImagePath);
				int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
				rotationInDegrees = exifToDegrees(rotation);
				Matrix matrix = new Matrix();
				if (rotationInDegrees!=0) matrix.preRotate(rotationInDegrees);
				
				Bitmap bitm  = Bitmap.createBitmap(mBitmap, 0, 0, bmWidth, bmHeight, matrix, true);
				try {
						fos = new FileOutputStream(mImagePath);
						bitm.compress(CompressFormat.JPEG, 100, fos);
						fos.close();
					mBitmap=bitm;	
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printSt
				//ackTrace();
			}
            
			if (mBitmap != null) {
				OutPhoto.setImageBitmap(mBitmap);
			}
            
		} else if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
				&& resultCode == RESULT_OK) {
			ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			if (matches.size() > 0) {
				String[] voices = new String[matches.size()];
				for (int i = 0; i < voices.length; i++) {
					voices[i] = matches.get(i);
				}
				DialogUtilis.showDialog(AItem.this, "請選擇語音資料", -1, voices,
						new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								// TODO Auto-generated method stub
								((EditText) findViewById(R.id.edit_itemname)).setText(choice);
							}
						});
			}
		} else if (requestCode == VOICE_RECOGNITION_REQUEST_CODE_PS
				&& resultCode == RESULT_OK) {
			ArrayList<String> matches = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			if (matches.size() > 0) {
				String[] voices = new String[matches.size()];
				for (int i = 0; i < voices.length; i++) {
					voices[i] = matches.get(i);
				}
				DialogUtilis.showDialog(AItem.this, "請選擇語音資料", -1, voices,
						new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								// TODO Auto-generated method stub
								((EditText) findViewById(R.id.edit_ps)).setText(choice);
							}
						});
			}
		} else if ((requestCode == SERCHGOODS) && (resultCode == RESULT_OK)) { // 載入搜尋商品的結果
			// 搜尋回來的商品檔要載入目前的商品檔
			int mid = data.getIntExtra("search_mid", 0);
			if (mid > 0 && mADD==1) {
				ItemData newData = DBUtil.CItem.getData(AItem.this, mid, true);
				if (newData != null) {
					mData = newData;
					setAllData(false);//不要置換置入批號
					mADD=1;
					Toast.makeText(AItem.this, "可以進行[存入],視為追加商品", Toast.LENGTH_SHORT).show();
					((EditText) findViewById(R.id.edit_cate)).requestFocus();
				} else {
					Toast.makeText(AItem.this, "發生"+ "載入時的錯誤！", Toast.LENGTH_SHORT).show();
					mADD=0;
				}
			} else {
				Toast.makeText(AItem.this, "發生載入時的錯誤！", Toast.LENGTH_SHORT).show();
				mADD=0;
			}
		} else if (requestCode == APSWD) {
			if (resultCode == RESULT_OK) {
				// 還是要帶入正常的流程
				if (isPass<6 && isPass!=3 && isPass!=4) firstAction();
			} else {
				finish();
			}
		}
		if ((requestCode == TPICTURE || requestCode == TPICTUREP ) && (resultCode == RESULT_OK)) // 照相
		{
			//ContentResolver cr = this.getContentResolver();
			// try
			if (data != null) {
				try {
					Bundle extras = data.getExtras();
					if (extras != null) {
						Bitmap bitmap=null;
							OutPhotoURI = mImageCaptureUri.getPath();
							//bitmap = Utilis.getLimitBitmap(mImageCaptureUri.getPath(), 210, 280);
							bitmap = Utilis.getLimitBitmap(OutPhotoURI, bmW, bmH);
						if (bitmap != null) {
							Matrix matrix = new Matrix();
							ExifInterface exif = new ExifInterface(OutPhotoURI);
							exif = new ExifInterface(OutPhotoURI);
								
							int rotation = exif.getAttributeInt(OutPhotoURI, ExifInterface.ORIENTATION_NORMAL);
							rotationInDegrees = exifToDegrees(rotation);
							if (rotationInDegrees!=0) matrix.preRotate(rotationInDegrees);
							Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmW, bmH, matrix, true);
							mBitmap=adjustedBitmap;
							//旋轉的測試SOURCE_CODE							
						}else{ //失敗
							mBitmap=null;	
							mImagePath = null;
						}
						 //eventImgCrop(OutPhotoURI);
					}
				} catch (Exception e) {
				}
			} else {
				try {
					OutPhotoURI = mImageCaptureUri.getPath();
					Bitmap bitmap = Utilis.getLimitBitmap(OutPhotoURI, bmW, bmH);
					if (bitmap != null) {
						
						Matrix matrix = new Matrix();
						ExifInterface exif = new ExifInterface(OutPhotoURI);
						int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
						rotationInDegrees = exifToDegrees(rotation);
						
						if (rotationInDegrees!=0) matrix.preRotate(rotationInDegrees);
						Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
						
						ByteArrayOutputStream stream = new ByteArrayOutputStream();
						adjustedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// (0 - 100)压缩文件
				        FileOutputStream fos = null;
						try {
								fos = new FileOutputStream(OutPhotoURI);
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						try {
							adjustedBitmap.compress(CompressFormat.JPEG, 100, fos);
							fos.close();
							mBitmap=adjustedBitmap;
							
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				} catch (Exception e) {
				}
			}
			
			
			if (mBitmap!=null){
					if (requestCode == TPICTURE){
						mImagePath = OutPhotoURI;
						OutPhoto.setImageBitmap(mBitmap);
					}else{
						mImagePathP = OutPhotoURI;
						OutPhotoP.setImageBitmap(mBitmap);
					}
	            	bmWidth=mBitmap.getWidth();
	            	bmHeight=mBitmap.getHeight();
			}
			// File file = new File(mImagePath);
			// eventImgCrop(Uri.fromFile(file));
		}
	}


	private static int exifToDegrees(int exifOrientation) {        
	    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90 || rotateN==1) { return 90; } 
	    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {  return 180; } 
	    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270  || rotateN==1) {  return 270; }
	    else return nPicDegree;    
	 }

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_layout);
		// Edit:New , Add:Photos
		((Button) findViewById(R.id.btn_new)).setOnClickListener(new MainClick());
		// Edit:Income , Add:Voice
		((Button) findViewById(R.id.btn_income)).setOnClickListener(new MainClick());
		((Button) findViewById(R.id.btn_remind)).setOnClickListener(new MainClick());
		((Button) findViewById(R.id.btn_save)).setOnClickListener(new MainClick());
		((Button) findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());
		((Button) findViewById(R.id.btn_season)).setOnClickListener(new MainClick());
		((TextView) findViewById(R.id.btn_ps)).setOnClickListener(new MainClick());
		OutPhoto = (ImageView) findViewById(R.id.img_item);
		OutPhotoP = (ImageView) findViewById(R.id.img_post);
		((RelativeLayout) findViewById(R.id.layout_img_item)).setOnLongClickListener(new MainLongClick());
		OutPhotoP.setOnLongClickListener(new MainLongClick());
		((TextView) findViewById(R.id.itemname_btn)).setOnLongClickListener(new MainLongClick());
		((TextView) findViewById(R.id.btn_ps)).setOnLongClickListener(new MainLongClick());
		
		((RelativeLayout) findViewById(R.id.layout_img_item))	.setOnClickListener(new MainClick());
		OutPhotoP.setOnClickListener(new MainClick());

		isPass=AppUtil.isRegSucceed(this,1);
		
		InputFilter[] FilterArray10 = new InputFilter[1];
    	FilterArray10[0] = new InputFilter.LengthFilter(10);
		InputFilter[] FilterArray13 = new InputFilter[1];
    	FilterArray13[0] = new InputFilter.LengthFilter(13);
		InputFilter[] FilterArray14 = new InputFilter[1];
    	FilterArray14[0] = new InputFilter.LengthFilter(14);
		

		getCountryData(this); // 取得國家資料
		mMode = getIntent().getIntExtra("item_mode", ItemMode.ADD);
		mModeD = getIntent().getIntExtra("item_mode", ItemMode.ADD);
		//新增就是新增 不變
		nWhere = getIntent().getIntExtra("item_from", 0);
		mMid = getIntent().getIntExtra("item_mid",0);
		//"item_from" //0.ManagerItem(Default) 1.GalleryView
		// 取得參數資料 (預設)
		getDefaultData();		
		
		nPicDegree =Utilis.toInt(Utilis.getIni(AItem.this, "SYS", "BACKOUT", 8)); // 拍照鏡頭角度		
		if (mMode == ItemMode.EDIT) {
			getData(mMid, null);
			setAllData(true); //置入批號
			if (mData.dP2!=0) mPrice[2]=mData.dP2-mData.dAddCost;
			if (mData.dP3!=0) mPrice[3]=mData.dP3-mData.dAddCost;
			if (mData.dP4!=0) mPrice[4]=mData.dP4-mData.dAddCost;
			if (mData.dP5!=0) mPrice[5]=mData.dP5-mData.dAddCost;
			if (mData.GoodsNo !=null && mData.GoodsNo.length()>0){
				//@@@未來條件增類別等
				((Button) findViewById(R.id.btn_income)).setText("展開");
				if (mData.time != null && mData.time.length() > 0) {
					String[] times = mData.time.split("-");
					if (times.length >= 3) {
						mStartYear = Utilis.toInt(times[0]);
						mStartMonth = Utilis.toInt(times[1]);
						mStartDay = Utilis.toInt(times[2]);
					}
				}
			}else{
				mMode = ItemMode.ADD;
			}
		} else { // ADD
			/**
			 * 此時會載入參數的值
			 */
			mData = new ItemData();
			// 設定國家
			mCountry = mDefaultData.nCountry;
			mData.nCountry = mCountry;
			mData.nAccountId = mDefaultData.nAccountId;
			((ImageView) findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(this,mCountryIcon.get(mCountry - 1)));
			// 設定產品狀態跟季節
			mData.nUnit2= String.valueOf(mDefaultData.nYear);
			mData.nSeason = mDefaultData.nSeason;
			getYS[0]=Utilis.toInt(mData.nUnit2); 
			getYS[1]=mDefaultData.nSeason;
			setSeason(findViewById(R.id.btn_season));
			
			mBatch=mDefaultData.batch;
			mData.nUnit=1;
			// 設定 BillRate
			((EditText) findViewById(R.id.edit_rate)).setText(""+ mDefaultData.dBillRate);

			// 來源貨號產生 (空白,批號,日期)
			String sourceNo = null;
			switch (mDefaultData.nSourceNumber) {
			case 0:
				sourceNo = "";
				break;
			case 1:
				sourceNo = "" + mBatch.toUpperCase();
				break;
			default:
				sourceNo = "";
				break;
			}
			
			mData.sourceNo = sourceNo.toUpperCase();

			// 貨號產生
			// 0. 自訂_空白 (可修改)
			// 1. 來源編號 + 流水號 (3碼)
			// 2. 廠商編號 + 來源編號 (根據兩個加起來)
			// 3. 廠商編號 + 流水號 (5碼)
			// 4. 批號+流水號 (3碼)[R]
			// 5. 同來源編號
			// 6. 廠商+批號+流水號
			String productNo = null;
			switch (mDefaultData.nItemProduct) {
			case 0:
				productNo = "";
				break;
			case 1:
				//productNo = "";
				productNo = AppUtil.getItemNo(this, AppUtil.Format.SourceNo,sourceNo);
				break;
			case 2:
				productNo = (mDefaultData.factno + sourceNo).toUpperCase();
				break;
			case 3:
				// productNo = mDefaultData.factno + flowNumber;
				productNo = AppUtil.getItemNo(this, AppUtil.Format.Company,mDefaultData.factno);
				break;
			case 4:
				productNo = AppUtil.getItemNo(this, AppUtil.Format.Batch,mDefaultData.batch);
				break;
			case 5: // 貨號同來源編號
				productNo = sourceNo;
				break;
			case 6: // 廠商+批號+流水號
				//String SS=
				sourceNo = AppUtil.getItemNo(this, AppUtil.Format.BatchSourceNo,DateUtil.getCurrentYearFormat1().substring(1,3));
				mData.sourceNo = sourceNo.toUpperCase();
				productNo =mDefaultData.factno+"."+mData.sourceNo;
				break;
			case 7: // 年度+季別+流水號
				String Stile=getYS[0]+""+getYS[1];
				productNo = AppUtil.getItemNo(this, AppUtil.Format.YearSeason,Stile.substring(2));
				sourceNo=productNo.substring(3);
				mData.sourceNo = sourceNo;
				break;
			default:
				productNo = "";
				break;
			}
			
	    	((EditText) findViewById(R.id.edit_supply)).setFilters(FilterArray10);			
	    	((EditText) findViewById(R.id.edit_source_number)).setFilters(FilterArray13);
	    	((EditText) findViewById(R.id.edit_goods_number)).setFilters(FilterArray14);
	    	((EditText) findViewById(R.id.edit_batch)).setFilters(FilterArray13);
	    	
			mData.GoodsNo = productNo.toUpperCase();
			((EditText) findViewById(R.id.edit_supply)).setText(mDefaultData.factno.toUpperCase());
			mData.supply = mDefaultData.factno.toUpperCase();
			((EditText) findViewById(R.id.edit_source_number)).setText(""+ sourceNo.toUpperCase());
			((EditText) findViewById(R.id.edit_goods_number)).setText(""+ productNo.toUpperCase());
			((EditText) findViewById(R.id.edit_batch)).setText(mBatch);
			((EditText) findViewById(R.id.edit_cate)).setText("");
			((EditText) findViewById(R.id.edit_cost)).setText("0");
			((EditText) findViewById(R.id.edit_inprice)).setText("0");
			((EditText) findViewById(R.id.edit_itemname)).setText("");
			((EditText) findViewById(R.id.edit_addcost)).setText("0");
			((EditText) findViewById(R.id.edit_midprice)).setText("0");
			((EditText) findViewById(R.id.edit_netprice)).setText("0");
			// ((EditText)findViewById(R.id.edit_rate)).setText("");
			((EditText) findViewById(R.id.edit_retailprice)).setText("0");
			((EditText) findViewById(R.id.edit_wholeprice)).setText("0");

			mData.time = DateUtil.getCurrentDateDb();  //
			((EditText) findViewById(R.id.edit_datetime)).setText(mData.time);
			((EditText) findViewById(R.id.edit_psf)).setText(mFactPhone);			
			((EditText) findViewById(R.id.edit_ps)).setText("");
			setTitleName(mData.time);

			// fistAction();
		}

		// 設定帳戶
		mAccountList = DBUtil.CAccount.getAccountData(this);
		if (mAccountList.size() > 0) {
			mAccount = new String[mAccountList.size()];
			for (int i = 0; i < mAccountList.size(); i++) {
				mAccount[i] = mAccountList.get(i).strShowInfo;
			}
		} else {
			mAccount = new String[] { "無" };
		}

		mSpinnerAccount = AccountUtil.getAccountIndex(mAccountList,mData.nAccountId);
		ArrayAdapter<CharSequence> adapterAccount = new ArrayAdapter<CharSequence>(
				this, android.R.layout.simple_spinner_item, mAccount);
		adapterAccount.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
		Spinner account = (Spinner) findViewById(R.id.spin_account);
		account.setAdapter(adapterAccount);
		account.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(@SuppressWarnings("rawtypes") AdapterView adapterView, View view,
					int position, long id) {
				mSpinnerAccount = position;
			}

			@SuppressWarnings("rawtypes")
			public void onNothingSelected(AdapterView arg0) {
			}
		});
		account.setSelection(mSpinnerAccount);

		
		ArrayAdapter<CharSequence> adapterUNIT = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beUNIT);
		adapterUNIT.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
		Spinner spinnerUNIT = (Spinner) findViewById(R.id.spin_unit);
		spinnerUNIT.setAdapter(adapterUNIT);
		spinnerUNIT.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(@SuppressWarnings("rawtypes") AdapterView adapterView, View view,
					int position, long id) {
				mData.nUnit = position;
			}

			@SuppressWarnings("rawtypes")
			public void onNothingSelected(AdapterView arg0) {
			}
		});
		spinnerUNIT.setSelection(mData.nUnit);
		
		((EditText) findViewById(R.id.edit_inprice)).setOnLongClickListener(new OnLongClickListener() {
					@Override
					public boolean onLongClick(View v) {
						// TODO Auto-generated method stub
						int id = v.getId();
						Utilis.runVibrate(AItem.this);
						showComputer(id);
						return false;
					}
				});

		((EditText) findViewById(R.id.edit_inprice)).setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent();
						intent.setClass(AItem.this, CodeList.class);
						intent.putExtra("code_mode", CodeMode.PRICING);
						intent.putExtra("edit_mode", 1);
						intent.putExtra("edit_country", mData.nCountry);
						AItem.this.startActivityForResult(intent, PRICING_CODE);
					}
				});

		((EditText) findViewById(R.id.edit_supply)).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 && ((EditText) findViewById(R.id.edit_supply)).getText().toString().length()>0){
						((EditText) findViewById(R.id.edit_source_number)).requestFocus();
						return true;
					}
			}
			return false;
			}
		});
		
		((EditText) findViewById(R.id.edit_source_number)).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 && ((EditText) findViewById(R.id.edit_source_number)).getText().toString().length()>0){
						((EditText) findViewById(R.id.edit_source_number)).setText(((EditText) findViewById(R.id.edit_source_number)).getText().toString().toUpperCase());
						mSearch=((EditText) findViewById(R.id.edit_goods_number)).getText().toString();
						if (mMode==ItemMode.ADD){
							String search = searchGoodsItem("GOODSNO",	mSearch,0);
							if (search != null && search.length() > 0) {
								Searched(search);
							}else{  //視為新品
								((EditText) findViewById(R.id.edit_batch)).requestFocus();
							}
						}else
								((EditText) findViewById(R.id.edit_batch)).requestFocus();
						return true;
					}
			}
			return false;
			}
		});
		
		// 貨號如果是 編輯的話就不可變更了 , 並且要變更顏色 做區別
if (mMode == ItemMode.EDIT) {
	((EditText) findViewById(R.id.edit_goods_number)).setBackgroundResource(R.drawable.keypad_edit_no);
} else {
			((EditText) findViewById(R.id.edit_goods_number)).setOnClickListener(new MainClick());
}

		((EditText) findViewById(R.id.edit_addcost)).setOnClickListener(new NumberClick());
		((EditText) findViewById(R.id.edit_midprice)).setOnClickListener(new NumberClick());
		((EditText) findViewById(R.id.edit_netprice)).setOnClickListener(new NumberClick());
		((EditText) findViewById(R.id.edit_rate)).setOnClickListener(new NumberClick());
		((EditText) findViewById(R.id.edit_retailprice)).setOnClickListener(new NumberClick());

		((EditText) findViewById(R.id.edit_wholeprice)).setOnClickListener(new NumberClick());
		((EditText) findViewById(R.id.edit_cost)).setOnClickListener(new NumberClick());
		((EditText) findViewById(R.id.edit_batch)).setOnClickListener(new MainClick());
		((EditText) findViewById(R.id.edit_supply)).setOnLongClickListener(new MainLongClick());
		// new insert date
		((EditText) findViewById(R.id.edit_datetime)).setOnClickListener(new MainClick());
		((EditText) findViewById(R.id.edit_cate)).setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent();
						intent.setClass(AItem.this, CodeList.class);
						intent.putExtra("code_mode", CodeMode.CATEGORY);
						intent.putExtra("edit_mode", 1);
						intent.putExtra("edit_season", getYS[1]);
						intent.putExtra("edit_country", mData.nCountry);
						AItem.this.startActivityForResult(intent, ITEM_CATEGORY);
					}
				});
		((ImageView) findViewById(R.id.img_country)).setOnClickListener(new MainClick());

		((ImageView) findViewById(R.id.pic_batch)).setOnClickListener(new MainClick());

		if (mMode != ItemMode.EDIT) {
			((EditText) findViewById(R.id.edit_source_number)).addTextChangedListener(watcherSource);
			((EditText) findViewById(R.id.edit_supply)).addTextChangedListener(watcherSupply);
			((EditText)findViewById(R.id.edit_batch)).addTextChangedListener(watcherBatch);
			((Button)findViewById(R.id.btn_season)).addTextChangedListener(watcherSeason);
		}
		// 先判斷時間有沒有過 ， 有過的話再判斷密碼
						if (mMode == ItemMode.ADD) {
							if (isPass<6 && isPass!=3 && isPass!=4) firstAction();
						}
	}
	
	private void firstAction() {
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0: // 拍照
					eventImgCapture(TPICTURE);
					break;
				case 1: // 供應商
				{
					Intent intent = new Intent();
					intent.setClass(AItem.this, Qfactff.class);
					intent.putExtra("mode", EMode.EDIT);
					intent.putExtra("countryid", mCountry);
					startActivityForResult(intent, ASUPPLY);
					Toast.makeText(AItem.this, "請先輸入廠商編號", Toast.LENGTH_SHORT).show();
					break;
				}
				case 2: // 來源編號
				{
					((EditText)findViewById(R.id.edit_source_number)).setFocusableInTouchMode(true);
					((EditText)findViewById(R.id.edit_source_number)).requestFocus();
					InputMethodManager m = (InputMethodManager) AItem.this.getSystemService(Context.INPUT_METHOD_SERVICE);
					m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
					Toast.makeText(AItem.this, "請先輸入來源編號", Toast.LENGTH_SHORT).show();
					break;
				}
				case 3: // 商品編號
				{
					// showComputer(R.id.edit_goods_number);
					((EditText) findViewById(R.id.edit_goods_number)).setFocusableInTouchMode(true);
					((EditText) findViewById(R.id.edit_goods_number)).requestFocus();
					InputMethodManager m = (InputMethodManager) AItem.this.getSystemService(Context.INPUT_METHOD_SERVICE);
					m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
					Toast.makeText(AItem.this, "請先輸入商品編號", Toast.LENGTH_SHORT).show();
					break;
				}
				case 4: // 類別
				{
					Intent intent = new Intent();
					intent.setClass(AItem.this, CodeList.class);
					intent.putExtra("code_mode", CodeMode.CATEGORY);
					intent.putExtra("edit_mode", 1);
					intent.putExtra("edit_season", getYS[1]);
					intent.putExtra("edit_country", mData.nCountry);
					AItem.this.startActivityForResult(intent, ITEM_CATEGORY);
					Toast.makeText(AItem.this, "請先選擇類別", Toast.LENGTH_SHORT).show();
					break;
				}
				case 5: // 進價
					// showComputer(R.id.edit_inprice);
					Toast.makeText(AItem.this, "請先輸入進價", Toast.LENGTH_SHORT).show();
					Intent intent = new Intent();
					intent.setClass(AItem.this, CodeList.class);
					intent.putExtra("code_mode", CodeMode.PRICING);
					intent.putExtra("edit_mode", 1);
					intent.putExtra("edit_country", mData.nCountry);
					AItem.this.startActivityForResult(intent, PRICING_CODE);
					break;
				}
			}
		};
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				handler.sendEmptyMessage(mDefaultData.nItemFirst);
			}

		}, 500);
	}

	public void setAllData(boolean bSomeDataOverride) {
		getTypeData(this);
		if (mData != null) {
			((EditText) findViewById(R.id.edit_supply)).setText(mData.supply);
			((EditText) findViewById(R.id.edit_source_number)).setText(mData.sourceNo);
			((EditText) findViewById(R.id.edit_goods_number)).setText(mData.GoodsNo);
			((EditText) findViewById(R.id.edit_inprice)).setText(myformat3.format(mData.dP0));
			((EditText) findViewById(R.id.edit_cost)).setText(myformat3.format(mData.dP1));
			((EditText) findViewById(R.id.edit_itemname)).setText(mData.goodsname);
			((EditText) findViewById(R.id.edit_addcost)).setText(myformat2.format(mData.dAddCost));
			((EditText) findViewById(R.id.edit_midprice)).setText(myformat2.format(mData.dP2));
			((EditText) findViewById(R.id.edit_wholeprice)).setText(myformat2.format(mData.dP3));
			((EditText) findViewById(R.id.edit_netprice)).setText(myformat2.format(mData.dP4));
			((EditText) findViewById(R.id.edit_retailprice)).setText(myformat2.format(mData.dP5));
			((EditText) findViewById(R.id.edit_rate)).setText(""	+ mData.dBillRate);
			((EditText) findViewById(R.id.edit_psf)).setText(mFactPhone);
			((EditText) findViewById(R.id.edit_datetime)).setText(mData.time);
			((EditText) findViewById(R.id.edit_ps)).setText(mData.mPS);
			// 設定正式/樣品
			if(mData.nState == 0){
				((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_1);
			}else if(mData.nState == 1){
				((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_2);
			}else if(mData.nState == 2){
				((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_3);
			}else {
				((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_4);
			}
			

			setTitleName(mData.time);

			// 有一些值不要帶入
			// 批號
			if (bSomeDataOverride == true) {
				((EditText) findViewById(R.id.edit_batch)).setText(mData.batch);
			} else {
				mData.batch = ((EditText) findViewById(R.id.edit_batch)).getText().toString();
			}
			mBatch=mData.batch;
			// 設定國家
			((ImageView) findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(this,mCountryIcon.get(mData.nCountry - 1)));
			// 設定產品類別
			mType = mData.nGoodsType;
			mCountry = mData.nCountry;
			getYS[0]=Utilis.toInt(mData.nUnit2);
			getYS[1]=mData.nSeason;
			
			
			int index = mTypeIdList.indexOf(mData.nGoodsType);
			if (index >= 0) {
				((EditText) findViewById(R.id.edit_cate)).setText(mTypeList.get(index));
			}

			if (mData.pic1 != null && mData.pic1.length() > 0) {
				Bitmap bitmap = Utilis.getLimitBitmap(mData.pic1, bmW, bmH);
				if (bitmap != null) {
					mImagePath = mData.pic1;
					OutPhoto.setImageBitmap(bitmap);
				}
			}
			if (mData.pic2 != null && mData.pic2.length() > 0) {
				//Bitmap bitmap = Utilis.getLimitBitmap(mData.pic2, 210, 280);
				Bitmap bitmap = Utilis.getLimitBitmap(mData.pic2, 600, 1200);
				mBitmap=bitmap;
				if (bitmap != null) {
					mImagePathP = mData.pic2;
					// OutPhoto.setScaleType(ScaleType.FIT_XY);
					OutPhotoP.setImageBitmap(bitmap);
				}
			}
//			setState(findViewById(R.id.btn_state), mState);
			setSeason(findViewById(R.id.btn_season));
			
			
		}
	}

	public void getData(int mid, String goodsno) { //Come from Line 434 (Edit_mode)
		// getTypeData(this);
		SQLiteDatabase db = Utilis.getDB(this);
		try {
			Cursor cursor = null;
			if (mid > 0) {
				cursor = db.rawQuery("select * from " + TbName.QDETAIL
						+ " where MID=" + mid, null);
			} else if (goodsno != null && goodsno.length() > 0) {
				cursor = db.rawQuery("select * from " + TbName.QDETAIL
						+ " where GOODSNO like '%" + goodsno + "%'", null);
			}
			if (cursor != null) {
				try {
					if (cursor.getCount() > 0) {
						cursor.moveToLast();  //moveToFirst();
						ItemData data = new ItemData();
						data = new ItemData();
						data.nTR = cursor.getInt(cursor.getColumnIndex("TR"));
						data.nMid = cursor.getInt(cursor.getColumnIndex("MID"));
						data.supply = cursor.getString(cursor.getColumnIndex("SUPPLY"));
						data.nCountry = cursor.getInt(cursor.getColumnIndex("COUNTRY"));
						data.country = mCountryList.get(data.nCountry - 1);
						data.sourceNo = cursor.getString(cursor.getColumnIndex("SOURCENO"));
						data.GoodsNo = cursor.getString(cursor.getColumnIndex("GOODSNO"));
						data.nGoodsType = cursor.getInt(cursor.getColumnIndex("GOODSTYPE"));
						data.goodsname = cursor.getString(cursor.getColumnIndex("GOODSNAME"));
						data.nUnit1 = cursor.getString(cursor.getColumnIndex("UNIT1"));
						data.nUnit2 = cursor.getString(cursor.getColumnIndex("UNIT2"));
						data.nUnit = cursor.getInt(cursor.getColumnIndex("UNIT"));
						data.batch = cursor.getString(cursor.getColumnIndex("BATCH"));
						data.dBill = cursor.getDouble(cursor.getColumnIndex("BILL"));
						data.dBillRate = cursor.getDouble(cursor.getColumnIndex("BILLRATE"));
						data.dAddCost = cursor.getDouble(cursor.getColumnIndex("ADDCOST"));
						data.dP0 = cursor.getDouble(cursor.getColumnIndex("P0"));
						data.dP1 = cursor.getDouble(cursor.getColumnIndex("P1"));
						data.dP2 = cursor.getDouble(cursor.getColumnIndex("P2"));
						data.dP3 = cursor.getDouble(cursor.getColumnIndex("P3"));
						data.dP4 = cursor.getDouble(cursor.getColumnIndex("P4"));
						data.dP5 = cursor.getDouble(cursor.getColumnIndex("P5"));
						data.nSeason = cursor.getInt(cursor.getColumnIndex("SEASON"));
						data.mPS = cursor.getString(cursor	.getColumnIndex("PS"));
						data.time = cursor.getString(cursor	.getColumnIndex("CREATEDATETIME"));
						data.nState = cursor.getInt(cursor.getColumnIndex("STATE"));
						data.pic1 = cursor.getString(cursor.getColumnIndex("PIC"));
						data.pic2 = cursor.getString(cursor.getColumnIndex("PICTURE"));
						data.nQualityID = cursor.getInt(cursor.getColumnIndex("QUALITY_ID"));
						data.nWashID = cursor.getInt(cursor.getColumnIndex("WASH_ID"));
						mBatch=cursor.getString(cursor.getColumnIndex("BATCH"));
						getYS[0]=Utilis.toInt(data.nUnit2); 
						getYS[1]=data.nSeason; 
						if (mid > 0) {
							data.nTotalCount = cursor.getInt(cursor	.getColumnIndex("IMPO"));
							data.nAccountId = cursor.getInt(cursor.getColumnIndex("ACCOUNT"));
							// new add
							data.mSizes = cursor.getString(cursor	.getColumnIndex("SIZE"));
							data.mColors = cursor.getString(cursor.getColumnIndex("COLOR"));
							data.mColorsNo = cursor.getString(cursor.getColumnIndex("COLORNO"));
							data.mCountList = cursor.getString(cursor.getColumnIndex("INLIST"));
							
						}
						if (data != null) {
							mData = data;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					cursor.close();
					cursor = null;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Cursor supplyCs=db.rawQuery("select MOBIL from qfact where FACTNO='"+mData.supply+"'", null);
		if (supplyCs.getCount()>0) {
			supplyCs.moveToFirst();
			mFactPhone=supplyCs.getString(0);
		} else mFactPhone="";
		
		supplyCs.close();
		
		db.close();
		db = null;
	}
	
	// 取得國家資料
	public void getCountryData(Context context) {
		if (mCountryIcon != null) {
			mCountryIcon.clear();
		}
		if (mCountryList != null) {
			mCountryList.clear();
		}
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cursor = db.rawQuery(
				"select NAME,PIC 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++) {
						String pic = cursor.getString(cursor
								.getColumnIndex("PIC"));
						String name = cursor.getString(cursor
								.getColumnIndex("NAME"));
						mCountryIcon.add(pic);
						mCountryList.add(name);
						cursor.moveToNext();
					}
				}
			} catch (Exception e) {

			} finally {
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}

	// 取得類別資料
	public void getTypeData(Context context) {
		if (mTypeList != null) {
			mTypeList.clear();
		}
		if (mTypeIdList != null) {
			mTypeIdList.clear();
		}
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cursor = db.rawQuery(
				"select GOODTYPE,_ID from qc_type order by _ID", null);
		if (cursor != null) {
			try {
				if (cursor.getCount() > 0) {
					cursor.moveToFirst();
					for (int i = 0; i < cursor.getCount(); i++) {
						String name = cursor.getString(cursor
								.getColumnIndex("GOODTYPE"));
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						mTypeList.add(name);
						mTypeIdList.add(id);
						cursor.moveToNext();
					}
				}
			} catch (Exception e) {

			} finally {
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}

	// 取得預設參數
	private void getDefaultData() {
		SQLiteDatabase db = Utilis.getDB(this);
		if (db != null) {
			Cursor cursor = db.rawQuery("select * from qc_default", null);
			if (cursor != null) {
				try {
					if (cursor.getCount() > 0) {
						cursor.moveToFirst();
						mDefaultData = new DefaultData();
						mDefaultData.nCountry = cursor.getInt(cursor.getColumnIndex("COUNTRY"));
						mDefaultData.country = mCountryList.get(mDefaultData.nCountry - 1);
						mDefaultData.dBillRate = cursor.getDouble(cursor.getColumnIndex("BILLRATE"));
						mDefaultData.batch = cursor.getString(cursor.getColumnIndex("BATCH"));
						mDefaultData.factno = cursor.getString(cursor	.getColumnIndex("FACTNO"));
						mDefaultData.nItemState = cursor.getInt(cursor.getColumnIndex("STATE"));
						mDefaultData.nSourceNumber = cursor.getInt(cursor.getColumnIndex("SOURCENO"));
						mDefaultData.nItemProduct = cursor.getInt(cursor.getColumnIndex("PRODUCT"));
						mDefaultData.nItemFirst = cursor.getInt(cursor.getColumnIndex("ITEMFIRST"));
						mDefaultData.nSeason = cursor.getInt(cursor.getColumnIndex("SEASON"));
						mDefaultData.nYear = cursor.getInt(cursor.getColumnIndex("YEAR"));
						mDefaultData.employ = cursor.getString(cursor.getColumnIndex("EMPLOY"));
						mDefaultData.nAccountId = cursor.getInt(cursor.getColumnIndex("ACCOUNT"));
						mBatch=mDefaultData.batch;
						getYS[0]=mDefaultData.nYear; 
						getYS[1]=mDefaultData.nSeason; 
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					cursor.close();
				}
			}
			Cursor supplyCs=db.rawQuery("select MOBIL from qfact where FACTNO='"+mDefaultData.factno+"'", null);
			if (supplyCs.getCount()>0) {
				supplyCs.moveToFirst();
				mFactPhone=supplyCs.getString(0);
			} else mFactPhone="";
			db.close();
		}
	}

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	private String getRealPathFromURI(Uri contentUri ) {
        String[] proj = { MediaStore.Images.Media.DATA };
        CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
	private void updateDefault(SQLiteDatabase db, int country,double mBillRate ,String batch) {
		boolean bOK = false;
		ContentValues value = new ContentValues();
		value.put("COUNTRY", country);
		value.put("BATCH", batch);
		value.put("SEASON", getYS[1]);
		value.put("YEAR", getYS[0]);
		value.put("BILLRATE", mBillRate);
		String[] args = new String[] {};
		int success = db.update("qc_default", value, "", null);
		if (success > 0) {
			bOK = true;
		}
	}

	private boolean saveData() {
    	int checkStateId = ((RadioGroup)findViewById(R.id.group_state)).getCheckedRadioButtonId();
    	switch(checkStateId){
    	case R.id.radio_state_1:
    		mData.nState = 0;
    		break;
    	case R.id.radio_state_2:
    		mData.nState = 1;
    		break;
    	case R.id.radio_state_3:
    		mData.nState = 2;
    		break;
    	case R.id.radio_state_4:
    		mData.nState = 3;
    		break;
    	}
    	
		SQLiteDatabase db = Utilis.getDB(this);
		String supply = ((EditText) findViewById(R.id.edit_supply)).getText().toString().toUpperCase();
		String SourceNo = ((EditText) findViewById(R.id.edit_source_number)).getText().toString().toUpperCase();
		String GoodsNo = ((EditText) findViewById(R.id.edit_goods_number)).getText().toString().toUpperCase();
		// mType
		double dP0 = Utilis.toDouble(((EditText) findViewById(R.id.edit_inprice)).getText().toString());
		double dP1 = Utilis.toDouble(((EditText) findViewById(R.id.edit_cost))	.getText().toString());
		double dP2 = Utilis.toDouble(((EditText) findViewById(R.id.edit_midprice)).getText().toString());
		double dP3 = Utilis.toDouble(((EditText) findViewById(R.id.edit_wholeprice)).getText().toString());
		double dP4 = Utilis.toDouble(((EditText) findViewById(R.id.edit_netprice)).getText().toString());
		double dP5 = Utilis.toDouble(((EditText) findViewById(R.id.edit_retailprice)).getText().toString());
		// mSeason
		// state
		double dBillRate = Utilis.toDouble(((EditText) findViewById(R.id.edit_rate)).getText().toString());
		double dAddCost = Utilis.toDouble(((EditText) findViewById(R.id.edit_addcost)).getText().toString());
		String itemname = ((EditText) findViewById(R.id.edit_itemname))	.getText().toString();
		mBatch = ((EditText) findViewById(R.id.edit_batch)).getText().toString().toUpperCase();

		String datetime = ((EditText) findViewById(R.id.edit_datetime))	.getText().toString();

		String mPS = ((EditText) findViewById(R.id.edit_ps)).getText().toString();
		
		int nAccountId = mAccountList.get(mSpinnerAccount).nID;

		if (GoodsNo.equalsIgnoreCase(supply)){//表示建新品,但尚未填完整資料
			GoodsNo="";
		}
		
		if (mMode == ItemMode.ADD && mADD==0 && GoodsNo !=null && GoodsNo.length()>0 ){ //如果純為新增,須檢查主貨號是否重複了
			Cursor csC = db.rawQuery("select GOODSNO from "+TbName.QDETAIL+" where GOODSNO='"+GoodsNo+"'", null);
			if (csC.getCount()>0){
				Toast.makeText(this, "新增的主貨號重複了,請檢查或重新輸入 !!", Toast.LENGTH_SHORT).show();
				db.close();
				csC.close();
				return false;
			}
		}else if (mMode == ItemMode.ADD && GoodsNo !=null && GoodsNo.length()>0 ){
			Cursor csC = db.rawQuery("select GOODSNO from "+TbName.QDETAIL+" where GOODSNO='"+GoodsNo+"' and BATCH='"+mBatch+"'", null);
			if (csC.getCount()>0){
				Toast.makeText(this, "新增的主貨號不可以在同一張批號,請檢查或重新輸入 !!", Toast.LENGTH_SHORT).show();
				db.close();
				csC.close();
				return false;
			}
		}

		ContentValues value = new ContentValues();
		supply=DBCloud.chkStrB(supply);
		value.put("SUPPLY", supply);
		value.put("SOURCENO", DBCloud.chkStrB(SourceNo));
		value.put("GOODSNO", DBCloud.chkStrB(GoodsNo));
		value.put("GOODSTYPE", mType);
		value.put("GOODSNAME", DBCloud.chkStrB(itemname));
		value.put("UNIT1", mUnit1);
		value.put("UNIT2", ""+getYS[0]);
		value.put("BILL",DateUtil.getSystemTime().substring(2,12));
		value.put("BILLRATE", dBillRate);
		value.put("ADDCOST", dAddCost);
		value.put("COUNTRY", mCountry);
		value.put("BATCH", mBatch);
		value.put("P0", dP0);
		value.put("P1", dP1);
		value.put("P2", dP2);
		value.put("P3", dP3);
		value.put("P4", dP4);
		value.put("P5", dP5);
		value.put("CREATEDATETIME", DateUtil.getCurrentDateDb());
		//	//value.put("CREATEDATETIME", datetime);  // or Utilis.getCurrentDateDB();
		value.put("PS", DBCloud.chkStrB(mPS));
		value.put("SEASON", getYS[1]);
		//value.put("STATE", (mState % 2));
		value.put("STATE", (mData.nState));
		value.put("UNIT",mData.nUnit);  
//	File file = new File(mImagePath);
		if(mImagePath==null || mImagePath.length() <= 0)
		mImagePath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png";
		value.put("PIC", mImagePath);
		Utilis.checkPicSize(mImagePath);
		
		if(mImagePathP==null || mImagePathP.length() <= 0)
		mImagePathP=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png";
		value.put("PICTURE", mImagePathP);
		Utilis.checkPicSize(mImagePathP);
		
		value.put("WASH_ID", mData.nWashID <= 0 ? 1 : mData.nWashID);
		value.put("QUALITY_ID", mData.nQualityID <= 0 ? 1 : mData.nQualityID);
		value.put("ACCOUNT", nAccountId);
		String Inlist=mData.mCountList;
		
		long result=0;
		if (mMode == ItemMode.ADD) {
			// 先修改預設參數
			updateDefault(db, mCountry,dBillRate, mBatch);
			value.put("TR",1004);
			//(上架 預設 7) (不上架 0) 
			if (isSendUp==0) value.put("SPOSS", 0); else 	value.put("SPOSS", 1);  //上架
			value.put("IM_OUTSTK", 1);//A群組
			value.put("IM_POSSTK", 1);//B群組
			if (mADD==0){
				value.put("COLORNO","00");
				value.put("COLOR","混色");
				value.put("SIZE","F");
				value.put("INLIST","0");
				Inlist="0";
			}else{
				value.put("SIZE", mData.mSizes);
				value.put("COLOR", mData.mColors);
				value.put("COLORNO", mData.mColorsNo);
				Inlist=Inlist.replace("1", "0");
				Inlist=Inlist.replace("2", "0");
				Inlist=Inlist.replace("3", "0");
				Inlist=Inlist.replace("4", "0");
				Inlist=Inlist.replace("5", "0");
				Inlist=Inlist.replace("6", "0");
				Inlist=Inlist.replace("7", "0");
				Inlist=Inlist.replace("8", "0");
				Inlist=Inlist.replace("9", "0");
				Inlist=Inlist.replace("00", "0");
				Inlist=Inlist.replace("000", "0");
				value.put("INLIST", Inlist);
			}
			value.put("IMPO","0");
			value.put("IMPOS","0");
			value.put("OUTPO","0");
			value.put("OUTPOS","0");
			value.put("SPOS","0");
			value.put("ORD","0");
			if (mMid<=0)
			 result = db.insert(TbName.QDETAIL, null, value);
			else {
				String[] args = { String.valueOf(mMid) };
				result= db.update(com.cwbuyer.lib.TbName.QDETAIL, value,	"MID=?", args);
			}
			if (result > 0) {
				Toast.makeText(this, "存取明細資料成功", Toast.LENGTH_SHORT).show();
				//@@雲端insert
			} else {
				Toast.makeText(this, "存取明細資料失敗", Toast.LENGTH_SHORT).show();
				db.close();
				return false;
			}
			/**
			 * 新增的時候才需要去 更新 主要商品檔資料!
			 */
//			value.remove("ACCOUNT");

			//意思是因為新增一筆貨品後,會產生一個新的 mMid(autocrement) 
			//猜測會在最後一筆
			//@@@須先檢查 資料是否完整
 
				if (supply!=null && supply.length()>0 && GoodsNo!=null && GoodsNo.length()>0 && mType>0 && mBatch.length()>0) 
				{
					if (mMid<=0) {
					Cursor cursor = db.rawQuery("Select MID from qdetail order by MID desc limit 1",null);
						if (cursor != null) {
							if (cursor.getCount() > 0) {
								cursor.moveToFirst();
								mMid = cursor.getInt(cursor.getColumnIndex("MID"));
							}
							cursor.close();
						}
					}
				mMode = ItemMode.EDIT;
				Intent intent = new Intent();
				intent.putExtra("mid", mMid);
				intent.putExtra("batch", GoodsNo);
				intent.putExtra("item_mode", ItemMode.EDIT); // 非新增 對應帳戶使用
				intent.putExtra("cong", 0);
				intent.putExtra("unit", mData.nUnit);
				if (mData.mSizes != null && mData.mSizes.length()>0) intent.putExtra("size",mData.mSizes ); else intent.putExtra("size", "F");
				if (mData.mColorsNo != null && mData.mColorsNo.length()>0) intent.putExtra("colorno", mData.mColorsNo); else intent.putExtra("colorno", "YN");
				if (mData.mColors != null && mData.mColors.length()>0)intent.putExtra("color", mData.mColors); else intent.putExtra("color", "混色");
				intent.putExtra("countlist", Inlist);
				intent.putExtra("mkind", "20");
				intent.putExtra("unitprice", mData.dP0);
				intent.putExtra("discount", 100.0);
				if (isOnkey==1)
					intent.setClass(AItem.this, AIncomePc.class);
				else
					intent.setClass(AItem.this, AIncome.class);
				startActivity(intent);
			}
		} else { // EDIT
			String[] args = { String.valueOf(mMid) };
			if (mData.nTR!=1004) value.put("TR", 1006);
			value.put("SIZE", mData.mSizes);
			value.put("COLOR", mData.mColors);
			value.put("COLORNO", mData.mColorsNo);
			value.put("INLIST", mData.mCountList);
			value.put("IMPO", mData.nTotalCount);
			int success = db.update(com.cwbuyer.lib.TbName.QDETAIL, value,
					"MID=?", args);
			if (success > 0) {
				Toast.makeText(this, "修改資料成功", Toast.LENGTH_SHORT).show();
				//以下是因應展開而要置入的欄位
				mData.GoodsNo=GoodsNo;mData.nGoodsType=mType;mData.batch=mBatch;
				String [] argss = { GoodsNo, DBCloud.chkStrB(itemname), mImagePath, String.valueOf(mType), String.valueOf(dP0), String.valueOf(dP1), String.valueOf(dP2), String.valueOf(dP3), String.valueOf(dP4), String.valueOf(dP5)};
				value = new ContentValues();
				value.put("GOODSNAME", DBCloud.chkStrB(itemname));				
				value.put("PIC", mImagePath);
				value.put("PICTURE", mImagePathP);
				value.put("GOODSTYPE", mType);
				value.put("P0", dP0);
				value.put("P1", dP1);
				value.put("P2", dP2);
				value.put("P3", dP3);
				value.put("P4", dP4);
				value.put("P5", dP5);
				success = db.update(com.cwbuyer.lib.TbName.QDETAIL, value,
						"GOODSNO=? and (GOODSNAME<>? or PIC<>? or GOODSTYPE<>? or P0<>? or P1<>? or P2<>? or P3<>? or P4<>? or P5<>? )", argss);
				//異動
				db.execSQL("update qitems set  PIC='"+mImagePath+"', COLORS='"+mData.mColors+"', SIZES='"+mData.mSizes+"', UNIT2='"+mData.mColorsNo+"', GOODSNAME='"+DBCloud.chkStrB(itemname)+"', P0="+dP0+",P1="+dP1+",P2="+dP2+", P3="+dP3+", P4="+dP4+", P5="+dP5 +" where GOODSNO='"+GoodsNo+"' and ( PIC<>'"
						+mImagePath+"' or COLORS<>'"+mData.mColors+"' or SIZES<>'"+mData.mSizes+"' or UNIT2<>'"+mData.mColorsNo+"' or GOODSNAME<>'"+DBCloud.chkStrB(itemname)+"' or P0<>'"+dP0+"' or P1<>'"+dP1+"' or P2<>'"+dP2+"' or P3<>'"+dP3+"' or P4<>'"+dP4+"' or P5<>'"+dP5+"' )"	);

				if (Utilis.haveInternet(this) && of_line==1 ) {
					if (DSend[8].equalsIgnoreCase("1")){
					Toast.makeText(AItem.this, "單品異動雲端!!", Toast.LENGTH_SHORT).show();
					Intent intent = new Intent();
					intent.setClass(AItem.this,MakeTransDetail.class);
					intent.putExtra("make_batch",mBatch);
					intent.putExtra("make_mode",0);
					intent.putExtra("make_kind",0);
					intent.putExtra("make_user",GoodsNo);
					intent.putExtra("make_01",1);
					startActivity(intent);
					}	
				}
			} else {
				Toast.makeText(this, "修改資料失敗", Toast.LENGTH_SHORT).show();
				db.close();
				return false;
			}

		}
		
		if(supply.length()>0 &&mBatch.length()>0 ){
			ContentValues valueDefault = new ContentValues();
			valueDefault.put("FACTNO", supply);
			valueDefault.put("COUNTRY", mCountry);
			valueDefault.put("SEASON", getYS[1]);
			valueDefault.put("BATCH", mBatch);
			valueDefault.put("BILLRATE", dBillRate);
			try{
				int success = db.update(com.cwbuyer.lib.TbName.QC_DEFAULT, valueDefault,"", new String[]{});
			}catch(Exception e){
				e.printStackTrace();
			}
			mFactPhone=((EditText) findViewById(R.id.edit_psf)).getText().toString();
			// 確認qfact是否存在於資料庫
			if (DBUtil.CFact.isQFactExist(AItem.this, supply,mFactPhone,10) == false) {
				DBUtil.CFact.createNewFact(AItem.this, supply, mFactPhone,mCountry,10);//10廠商(QKIND)
			}
		}		
		db.close();
		//應該追加單筆傳送雲端功能,這要是參數啟動直接存入伺服器
		
		return true;
	}

	private void showItemDialog(final Activity activity, final int vid,String itemNumber) {
		// AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
		final View root = activity.getLayoutInflater().inflate(	R.layout.dlg_product_number, null);

		final AlertDialog dialog = new AlertDialog.Builder(activity).setNeutralButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						try {
							String source = ((EditText) root	.findViewById(R.id.edit_source_1)).getText().toString();
							String flow = ((EditText) root	.findViewById(R.id.edit_source_2)).getText().toString();
							source = source + flow;
							View view = null;
							try {
								view = activity.findViewById(vid);
								if (view instanceof EditText) {
									((EditText) view).setText(source);
								}
								if (view instanceof TextView) {
									((TextView) view).setText(source);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						} catch (Exception e) {
						}
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int which) {
							}
						})
				.setPositiveButton("搜尋編號",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int which) {
								// 搜尋商品
								String source = ((EditText) root	.findViewById(R.id.edit_source_1)).getText().toString();
								try {

									if (source == null || source.length() <= 0) {
										Toast.makeText(activity, "商品號碼不能為空",
												Toast.LENGTH_SHORT).show();
										return;
									}
									String flow = ((EditText) root.findViewById(R.id.edit_source_2)).getText().toString();
									// source = source + flow;
									// //[R]查詢貨號時不要串起來,只要 R.id.edit_source_1
									View view = null;
									try {
										view = activity.findViewById(vid);
										if (view instanceof EditText) {
											((EditText) view).setText(source);
										}
										if (view instanceof TextView) {
											((TextView) view).setText(source);
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
								} catch (Exception e) {
								}

								String search = searchGoodsItem("GOODSNO",source,1);
								if (search != null && search.length() > 0) {
									mADD=1;
									Intent intent = new Intent();
									intent.setClass(AItem.this,AShowSearch.class);
									intent.putExtra("search_item", search);
									startActivityForResult(intent, SERCHGOODS);
								}
							}
						}).create();

		// 限制最多只能5個字
//		InputFilter[] FilterArray = new InputFilter[1];
//		FilterArray[0] = new InputFilter.LengthFilter(5);
//		((EditText) root.findViewById(R.id.edit_source_2)).setFilters(FilterArray);

		if (itemNumber != null && itemNumber.length() > 0) {
			((EditText) root.findViewById(R.id.edit_source_1)).setText(itemNumber);
		}

		// 只有自定的時候才能修改 商品編號 [R]不能限制,如果USER擅改之後果考量???
		// if(mDefaultData.nItemProduct == 0){
		((EditText) root.findViewById(R.id.edit_source_1)).setFocusable(true);
		((EditText) root.findViewById(R.id.edit_source_1)).setFocusableInTouchMode(true);
		// }

		// 搜尋商品名稱
		String goodsname = ((EditText) findViewById(R.id.edit_itemname)).getText().toString();
		if (goodsname != null && goodsname.length() > 0) {
			((EditText) root.findViewById(R.id.edit_source_3)).setText(goodsname);
		}

		((Button) root.findViewById(R.id.btn_search)).setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// 從商品名稱取得值
						String goodsname = ((EditText) root.findViewById(R.id.edit_source_3)).getText().toString();
						try {
							if (goodsname == null || goodsname.length() <= 0) {
								Toast.makeText(activity, "商品名稱不能為空",Toast.LENGTH_SHORT).show();
								return;
							}
							String search = searchGoodsItem("GOODSNAME",goodsname,1);
							if (search != null && search.length() > 0) {
								mADD=1;
								Intent intent = new Intent();
								intent.setClass(AItem.this, AShowSearch.class);
								intent.putExtra("search_item", search);
								startActivityForResult(intent, SERCHGOODS);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						dialog.dismiss();
					}
				});

 ((EditText) root.findViewById(R.id.edit_source_1)).setOnKeyListener(new View.OnKeyListener() {
	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
	//監視鍵盤按鍵
		if (mMode!=PItemMode.SEARCH){				
		 if(event.getAction()== KeyEvent.ACTION_DOWN){ 
			if  (keyCode==KeyEvent.KEYCODE_ENTER && ((EditText) root	.findViewById(R.id.edit_source_1)).getText().toString().length()>0){
				String source=((EditText) root.findViewById(R.id.edit_source_1)).getText().toString().toUpperCase();
				String search = searchGoodsItem("GOODSNO",source,1);
				if (search != null && search.length() > 0) {
					mADD=1;
					dialog.dismiss();
					Intent intent = new Intent();
					intent.setClass(AItem.this,AShowSearch.class);
					intent.putExtra("search_item", search);
					startActivityForResult(intent, SERCHGOODS);
				}

				return true;
			}
		 }
		}
	return false;
	}
	
});
 		
 ((EditText) root.findViewById(R.id.edit_source_3)).setOnKeyListener(new View.OnKeyListener() {
	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
	//監視鍵盤按鍵
		if (mMode!=PItemMode.SEARCH){				
		 if(event.getAction()== KeyEvent.ACTION_DOWN){ 
			if  (keyCode==KeyEvent.KEYCODE_ENTER && ((EditText) root	.findViewById(R.id.edit_source_3)).getText().toString().length()>0){
				String source=((EditText) root	.findViewById(R.id.edit_source_3)).getText().toString().toUpperCase();
				String search = searchGoodsItem("GOODSNAME",source,1);
				if (search != null && search.length() > 0) {
					dialog.dismiss();
					mADD=1;
					Intent intent = new Intent();
					intent.setClass(AItem.this,AShowSearch.class);
					intent.putExtra("search_item", search);
					startActivityForResult(intent, SERCHGOODS);
				}

				return true;
			}
		 }
		}
	return false;
	}
	
});
 		
		
		String goodno = itemNumber;
		((EditText) root.findViewById(R.id.edit_source_1)).setText(goodno);
		((EditText) root.findViewById(R.id.edit_source_2)).setText("");
		dialog.setView(root);
		dialog.show();
	}

	private ListView mDialogListView = null;

	// 主要需要修改這個 show search
	private void showSearchResult(final List<ItemData> listData) {
		final View root = this.getLayoutInflater().inflate(R.layout.dlg_search_item, null);
		final AlertDialog dialog = new AlertDialog.Builder(this).setTitle("搜尋結果共 (" + listData.size() + ") 筆").setView(root)
				.setPositiveButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// callback.onAction();
						try {
							dialog.dismiss();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}).create();

		mDialogListView = (ListView) root.findViewById(R.id.list_item);
		CItemAdapter adapter = new CItemAdapter(AItem.this, listData);
		mDialogListView.setAdapter(adapter);
		mDialogListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// 直接帶入值給自己
				mData = listData.get(position);
				if (mData != null) {
					setAllData(false);//不要置換置入批號
					Toast.makeText(AItem.this, "恢復此商品編號資料", Toast.LENGTH_SHORT).show();
				}
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	// 將日期顯示再 title 由於480x800會無法顯示！
	private void setTitleName(String date) {
		StringBuffer buf = new StringBuffer();
		buf.append(getString(R.string.app_name)).append(" (").append(date.replace("-", "/")).append(")");
		this.setTitle(buf.toString());
	}
	
	private void showComputer(final int vid) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		final View root = this.getLayoutInflater().inflate(R.layout.dlg_computer, null);
		final Calculator calu = new Calculator(AItem.this, root);
		final TextView print = (TextView) root.findViewById(R.id.text_print);
		String strValue = ((EditText) AItem.this.findViewById(vid)).getText().toString();
		if (strValue != null && strValue.length() > 0) {
			print.setText(strValue);
			// 凡是編號的都需要設定可以直接編輯數字
			switch (vid) {
			// case R.id.edit_source_number:
			// case R.id.edit_goods_number:
//20130131 change to MainClick()			
//			case R.id.edit_batch:
//				calu.setBuffer(strValue);
//				break;
			}
		}

		dialog.setView(root);
		dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				calu.resultNumber();
				EditText edit = (EditText) AItem.this.findViewById(vid);
				try {
					String result = print.getText().toString();
					if (result == null || result.length() <= 0) {
						print.setText("0");
					} else if (result.indexOf("+") > 0) {
						print.setText("0");
					} else if (result.indexOf("-") > 0) {
						print.setText("0");
					} else if (result.indexOf("×") > 0) {
						print.setText("0");
					} else if (result.indexOf("÷") > 0) {
						print.setText("0");
					}
					edit.setText(print.getText().toString());

					if (vid == R.id.edit_inprice || vid == R.id.edit_addcost
							|| vid == R.id.edit_rate) {
						// 重新計算成本
						refreshCost(0);
						
					}else if (vid == R.id.edit_cost ) {
						// 重新計算成本
						refreshCost(1);
					}else if (vid == R.id.edit_wholeprice) {
						// 重新計算成本
						refreshCost(2);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				calu.clear();
			}
		});
		dialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		dialog.show();
	}

	// 重新計算成本
	private void refreshCost(int mode) {
		double d0 = Utilis.toDouble(((EditText) findViewById(R.id.edit_inprice)).getText().toString());
		double rate = Utilis.toDouble(((EditText) findViewById(R.id.edit_rate)).getText().toString());
		double addcost = Utilis.toDouble(((EditText) findViewById(R.id.edit_addcost)).getText().toString());
		if (mode==0){
			double d1 = (d0 * rate) + addcost;
			((EditText) findViewById(R.id.edit_cost)).setText(myformat3.format(d1));
		}
		
		if (SysDb[5].equalsIgnoreCase("1")){
			if (mode<2){
			if (Utilis.toDouble(((EditText) findViewById(R.id.edit_midprice)).getText().toString())>0)  ((EditText) findViewById(R.id.edit_midprice)).setText(myformat2.format(mPrice[2]+addcost));
			if (Utilis.toDouble(((EditText) findViewById(R.id.edit_wholeprice)).getText().toString())>0)  ((EditText) findViewById(R.id.edit_wholeprice)).setText(myformat2.format(mPrice[3]+addcost));
			}
			double dealer=Utilis.toDouble(((EditText) findViewById(R.id.edit_wholeprice)).getText().toString());
			if (SysDb[8].indexOf(":")>0){
				String pix[]=SysDb[8].split(":");
				 ((EditText) findViewById(R.id.edit_netprice)).setText(myformat2.format(Math.ceil(dealer*Utilis.toDouble(pix[2])/10)*10));
				 ((EditText) findViewById(R.id.edit_retailprice)).setText(myformat2.format(Math.ceil(dealer*Utilis.toDouble(pix[3])/10)*10));
			}
			//if (Utilis.toDouble(((EditText) findViewById(R.id.edit_netprice)).getText().toString())>0)  ((EditText) findViewById(R.id.edit_netprice)).setText(myformat2.format(mPrice[4]+addcost));
			//if (Utilis.toDouble(((EditText) findViewById(R.id.edit_retailprice)).getText().toString())>0)  ((EditText) findViewById(R.id.edit_retailprice)).setText(myformat2.format(mPrice[5]+addcost));
		}else if (SysDb[5].equalsIgnoreCase("2")){//以公式
			if (SysDb[8].indexOf(":")>0){
				String pix[]=SysDb[8].split(":");
				double cost=Utilis.toDouble(((EditText) findViewById(R.id.edit_cost)).getText().toString());
				if (mode<2){
				 ((EditText) findViewById(R.id.edit_midprice)).setText(myformat2.format(Math.ceil(cost*Utilis.toDouble(pix[0])/10)*10));
				 ((EditText) findViewById(R.id.edit_wholeprice)).setText(myformat2.format(Math.ceil(cost*Utilis.toDouble(pix[1])/10)*10));
				} 
				double dealer=Utilis.toDouble(((EditText) findViewById(R.id.edit_wholeprice)).getText().toString());
				 ((EditText) findViewById(R.id.edit_netprice)).setText(myformat2.format(Math.ceil(dealer*Utilis.toDouble(pix[2])/10)*10));
				 ((EditText) findViewById(R.id.edit_retailprice)).setText(myformat2.format(Math.ceil(dealer*Utilis.toDouble(pix[3])/10)*10));
			}
			
		}
	}

	class NumberClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(AItem.this);
			showComputer(id);
		}
	}

	class MainLongClick implements OnLongClickListener {
		@Override
		public boolean onLongClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(AItem.this);
			switch (id) {
				case R.id.edit_supply:
					Intent intent = new Intent();
					intent.setClass(AItem.this, Qfactff.class);
					intent.putExtra("mode", EMode.EDIT);
					intent.putExtra("countryid", mCountry);
					startActivityForResult(intent, ASUPPLY);
					break;
					
				case R.id.img_post: 
					eventImgCapture(TPICTUREP);
					break;
				
				case R.id.layout_img_item: 
					eventImgCapture(TPICTURE);
					break;
				
				case R.id.btn_ps:  //語音
					startVoiceRecognitionActivity_ps();
					break;

				case R.id.itemname_btn :  //語音
					startVoiceRecognitionActivity();
					break;
			}
			return false;
		}
	}

	class MainClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(AItem.this);
			switch (id) {
			case R.id.btn_new:
				eventImgFile();
				break;
			case R.id.edit_source_number: {
				String source = ((EditText) findViewById(R.id.edit_source_number))
						.getText().toString();
				DialogUtilis.showSourceItem(AItem.this,
						R.id.edit_source_number, source);
				break;
			}
			case R.id.edit_goods_number: {
				String goods = ((EditText) findViewById(R.id.edit_goods_number))
						.getText().toString();
				showItemDialog(AItem.this, R.id.edit_goods_number, goods);
				break;
			}
			case R.id.btn_income:
				if (mMode == ItemMode.EDIT && mMid>0 )  {
					 //@@getCountDetail(mData.GoodsNo);
					if (saveData() == true) {
						
						if (mData.GoodsNo !=null && mData.GoodsNo.length()>0 &&  mData.nGoodsType>0 && mData.batch!=null &&mData.batch.length()>0){

							Intent intent = new Intent();
							intent.putExtra("mid", mMid);
							intent.putExtra("batch", mData.GoodsNo);
							intent.putExtra("item_mode", ItemMode.EDIT); // 新增 對應帳戶使用
							intent.putExtra("cong", 0);
							intent.putExtra("unit", mData.nUnit);
							intent.putExtra("size", mData.mSizes);
							intent.putExtra("colorno", mData.mColorsNo);
							intent.putExtra("color", mData.mColors);
							intent.putExtra("countlist", mData.mCountList);
	 						intent.putExtra("mkind", "20");
							intent.putExtra("unitprice", mData.dP0);
							intent.putExtra("discount", 100);
		
							if (isOnkey==1)
								intent.setClass(AItem.this, AIncomePc.class);
							else
								intent.setClass(AItem.this, AIncome.class);
							
							startActivityForResult(intent, RESULT_INCOME);
						}
				 }else{
				        	Toast.makeText(AItem.this, "請先補充完整資料!!再展開!!", Toast.LENGTH_SHORT).show();
				 }
				} else {
					// eventImgFile();
					startVoiceRecognitionActivity();
				}
				break;
			case R.id.btn_remind: {
				Intent intent = new Intent();
				intent.setClass(AItem.this, AElements.class);
				// intent.putExtra("mid", mMid);
				if (mData.nWashID <= 0) {
					intent.putExtra("wash_id", 1);
				} else {
					intent.putExtra("wash_id", mData.nWashID);
				}
				if (mData.nQualityID <= 0) {
					intent.putExtra("quality_id", 1);
				} else {
					intent.putExtra("quality_id", mData.nQualityID);
				}
				startActivityForResult(intent, ELEEMENTS_CODE);
				break;
			}
			
			case R.id.btn_save:
				if (saveData() == true) {
					Intent intent = new Intent();
					if (nWhere<1){//0.ManagerItem 1.GalleryView
						intent.putExtra("item_batch", ((EditText) findViewById(R.id.edit_batch)).getText().toString());
						AItem.this.setResult(RESULT_OK,intent);
					}else if (nWhere==2 && mModeD==ItemMode.ADD){//Qposff maybe GalleryViewP
						if (((EditText) findViewById(R.id.edit_batch)).getText().toString().length()>0
							 && ((EditText) findViewById(R.id.edit_goods_number)).getText().toString().length()>0 
							 && ((EditText) findViewById(R.id.edit_supply)).getText().toString().length()>0 
							 && mType>0){							
								intent.putExtra("item_batch", ((EditText) findViewById(R.id.edit_goods_number)).getText().toString());
								AItem.this.setResult(RESULT_OK,intent);
						}
					}else if (nWhere==3 && mModeD==ItemMode.ADD){//Qposff maybe GalleryViewP
						if (((EditText) findViewById(R.id.edit_batch)).getText().toString().length()>0
							 && ((EditText) findViewById(R.id.edit_source_number)).getText().toString().length()>0 
							 && ((EditText) findViewById(R.id.edit_supply)).getText().toString().length()>0 
							 && mType>0){
								intent.putExtra("item_batch", ((EditText) findViewById(R.id.edit_source_number)).getText().toString());
								AItem.this.setResult(RESULT_OK,intent);
						}
					}
					
					finish();
				}
				break;
			case R.id.btn_exit:
				finish();
				break;
			case R.id.btn_season: {
				getYS = DateUtil.showSeason(AItem.this,id,"",getYS[0],getYS[1],1);
				break;
			}
			case R.id.img_country: {
				Intent intent = new Intent();
				intent.setClass(AItem.this, CodeList.class);
				intent.putExtra("code_mode", CodeMode.COUNTRY);
				intent.putExtra("edit_mode", 1);
				AItem.this.startActivityForResult(intent, COUNTRY_CODE);
				break;
			}
			case R.id.pic_batch: {
				try {
					Bitmap bitmap = Utilis.getScaleBitmap(mImagePath, bmW, bmH);
					if (bitmap != null) {
						ExifInterface exif = new ExifInterface(mImagePath);
						int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
						Bitmap adjustedBitmap=Utilis.exifToDegrees(mImagePath,bitmap,rotation);
						OutPhoto.setImageBitmap(adjustedBitmap);
					}
				} catch (Exception e) {
				}
				break;
			}
			//可以放大顯示圖
			case R.id.layout_img_item: {
				if (mImagePath!=null  && mImagePath.length()>10){
					Intent intent = new Intent();
					intent.setClass(AItem.this,Show_imagebig.class);
					intent.putExtra("image", mImagePath);
					startActivity(intent);
				}
				break;
			}

			//可以放大顯示圖
			case R.id.img_post: {
				if (mImagePathP!=null  && mImagePathP.length()>10){
					Intent intent = new Intent();
					intent.setClass(AItem.this,Show_imagebig.class);
					intent.putExtra("image", mImagePathP);
					startActivity(intent);
				}
				break;
			}
			//btn_ps
			case R.id.btn_ps: {
				//PS 複製串文字 如果內文為空
				//((EditText) findViewById(R.id.edit_ps)).setText(mData.mPS);
				if (((EditText) findViewById(R.id.edit_ps)).getText().toString().length()<=0)
					((EditText) findViewById(R.id.edit_ps)).setText("胸圍: 腰圍: 臀圍: 下擺: 袖長: 腋圍: 袖圍: 肩寬: 全長:");
				break;
			}

			case R.id.edit_supply: {
				break;
			}
			case R.id.edit_datetime: {
				Calendar c = Calendar.getInstance();
				if (mStartYear != 0) {
					c.set(Calendar.YEAR, mStartYear);
					c.set(Calendar.MONTH, mStartMonth - 1);
					c.set(Calendar.DAY_OF_MONTH, mStartDay);
				}
				DateUtil.showDateDialog(AItem.this, "請選擇採購日期", c,
						new IDateDialog() {
							@Override
							public void onDateDialogFinish(String date,
									int year, int month, int day) {
								if (date != null && date.length() > 0) {
									((EditText) findViewById(R.id.edit_datetime))
											.setText(date);
									setTitleName(date);
									mStartYear = year;
									mStartMonth = month;
									mStartDay = day;
								}
							}
						});
				break;
			}
			default:
				break;
			}
		}
	}

	/**
	 * 
	 * @return
	 */
	
	public String getPath(Uri uri) {
        if( uri == null ) {
            return null;
        }
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if( cursor != null ){
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        return null;
	}
	
	@SuppressWarnings("finally")
	private String searchGoodsItem(String param, String key,int mode) {
		SQLiteDatabase db = Utilis.getDB(AItem.this);
		List<ItemData> listData = null;

		StringBuffer buf = new StringBuffer();
		listData = getSearchItem(db, param, key);
		try {
			if (listData != null && listData.size() > 0) {
					listData.clear();
					if (param.equalsIgnoreCase("GOODSNO")) {
						Toast.makeText(AItem.this, "從\"商品編號\"找到相關的商品資料",
								Toast.LENGTH_SHORT).show();
						buf.append("Select B.Name,A.* from qdetail A inner join qc_country B on A.COUNTRY=B._ID WHERE ");
						if (mode==0){
							buf.append("GOODSNO").append(" ='").append(key)
							.append("' order by BATCH desc");
						}else{
							buf.append("GOODSNO").append(" like '%").append(key)
							.append("%' order by BATCH desc");
						}
					} else {
						Toast.makeText(AItem.this, "從\"商品名稱\"找到相關的商品資料",
								Toast.LENGTH_SHORT).show();
						buf.append("Select B.Name,A.* from qdetail A inner join qc_country B on A.COUNTRY=B._ID WHERE ");
						buf.append("GOODSNAME").append(" like '%").append(key)
								.append("%' order by BATCH desc");
					}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (db != null) {
				db.close();
			}
			return buf.toString();
		}
	}

	// 搜尋指定的項目 是否有資料回傳
	private List<ItemData> getSearchItem(SQLiteDatabase db, String param,
			String key) {
		List<ItemData> listData = null;
		try {
			if (key == null || key.length() <= 0) {
				return null;
			}
			StringBuffer buf = new StringBuffer();
			buf.append("Select B.Name,A.* from qdetail A inner join qc_country B on A.COUNTRY=B._ID WHERE ");
			if (param.equalsIgnoreCase("P5") != true) {
				buf.append(param).append(" like '%").append(key).append("%'")
						.append(" order by BATCH DESC limit 50");
			} else {
				buf.append("P5=").append(key)
						.append(" order by BATCH DESC limit 50");
			}
			Cursor cursor = db.rawQuery(buf.toString(), null);
			if (cursor != null) {
				if (cursor.getCount() > 0) {
					listData = new ArrayList<ItemData>();
					cursor.moveToFirst();
					for (int k = 0; k < cursor.getCount(); k++) {
						ItemData data = DBUtil.CItem.parseDetailData(cursor);
						listData.add(data);
						cursor.moveToNext();
					}
				}
				cursor.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return listData;
	}

	private void setSeason(View v) {
			((Button) v).setText(getYS[0]+"/"+mSeason[getYS[1]]);
	}

	private int REQUEST_CROP_IMAGE = 1022;

	private void eventImgCrop(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setData(uri);
		intent.putExtra("crop", "true");
		intent.putExtra("return-data", true);
		startActivityForResult(intent, REQUEST_CROP_IMAGE);
	}

	private void eventImgCapture(int PHOTO) {
		Toast.makeText(AItem.this, "相機請使用直拍", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File folder = new File(SAVE_FOLDER + mBatch);
		if (folder.exists() == false) folder.mkdirs();
		File file = new File(SAVE_FOLDER + mBatch + File.separator, "mtr_"+ String.valueOf(DateUtil.getSystemTime())+ ".jpg");

		if (file.exists() == false) {
			try {
				file.createNewFile();
			} catch (Exception e) {

			}
		}
		mImageCaptureUri = Uri.fromFile(file);

		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,	mImageCaptureUri);

		try {
			intent.putExtra("return-data", true);
			startActivityForResult(intent, PHOTO);
		} catch (ActivityNotFoundException e) {
			// Do nothing for now
		} catch (Exception e) {
		}
	}

	private void eventImgFile() {
		
		Intent intent = new Intent();
		// 取得相片後返回本畫面 
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Picture"),SELECT_PICTURE);
	}

	/**
	 * Fire an intent to start the speech recognition activity.
	 */
	private void startVoiceRecognitionActivity() {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
				"Speech recognition demo");
		startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
	}
	
	private void startVoiceRecognitionActivity_ps() {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
				"Speech recognition demo");
		startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE_PS);
	}
	
	public class CItemAdapter extends BaseAdapter {

		private List<ItemData> mListData = null;
		private LayoutInflater mInflater;
		private AsyncImageFileLoader asyncImageFileLoader;

		public CItemAdapter(Context cnt, List<ItemData> listData) {
			mInflater = LayoutInflater.from(cnt);
			mListData = listData;
			asyncImageFileLoader = new AsyncImageFileLoader();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mListData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_item, null);
				holder = new ViewHolder();
				holder.imageItem = (ImageView) convertView
						.findViewById(R.id.img_pic);
				holder.textGoodsNo = (TextView) convertView
						.findViewById(R.id.text_goodsno);
				holder.textImpo = (TextView) convertView
						.findViewById(R.id.text_impo);
				holder.textName = (TextView) convertView
						.findViewById(R.id.text_name);
				holder.textNumber = (TextView) convertView
						.findViewById(R.id.text_number);
				holder.textMoney = (TextView) convertView
						.findViewById(R.id.text_money);
				holder.textCountry = (TextView) convertView
						.findViewById(R.id.text_country);
				holder.textCompany = (TextView) convertView
						.findViewById(R.id.text_company);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			ItemData data = mListData.get(position);

			String tag = data.pic1 + position;
			holder.imageItem.setTag(tag);
			try {
				Bitmap cachedBitmap = asyncImageFileLoader.loadBitmap(
						data.pic1, 70, 96, tag, new ImageCallback() {
							public void imageCallback(Bitmap imageBitmap,
									String imageFile, String tag) {
								// 利用檔案名稱找尋當前mHolder.icon
								ImageView imageViewByTag = (ImageView) mDialogListView
										.findViewWithTag(tag);
								if (imageViewByTag != null) {
									if (imageBitmap != null)
										imageViewByTag
												.setImageBitmap(imageBitmap);
								} else {
									Log.e("cwbuyer", "error ImageView null : "
											+ position);
								}
							}
						});
				if (cachedBitmap != null) {
					holder.imageItem.setImageBitmap(cachedBitmap);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			// int w = bmp.getWidth();
			// int h = bmp.getHeight();
			// holder.imageItem.setImageBitmap(bmp);
			holder.textName.setText(data.goodsname);
			holder.textGoodsNo.setText(data.GoodsNo);
			holder.textImpo.setText("總件數 " + data.nTotalCount);
			// holder.textMoney.setText(" $" + data.dP0);
			holder.textMoney.setText(" $"+ myformat2.format((data.nTotalCount * data.dP1)));
			holder.textCountry.setText(data.country);
			holder.textCompany.setText(data.supply);
			holder.textNumber.setText(data.sourceNo);
			return convertView;
		}

		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textName;
			TextView textMoney;
			TextView textCountry;
			TextView textNumber;
			TextView textCompany;
			TextView textGoodsNo;
			TextView textImpo;
		}
	}

	private void Searched(String search){
	
		Utilis.runVibrate(this);
		mSearch=search;
		mADD=1;
		DialogUtilis.showDialog(AItem.this, "請選擇以下功能", -1,
				new String[] {"追加原有商品","重新輸入"}, new IDialog() {
					@Override
					public void onDialogFinish(int pos, String choice) {
						switch (pos) {
							case 0:
							{
								mADD=1;
								Intent intent = new Intent();
								intent.setClass(AItem.this, AShowSearch.class);
								intent.putExtra("search_item", mSearch);
								startActivityForResult(intent, SERCHGOODS);
								break;
							}
							case 1:mADD=0;
						}
					}
				});
	}
	
	// 批號的傾聽
	private TextWatcher watcherBatch = 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) {

			mBatch = ((EditText) findViewById(R.id.edit_batch)).getText().toString().toUpperCase();
			
			if (mDefaultData.nItemProduct == 4) {
				((EditText) findViewById(R.id.edit_goods_number)).setText(AppUtil.getItemNo(AItem.this,AppUtil.Format.Batch, mBatch));
			}

			// 來源編號以批號為主
			if (mDefaultData.nSourceNumber == 1) {
				if (mBatch != null && mBatch.length() > 0) {
					mData.sourceNo = mBatch.toString();
				} else {
					mData.sourceNo = "";
				}
				((EditText) findViewById(R.id.edit_source_number)).setText(mData.sourceNo);
				try {
					if (mDefaultData.nItemProduct == 1) {
						((EditText) findViewById(R.id.edit_goods_number)).setText(AppUtil.getItemNo(AItem.this,AppUtil.Format.SourceNo,mData.sourceNo));
					} else if (mDefaultData.nItemProduct == 2) {
						if (mBatch != null && mBatch.length() > 0) {
							((EditText) findViewById(R.id.edit_goods_number)).setText(mData.supply+ mData.sourceNo);
						} else {
							((EditText) findViewById(R.id.edit_goods_number)).setText("");
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
//			((EditText) findViewById(R.id.edit_batch)).setText(batch);
		}
		
	};

	// 來源編號的傾聽
	private TextWatcher watcherSource = 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) {
			// 1. 自訂_空白 (可修改)
			// 2. 來源編號 + 流水號 (3碼)
			// 3. 廠商編號 + 來源編號 (根據兩個加起來)
			// 4. 廠商編號 + 流水號 (5碼)
			// 5. 批號+流水號 (5碼)
			// 6. 同系統流水號 (5碼)

			if (s != null && s.length() > 0) {
				mData.sourceNo = s.toString();
			} else {
				mData.sourceNo = "";
			}

			try {
				if (mDefaultData.nItemProduct == 1) {
					((EditText) findViewById(R.id.edit_goods_number)).setText(AppUtil.getItemNo(AItem.this,AppUtil.Format.SourceNo, mData.sourceNo));
				} else if (mDefaultData.nItemProduct == 2) {
					if (s != null && s.length() > 0) {
						((EditText) findViewById(R.id.edit_goods_number)).setText(mData.supply + mData.sourceNo);
					} else {
						((EditText) findViewById(R.id.edit_goods_number)).setText("");
					}
				}else if (mDefaultData.nItemProduct == 5) {
					((EditText) findViewById(R.id.edit_goods_number)).setText( mData.sourceNo);					
				}else if (mDefaultData.nItemProduct == 6) {//廠商+批號+流水號
					((EditText) findViewById(R.id.edit_goods_number)).setText(mData.supply+"."+mData.sourceNo);
				}else if (mDefaultData.nItemProduct == 7) {//年度季別+流水號
					if (mADD==0){
					String Stile=""+mDefaultData.nYear+""+mData.nSeason;
					((EditText) findViewById(R.id.edit_goods_number)).setText(Stile.substring(2)+mData.sourceNo);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	// 廠商編號的傾聽
	// 注意：在callback的時候也要去修改商品名稱
	private TextWatcher watcherSupply = 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) {
			Log.d("TAG", "[TextWatcher][onTextChanged]" + s);
			if (s != null && s.length() > 0) {
				mData.supply = s.toString();
			} else {
				mData.supply = "";
			}
			try {
				if (mDefaultData.nItemProduct == 2) {
					((EditText) findViewById(R.id.edit_goods_number)).setText(mData.supply + mData.sourceNo);
				} else if (mDefaultData.nItemProduct == 3) {
					if (s != null && s.length() > 0) {
						((EditText) findViewById(R.id.edit_goods_number)).setText(AppUtil.getItemNo(AItem.this,	AppUtil.Format.Company, mData.supply));
					} else {
						((EditText) findViewById(R.id.edit_goods_number)).setText("");
					}
				}else if (mDefaultData.nItemProduct == 6) {//廠商+批號+流水號
						((EditText) findViewById(R.id.edit_goods_number)).setText(mData.supply+"."+mData.sourceNo);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	// 批號的傾聽
	private TextWatcher watcherSeason = 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) {
				try {
					if (mDefaultData.nItemProduct == 7) {
						if (mADD==0){
							String Stile=getYS[0]+""+getYS[1];
							String productNo = AppUtil.getItemNo(AItem.this, AppUtil.Format.YearSeason,Stile.substring(2));
							String sourceNo=productNo.substring(3);
							mData.sourceNo = sourceNo;
							mData.GoodsNo = productNo; 
					
							((EditText) findViewById(R.id.edit_goods_number)).setText(productNo);
							((EditText) findViewById(R.id.edit_source_number)).setText(sourceNo);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
	};

	
}
