package com.cwbuyer.lib;

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

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.pwbuyer.main.R;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.ItemData;
import com.cwbuyer.main.APos.PItemKind;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.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.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

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

	private Gallery mGallery01;
	private ImageView mImage;
	private TextView mTextView01;
	private TextView mTextView02;
	private TextView mTextView03;
	private TextView mTextView04;
	private TextView mTextView05;
	
//  	private LinearLayout lTableView = null;
	private final  String SAVE_FOLDER = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+"CWBuyer/web/uploadfile/images/" ;
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + "CWBuyer"  ;
	String uriAPI=null;
	Bitmap mBitmap=null;
	private int rotationInDegrees=0;
	private final int TPICTURE = 1009;
	private final int SELECT_PICTURE = 1010;
	private String mImagePath = null;
	private static int nPicDegree =0;
	Uri mImageCaptureUri = null;

	public ItemData iData;	

	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<Integer> mCountryIdList = new ArrayList<Integer>();
	private ArrayList<String> mTypeList = new ArrayList<String>();
	private ArrayList<Integer> mTypeIdList = new ArrayList<Integer>();
	
	HashMap<Integer,Integer> mCountRow = new HashMap<Integer,Integer>(); // 列資料
	HashMap<Integer,String> mCountCell = new HashMap<Integer,String>();  // 行資料

	int nPart=0;
	int maxRec = 20;
	int positions = 0;
	String mGoods="";
	private Bitmap reflactionBitmap; //提供畫布用
	//int PSWD=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT",5));
	private String [] DialogMenu={"編輯-照相","編輯-相本","移除","返回"};	
	
	String[] menu_X={"追蹤","返回" };
	String[] menu_Y={"沒有異動過","已異動過" };
	
	String goodsPic = "";
	String prod_id=null;
	String prod_detail=null;
	private String batch=null;
	private String[] Apicstr; //圖檔名稱
	private String[] GoodsNo; //商品編號
	private int[] StyleSrc;
	int Wheight;
	int Wwidth;
	
	//For Cloud
	public ProgressDialog myDialog = null;
	protected static final int REFRESH_DATA = 0x00000001;
	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	
	Bundle bundle;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		String OutPhotoURI="";
		if ((requestCode == SELECT_PICTURE) && (resultCode == RESULT_OK)) // 相本
		{
			//Uri uri = data.getData();
            Uri selectedImageUri = data.getData();
	            if (Apicstr[positions].length()<=0){//ADD
	        		File folder = new File(SAVE_FOLDER.substring(0, SAVE_FOLDER.length()-1));
	        		if (folder.exists() == false) folder.mkdirs();
	            	mImagePath=SAVE_FOLDER + "mtr_"+ String.valueOf(DateUtil.getSystemTime())+ ".jpg";
	            	Apicstr[positions]=mImagePath;
	            }else{//EDIT 使用原來的檔名
	            	mImagePath=Apicstr[positions];
	            }
            
            Bitmap bitmap=null;
//        	Toast.makeText(this, "成功"+Build.VERSION.SDK_INT, Toast.LENGTH_SHORT).show();
            
            if (Build.VERSION.SDK_INT < 19) {
            	OutPhotoURI = getPath(selectedImageUri);
            	mBitmap = Utilis.getScaleBitmap(OutPhotoURI, 650, 952);
                //mBitmap = BitmapFactory.decodeFile(OutPhotoURI);
//            	Toast.makeText(this, "成功"+Build.VERSION.SDK_INT, Toast.LENGTH_SHORT).show();
				try {
					ExifInterface exif = new ExifInterface(OutPhotoURI);
					int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
					rotationInDegrees = exifToDegrees(rotation);
					Matrix matrix = new Matrix();
					matrix.preRotate(rotationInDegrees);
					bitmap = Bitmap.createBitmap(mBitmap, 0, 0, 650, 952, matrix, true);
					
    		        FileOutputStream fos = null;
    				try {
    						fos = new FileOutputStream(mImagePath);
   	    					bitmap.compress(CompressFormat.JPEG, 90, fos);
   	    					fos.close();
   	    					mBitmap=bitmap;	
    				} catch (FileNotFoundException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
            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, 90, stream);// (0 - 100)
    		        FileOutputStream fos = null;
    				try {
    						fos = new FileOutputStream(mImagePath);
    				} catch (FileNotFoundException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    				try {
    					bitmap.compress(CompressFormat.JPEG, 90, fos);
    					fos.close();
    					mBitmap = Utilis.getScaleBitmap(mImagePath,650, 952);
    	                //mBitmap = BitmapFactory.decodeFile(OutPhotoURI);
    					
    					try {
    						ExifInterface exif = new ExifInterface(mImagePath);
    						int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    						rotationInDegrees = exifToDegrees(rotation);
    						Matrix matrix = new Matrix();
    						matrix.preRotate(rotationInDegrees);
    						bitmap = Bitmap.createBitmap(mBitmap, 0, 0, 650, 952, matrix, true);

    						try {
    	    						fos = new FileOutputStream(mImagePath);
    	   	    					bitmap.compress(CompressFormat.JPEG, 90, fos);
    	   	    					fos.close();
    	   	    					mBitmap=bitmap;	
    	    				} catch (FileNotFoundException e) {
    	    					// TODO Auto-generated catch block
    	    					e.printStackTrace();
    	    				}

    					} catch (IOException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					
    					
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
                    
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
            
			if (bitmap != null) {
            	StyleSrc[positions]=1;
	    		mGallery01.setAdapter(new ImageAdapter(GalleryViewWeb.this, ChkPic()));
			}
		}else if ((requestCode == TPICTURE ) && (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(), 650, 952);
						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);
							matrix.preRotate(rotationInDegrees);
							Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, 650, 952, 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, 650, 952);
					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);
						
						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, 90, 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, 90, fos);
							fos.close();
							mBitmap=adjustedBitmap;
							
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				} catch (Exception e) {
				}
			}
			
			
			if (mBitmap!=null){
				Apicstr[positions]=OutPhotoURI;
            	StyleSrc[positions]=1;
	    		mGallery01.setAdapter(new ImageAdapter(GalleryViewWeb.this, ChkPic()));
			}
		}
	}
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Wwidth = dm.widthPixels;
        Wheight = dm.heightPixels;
		
		setContentView(R.layout.galleryweb);
		mGallery01 = (Gallery) findViewById(R.id.myGallery1);
		mImage = (ImageView) findViewById(R.id.imageView105);

		mImage.getLayoutParams().width=(int) (Wwidth/4);
		mImage.getLayoutParams().height=(int) (Wheight/3.5);

    	mTextView01 = (TextView) findViewById(R.id.textViewg1);
		mTextView02 = (TextView) findViewById(R.id.textViewg2);
		mTextView03 = (TextView) findViewById(R.id.textViewg3);
		mTextView04 = (TextView) findViewById(R.id.textViewg4);
		mTextView05 = (TextView) findViewById(R.id.textViewg5);

    	Bundle bundle = this.getIntent().getExtras();
		String fromW=bundle.getString("GalleryChild");
		String[] arrayW = fromW.split(",");
		batch=arrayW[0];
        
		getTypeData(this);
		getCountryData(this);

		String path = SAVE_FOLDER.substring(0, SAVE_FOLDER.length()-1);
        File myDataPath = new File(path);
        if (!myDataPath.exists()){
        	myDataPath.mkdirs();  //若不存在 則建立之
        }else{//若存在則一一刪除(歸零)
			File f = new File(path);        
			File file[] = f.listFiles();
			for (int i=0; i < file.length; i++)
			{
				Utilis.DeleteFile(SAVE_FOLDER+file[i].getName());
			    Log.d("Files", "FileName:" + file[i].getName());
			}
        }

        SQLiteDatabase db = Utilis.getDB(this);
		Cursor cs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		//多門市庫存分析表 @@@還要分總倉 OR 門市倉
		mySqlBuf.append("select GOODSNO,BATCH,PIC,MID from qdetail");
		mySqlBuf.append(" where GOODSNO ='" + batch+"'");
		mySqlBuf.append(" group by GOODSNO,BATCH,PIC ");
		cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount() > 0) {
				cs.moveToFirst();
				goodsPic=cs.getString(cs.getColumnIndex("PIC"));
			} else {
				db.close();
				finish();
			}
	db.close();
	cs.close();
	
	((Button) findViewById(R.id.btn_gryexit)).setOnClickListener(new Button.OnClickListener(){
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int Modify=0;
			for (int g=0;g<StyleSrc.length;g++){
				if (StyleSrc[g]==1) {Modify=1;break;}
			}
			if (Modify==1){
			new AlertDialog.Builder(GalleryViewWeb.this).setTitle(getString(R.string.str_msg)).setMessage(getString(R.string.msg_exit)).setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	              finish();
	            }
	          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	            }
	          }).show();
			}else{//因為沒有異動,所以直接離開
	              finish();
			}
		}
	});

	((Button) findViewById(R.id.btn_grysave)).setOnClickListener(new Button.OnClickListener(){
		@SuppressWarnings("unused")
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
		      myDialog = ProgressDialog.show(GalleryViewWeb.this,"資料上傳中.....","請稍候.............",true);//		setAutoRotationMode();			  
			int Modify=0;
			for (int g=0;g<StyleSrc.length;g++){
				if (StyleSrc[g]==1) {
					//FTP上傳檔案到SERVER
					String  AutoFile=Apicstr[g];
					if (AutoFile.length()>0){
						String ServerT=Apicstr[g].replace(SAVE_FOLDER, "web/uploadFile/images/");
						final File localFile = new File(AutoFile);
						final String serverFile =ServerT;
						boolean success=false;
						try {
							success=DBCloud.ftpUpdateFile(GalleryViewWeb.this,Utilis.getIni(GalleryViewWeb.this, "SYS", "IMPORT",1), 21,Utilis.getIni(GalleryViewWeb.this, "SYS", "IMPORT",4), Utilis.getIni(GalleryViewWeb.this, "SYS", "IMPORT",5), serverFile, localFile);												
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					Modify=1;
				}
			}
			if (Modify==1){
				String upWebStr="<p> ";
				for (int g=0;g<Apicstr.length;g++){
					if (Apicstr[g].length()>0){
						String WebPic=Apicstr[g].replace(SAVE_FOLDER, "../uploadFile/images/");
						upWebStr+="<a href=\""+WebPic+"\">";
						upWebStr+="<img alt=\"\" src=\""+WebPic+"\" style=\"height:952px; width:650px\" /></a>";
					}
				}
				upWebStr+="</p>";

	        	//Toast.makeText(GalleryViewWeb.this, upWebStr, Toast.LENGTH_SHORT).show();
	        	putInternet(batch,upWebStr);
				
			}
            myDialog.dismiss();
			finish();
		}
	});

	
	

	mGallery01.setOnItemLongClickListener(new OnItemLongClickListener(){

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int position, long arg3) {
			// TODO Auto-generated method stub
			Utilis.runVibrate(GalleryViewWeb.this);
			positions=position;
			//照相以編輯之 相本編輯之  移除
			DialogMenu[0]="照相-"+menu_Y[StyleSrc[positions]];
			DialogMenu[1]="相本-"+menu_Y[StyleSrc[positions]];
			DialogUtilis.showDialog(GalleryViewWeb.this, "請選擇以下功能", -1,
					DialogMenu, new IDialog() {
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch (pos) {
								case 0: //編輯-照相
								{
									eventImgCapture(TPICTURE);
								break;	
								}
								case 1: //編輯-相本
								{
									eventImgFile();
									
								break;	
								}
								case 2: //移除
								{
									StyleSrc[positions]=1;
									Apicstr[positions]="";
						    		mGallery01.setAdapter(new ImageAdapter(GalleryViewWeb.this, ChkPic()));
						    		Toast.makeText(GalleryViewWeb.this,"pic="+ Apicstr[positions]+"flag="+StyleSrc[positions]+"positions="+positions, Toast.LENGTH_SHORT).show();
								break;	
								}
								case 3: //返回
								{
								break;	
								}
							}
						}
				});
			
				return true;
		}
	});

	
	mGallery01.setOnItemClickListener(new Gallery.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long ids) {
				// TODO Auto-generated method stub
				Utilis.runVibrate(GalleryViewWeb.this);
				positions=position;
				//照相以編輯之 相本編輯之  移除
				DialogMenu[0]="照相-"+menu_Y[StyleSrc[positions]];
				DialogMenu[1]="相本-"+menu_Y[StyleSrc[positions]];
				DialogUtilis.showDialog(GalleryViewWeb.this, "請選擇以下功能", -1,
						DialogMenu, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								switch (pos) {
									case 0: //編輯-照相
									{
										eventImgCapture(TPICTURE);
									break;	
									}
									case 1: //編輯-相本
									{
										eventImgFile();
										
									break;	
									}
									case 2: //移除
									{
										StyleSrc[positions]=1;
										Apicstr[positions]="";
							    		mGallery01.setAdapter(new ImageAdapter(GalleryViewWeb.this, ChkPic()));
							    		Toast.makeText(GalleryViewWeb.this,"pic="+ Apicstr[positions]+"flag="+StyleSrc[positions]+"positions="+positions, Toast.LENGTH_SHORT).show();
									break;	
									}
									case 3: //返回
									{
									break;	
									}
								}
							}
					});
			}
		});

		//製作一組畫面 多功能的
		//補印條碼/追蹤/返回該批號單
		mImage.setOnClickListener(new ImageView.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Utilis.runVibrate(GalleryViewWeb.this);
				DialogUtilis.showDialog(GalleryViewWeb.this, "請選擇以下功能", -1,
						menu_X, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								switch (pos) {
									case 0: //商品追蹤
									{
										mGoods=GoodsNo[positions];
										Intent intent = new Intent();
										intent.putExtra("QHis_kind", PItemKind.TR10);
										intent.putExtra("QHis_mode", 1);
										intent.putExtra("QHis_User","" );
										intent.putExtra("QHis_Goods",mGoods );
										intent.setClass(GalleryViewWeb.this, QHis.class);
										startActivity(intent);
										
									break;	
									}
									case 1: //返回
									{
									break;	
									}
								}
							}
					});
			}
		});
		
		getInternet(batch);
	}		
	
	private void getInternet(String mGoods){

		if (Utilis.haveInternet(this) && of_line!=0){  //雲端&&網路OK
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
			
				bfstr.append(Utilis.getIni(this, "SYS", "IMPORT", 2)).append(";");
				bfstrF.append("UID").append(";");
				bfstr.append(mGoods).append(";");
				bfstrF.append("GOODSNO").append(";");
				bfstr.append(Utilis.getIni(this, "SYS", "DEPT", 6)).append(";");
				bfstrF.append("PARTNO").append(";");  //總倉代號 名稱
				bfstr.append(Utilis.getIni(this, "SYS", "DEPT", 7));
				bfstrF.append("PARTNA");
				
				final String []fields=bfstr.toString().split(";");
				final String []fieldFs=bfstrF.toString().split(";");
				
			      myDialog = ProgressDialog.show(this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
				  
			      new Thread()
			      { 
			        public void run()
			        { 
			          try
			          { 
							uriAPI="http://"+Utilis.getIni(GalleryViewWeb.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(GalleryViewWeb.this, "SYS", "IMPORT", 2)+File.separator+"getweb_prod.php";
							HttpPost httpRequest = new HttpPost(uriAPI);
							// Post運作傳送變數必須用NameValuePair[]陣列儲存
							
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							for(int x=0;x<fields.length;x++){
								params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
							}
							try {
								// 發出HTTP request(請求) 
								httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								// 取得HTTP response(回傳) 
								HttpResponse httpResponse = new DefaultHttpClient()
										.execute(httpRequest);
								// 若狀態碼為200 ok 
								if (httpResponse.getStatusLine().getStatusCode() == 200)
								{
									// 取出回應字串
									Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI);
									String strResult = EntityUtils.toString(httpResponse	.getEntity());
									mHandlerWP.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
								}
							} catch (Exception e)
							{
								e.printStackTrace();
							}

			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			            // 卸載所建立的myDialog物件。
			            myDialog.dismiss();
			          }
			        }
			      }.start(); /* 開始執行執行緒 */

		
		}		
	}
	
	private void putInternet(String mGoods,String upWeb){

		if (Utilis.haveInternet(this) && of_line!=0){  //雲端&&網路OK
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
			
				bfstr.append(Utilis.getIni(this, "SYS", "IMPORT", 2)).append("okok");
				bfstrF.append("UID").append("okok");
				bfstr.append(mGoods).append("okok");
				bfstrF.append("GOODSNO").append("okok");
				bfstr.append(Utilis.getIni(this, "SYS", "DEPT", 6)).append("okok");
				bfstrF.append("PARTNO").append("okok");  //總倉代號 名稱
				bfstr.append(upWeb);
				bfstrF.append("PARTNA");
				
				final String []fields=bfstr.toString().split("okok");
				final String []fieldFs=bfstrF.toString().split("okok");
				
				  
			      new Thread()
			      { 
			        @SuppressWarnings("unused")
					public void run()
			        { 
			          try
			          { 
							uriAPI="http://"+Utilis.getIni(GalleryViewWeb.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(GalleryViewWeb.this, "SYS", "IMPORT", 2)+File.separator+"putweb_prod.php";
							HttpPost httpRequest = new HttpPost(uriAPI);
							// Post運作傳送變數必須用NameValuePair[]陣列儲存
							
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							for(int x=0;x<fields.length;x++){
								params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
							}
							try {
								// 發出HTTP request(請求) 
								httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								// 取得HTTP response(回傳) 
								HttpResponse httpResponse = new DefaultHttpClient()
										.execute(httpRequest);
								// 若狀態碼為200 ok 
								if (httpResponse.getStatusLine().getStatusCode() == 200)
								{
									// 取出回應字串
									Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI);
									String strResult = EntityUtils.toString(httpResponse	.getEntity());
								}
							} catch (Exception e)
							{
								e.printStackTrace();
							}

			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			            // 卸載所建立的myDialog物件。
			          }
			        }
			      }.start(); /* 開始執行執行緒 */
		}		
	}
	
	
	private List<String> ChkPic() {
		/* 設定目前所在路徑 */
		List<String> it = new ArrayList<String>();
		/* 將所有檔案加入ArrayList中 */
		for (int i = 0; i < maxRec; i++) {
			if (getImageFile(Apicstr[i]))
				it.add(Apicstr[i]);
			else {it.add(filepath+"/0916961962.png");}
		}
		return it;
	}

	private boolean getImageFile(String fName) {
		boolean re;

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

		/* 依附檔名的類型決定MimeType */
		if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			re = true;
		} else {
			re = false;
		}
		return re;
	}
	
	/* 改寫BaseAdapter自訂一ImageAdapter class */
	public class ImageAdapter extends BaseAdapter {
		/* 宣告變數 */
		int mGalleryItemBackground;
		private Context mContext;
		private List<String> lis;

		/* ImageAdapter的建構子 */
		public ImageAdapter(Context c, List<String> li) {
			mContext = c;
			lis = li;
			/*
			 * 使用在res/values/attrs.xml中的<declare-styleable>定義 的Gallery屬性.
			 */
			TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
			/* 取得Gallery屬性的Index id */
			mGalleryItemBackground = a.getResourceId(
					R.styleable.Gallery_android_galleryItemBackground, 0);
			/* 讓物件的styleable屬性能夠反覆使用 */
			a.recycle();
		}

		/* 一定要覆寫的方法getCount,傳回圖片數目 */
		public int getCount() {
			return lis.size();
		}

		/* 一定要覆寫的方法getItem,傳回position */
		public Object getItem(int position) {
			return position;
		}

		/* 一定要覆寫的方法getItemId,傳回position */
		public long getItemId(int position) {
			return position;
		}

		/* 一定要覆寫的方法getView,傳回一View物件 */
		public View getView(int position, View convertView, ViewGroup parent) {
			/* 產生ImageView物件 */
			ImageView i = new ImageView(mContext);
			/* 設定圖片給imageView物件 */
				Bitmap bm = Utilis.getLimitBitmap(lis.get(position).toString(), 650, 952);
				i.setImageBitmap(bm);

			/* 重新設定圖片的寬高 */
			i.setScaleType(ImageView.ScaleType.FIT_XY);
			/* 設定Gallery背景圖 */
			i.setBackgroundResource(mGalleryItemBackground);
			/* 傳回imageView物件 */
			return i;
		}
	}
	
	
		/* 新增一ImageAdapter並設定給Gallery物件 */

