package com.cwbuyer.lib;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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 android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
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;
	
@SuppressLint({ "DefaultLocale", "HandlerLeak" })
@SuppressWarnings("deprecation")
public class MkqrList extends Activity {

	//這是針對 Qdetail 單一商品 顯示 A4 直式 六方格的 單頁 輸出  
	public String bacoText = "This is a CWBuyer 銷售王";
	//橫式
	//public Bitmap vBitmap = Bitmap.createBitmap( 1880,1280, Bitmap.Config.RGB_565);
	//以下 直式
	public Bitmap vBitmap = Bitmap.createBitmap( 1280,1880, Bitmap.Config.RGB_565);
	public Canvas vBitmapCanvas = new Canvas( vBitmap );
	private Gallery mGallery01;
	private ImageView mImage;
	private String [] zipList;
	
	//about get web pctures like GalleryViewWeb
	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	public ProgressDialog myDialog = null;
	String uriAPI=null;
	protected static final int REFRESH_DATA = 0x00000001;
	private String[] Apicstr; //圖檔名稱
	private int[] StyleSrc;
	private int[][] LocaXY={{120,600},{120,600},{700,600},{120,1250},{700,1250}};
	int maxRec = 5;
	public final  String SAVE_FOLDER = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+"CWBuyer/web/uploadfile/images/" ;
	String prod_id=null;
	String prod_detail=null;
	
	Bitmap rsizebar;
	public Bitmap bm =null;
	Bitmap rsizeBM;
    StringBuffer albun_array = new StringBuffer();
    Calendar  cld = Calendar.getInstance();
	int counts;
	int GVlocate=0;
	String ini=null; 	
//	String[] inis={"460","25","350","600","480","600","-75","25","10"};
	String[] inis={"460","25","350","600","350","450","-75","40","10"};
	String[] season_array={"春裝","夏裝","秋裝","冬裝","四季"};
	String title=null; 	
	String[] titles;
	String[]country_array;
	
    int picX=0;
    int picY=0;
    int qrlocX=0;
    int qrlocY=0;
    int pz=0;
    
    String oedpic ="";
	String eno="";
	String ename="";
	String country="";
	String season="";
	String eprice="";
	String eprice3="";
	String eprice5="";
	String ecolor="";
	String esize="";	
	String epics="";
	String ebars="";
	String batch="";
	String supply="";
	String eps="";
	String eps1="";
	String eps2="";
	String eps3="";
	String eps4="";
	Button mBt1;
	TextView tv1;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.mkqr);
	//傳遞規劃 共五個 主貨號 附圖一 二 三 四
	//3456相關的 附圖 資訊 就是 圖檔PATH 最多4張
	//12主貨號 從資料庫 取得 圖檔PATH 所有其他資訊
	//如果沒有附圖的部份 將留白(不繪)	
		
		Bundle bundle = this.getIntent().getExtras();
		String fromW=bundle.getString("MkqrList");
		String[] arrayW = fromW.split(",");
		batch=arrayW[0];

		    picX=Utilis.toInt(inis[4]);//292
		    picY=Utilis.toInt(inis[5]);//430
		    qrlocX=Utilis.toInt(inis[6]);
		    qrlocY=qrlocX+80;
		    pz=Utilis.toInt(inis[7]);//16
	    
    	title=Utilis.getIni(this,"USER","COMPANY",9);
    	titles=title.split("!&!");
	    
		tv1=(TextView)findViewById(R.id.tv113);
		mBt1 =(Button)findViewById(R.id.button113);
		mImage = (ImageView) findViewById(R.id.imageView105);
		mGallery01 = (Gallery) findViewById(R.id.myGallery1);
		
		// 取得螢幕解析像素 
