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.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.pwbuyer.main.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
	
@SuppressLint("DefaultLocale")
@SuppressWarnings("deprecation")
public class Mkqr extends Activity {

	public String bacoText = "This is a CWBuyer 採購王";
	public Bitmap vBitmap = Bitmap.createBitmap( 1880,1280, Bitmap.Config.RGB_565);
	public Canvas vBitmapCanvas = new Canvas( vBitmap );
	private Gallery mGallery01;
	private ImageView mImage;
	private String [] zipList;
	
	Bitmap rsizebar;
	public Bitmap bm =null;
	Bitmap rsizeBM;
    private List<HashMap<String, Object>> albun_list = null;
    //private List<HashMap<String, Object>> page_list = null;
    StringBuffer albun_array = new StringBuffer();
    Calendar  cld = Calendar.getInstance();
    String mMode=null;
    String xMode=null;
	int counts;
	int GVlocate=0;
	String ini=null; 	
	String[] inis={"460","25","350","600","292","430","-75","25","10"};
	String title=null; 	
	String[] titles;
	
	String mStartDay="";
	String mEndDay="";
	
	int locX=60;
	int locY=60;
    int qrX=0;
    int qrY=0;//	->422	二維條碼 Y 座標
    int max=0; //	累加	 每張A4 最多10筆 這是固定規格
    int mmax=0; //10 -> 15
    int momo=0; //2行 3行
    int L1=0;
    int LL=0;
    int L2=0;
    int L3=0;
    int L4=0;
    int L5=0;
    int L6=0;
    int picX=0;
    int picY=0;
    int qrlocX=0;
    int qrlocY=0;
    int pz=0;
    