//事先整理出產地國別	
	public void getCountryData(Context context){
		if(mCountryIdList != null){
			mCountryIdList.clear();
		}
		if(mCountryList != null){
			mCountryList.clear();
		}
		SQLiteDatabase dbs = Utilis.getDB(context);
		Cursor cursor = dbs.rawQuery("select NAME,_ID from qc_country order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));						
						String name = cursor.getString(cursor.getColumnIndex("NAME"));
						mCountryIdList.add(id);
						mCountryList.add(name);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		dbs.close();
		dbs = null;
	}
	
	// 取得類別資料
	public void getTypeData(Context context){
		if(mTypeList != null){
			mTypeList.clear();
		}
		if(mTypeIdList != null){
			mTypeIdList.clear();
		}
		SQLiteDatabase dbs = Utilis.getDB(context);
		Cursor cursor = dbs.rawQuery("select GOODTYPE,_ID from qc_type order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						String name = cursor.getString(cursor.getColumnIndex("GOODTYPE"));
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						mTypeList.add(name);
						mTypeIdList.add(id);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		dbs.close();
		dbs = null;
	}
	
	
	@SuppressWarnings("unused")
	private void Display(int positionid) {
		int position = positionid;
        SQLiteDatabase db = Utilis.getDB(this);		
		Cursor cs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		mGoods=batch;
		mySqlBuf.append("select GOODSNO,GOODSNAME,GOODSTYPE,COUNTRY,")
		.append("BATCH,SUPPLY,SOURCENO,P0,P1,P2,P3,P4,P5,COLORNO,COLOR,SIZE,INLIST,PS")
		.append(" from qdetail where GOODSNO='" + mGoods+"'");
		cs = db.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){
			cs.moveToFirst();
						mTextView01.setText(cs.getString(cs.getColumnIndex("GOODSNO")));		
						mTextView02.setText(cs.getString(cs.getColumnIndex("GOODSNAME")));
						
						int gtype = cs.getInt(cs.getColumnIndex("GOODSTYPE"));  //代號需轉換為文字
				        	int index = mTypeIdList.indexOf(gtype);
				        	if(index >= 0){	mTextView03.setText(mTypeList.get(index));	}
				        	else {
				        		mTextView03.setText(cs.getString(cs.getColumnIndex("GOODSTYPE")));
				        	}
						
						int gcountry= cs.getInt(cs.getColumnIndex("COUNTRY"));   //代號需轉換為文字
							int cindex = mCountryIdList.indexOf(gcountry);
							if(cindex>=0){mTextView04.setText(mCountryList.get(cindex));}
							else {
								mTextView04.setText(cs.getString(cs.getColumnIndex("COUNTRY")));
							}
						mTextView05.setText(cs.getString(cs.getColumnIndex("PS")));
					
			//新的一段處理顏色尺寸表-開始			
			//取得4組資料 色號 色名 尺寸表 數量表			
			}

			
			Bitmap bm = Utilis.getLimitBitmap(goodsPic, 200,200);
			
			if (bm!=null){	
				reflactionBitmap = createReflectionBitmap(bm);
				mImage.setImageBitmap(reflactionBitmap);
				AnimationSet animation = new AnimationSet(true);
				animation.addAnimation(new AlphaAnimation(0.0F, 1.0F));
				animation.addAnimation(new TranslateAnimation(30, 0, 10, 0));
				animation.setDuration(1000);
				mImage.startAnimation(animation);
			}
		cs.close();
		db.close();
	}

	Handler mHandlerWP = new Handler()
	{
		@SuppressWarnings("unused")
		@Override
		public  void handleMessage(Message msg)
		{
			//傳回的//upup_1-30_系統時間
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
					Apicstr = new String[maxRec];
					StyleSrc = new int[maxRec];
					for (int g=0;g<maxRec;g++) StyleSrc[g]=0;
					for (int g=0;g<maxRec;g++) Apicstr[g]="";

				if (Hresult != null ){
				
					Log.i("DOWNLOAD_WP", Hresult);
					
					if (Hresult.indexOf("prod_okok")>2){
						String Lines [] = Hresult.split("prod_okok");
						//取得 0=success 1=prod_id 2=prod_detail  3=prod_id
						prod_id=Lines[1];
						prod_detail=Lines[2]; 
						//剖析prod_detail 取得所有圖檔,並透過FTP 傳回 CWBuyer/web/uploadfile/images
						String WEBPATH=SAVE_FOLDER.substring(0, SAVE_FOLDER.length()-1);
				        File myDataPath = new File(WEBPATH);
				        if (!myDataPath.exists()) 	myDataPath.mkdirs();  //若不存在 則建立之
				        String prod_pic[] =prod_detail.split("src="); // [>]為截止符號
				        if (prod_pic.length>0){ //表示有圖檔存在
				        	for (int g=1;g<prod_pic.length;g++){
				        		prod_pic[g]=prod_pic[g].substring(1, prod_pic[g].indexOf("style")-2); //陸續取得所有圖檔名
				        		//   ../uploadFile/images/01bs_01.jpg
				        		//逐一以FTP 傳回 CWBuyer/web/uploadfile/images
//					        		if (prod_pic[g].indexOf(".jpg")>0 || prod_pic[g].indexOf(".jpeg")>0 || prod_pic[g].indexOf(".png")>0){
									String  AutoFile=prod_pic[g].replace("../uploadFile/images", WEBPATH);
									String ServerT=prod_pic[g].replace("../", "web/");
									//   web/uploadFile/images/01bs_01.jpg
									final File localFile = new File(AutoFile);
									final String serverFile =ServerT;
						        	boolean success=false;
						        	
									try {
										success=DBCloud.ftpDownloadAndSaveFile(GalleryViewWeb.this,Utilis.getIni(GalleryViewWeb.this, "SYS", "IMPORT",1), 21,Utilis.getIni(GalleryViewWeb.this, "SYS", "IMPORT",4), Utilis.getIni(GalleryViewWeb.this, "SYS", "IMPORT",5), serverFile, localFile);
										Apicstr[g-1]=AutoFile;
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
//				        		}
				        	}
				        }
					}
				}
	    		mGallery01.setAdapter(new ImageAdapter(GalleryViewWeb.this, ChkPic()));
	    		Display(0);
			}
		}
	};

	private void eventImgCapture(int PHOTO) {
		Toast.makeText(GalleryViewWeb.this, "相機請使用直拍", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// Wysie_Soh: Create path for temp file
		//batch = ((EditText) findViewById(R.id.edit_batch)).getText().toString();
        if (Apicstr[positions].length()<=0){//ADD
    		File folder = new File(SAVE_FOLDER.substring(0, SAVE_FOLDER.length()-1));
    		if (folder.exists() == false) folder.mkdirs();
        	mImagePath=SAVE_FOLDER +"mtr_"+ String.valueOf(DateUtil.getSystemTime())+ ".jpg";
        }else{//EDIT 使用原來的檔名
        	mImagePath=Apicstr[positions];
        }

        File file = new File(mImagePath);
/*        
		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) {
		}
	}

	
	public String getPath(Uri uri) {
        if( uri == null ) {
            return null;
        }
        String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(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 uri.getPath();
}
	
	private static int exifToDegrees(int exifOrientation) {        
	    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } 
	    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {  return 180; } 
	    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {  return 270; }
	    return nPicDegree;    
	 }

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

	
   	public int[] toInt(Set<Integer> set) {
	    		int[] a = new int[set.size()];
	    		int i = 0;
	    		for (Integer val : set)
	    			a[i++] = val;
	    		return a;
   	}
   	
	public static Bitmap createReflectionBitmap(Bitmap src) {
		// 原始圖片與反射圖片的邊界
		int margin = 4;
		int width = src.getWidth();
		int height = src.getHeight();

		// 用來做上下顛倒的Matrix
		Matrix matrix = new Matrix();
		matrix.preScale(1.0f, -1.2f);

		// 以原始圖片下半部顛倒過來產生Bitmap
		Bitmap reflection;
		reflection = Bitmap.createBitmap(src, 0, height / 2, width, height / 2,
				matrix, true);
		// 產生原始圖片與反射圖片合體後的結果圖片Bitmap
		// 這時還是空的
		Bitmap result;
		result = Bitmap.createBitmap(width, height + height / 5,
				Config.ARGB_8888);
		// 使用畫布
		Canvas canvas;
		canvas = new Canvas(result);
		// 將原始圖片寫到結果圖片畫布上
		canvas.drawBitmap(src, 0, 0, null);
		// 將反射圖片寫到結果圖片畫布上
		canvas.drawBitmap(reflection, 0, height + margin, null);

		// 到這裡已經與反射圖片合體完成了
		// 接下來要做淡化處理
		Paint paint = new Paint();
		// 使用LinearGradient這個直線方向的漸層
		LinearGradient shader;
		// 製作漸入透明的漸層
		// 0x90ffffff(稍微透明) -> 0x00FFFFFF(完全透明)
		shader = new LinearGradient(0, height, 0, result.getHeight() + margin,
				0x80ffffff, 0x00ffffff, TileMode.CLAMP);
		// 因為繼承Shader類別，所以使用setShader設定給Paint。
		paint.setShader(shader);
		// 指定顏色轉換模式
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		// 描繪漸層
		canvas.drawRect(0, height, width, result.getHeight(), paint);

		return result;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
//		db.close();
	}

}