//		DisplayMetrics dm = new DisplayMetrics();
//		getWindowManager().getDefaultDisplay().getMetrics(dm);
		
		try {
			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(MkqrList.this);		
			Cursor cs = null;
			String SQL="select _ID,NAME from qc_country order by _ID";
			country="";

			cs = db.rawQuery(SQL,null);
			if (cs.getCount()>0){
				country_array = new String[cs.getCount()*2];
				for (int x=0;x<(cs.getColumnCount()*2);x++) country_array[x]="";
				
				while (cs.moveToNext()){
					country_array[cs.getInt(0)]=cs.getString(1);
				}
			}
			cs=null;
			
			SQL="select GOODSNO,GOODSNAME,COUNTRY,P3,P5,COLORNO,COLOR,SIZE,PS,UNIT2,SEASON,PIC from qdetail where GOODSNO='" + batch+"' order by MID desc LIMIT 1";
			cs = db.rawQuery(SQL,null);

			if (cs.getCount()>0){
				cs.moveToFirst();
				eno="貨號:"+cs.getString(0);
				ename="品名:"+cs.getString(1);
				eprice3="批價:"+cs.getString(3);
				eprice5="零售:"+cs.getString(4);
				country="產地:"+country_array[cs.getInt(2)];
				season=""+cs.getString(9)+" "+season_array[cs.getInt(10)];
				supply=cs.getString(5);
				ecolor=cs.getString(6);
				esize="尺寸:"+cs.getString(7);
				//借位因顏色太長 而併了尺寸
				if (ecolor.length()>17) {
					esize=ecolor.substring(18)+"  "+esize;
					ecolor=ecolor.substring(0,18);
				}
				
				eps="規格:"+cs.getString(8);
				if (eps.length()>120){
					eps1=eps.substring(30,60);
					eps2=eps.substring(60,90);
					eps3=eps.substring(90,120);
					eps4=eps.substring(120);
					eps=eps.substring(0,30);
				}else if (eps.length()>90){
					eps1=eps.substring(30,60);
					eps2=eps.substring(60,90);
					eps3=eps.substring(90);
					eps=eps.substring(0,30);
				}else if (eps.length()>60){
					eps1=eps.substring(30,60);
					eps2=eps.substring(60);
					eps=eps.substring(0,30);
				}else if (eps.length()>30){
					eps1=eps.substring(30);
					eps=eps.substring(0,30);
				}
				//備註太長 分成兩行
				epics=cs.getString(11);
				
			} else finish(); //表示進行不下去了
			cs.close();
			db.close();

    		Paint mPaintT1 = new Paint();
    		Paint mPaintT2 = new Paint();
    		Paint mPaintT3 = new Paint();
    		Paint mPaintT5 = new Paint();
    		// 設定畫筆顏色及樣式 
    		mPaintT1.setStyle(Paint.Style.FILL);
    	mPaintT1.setColor(-1);
    		mPaintT1.setStrokeWidth(1.0F);
    		mPaintT1.setTextSize(32);
    		// 設定畫筆顏色及樣式 
    		mPaintT2.setStyle(Paint.Style.FILL);
    	mPaintT2.setColor(-6250336);
    		mPaintT2.setStrokeWidth(1.0F);
    		mPaintT2.setTextSize(18);
    		
    		mPaintT3.setStyle(Paint.Style.FILL);
    	mPaintT3.setColor(-16777216);
    		mPaintT3.setStrokeWidth(3.0F);
    		mPaintT3.setAntiAlias(true);

    		mPaintT5.setStyle(Paint.Style.FILL);
    	mPaintT5.setColor(-16777216);
    		mPaintT5.setStrokeWidth(1.0F);
    		mPaintT5.setTextSize(30);


			
			vBitmapCanvas.drawColor(getResources().getColor(R.drawable.white));
			//印製台頭
			vBitmapCanvas.drawRect(100, 20, 350, 70, mPaintT3);
			vBitmapCanvas.drawRect(350, 45, 1200, 70, mPaintT3);
			vBitmapCanvas.drawCircle(100, 45, 25, mPaintT3);
			vBitmapCanvas.drawCircle(350, 45, 25, mPaintT3);
			vBitmapCanvas.drawRect(950, 20, 1200, 70, mPaintT3);
			vBitmapCanvas.drawCircle(950, 45,25 , mPaintT3);
			vBitmapCanvas.drawCircle(1200, 45,25 , mPaintT3);
			vBitmapCanvas.drawText(titles[0],110 ,60 , mPaintT1);
			vBitmapCanvas.drawText(eno,460 ,40 , mPaintT5);
			vBitmapCanvas.drawText(season,1000 ,60 , mPaintT1);
			vBitmapCanvas.drawText(titles[2],670 ,63 , mPaintT2);

			
			
			Paint mPaint00 = new Paint();
			Paint mPaint01 = new Paint();
			Paint mPaint02 = new Paint();
			Paint mPaint03 = new Paint();
			
			// 設定畫筆顏色及樣式 
			mPaint00.setStyle(Paint.Style.FILL);
			mPaint00.setColor(-15391648);
			mPaint00.setStrokeWidth(1.0F);
	    	mPaint00.setTextSize(pz+2);
			// 設定畫筆顏色及樣式 
			mPaint01.setStyle(Paint.Style.FILL);
			mPaint01.setColor(getResources().getColor(R.drawable.black));
			mPaint01.setStrokeWidth(1.0F);
	    	mPaint01.setTextSize(pz);
			// 設定畫筆顏色及樣式 
			mPaint02.setStyle(Paint.Style.FILL);
			mPaint02.setColor(getResources().getColor(R.drawable.black));
			mPaint02.setStrokeWidth(1.0F);
	    	mPaint02.setTextSize(pz-5);
		    
			mPaint03.setStyle(Paint.Style.FILL);
			mPaint03.setColor(0XFFCC0000);
			mPaint03.setStrokeWidth(1.0F);
			mPaint03.setTextSize(pz+4);
			
			//製造 左上 商品主圖 及 右上 商品內文
			 File file=new File(epics);
			 if (!file.exists() || epics.length()<=0) epics=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png";  

			bm=Utilis.getLimitBitmap(epics, 210, 280);				
				int swidth = bm.getWidth();
				int shgh = bm.getHeight();
				float SWx=(float)picX/swidth;
				float SHx=0;
				SHx=(float)(picY)/shgh;
				
				Matrix scaleMatrix = new Matrix();

				scaleMatrix.postScale(SWx, SHx);

				// 產生縮圖後的 bitmap
				rsizeBM =Bitmap.createBitmap(bm, 0, 0, swidth, shgh, scaleMatrix, true);
				 if (bm!=null) {bm.recycle();}
				 
			      vBitmapCanvas.drawBitmap( rsizeBM, 60,120 , null );
			      
		         vBitmapCanvas.drawText(ename ,460,130, mPaint01);
		         
		         vBitmapCanvas.drawText(eprice3, 460,185, mPaint01);
		         vBitmapCanvas.drawText(eprice5, 800,185, mPaint01);
		         
		         vBitmapCanvas.drawText("顏色:"+supply, 460,235, mPaint02);
		         vBitmapCanvas.drawText(ecolor, 460,290, mPaint03);         
		         vBitmapCanvas.drawText(esize,460,345, mPaint03);
		         
		         vBitmapCanvas.drawText(eps, 460,400, mPaint02);
		         vBitmapCanvas.drawText(eps1, 460,450, mPaint02);
		         vBitmapCanvas.drawText(eps2, 460,500, mPaint02);
		         vBitmapCanvas.drawText(eps3, 460,550, mPaint02);
		         vBitmapCanvas.drawText(eps4, 460,600, mPaint02);

		   		getInternet(batch);		   		
		    //設法將ZIP檔 改為 多圖檔輸出(這是個陣列型態的URI)
		} catch (Exception e) {
			finish();
		}
		
		//已在進入程式完成CANVAS 且已存入檔案,後續應為列印或傳送到遠端伺服器的後續處理
		mBt1.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View arg0) {
            	
				 ArrayList<Uri> imageUris = new ArrayList<Uri>();
				 for (int xyz=0;xyz<zipList.length;xyz++)
				 {
					 imageUris.add(Uri.parse("file://"+zipList[xyz])); // Add your image URIs here
				 }
				Intent shareIntent = new Intent();
				shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
				shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
				shareIntent.setType("image/*");
				startActivity(Intent.createChooser(shareIntent, "Share images to..")); 			    
            }
        }); 
  
		mGallery01.setOnItemClickListener(new Gallery.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long ids) {
				// TODO Auto-generated method stub
				Bitmap bm = Utilis.getLimitBitmap(zipList[position], 500,500);
				GVlocate=position;
				if (bm!=null){	
					Bitmap reflactionBitmap;
					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);
				}
			}
		});

		mImage.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
		    	Intent send = new Intent(Intent.ACTION_SEND);
		    	send.setType("image/jpeg");
			    String uriText;
			    Uri U=Uri.parse("file://"+zipList[GVlocate]);  //重要的範例