    String oedpic =null;
	String eno=null;
	String ename=null;
	String eprice=null;
	String ecolor=null;
	String esize=null;	
	String epics=null;
	String ebars=null;
	String batch=null;
	String supply=null;
	String supplyO=null;
	Button mBt1;
	TextView tv1;


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

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.mkqr);
	//取得傳來需要列印的資料(LST檔)	
		Bundle bundle = this.getIntent().getExtras();
		String fromW=bundle.getString("Mkqrs");
		String[] arrayW = fromW.split(",");
		final String myAlbunPath=arrayW[0];
		batch=arrayW[1];
		 //(1)5*2  (2)6*3 (3)報價對外
		mMode=arrayW[2];
		xMode=arrayW[6];
		
	    if (!mMode.equalsIgnoreCase("1") && !mMode.equalsIgnoreCase("4")){ //2,3 含客戶報價單
	    	qrX=292; 	qrY=400;	max=0;	 	mmax=18;		momo=3;	L1=287;
	    	LL=23;		picX=230;	picY=260;	qrlocX=-75;	qrlocY=qrlocX+80;	pz=24;
	    }else {  	
	    	locY=40;
		    qrX=Utilis.toInt(inis[2]);
		    qrY=Utilis.toInt(inis[3]);//	->422	二維條碼 Y 座標
		    max=0; //	累加	 每張A4 最多10筆 這是固定規格
		    mmax=Utilis.toInt(inis[8]); //10 -> 15
		    momo=2; //2行 3行
		    L1=Utilis.toInt(inis[0])+2; //272
		    LL=Utilis.toInt(inis[1]);
		    picX=Utilis.toInt(inis[4]);//187
		    picY=Utilis.toInt(inis[5]);//448
		    qrlocX=Utilis.toInt(inis[6]);
		    qrlocY=qrlocX+80;
		    pz=Utilis.toInt(inis[7]);//16
	    }
	    
	    if (arrayW.length>3){
	    	mStartDay=arrayW[4];
	    	mEndDay=arrayW[5];
	    } 
	    
	    if (mMode.equalsIgnoreCase("3")){
	    	L2=L1+LL+5; //304
	    	L3=L2+LL+5; //336
		    L4=L3+LL; //368
		    L5=L3+LL+7; //400
		    L6=L5+LL+7; //400
	    }else{
		    L2=L1+LL; //304
		    L3=L2+LL; //336
		    L4=L3+LL; //368
		    L5=L4+LL; //400
		    L6=L5+LL; //400
	    }

    	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);
		
		FileInputStream istream = null;
		ObjectInputStream br = null;

		try {
			istream = new FileInputStream(myAlbunPath);
			br = new ObjectInputStream(istream);
			albun_list =(List<HashMap<String, Object>>)br.readObject();
			br.close();
			istream.close();
            String keyString[] = { "eno" ,"ename" ,"eprice" ,"ecolor" ,"esize" ,"ebars" ,"epics","supply"};
        	max=0;
    		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(28);
			
			for (int d1=0;d1<albun_list.size();d1++) {
				HashMap<String, Object> maps = albun_list.get(d1);
					supply=(String) maps.get(keyString[7]);
					if (d1==0) supplyO=supply;
				if (mMode.equalsIgnoreCase("4") && !supply.equalsIgnoreCase(supplyO) && !xMode.equalsIgnoreCase("8") ){
						saved();
						max=0;
				}
					
				if (max==0){
					supplyO=supply;
					vBitmapCanvas = new Canvas( vBitmap );
					vBitmapCanvas.drawColor(getResources().getColor(R.drawable.white));
					//印製台頭
					vBitmapCanvas.drawRect(100, 15, 500, 65, mPaintT3);
					vBitmapCanvas.drawRect(400, 40, 1800, 65, mPaintT3);
					vBitmapCanvas.drawCircle(100, 40, 25, mPaintT3);
					vBitmapCanvas.drawCircle(500, 40, 25, mPaintT3);
					vBitmapCanvas.drawRect(1400, 15, 1800, 65, mPaintT3);
					vBitmapCanvas.drawCircle(1400, 40,25 , mPaintT3);
					vBitmapCanvas.drawCircle(1800, 40,25 , mPaintT3);
					vBitmapCanvas.drawText(titles[0],110 ,55 , mPaintT1);
					if (xMode.equalsIgnoreCase("9") || xMode.equalsIgnoreCase("10")) vBitmapCanvas.drawText("統計區間:"+mStartDay+"～"+mEndDay,720 ,35 , mPaintT5);
					else vBitmapCanvas.drawText("統計區間:"+batch,720 ,35 , mPaintT5);
					if (mMode.equalsIgnoreCase("4") && !xMode.equalsIgnoreCase("8"))  vBitmapCanvas.drawText("訂單TO:"+supply,1450 ,55 , mPaintT1);
					else vBitmapCanvas.drawText("最新資訊:"+DateUtil.getCurrentDate().substring(0, 4),1450 ,55 , mPaintT1);
					vBitmapCanvas.drawText("mailTo:"+titles[1]+" 地址:"+titles[2]+" TEL:"+titles[3]+" FAX:"+titles[4],520 ,58 , mPaintT2);
				}
				//開始判斷如果F
			if (maps.get(keyString[3]).toString().indexOf("，")>0 ){	
				
				String ChkSize=maps.get(keyString[3]).toString();
				String ChkCol=null;
				String [] Cols;
				String [] SizL;
				String aSizl=maps.get(keyString[4]).toString();
				int sepa=0; //分割 如果為F 5X2(6色)  6X3(5色) 否則一律為(3色)
				if ( !mMode.equalsIgnoreCase("3")){
						ChkCol=ChkSize.substring(0,ChkSize.indexOf("/"));  //取得顏色
						Cols=ChkCol.split("，");
					    SizL=maps.get(keyString[4]).toString().split("，");
						if (mMode.equalsIgnoreCase("1")){	sepa=4;	}else {	sepa=6;	}
				}else{
						Cols=ChkSize.split("，");
						SizL=ChkSize.split("，");
					    sepa=5;
				}
				String Colors="";
				String Sizes="";
				for (int ii=1;ii<=(Cols.length);ii++){
					if ( !mMode.equalsIgnoreCase("3")){					
						if ((ii % sepa)==0){
							Colors=Colors+Cols[ii-1];
							if (ii<=SizL.length) Sizes=Sizes+SizL[ii-1];
						} else {
							Colors=Colors+Cols[ii-1]+"，";
							if (ii<=SizL.length) Sizes=Sizes+SizL[ii-1]+"，";
						}
					}else{
						Sizes=aSizl;
						if ((ii % sepa)==0){
							Colors=Colors+Cols[ii-1];
						} else {
							Colors=Colors+Cols[ii-1]+"，";
						}
						
					}
					if ((ii>1 && (ii%sepa ==0)) || (ii==(Cols.length))){
						//( 如果迴圈>0 且 迴圈為sepa的倍數 ) 或 ( 迴圈=最後一個顏色  )
						if ( !mMode.equalsIgnoreCase("3")){					
							Colors=Colors+ChkSize.substring(ChkSize.indexOf("/")+1,ChkSize.length());
						}
						eno=(String) maps.get(keyString[0]);
						ename=(String) maps.get(keyString[1]);
						eprice=(String) maps.get(keyString[2]);
						ecolor=Colors;
						esize=Sizes;				
						ebars=(String) maps.get(keyString[5]);						
						epics=(String) maps.get(keyString[6]);
						supply=(String) maps.get(keyString[7]);
					
						//進入一筆資料產生一格內容
						 File file=new File(epics);
						 if (!file.exists() || epics.length()<=0) epics=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png";  

						 
						 	Bitmap bm=Utilis.getLimitBitmap(epics, 210, 280);				
						 	//bm=Utilis.getLimitBitmap(epics, 210, 280);				
							int swidth = bm.getWidth();
							int shgh = bm.getHeight();
							float SWx=(float)picX/swidth;
							float SHx=0;
							if (momo==2) SHx=(float)(picY-30)/shgh; else SHx=(float)(picY)/shgh;
							//if (SWx<SHx){SHx=SWx;}
							
							Matrix scaleMatrix = new Matrix();

							scaleMatrix.postScale(SWx, SHx);

							// 產生縮圖後的 bitmap
							rsizeBM =Bitmap.createBitmap(bm, 0, 0, swidth, shgh, scaleMatrix, true);
							 if (bm!=null) {bm.recycle();}
							AndroidQREncode();
							supplyO=supply;
							max++; //5*2 須判斷 ==10 或 ==list.size() 不同處置 6*3 須判斷 ==18 或 ==list.size() 
						if (max%mmax==0){
							saved();
							max=0;
							vBitmapCanvas = new Canvas( vBitmap );
							vBitmapCanvas.drawColor(getResources().getColor(R.drawable.white));
							//印製台頭
							vBitmapCanvas.drawRect(100, 15, 500, 65, mPaintT3);
							vBitmapCanvas.drawRect(400, 40, 1800, 65, mPaintT3);
							vBitmapCanvas.drawCircle(100, 40, 25, mPaintT3);
							vBitmapCanvas.drawCircle(500, 40, 25, mPaintT3);
							vBitmapCanvas.drawRect(1400, 15, 1800, 65, mPaintT3);
							vBitmapCanvas.drawCircle(1400, 40,25 , mPaintT3);
							vBitmapCanvas.drawCircle(1800, 40,25 , mPaintT3);
							vBitmapCanvas.drawText(titles[0],110 ,55 , mPaintT1);
							if (arrayW.length>3) vBitmapCanvas.drawText("統計區間:"+mStartDay+"～"+mEndDay,720 ,35 , mPaintT5);
							if (mMode.equalsIgnoreCase("4")) vBitmapCanvas.drawText("訂單TO:"+supply,1450 ,55 , mPaintT1);
							else vBitmapCanvas.drawText("最新資訊:"+DateUtil.getCurrentDate().substring(0, 4),1450 ,55 , mPaintT1);
							vBitmapCanvas.drawText("mailTo:"+titles[1]+"   地址:"+titles[2]+"   TEL:"+titles[3]+"   FAX:"+titles[4],520 ,58 , mPaintT2);
							
						} else if (d1==(albun_list.size()-1) && (ii==(Cols.length))  ){
						//} else if (d1>=(albun_list.size()) && (ii==(Cols.length))  ){
							saved();
							break;
						}

					Sizes="";
					Colors="";
					}
					
				}
			}else {
				eno=(String) maps.get(keyString[0]);
				ename=(String) maps.get(keyString[1]);
				eprice=(String) maps.get(keyString[2]);
				ecolor=(String) maps.get(keyString[3]);
				esize=(String) maps.get(keyString[4]);				
				ebars=(String) maps.get(keyString[5]);						
				epics=(String) maps.get(keyString[6]);
				supply=(String) maps.get(keyString[7]);
			
				//進入一筆資料產生一格內容
				 File file=new File(epics);
				 if (!file.exists() || epics.length()<=0) epics=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png";  
				 	Bitmap bm=Utilis.getLimitBitmap(epics, 210, 280);				
				 	//bm=Utilis.getLimitBitmap(epics, 210, 280);				
					int swidth = bm.getWidth();
					int shgh = bm.getHeight();
					float SWx=(float)picX/swidth;
					float SHx=0;
					if (momo==2) SHx=(float)(picY-30)/shgh; else SHx=(float)(picY)/shgh;
					//if (SWx<SHx){SHx=SWx;}
					
					Matrix scaleMatrix = new Matrix();

					scaleMatrix.postScale(SWx, SHx);

					// 產生縮圖後的 bitmap
					rsizeBM =Bitmap.createBitmap(bm, 0, 0, swidth, shgh, scaleMatrix, true);
					 if (bm!=null) {bm.recycle();}
					AndroidQREncode();
					supplyO=supply;
				max++; //5*2 須判斷 ==10 或 ==list.size() 不同處置 6*3 須判斷 ==18 或 ==list.size() 
				if (max%mmax==0){
					saved();
					max=0;
				} else if (d1==(albun_list.size()-1)){
				//} else if (d1>=(albun_list.size())){
					saved();
					break;
				}
			}	
			} //end for
			
		    zipList= (albun_array.toString().substring(0,albun_array.toString().length()-1)).split(",");
		    //toZipF(Mkqr.this,zipList, android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(Mkqr.this, "SYS","YEAR", 8)+File.separator+"cwbuyer_albun_"+batch+".zip");
		    //暫時關閉壓縮圖檔輸出
			mGallery01.setAdapter(new ImageAdapter(Mkqr.this, ChkPic()));		

			Bitmap bm = Utilis.getLimitBitmap(zipList[0], 900,600);
			
			if (bm!=null){	
				mImage.setImageBitmap(bm);
			}

		    //設法將ZIP檔 改為 多圖檔輸出(這是個陣列型態的URI)
		} catch (Exception e) {	}
		
		//已在進入程式完成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], 900,600);
				GVlocate=position;
				if (bm!=null){	
					mImage.setImageBitmap(bm);
				}
			}
		});

		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=bb160853-6274-0f65-eb1f-34ae2c9ed6e1&key=19901109";
			    uriText = "請選擇送到哪一個多媒體";
			    send.putExtra(Intent.ACTION_SENDTO,uriText);
			    send.putExtra(Intent.EXTRA_STREAM,U);
			    startActivity(Intent.createChooser(send, uriText));
			}
		});
		
	} //主程式結束

	// 自訂產生QR Code的函數 
	public void AndroidQREncode() {
		try {
			Bitmap bEncoding=null;
			if (!xMode.equalsIgnoreCase("9") && !xMode.equalsIgnoreCase("10")  && !mMode.equalsIgnoreCase("4")){
				String mBars=ebars;
				if (ebars.indexOf(";")>0) mBars=ebars.substring(0,ebars.indexOf(";")-1);
					if (!mMode.equalsIgnoreCase("3")) bEncoding= mkBar39(mBars.toUpperCase());
					drawQRCode(bEncoding, getResources().getColor(R.drawable.black));
			}else{
				drawQRCode(bEncoding, getResources().getColor(R.drawable.black));
			}
		
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	// 在SurfaceView上繪製QRCode圖片 
	private void drawQRCode(Bitmap bRect, int colorFill) {
		// test Canvas 
		//int intPadding =2;
		//int asb=3;

		// 建立畫筆
		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);
	    if (!mMode.equalsIgnoreCase("3")){
	    	mPaint00.setTextSize(pz+2);
	    }else{
	    	mPaint00.setTextSize(pz+6);
	    }
		// 設定畫筆顏色及樣式 
		mPaint01.setStyle(Paint.Style.FILL);
	mPaint01.setColor(colorFill);
		mPaint01.setStrokeWidth(1.0F);
	    if (!mMode.equalsIgnoreCase("3")){
	    	mPaint01.setTextSize(pz);
	    }else{
	    	mPaint01.setTextSize(pz+4);
	    }
		// 設定畫筆顏色及樣式 
		mPaint02.setStyle(Paint.Style.FILL);
		mPaint02.setColor(colorFill);
		mPaint02.setStrokeWidth(1.0F);
	    if (!mMode.equalsIgnoreCase("3")){
	    	mPaint02.setTextSize(pz-5);
	    }else{
	    	mPaint02.setTextSize(pz-5);
	    }
	    
		mPaint03.setStyle(Paint.Style.FILL);
		mPaint03.setColor(0XFFCC0000);
		mPaint03.setStrokeWidth(1.0F);
		mPaint03.setTextSize(pz+4);
	    
//  目前二維條碼是直接畫在大畫布上 ,不再作間接縮放 (較不失真)         
      vBitmapCanvas.drawBitmap( rsizeBM, (int)(max/momo)*qrX+5+locX, (max%momo)*qrY+5+locY+(picY-rsizeBM.getHeight()), null );

    if (!mMode.equalsIgnoreCase("3")){
         vBitmapCanvas.drawText(eno, (int)(max/momo)*qrX+1+locX, (max%momo)*qrY+L1+locY, mPaint00);
         vBitmapCanvas.drawText(ename, (int)(max/momo)*qrX+1+locX, (max%momo)*qrY+L2+locY, mPaint01);
         vBitmapCanvas.drawText(eprice, (int)(max/momo)*qrX+1+locX,(max%momo)*qrY+L3+locY, mPaint01);
         vBitmapCanvas.drawText(supply, (int)(max/momo)*qrX+1+locX, (max%momo)*qrY+L4+locY, mPaint03);
         vBitmapCanvas.drawText(ecolor, (int)(max/momo)*qrX+1+locX, (max%momo)*qrY+L6+locY, mPaint02);         
         vBitmapCanvas.drawText(esize, (int)(max/momo)*qrX+1+locX, (max%momo)*qrY+L5+locY, mPaint02);
     	if (xMode.equalsIgnoreCase("9") || xMode.equalsIgnoreCase("10")  || mMode.equalsIgnoreCase("4"))
    		vBitmapCanvas.drawText(ebars, (int)(max/momo)*qrX+1+locX, (max%momo)*qrY+L6+locY+LL, mPaint02);
         if (rsizeBM !=null) {rsizeBM.recycle();}
    }else{
        vBitmapCanvas.drawText(eno, (int)(max/momo)*qrX+1+locX, (max%momo)*qrY+L1+locY, mPaint00);
        vBitmapCanvas.drawText(ename, (int)(max/momo)*qrX+1+locX, (max%momo)*qrY+L2+locY, mPaint01);
        vBitmapCanvas.drawText(eprice, (int)(max/momo)*qrX+1+locX,(max%momo)*qrY+L3+locY, mPaint03);
        vBitmapCanvas.drawText(ecolor, (int)(max/momo)*qrX+1+locX, (max%momo)*qrY+L6+locY, mPaint02);         
        vBitmapCanvas.drawText(esize, (int)(max/momo)*qrX+1+locX, (max%momo)*qrY+L5+locY, mPaint02);
        if (rsizeBM !=null) {rsizeBM.recycle();}
    }

    if (momo==2){
    	if (!xMode.equalsIgnoreCase("9") && !xMode.equalsIgnoreCase("10")  && !mMode.equalsIgnoreCase("4") && !mMode.equalsIgnoreCase("3"))
    		vBitmapCanvas.drawBitmap( bRect, (int)(max/momo)*qrX+locX, (max%momo)*qrY+locY+L6+8, null );
	}else{
		vBitmapCanvas.drawBitmap( bRect, (int)(max/momo)*qrX+locX-10, (max%momo)*qrY+locY+(picY-30), null );
	}
    
	}
	
	public void saved() throws IOException {
		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;
		if (!mMode.equalsIgnoreCase("1")) 		
			edpic = filepath+File.separator+batch+"_6X3_"+ (100+counts)+".png";
		 else 
			edpic = filepath+File.separator+batch+"_5X2_"+ (100+counts)+".png";

		int swidth = vBitmap.getWidth();
		int shgh = vBitmap.getHeight();
		
		Matrix scaleMatrix = new Matrix();
		scaleMatrix.postScale(1,1);
		Bitmap 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);
    		rsizebar.compress(CompressFormat.PNG, 100, fos);
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
                if (fos != null) {
                	fos.flush();fos.close();
    				albun_array.append(edpic+",");
    				counts=counts+1;		
    				if (rsizebar!=null) rsizebar.recycle();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }			
		}
	}

	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 class ImageAdapter extends BaseAdapter {
		/* 宣告變數 */
		int mGalleryItemBackground;
		private Context mContext;
		private List<String> lis;

		/* ImageAdapter的建構子 */
		@SuppressLint("DefaultLocale")
		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(), 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();
	}