//			    uriText = "https://www.google.com/cloudprint/addpublicprinter.html?printerid=bfcafa8e-0ab8-1a5c-8533-55da3b447c7c&key=1525231132";
			    uriText = "https://www.google.com/cloudprint/addpublicprinter.html?printerid=bb160853-6274-0f65-eb1f-34ae2c9ed6e1&key=19901109";
			    send.putExtra(Intent.ACTION_SENDTO,uriText);
			    send.putExtra(Intent.EXTRA_STREAM,U);
			    startActivity(Intent.createChooser(send, uriText));
			}
		});
		
	} //主程式結束

	// 自訂產生QR Code的函數 
	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(MkqrList.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(MkqrList.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(); /* 開始執行執行緒 */

		
		}		
	}
	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
						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++){
					        	if (g<=4){
					        		prod_pic[g]=prod_pic[g].substring(1, prod_pic[g].indexOf("style")-2); //陸續取得所有圖檔名
				        		//   ../uploadFile/images/01bs_01.jpg
				        		//逐一以FTP 傳回 CWBuyer/web/uploadfile/images
									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(MkqrList.this,Utilis.getIni(MkqrList.this, "SYS", "IMPORT",1), 21,Utilis.getIni(MkqrList.this, "SYS", "IMPORT",4), Utilis.getIni(MkqrList.this, "SYS", "IMPORT",5), serverFile, localFile);
										Apicstr[g-1]=AutoFile;
										
										//開始一一製作繪圖,最多四張 尺寸 較大些

							 			 File file=new File(AutoFile);
										 if (!file.exists() || AutoFile.length()<=0) AutoFile=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png";  
							
										bm=Utilis.getLimitBitmap(AutoFile, 210, 280);				
											int swidth = bm.getWidth();
											int shgh = bm.getHeight();
											float SWx=(float)480/swidth;
											float SHx=0;
											SHx=(float)(600)/shgh;
											Matrix scaleMatrix = new Matrix();
											scaleMatrix.postScale(SWx, SHx);
											// 產生縮圖後的 bitmap
											rsizeBM =Bitmap.createBitmap(bm, 0, 0, swidth, shgh, scaleMatrix, true);
											 if (bm!=null) {bm.recycle();}
										      vBitmapCanvas.drawBitmap( rsizeBM, LocaXY[g][0],LocaXY[g][1] , null );
										
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
					        	}
				        	}
				        }
					} 
					saved();
				    zipList= (albun_array.toString().substring(0,albun_array.toString().length()-1)).split(",");
				    toZipF(MkqrList.this,zipList, android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(MkqrList.this, "SYS","YEAR", 8)+File.separator+"cwbuyer_albun_"+batch+".zip");
				    
					mGallery01.setAdapter(new ImageAdapter(MkqrList.this, ChkPic()));		

					Bitmap bm = Utilis.getLimitBitmap(zipList[0], 500,500);
					
					if (bm!=null){	
						Bitmap reflactionBitmap;
						reflactionBitmap = createReflectionBitmap(bm);
						mImage.setImageBitmap(reflactionBitmap);
						AnimationSet animation = new AnimationSet(true);
						animation.addAnimation(new AlphaAnimation(0.0F, 1.0F));
						animation.addAnimation(new TranslateAnimation(30, 0, 10, 0));
						animation.setDuration(1000);
						mImage.startAnimation(animation);
					}

					
				}
			}
		}
	};

	public void saved() {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",6);
		File myAlbunPath= new File(filepath);
		if (!myAlbunPath.exists()){myAlbunPath.mkdirs(); }
		String edpic=null;
		edpic = filepath+File.separator+batch+"_6X_"+ (100+counts)+".png";
		
		albun_array.append(edpic+",");

		counts=counts+1;		
		int swidth = vBitmap.getWidth();
		int shgh = vBitmap.getHeight();
		
		Matrix scaleMatrix = new Matrix();
		scaleMatrix.postScale(1,1);
 		 rsizebar =Bitmap.createBitmap(vBitmap, 0, 0, swidth, shgh, scaleMatrix, true);
 		rsizebar.compress(Bitmap.CompressFormat.PNG, 100, stream);// (0 - 100)压缩文件

        FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(edpic);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
    try {
    	rsizebar.compress(CompressFormat.PNG, 100, fos);
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Toast.makeText(MkqrList.this, edpic + "存檔失敗!!", Toast.LENGTH_LONG).show();					
			}
				          
	}

	public static void toZipF(Context context,String[] files, String destZip) {
		try {
			int BUFFER = 2048;
			BufferedInputStream origin = null;
			FileOutputStream dest = new FileOutputStream(destZip);
			ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
			byte data[] = new byte[BUFFER];
			for (int i = 0; i < files.length; i++) {
				Log.v("Compress", "Adding: " + files[i]);
				FileInputStream fi = new FileInputStream(files[i]);
				origin = new BufferedInputStream(fi, BUFFER);
				ZipEntry entry = new ZipEntry(files[i].substring(files[i].indexOf(Utilis.getIni(context, "SYS","YEAR", 6))+Utilis.getIni(context, "SYS","YEAR", 6).length()+1));
				
				out.putNextEntry(entry);
				int count;
				while ((count = origin.read(data, 0, BUFFER)) != -1) {
					out.write(data, 0, count);
				}
				origin.close();
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private List<String> ChkPic() {
		/* 設定目前所在路徑 */
		List<String> it = new ArrayList<String>();
		/* 將所有檔案加入ArrayList中 */
		for (int i = 0; i < counts; i++) {
			if (getImageFile(zipList[i]))
				it.add(zipList[i]);
			else {it.add(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png");}
		}
		return it;
	}

	private boolean getImageFile(String fName) {
		boolean re;

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

		/* 依附檔名的類型決定MimeType */
		if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			re = true;
		} else {
			re = false;
		}
		return re;
	}

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

	public class ImageAdapter extends BaseAdapter {
		/* 宣告變數 */
		int mGalleryItemBackground;
		private Context mContext;
		private List<String> lis;

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

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

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

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

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

			/* 重新設定圖片的寬高 */
			i.setScaleType(ImageView.ScaleType.FIT_XY);
			/* 重新設定Layout的寬高 */
				i.setLayoutParams(new Gallery.LayoutParams(150, 100));				
			/* 設定Gallery背景圖 */
			i.setBackgroundResource(mGalleryItemBackground);
			/* 傳回imageView物件 */
			return i;
		}
	}
	

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

	