private Bitmap mkBar39(String Bars){
	Bitmap b = Bitmap.createBitmap(600, 70, Bitmap.Config.ARGB_8888);	
	Canvas vBarcode = new Canvas( b );
	vBarcode.drawColor(getResources().getColor(R.drawable.white));
	Bitmap rsizebar;
	Paint mPaint01 = new Paint();
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	mPaint01.setStyle(Paint.Style.FILL);
	mPaint01.setColor(getResources().getColor(R.drawable.black));
	mPaint01.setStrokeWidth(2.0F);
	
	String TT="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*";
	String [] BARDATA={
			
	"100100001111001111001",
	"111100100001001001111",
	"100111100001001001111",
	"111100111100001001001",
	"100100001111001001111",
	"111100100001111001001",
	"100111100001111001001",
	"100100001001111001111",
	"111100100001001111001",
	"100111100001001111001",
	"111100100100001001111",
	"100111100100001001111",
	"111100111100100001001",
	"100100111100001001111",
	"111100100111100001001",
	"100111100111100001001",
	"100100100001111001111",
	"111100100100001111001",
	"100111100100001111001",
	"100100111100001111001",
	"111100100100100001111",
	"100111100100100001111",
	"111100111100100100001",
	"100100111100100001111",
	"111100100111100100001",
	"100111100111100100001",
	"100100100111100001111",
	"111100100100111100001",
	"100111100100111100001",
	"100100111100111100001",
	"111100001001001001111",
	"100001111001001001111",
	"111100001111001001001",
	"100001001111001001111",
	"111100001001111001001",
	"100001111001111001001",
	"100001001001111001111",
	"111100001001001111001",
	"100001111001001111001",
	"1000010000100001001",
	"1000010000100100001" , 
	"1000010010000100001",
	"1001000010000100001" , 
	"100001001111001111001"
	};
	
	String [] iList=Bars.split(";");
	Bars="*"+iList[0]+"*";  //39碼的前後碼
	StringBuffer RB39=new StringBuffer(); //準備放置
		
	for (int i=0;i<Bars.length();i++){
		int Q=TT.indexOf(Bars.substring(i,i+1));
		if (Q>=0){
			RB39.append(BARDATA[Q]+"00");
		}				
	}

	for (int i = 0; i < RB39.toString().length(); i++) {
		if (!RB39.toString().substring(i,i+1).equalsIgnoreCase("0")) {
				vBarcode.drawLine(20+i*2,5,20+i*2,75, mPaint01);
		}
	}
	Matrix scaleMatrix = new Matrix();
	scaleMatrix.postScale(0.55F,0.55F);
		 rsizebar =Bitmap.createBitmap(b, 0, 0, 600, 70, scaleMatrix, true);
		rsizebar.compress(Bitmap.CompressFormat.PNG, 100, stream);// (0 - 100)压缩文件
return rsizebar;	
}
	
}
	

	