package com.cwbuyer.lib;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.cwbuyer.code.CodeList;
import com.cwbuyer.code.CodeMode;
import com.cwbuyer.format.DefaultData;
import com.pwbuyer.main.R;

public class MakeTransDetail extends PreferenceActivity {

	private String[] beCode = new String[]{"不編","批發","零售","中盤","原幣","供應商","日期","網購","成本"};	
	private String[] beCodeLR = new String[]{"0","1","2","3","4","5","6","7","8"};
	private String[] beCodeNo = new String[]{"0","1","2","3","4","5","6","7","8"};
	private static final String[] season = { "春夏","春夏","秋","秋冬","四季"};

	final String myAlbunList =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",8)+File.separator+"Goods_albun.lst";	
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);
	final String myImagePath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator;
	
	private int COUNTRY_CODE = 1001;
	
	String dfPic=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/04.jpg";

	private ArrayList<String> mTypeList = new ArrayList<String>();
	private ArrayList<Integer> mTypeIdList = new ArrayList<Integer>();
	private ArrayList<Integer> mCountryIdList = new ArrayList<Integer>();	
	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<String> mCountryIcon = new ArrayList<String>();

	private List<HashMap<String, Object>> albun_list = null;
	private DefaultData mDefaultData = null; // 採購參數
    @SuppressWarnings("unused")
	private int transMode=0;
	int nKind=0;
	String[] mailList=null;
	 int goon=0;	
	String mKind=null;
	String batch=null;
	int Make01=0; //0未傳送 1.已傳送
	int nMode=0;  //0.天為單位 1.單號為單位
	String mUser=""; //nKind!=0非採購單時 指定當nMode=0時,mUser.length()>0時 依USER單一出單
	//否則,全部依USER序依依出單
	int deptN=1;
	String [] DepNo;
	String [] DepNa;
	int ColNoSizN=0;
	String [][] ColNoSiz;	
   	int [][] Otott;
   	int nCount=0;

	  String aIP="";
	  String aBase="";
	  String aFtp="";
	  String aPort="";
	  String aPswd="";
   	
   	
   	String[] list;
	String[] listsel;
	String[] listdept;
	String cust_no;
	String cust_name;
	private int mChoice = 0;
	int cust_tradetype=5;
	int cust_discount=100;
	String M5263="1";
	int country=0;
	String countryN="韓國";
	private int nbar=0;
	private static final String[] barStr = { "","","","","","","","",""};
	private static final String[] deptStr = { "","","","","","","","",""};
	private static final String[] dataSend = { "","","","","","","","",""};
   	String mStartDay;
   	String mEndDay;
   	String dbStartDay;
   	String dbEndDay;
   	
	LinkedList<String> mSizeLink = new LinkedList<String>();
	LinkedList<String> mSizeLink1 = new LinkedList<String>();
	LinkedList<String> mColorLink = new LinkedList<String>();
	
	HashMap<Integer,Integer> mCountRow = new HashMap<Integer,Integer>(); // 顏色行資料
	HashMap<Integer,String> mCountCell = new HashMap<Integer,String>();  // 尺寸欄資料
	
	public ProgressDialog myDialog = null;
	boolean success=false;	
	int of_line=Utilis.toInt(Utilis.getIni(MakeTransDetail.this, "SYS", "IMPORT", 3));
	
	Bundle bundle;	
	  @Override
	  public void onConfigurationChanged(Configuration config) {
		super.onConfigurationChanged(config);
		
//		int i = getRequestedOrientation();
		
		switch (getRequestedOrientation()) {
			case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
				if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
				}
				break;
			case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
				if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
				}
				break;
			case ActivityInfo.SCREEN_ORIENTATION_SENSOR:
				if (config.orientation == Configuration.ORIENTATION_LANDSCAPE){
				}else{
				}
			default:
				break;
		}
	  }

		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			// TODO Auto-generated method stub
			super.onActivityResult(requestCode, resultCode, data);
//			String OutPhotoURI;
			if (requestCode == COUNTRY_CODE) {
				if (resultCode == RESULT_OK) {
					country = data.getIntExtra("country_id", 0);
					countryN = data.getStringExtra("country_name");
					try{
						makeA5263(M5263);
						finish();
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		}	
	  
	  /** Called when the activity is first created. */
	  
	  @SuppressWarnings("deprecation")
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
		batch = getIntent().getStringExtra("make_batch");   ///999
		nMode = getIntent().getIntExtra("make_mode",0); //9預購彙整   1.單號(qitems_formno) 
		
		nKind = getIntent().getIntExtra("make_kind",0);  //1.預購彙整   0_qdetail 10進貨 20出貨 30銷貨 31銷貨 40員購
		mKind=""+nKind;
		mUser=getIntent().getStringExtra("make_user");  //""
		Make01=getIntent().getIntExtra("make_01",0);
		
		mStartDay=getIntent().getStringExtra("make_startday");
		mEndDay=getIntent().getStringExtra("make_endday");

		String btns=null; 	String[] bttns;
     	btns=Utilis.getIni(this,"SYS","BAR_IP",9);
	   	bttns = btns.split("!&!");  	for(int i=0;i<9;i++)	barStr[i] = bttns[i];
	   	nbar=Utilis.toInt(barStr[7]); if (nbar==0) nbar=1;
     	btns=Utilis.getIni(this,"SYS","DEPT",9);
	   	bttns = btns.split("!&!");  	for(int i=0;i<9;i++)	deptStr[i] = bttns[i];
	   	
     	btns=Utilis.getIni(this,"SYS","DATA_SEND",9);
	   	bttns = btns.split("!&!");  	for(int i=0;i<9;i++)	dataSend[i] = bttns[i];
	   	
	   	//dataSend
		
		getDefaultData();
		getCountryData(this);
		getTypeData(this);
		
		//事先判斷SDCARD是否已載入
//		android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
		
		//事先判斷nKind==0表原始設計,照表操作
		//nKind!=0 還需batch有料(單號)user(有料)者,,照表操作.
		//其餘來自庫存管理,直接進入壓縮功能,不予條碼不予照片輸出.
		
		if (nKind==1){  //來自非採購單&各式單據
			if(batch.length()<=0 && mUser.length()<=0){ //表示不用開出Menu
				if (nMode==0) { //總公司ZIPTO門市
					transMode=2;
					//AAZip2A1();
				}else if (nMode==1) {//門市ZIPTO總公司
					transMode=3;
					//A1Zip2AA();
				} else if (nMode==4 || nMode==5){
					transMode=nMode;
					//AA0Zip2AA1(nMode);
						//4總倉手機_總倉(驗入)-->總店 AA0-AA1()原先要傳送Qdetail(TR<>Z0)+Qhead(ID<>Z0)
						//5總倉手機_總倉-->總店(驗入) AA0-AA1()原先的只要傳送Qdetail(TR<>Z0)
				} else if (nMode==6 || nMode==7){ //6.7
						//6總店手機_總倉(驗入)-->總店 AA1-AA0()_Qhead(ID<>Z0) 且 QKIND<>10
						//7總店手機_總倉-->總店(驗入) AA1-AA0()_Qhead(ID<>Z0)
					transMode=nMode;
					//AA1Zip2AA0(nMode);
				}else if (nMode==9) { //9 預購轉入廠商訂單出圖
					M5263="1";
					selectCountry();
					//makeA5263(M5263);
				  //finish();
				}else if (nMode==10) { //9 預購轉入廠商訂單出圖
					M5263="4";
					selectCountry();
					  //makeA5263(M5263);
					 // finish();
				}
			}else { 
				if (nMode==8) {
					//makeQmtrio(); //8 保留給各門市彙整進銷存做各門市匯出功能
				}
			}
//			finish();	
//			if (nMode!=0) finish();			
		} else {
			File entryFile = new File(myAlbunList);
	        File entryDir = new File(entryFile.getParent());
	        if (!entryDir.exists()) {
	          entryDir.mkdirs();
	        }
	        if (Make01==1){//單筆匯出雲端
	        	
				  if (Utilis.haveInternet(MakeTransDetail.this) && of_line==1)
					  showImport2Dialog();
				   else 
					   Toast.makeText(MakeTransDetail.this, "網路wifi 未開啟或訊號不良,請稍候再試試!!", Toast.LENGTH_SHORT).show();								
	        	
			  finish();
				  
	        }else{
	        	Utilis.setAutoRotationMode(this);	    
	        	addPreferencesFromResource(R.xml.output_preferences);
			}
		}
	  }
		
	  
	  protected void onDestroy() {
	    super.onDestroy();
	  }
	  
	private void makeMkqr(String QR,String USER){ //QR="1"_5X2  "2"_6X3
		
      if (albun_list.size()>0){ 
  		FileOutputStream istream = null;
  		ObjectOutputStream os = null;
  		try {
  			istream = new FileOutputStream(myAlbunList);
  			os = new ObjectOutputStream(istream);
              if (albun_list !=null && albun_list.size()>0)
              { os.writeObject(albun_list); }
              	os.flush();
      			os.close();
      			istream.close();
					Bundle bundle = new Bundle();
        			Intent intent = new Intent();
        			bundle = new Bundle();
					bundle.putString("Mkqrs",myAlbunList+","+batch+","+QR+","+USER+","+mStartDay+","+mEndDay+","+nMode);
     			intent.setClass(MakeTransDetail.this, Mkqr.class);
     			intent.putExtras(bundle);
     			startActivity(intent);
  		} catch (Exception e) {

  		}
      }											
	}

	private void selectCountry(){
		Intent intent = new Intent();
		intent.setClass(MakeTransDetail.this, CodeList.class);
		intent.putExtra("code_mode", CodeMode.COUNTRY);
		intent.putExtra("edit_mode", 1);
		MakeTransDetail.this.startActivityForResult(intent, COUNTRY_CODE);
	}

	private void makeA5263(String mkqrA){
		SQLiteDatabase db = Utilis.getDB(MakeTransDetail.this);
		Cursor cursorAlbun = null;
    	//File myFile = new File(myAlbunList); 
    	albun_list = new ArrayList<HashMap<String, Object>>();					
    		StringBuffer bufQ = new StringBuffer();
    	int mkqrGoods=Utilis.toInt(dataSend[3]);//0品名1備註
    	int mkqrBar=Utilis.toInt(dataSend[4]);//0條碼或號1條碼來源
    	int mkqrSource=Utilis.toInt(dataSend[5]);//0預購或號1預購來源
    	int mkqrPrice=Utilis.toInt(Utilis.getIni(this,"SYS","BACKOUT",1));//0批價1零售價
    if (nKind==0) {  //原始的輸出 採購單以(批號)為單位,應強化mailTo:不同對象不同MAIL	        	
    	if (mkqrA.equalsIgnoreCase("4")){
    		bufQ.append("select * from qdetail");
			bufQ.append(" where BATCH='" + batch+"' and COUNTRY='"+country+"'");
			//bufQ.append(" order by SUPPLY, GOODSNO");
			if (mkqrSource==0)
				bufQ.append(" order by SUPPLY,GOODSNO");
			else
		   		bufQ.append(" order by SUPPLY,SOURCENO");
			
    	}else{	
    		bufQ.append("select * from qdetail");
			bufQ.append(" where BATCH='" + batch+"'");
			if (mkqrSource==0)
				bufQ.append(" order by GOODSNO");
			else
		   		bufQ.append(" order by SOURCENO");
    	}	
			//@@@未來應可以多種排序20130322改為供應商+建檔順序
    }else { //來自各式單據,如廠進單10(到貨通知]) 如會員銷貨30(圖片銷貨單) 如報價目錄單(輸出)MAIL用
    	if (nMode==9 || nMode==10){//設定為預購轉出圖
    		dbStartDay=mStartDay.replace("/", "-");
    		dbEndDay=mEndDay.replace("/", "-");
	   		bufQ.append("select distinct GOODSNO from qitems");
	   		bufQ.append(" where FORMDATE>='" +dbStartDay +"' and FORMDATE<='"+dbEndDay+"'");
	   		bufQ.append(" and (QKIND='30' or QKIND='31') and (COUNTRY='"+countryN+"' or COUNTRY='"+country+"')");
			bufQ.append("  and (ISCONFIRM='O' or (ISCONFIRM='N' and ISCHECK='Y'))");
					//and (ISCONFIRM='O' or ISCONFIRM='N') and ISCHECK='Y'");
			if (mkqrSource==0)
				bufQ.append(" order by SUPPLY,GOODSNO");
			else
		   		bufQ.append(" order by SUPPLY,SOURCENO");

         }else{ //
    		bufQ.append("select distinct GOODSNO,USER,SUPPLY from qitems");
    		bufQ.append(" where FORMNO='" + batch+"'");
    		bufQ.append(" order by GOODSNO,CREATEDATETIME ");
    	}
		
    }
			cursorAlbun = db.rawQuery(bufQ.toString(), null);
			String eacherO="";
			String HeadKind=null;
			double owlTot=0;
			double owlLast=0;
			switch (nKind) {
				case 10: HeadKind="進貨:";break;
				case 20: HeadKind="出貨:";break;
				case 21: HeadKind="轉貨:";break;
				case 30: HeadKind="銷貨:";break;
				case 31: HeadKind="銷貨:";break;
				case 40: HeadKind="員購:";break;
				case 41: HeadKind="員購:";break;
				default:HeadKind="預購:";break;
			}
					if (cursorAlbun != null) {
						if (cursorAlbun.getCount() > 0) {
							cursorAlbun.moveToFirst();
							if (nKind!=0) {
								if (nMode!=9 && nMode!=10){ //同一單
									eacherO=cursorAlbun.getString(cursorAlbun.getColumnIndex("USER"));
									Cursor cursorH=db.rawQuery("select * from qhead where FORMNO='"+batch+"'",null);
									if (cursorH.getCount()>0){ //取得單頭
										cursorH.moveToFirst();
	                					double Bsum=cursorH.getDouble(cursorH.getColumnIndex("BSUM"))-cursorH.getDouble(cursorH.getColumnIndex("CASH"))-cursorH.getDouble(cursorH.getColumnIndex("CARD"))-cursorH.getDouble(cursorH.getColumnIndex("ORDCASH"))-cursorH.getDouble(cursorH.getColumnIndex("ORDCARD"))-cursorH.getDouble(cursorH.getColumnIndex("ATM"));
	                					String YN=cursorH.getString(cursorH.getColumnIndex("ISCONFIRM"));
	                					if (!YN.equalsIgnoreCase("Y")) Bsum=0;
	                					
	                	        		//Toast.makeText(MakeTransDetail.this, "前帳運算的本單尚未結算的金額=="+Bsum, Toast.LENGTH_LONG).show();								
										
										HashMap<String, Object> maps = new HashMap<String, Object>();
										Cursor cursorC=null;
										String mMobil="";
										String mAddress="";
										String mPic=dfPic;
										if (nKind!=10)
											cursorC=db.rawQuery("select * from qcust where CUSTNO='"+cursorH.getString(cursorH.getColumnIndex("USER"))+"'",null);
										else
											//@@@未來是否嘗試讓不同的廠商,印製不同的輸出
											cursorC=db.rawQuery("select * from qfact where FACTNO='"+cursorH.getString(cursorH.getColumnIndex("USER"))+"'",null);
										
										if (cursorC.getCount()>0){
											cursorC.moveToFirst();
											mMobil=cursorC.getString(cursorC.getColumnIndex("MOBIL"));
											mAddress=cursorC.getString(cursorC.getColumnIndex("ADDRESS"));
											if(cursorC.getString(cursorC.getColumnIndex("PIC")) != null && cursorC.getString(cursorC.getColumnIndex("PIC")).length() > 0){
										        File file= new File(cursorC.getString(cursorC.getColumnIndex("PIC")));
										        if(file.exists())	mPic=cursorC.getString(cursorC.getColumnIndex("PIC"));
											}
										}
										cursorC.close();
										
										maps.put("eno", "單號"+cursorH.getString(cursorH.getColumnIndex("FORMNO")));
										maps.put("ename", cursorH.getString(cursorH.getColumnIndex("FORMDATE"))+"("+cursorH.getString(cursorH.getColumnIndex("EMPID"))+")");
										maps.put("eprice", cursorH.getString(cursorH.getColumnIndex("USER"))+"/"+cursorH.getString(cursorH.getColumnIndex("USERNAME")));
				                    		maps.put("esize", "TEL:"+mMobil);
				                    		maps.put("ecolor","AD:"+mAddress);
				                			StringBuffer mBuf = new StringBuffer();
				                			mBuf.append("select sum(BSUM) as BSUMS,sum(CASH) as CASHS,")
				                			.append("sum(CARD) as CARDS,sum(ORDCASH) as ORDCASHS,")
				                			.append("sum(ORDCARD) as ORDCARDS,sum(ATM) as ATMS,sum(TRCASH) as TRCASHS ")
				                			.append(" from " + TbName.QHEAD)
				                			.append(" where ISCONFIRM='Y'");
//				                			.append(" where (ISCONFIRM='Y' or (ISCHECK='Y' and ISCONFIRM='N'))");
			                				mBuf.append(" and QKIND LIKE '"+mKind.substring(0,1)+"%'");
				                			mBuf.append(" and USER='"+cursorH.getString(cursorH.getColumnIndex("USER"))+"'");
				                			
				                			Cursor cursor = db.rawQuery(mBuf.toString(), null);
				                			
				                			if (cursor.getCount()>0) {
				                				cursor.moveToFirst();
				                				//未結
				                					owlTot=cursor.getDouble(cursor.getColumnIndex("CASHS"))+
				                							cursor.getDouble(cursor.getColumnIndex("CARDS"))+
				                							cursor.getDouble(cursor.getColumnIndex("ORDCASHS"))+
				                							cursor.getDouble(cursor.getColumnIndex("ORDCARDS"))+
				                							cursor.getDouble(cursor.getColumnIndex("ATMS"))
				                							-cursor.getDouble(cursor.getColumnIndex("BSUMS"))
				                							;
			                						owlLast=owlTot+Bsum;
				                			}
				                    		
			                    		maps.put("ebars", cursorH.getString(cursorH.getColumnIndex("FORMNO"))+";"+cursorH.getString(cursorH.getColumnIndex("FORMDATE"))+";"+cursorH.getString(cursorH.getColumnIndex("USER"))+";");
			                    		maps.put("epics", mPic);  //客戶的圖片
			                    		maps.put("supply", HeadKind+"件數:"+cursorH.getString(cursorH.getColumnIndex("HANDNO")));
										
			                            albun_list.add(maps);
										
										HashMap<String, Object> map1 = new HashMap<String, Object>();
										map1.put("eno", "應收:"+cursorH.getString(cursorH.getColumnIndex("BSUM")));
										map1.put("ename","前帳:"+(owlLast*-1)+" 入金:"+(cursorH.getInt(cursorH.getColumnIndex("CASH"))+cursorH.getInt(cursorH.getColumnIndex("CARD"))+cursorH.getInt(cursorH.getColumnIndex("ORDCASH"))+cursorH.getInt(cursorH.getColumnIndex("ORDCARD"))));
										map1.put("eprice", "未結:"+(owlTot*-1)+" 代墊:"+cursorH.getString(cursorH.getColumnIndex("TRCASH")));
			                    		map1.put("ecolor", "現:"+cursorH.getString(cursorH.getColumnIndex("CASH"))+" 票:"+cursorH.getString(cursorH.getColumnIndex("CARD")));
			                    		map1.put("esize","訂:"+cursorH.getString(cursorH.getColumnIndex("ORDCASH"))+" 刷:"+cursorH.getString(cursorH.getColumnIndex("ORDCARD"))+" 匯:"+cursorH.getString(cursorH.getColumnIndex("ATM")));
			                    		map1.put("ebars", Utilis.getIni(MakeTransDetail.this,"USER","COMPANY",1)+";"+Utilis.getIni(MakeTransDetail.this,"USER","COMPANY",2)+";"+Utilis.getIni(MakeTransDetail.this,"USER","COMPANY",4)+";"+Utilis.getIni(MakeTransDetail.this,"USER","COMPANY",5));
			                    		String DP=Utilis.getIni(this,"SYS","BACKOUT",4);if (DP ==null || DP.length()<=0 ) DP=dfPic;
			                    		map1.put("epics", DP);  //門市的圖片
			                    		map1.put("supply", "");
										
			                            albun_list.add(map1);
										cursorH.close();
									}
								}
								
							}

							for (int i = 0; i < cursorAlbun.getCount(); i++) {
								StringBuffer isList = new StringBuffer();
								StringBuffer isList1 = new StringBuffer();
								StringBuffer isList2 = new StringBuffer();
								
								if (nKind==0){ //原始單
									HashMap<String, Object> maps = new HashMap<String, Object>();
									String SupplyM="/";
									if (cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY")).length()>0){
									Cursor cs=db.rawQuery("select * from qfact where FACTNO='"+cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY"))+"'", null);
										if (cs.getCount()>0){
											cs.moveToFirst();
											SupplyM=SupplyM+cs.getString(cs.getColumnIndex("MOBIL"));
										}
									cs.close();
									}
									
									if (mkqrSource==0)
										maps.put("eno", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")));
									else
										maps.put("eno", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("SOURCENO")));

									if (mkqrA.equalsIgnoreCase("4")){
										if (mkqrGoods==0)
											maps.put("ename", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNAME")));
										else
											maps.put("ename", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("PS")));
									}else if (mkqrA.equalsIgnoreCase("3")){
												maps.put("ename", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNAME")));
									}else{
										//!=4.3
										if (dataSend[8].equalsIgnoreCase("0"))
											maps.put("ename", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNAME")));
										else
											maps.put("ename", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("PS")));
									}

									if (mkqrA.equalsIgnoreCase("3")){
										if (mkqrPrice==0)
											maps.put("eprice",(String)"批發價 $:"+cursorAlbun.getString(cursorAlbun.getColumnIndex("P3")));
										else
											maps.put("eprice",(String)"會員價 $:"+cursorAlbun.getString(cursorAlbun.getColumnIndex("P5")));
										
										maps.put("ecolor",""+cursorAlbun.getString(cursorAlbun.getColumnIndex("COLOR")));
										maps.put("esize",""+cursorAlbun.getString(cursorAlbun.getColumnIndex("SIZE")));
										maps.put("ebars", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")));
			                    		maps.put("epics", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("PIC")));
			                    		maps.put("supply", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY"))+SupplyM);
			                            albun_list.add(maps);
									}else {
										if (!mkqrA.equalsIgnoreCase("4")){
											maps.put("eprice",getmCode(cursorAlbun,0));
											maps.put("ecolor",""+cursorAlbun.getString(cursorAlbun.getColumnIndex("COLOR"))+"/"+cursorAlbun.getString(cursorAlbun.getColumnIndex("SIZE")));
											maps.put("esize",""+cursorAlbun.getString(cursorAlbun.getColumnIndex("INLIST")));
											if (mkqrBar==0)
												maps.put("ebars", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")));
											else
												maps.put("ebars", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("SOURCENO")));
											
				                    		maps.put("epics", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("PIC")));
				                    		maps.put("supply", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY"))+SupplyM);
				                            albun_list.add(maps);
										}else{//從採購單製作出預購規格
											String [] iCol=cursorAlbun.getString(cursorAlbun.getColumnIndex("COLOR")).split("，");  //取得顏色中文陣列
											String [] iSiz=cursorAlbun.getString(cursorAlbun.getColumnIndex("SIZE")).split(","); //取得尺寸陣列
											String [] iLst=cursorAlbun.getString(cursorAlbun.getColumnIndex("INLIST")).split("，"); //取得色組
											int ig=0;
											int Toot=0;

											for (int x=0;x<iCol.length;x++){//共有幾色
												String []L=iLst[x].split(",");
												for (int y=0;y<iSiz.length;y++){
													if (!L[y].equalsIgnoreCase("0")){
														if (ig%3==0)
															isList.append(iCol[x]+iSiz[y]+"("+L[y]+")");
														else	if (ig%3==1)
															isList1.append(iCol[x]+iSiz[y]+"("+L[y]+")");
														else	if (ig%3==2)	
															isList2.append(iCol[x]+iSiz[y]+"("+L[y]+")");
														Toot=Toot+Utilis.toInt(L[y]);
														ig=ig+1;
														if (ig%9==0){
															
															HashMap<String, Object> mapn = new HashMap<String, Object>();
															if (mkqrSource==0)
																mapn.put("eno", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")));
															else
																mapn.put("eno", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("SOURCENO")));
															
															if (mkqrGoods==0)
																mapn.put("ename", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNAME")));
															else
																mapn.put("ename", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("PS")));
														
															mapn.put("eprice",cursorAlbun.getString(cursorAlbun.getColumnIndex("P0"))+" x "+Toot+" 件");
															mapn.put("ecolor",""+isList1.toString());
															mapn.put("esize",""+isList.toString());
															mapn.put("ebars", ""+isList2.toString());
								                    		mapn.put("epics", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("PIC")));
								                    		mapn.put("supply", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY"))+SupplyM);
								                            albun_list.add(mapn);
								                            isList.delete(0, isList.toString().length());
								                            isList1.delete(0, isList1.toString().length());
								                            isList2.delete(0, isList2.toString().length());
								                            Toot=0;
														}
													}
											}	}
											if (ig%9!=0){
												maps.put("eprice",cursorAlbun.getString(cursorAlbun.getColumnIndex("P0"))+" x "+Toot+" 件");
												maps.put("ecolor",""+isList1.toString());
												maps.put("esize",""+isList.toString());
												maps.put("ebars",""+isList2.toString());
					                    		maps.put("epics", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("PIC")));
					                    		maps.put("supply", ""+cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY"))+SupplyM);
					                            albun_list.add(maps);
											}
										}
									}
								} else {  //非原始單可能為單一張單,或日期範圍的預購
//									getUserGoods(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")),mKind,batch,nMode,albun_list);
										eacherO="";
										Cursor cs = null;
										StringBuffer bufi = new StringBuffer();
										if (nMode==9 || nMode==10){ //預購狀態
											String GoodsN=cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO"));
											String SupplyM="";
											String GoodsNo="";
											String GoodsM="";
											String GoodsPic="";
											
											int iP0=0;
											bufi.append("select GOODSNO,UNIT1,SIZE,P0,sum(UNIT) from qitems ")
											.append(" where GOODSNO='"+GoodsN+"'")											
									   		.append(" and FORMDATE>='").append(dbStartDay).append("' and FORMDATE<='").append(dbEndDay).append("'")
									   		.append(" and (QKIND='30' or QKIND='31') and (COUNTRY='"+countryN+"' or COUNTRY='"+country+"')")
											.append("  and (ISCONFIRM='O' or (ISCONFIRM='N' and ISCHECK='Y'))")
											.append(" group by GOODSNO,UNIT1,SIZE,P0 order by UNIT1,SIZE");
											
											cs = db.rawQuery(bufi.toString(), null);
											if (cs != null) {
												if (cs.getCount() > 0) {
													int Toot=0;
													 cs.moveToFirst();
													HashMap<String, Object> maps = new HashMap<String, Object>();
													Cursor csQdetail=db.rawQuery("select SOURCENO,GOODSNAME,SUPPLY,PIC,PS,P0 from QDETAIL where GOODSNO='"+GoodsN+"' order by BATCH DESC LIMIT 1", null);
													if (csQdetail.getCount()>0){
														csQdetail.moveToFirst();
														iP0=csQdetail.getInt(csQdetail.getColumnIndex("P0"));

														if (mkqrSource==0)
															GoodsNo=GoodsN;
														else
															GoodsNo=csQdetail.getString(csQdetail.getColumnIndex("SOURCENO"));
														if (mkqrGoods==0)
															GoodsM=csQdetail.getString(csQdetail.getColumnIndex("GOODSNAME"));
														else
															GoodsM=csQdetail.getString(csQdetail.getColumnIndex("PS"));
														
														GoodsPic=csQdetail.getString(csQdetail.getColumnIndex("PIC"));
														SupplyM=csQdetail.getString(csQdetail.getColumnIndex("SUPPLY"));
														if (SupplyM.length()>0){
															Cursor csf=db.rawQuery("select FACTNAME,MOBIL from qfact where FACTNO='"+SupplyM+"'", null);
																if (csf.getCount()>0){
																	csf.moveToFirst();
																	SupplyM=SupplyM+"/"+csf.getString(1);
																}
															csf.close();
														}
													}
													csQdetail.close();
													int ig=0;
													for ( int x = 0; x < cs.getCount(); x++) {
														if (ig%3==0)
															isList.append(cs.getString(1)+cs.getString(2)+"("+cs.getString(4)+")");
														else if (ig%3==1)
															isList1.append(cs.getString(1)+cs.getString(2)+"("+cs.getString(4)+")");
														else
															isList2.append(cs.getString(1)+cs.getString(2)+"("+cs.getString(4)+")");
														
														Toot=Toot+cs.getInt(4);
														ig=ig+1;
														
														if (ig%9==0){
															HashMap<String, Object> mapn = new HashMap<String, Object>();
															mapn.put("eno",""+GoodsNo);
															mapn.put("ename",""+GoodsM);
															mapn.put("epics",""+GoodsPic);
															mapn.put("eprice",iP0+" x "+Toot+" 件");
															mapn.put("supply",""+SupplyM);
															mapn.put("ecolor",""+isList1.toString());
															mapn.put("esize",""+isList.toString());
															mapn.put("ebars",""+isList2.toString());				
															albun_list.add(mapn);
								                            isList.delete(0, isList.toString().length());
								                            isList1.delete(0, isList1.toString().length());
								                            isList2.delete(0, isList2.toString().length());
								                            Toot=0;
														}
													cs.moveToNext();
													}
													if (ig%9!=0){
														maps.put("eno",""+GoodsNo);
														maps.put("ename",""+GoodsM);
														maps.put("epics",""+GoodsPic);
														maps.put("eprice",iP0+" x "+Toot+" 件");
														maps.put("supply",""+SupplyM);
														maps.put("ecolor",""+isList1.toString());
														maps.put("esize",""+isList.toString());
														maps.put("ebars",""+isList2.toString());				
														albun_list.add(maps);
													}
												 }
											}
											
										} else { //單號為單位
											int SUMS=0;
											int SUMA=0;
											bufi.append("select GOODSNO,GOODSNAME,COLORS,SIZES,UNIT1,SIZE,UNIT2,UNITPRICE,DISCOUNT,PIC,sum(SUBPRICE) ,sum(UNIT"+mKind.substring(0, 1)+"0),SOURCENO from qitems ");
											bufi.append(" where GOODSNO='"+cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO"))+"' and QKIND LIKE '"+mKind.substring(0,1)+"%'");
											bufi.append(" and FORMNO='"+batch+"'");
											bufi.append(" group by GOODSNO,GOODSNAME,COLORS,SIZES,UNIT1,SIZE,UNIT2,UNITPRICE,DISCOUNT,PIC,SOURCENO");
											cs = db.rawQuery(bufi.toString(), null);
											if (cs != null) {
												if (cs.getCount() > 0) {
													cs.moveToFirst();
													String [] iCol=cs.getString(2).split("，");  //取得顏色中文陣列
													String [] iSiz=cs.getString(3).split(","); //取得尺寸陣列
													int iList[]=new int[iCol.length*iSiz.length];
																for (int ig = 0; ig < cs.getCount(); ig++) { //				
																	for (int x=0;x<iCol.length;x++){
																		for (int y=0;y<iSiz.length;y++){
																			if (cs.getString(4).equalsIgnoreCase(iCol[x]) && cs.getString(5).equalsIgnoreCase(iSiz[y])){
																				iList[x*iSiz.length+y]=iList[x*iSiz.length+y]+cs.getInt(11);
																				SUMS=SUMS+cs.getInt(10);
																				SUMA=SUMA+cs.getInt(11);
																			}
																		}
																	}
																	cs.moveToNext();					
																}

														for (int x=0;x<iCol.length;x++){
															for (int y=0;y<iSiz.length;y++){
																	isList.append(""+iList[x*iSiz.length+y]);
																	if(y<iSiz.length-1) isList.append(",");
															}
															if(x<iCol.length-1) isList.append("，");
														}
													 cs.moveToFirst();
													HashMap<String, Object> maps = new HashMap<String, Object>();
													if (mkqrSource==0)
														maps.put("eno",""+cs.getString(cs.getColumnIndex("GOODSNO")));
													else
														maps.put("eno",""+cs.getString(cs.getColumnIndex("SOURCENO")));
													
													maps.put("ename",""+cs.getString(cs.getColumnIndex("GOODSNAME")));
													maps.put("eprice",""+cs.getString(cs.getColumnIndex("UNITPRICE"))+"x"+SUMA+"=$:"+SUMS);
													maps.put("ecolor",""+cs.getString(cs.getColumnIndex("COLORS"))+"/"+cs.getString(cs.getColumnIndex("SIZES")));
													maps.put("esize",""+isList.toString());
													maps.put("ebars", ""+cs.getString(cs.getColumnIndex("GOODSNO"))+";"+cs.getString(cs.getColumnIndex("GOODSNAME")));				
													maps.put("epics", ""+cs.getString(cs.getColumnIndex("PIC")));
													maps.put("supply", ""+cs.getString(cs.getColumnIndex("UNIT2")));
													albun_list.add(maps);
												 }
											}
										}
									cs.close();	
								}
								cursorAlbun.moveToNext();
							}
							if (db.isOpen())	db.close();
							if (albun_list.size()>0){
								//應該進行makeMkqr的程序
								if (nKind==0) makeMkqr(mkqrA,"");
								else makeMkqr(mkqrA,eacherO);  //原始										
							}
							
							}
					}
					if (db.isOpen())
					db.close();

	}
	
	  public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
		  
		  if (preference.getKey().equalsIgnoreCase("key_qra452")) {  //影像檔案條碼輸出格式(5*2)
			  
		      //myDialog = ProgressDialog.show(MakeTransDetail.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
			  
		      new Thread()
		      { 
		        public void run()
		        { 
		          try
		          {
		        	  if (nMode!=10 && nKind!=9) nMode=0;  
						M5263="1";
						makeA5263(M5263);
		          }
		          catch (Exception e)
		          {
		            e.printStackTrace();
		          }
		          finally
		          {
		            // 卸載所建立的myDialog物件。
		            //myDialog.dismiss();
		          }
		        }
		      }.start(); /* 開始執行執行緒 */
		      
		  } else if(preference.getKey().equalsIgnoreCase("key_qra463")){ //影像檔案條碼輸出格式(6*3)
		      //myDialog = ProgressDialog.show(MakeTransDetail.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
			  
		      new Thread()
		      { 
		        public void run()
		        { 
		          try
		          { 
						M5263="2";
						makeA5263(M5263);
		          }
		          catch (Exception e)
		          {
		            e.printStackTrace();
		          }
		          finally
		          {
		            // 卸載所建立的myDialog物件。
		            //myDialog.dismiss();
		          }
		        }
		      }.start(); /* 開始執行執行緒 */
		      
		  } else if(preference.getKey().equalsIgnoreCase("key_qcust463")){ //影像條碼輸出給批發客戶
		      //myDialog = ProgressDialog.show(MakeTransDetail.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
			  
		      new Thread()
		      { 
		        public void run()
		        { 
		          try
		          { 
		            // 在這裡寫上要背景執行的程式片段 
		            // 為了明顯看見效果，以暫停3秒作為示範 
						M5263="3";
						makeA5263(M5263);
		          }
		          catch (Exception e)
		          {
		            e.printStackTrace();
		          }
		          finally
		          {
		            // 卸載所建立的myDialog物件。
		            //myDialog.dismiss();
		          }
		        }
		      }.start(); /* 開始執行執行緒 */
		      
		  } else if(preference.getKey().equalsIgnoreCase("key_qdetail452")){ //採購單輸出預購模式
		      //myDialog = ProgressDialog.show(MakeTransDetail.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
			  
		      new Thread()
		      { 
		        public void run()
		        { 
		          try
		          {
		        	  nMode=8;
						M5263="4";
						selectCountry();
		          }
		          catch (Exception e)
		          {
		            e.printStackTrace();
		          }
		          finally
		          {
		            // 卸載所建立的myDialog物件。
		            //myDialog.dismiss();
		          }
		        }
		      }.start(); /* 開始執行執行緒 */
		      
		  } else if(preference.getKey().equalsIgnoreCase("key_exports_cloud")){
			  if (Utilis.haveInternet(MakeTransDetail.this) && of_line==1){
				  if (dataSend[0].equalsIgnoreCase("0")) listdept=getdeptList(0);
				  showImport2Dialog();
			  } else {
	        		Toast.makeText(MakeTransDetail.this, "網路wifi 未開啟或訊號不良,請稍候再試試!!", Toast.LENGTH_SHORT).show();								
			  }
			  
		  } else if(preference.getKey().equalsIgnoreCase("key_exports")){
			  //以批號為單位分色尺寸
				SQLiteDatabase db = Utilis.getDB(MakeTransDetail.this);
				Cursor csExp = null;
//				String eacherO="";
//				應開始命名所要存的 /cwbuyer/cwbuyer_trans_888168.csv"		
		        StringBuffer bufQ = new StringBuffer();
				bufQ.append("select * from qdetail");
				bufQ.append(" where BATCH='" + batch+"'");
				bufQ.append(" order by BATCH , MID");
				csExp = db.rawQuery(bufQ.toString(), null);
				String sepa=";";
				StringBuffer sPrice = new StringBuffer();
				StringBuffer zipList =new StringBuffer();
				StringBuffer zipDetail =new StringBuffer();
				if (csExp != null) {
					if (csExp.getCount() > 0) {																
					csExp.moveToFirst();
								for (int i = 0; i < csExp.getCount(); i++) {
								//貨品明細編號需透過回圈讀取顏色尺寸的組合
								String colornS=(String)csExp.getString(csExp.getColumnIndex("COLORNO"));
								String[] arrayColorNo = colornS.split("，"); //如此可以得到有幾個顏色代號
								String colorS=(String)csExp.getString(csExp.getColumnIndex("COLOR"));
								String[] arrayColor = colorS.split("，");//如此可以得到有幾個顏色名稱
								String sizeS=(String)csExp.getString(csExp.getColumnIndex("SIZE"));
		//						sizeS.replace(',', ';');
								String[] arraySize = sizeS.split(","); //如此可以得到有幾個尺寸
								String inlistT=(String)csExp.getString(csExp.getColumnIndex("INLIST"));
		//						inlistT.replace(',', ';');
								String[] arrayInlistT = inlistT.split("，"); //如此可以得到有幾組數字
								int colort=arrayColorNo.length;
								
								zipDetail.append(makeDetail(csExp));
								
								for (int ji=0;ji<colort;ji++){ //逐一讀取顏色代號,顏色名稱
									String[] arrayInlistS=arrayInlistT[ji].split(","); //取得各組明細數量
									for (int jk=0;jk<arrayInlistS.length;jk++) { //逐一讀取尺寸
										//產生貨品明細編號
									if (Utilis.toInt(arrayInlistS[jk])!=0){	//@@20131030增設檢查數量不為0者
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("TR"))+sepa);
										sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("GOODSNO")))+sepa);
										sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("SOURCENO")))+sepa);
										sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("GOODSNO")))+"-");
										sPrice.append((String)arrayColorNo[ji]+"-");
										sPrice.append((String)arraySize[jk]+sepa);
										int gtype = csExp.getInt(csExp.getColumnIndex("GOODSTYPE"));  //代號需轉換為文字
							        	int index = mTypeIdList.indexOf(gtype);
							        	if(index >= 0){	sPrice.append((String)mTypeList.get(index)+sepa);	}
							        	else {
							        		sPrice.append(DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("GOODSTYPE")))+sepa);
							        	}																			
										sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("GOODSNAME")))+sepa);
										sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("COLORNO")))+sepa);
										sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("COLOR")))+sepa);
										sPrice.append( '"'+DBCloud.chkStr(sizeS)+'"'+sepa);
										sPrice.append((String)DBCloud.chkStr(arrayColorNo[ji])+sepa);
										sPrice.append((String)DBCloud.chkStr(arrayColor[ji])+sepa);
										sPrice.append((String)DBCloud.chkStr(arraySize[jk])+sepa);
										sPrice.append((String)DBCloud.chkStr(arrayInlistS[jk])+sepa);
										sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("SUPPLY")))+sepa);
										sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("BATCH")))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("BILLRATE"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P0"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("ADDCOST"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P1"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P2"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P3"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P4"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P5"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("SEASON"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("STATE"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("QUALITY_ID"))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("WASH_ID"))+sepa);
										String picFileN =csExp.getString(csExp.getColumnIndex("PIC"));
										sPrice.append(picFileN+sepa);

										if(picFileN == null || picFileN.length() <= 0 || picFileN.equalsIgnoreCase(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png")){;} else {
											File file = new File(picFileN);
												if (file.exists() == true) {
													if (ji==0 &&jk==0) {
														if (zipList.toString().indexOf(picFileN)<0 ) zipList.append(picFileN+"，");
													}
												}
										}
										picFileN =csExp.getString(csExp.getColumnIndex("PICTURE"));
										sPrice.append(picFileN+sepa);
										if(picFileN == null || picFileN.length() <= 0 || picFileN.equalsIgnoreCase(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png")){;} else {
											File file = new File(picFileN);
												if (file.exists() == true) {
													if (ji==0 &&jk==0) {
														if (zipList.toString().indexOf(picFileN)<0 ) zipList.append(picFileN+"，");
													}
												}
										}
										int gcountry = csExp.getInt(csExp.getColumnIndex("COUNTRY"));  //代號需轉換為文字
							        	int cindex = mCountryIdList.indexOf(gcountry);
							        	if(cindex >= 0){	sPrice.append((String)mCountryList.get(cindex)+sepa);	}
							        	else {
							        		sPrice.append((String)csExp.getString(csExp.getColumnIndex("COUNTRY"))+sepa);
							        	}																			
										sPrice.append((String)DBCloud.chkStr(csExp.getString(csExp.getColumnIndex("PS")))+sepa);										
										sPrice.append( (String)DBCloud.chkStr(csExp.getString(csExp.getColumnIndex("UNIT1")))+sepa);
										sPrice.append( (String)DBCloud.chkStr(csExp.getString(csExp.getColumnIndex("UNIT2")))+sepa);
										sPrice.append( (String)csExp.getString(csExp.getColumnIndex("CREATEDATETIME"))+sepa+"SSSS"+"\r\n");
									}	
									}
								}
						csExp.moveToNext();
								}
									
								//每產生一個STRINGBUF:sPrice 就是一份完整的文件
								saveZip(sPrice.toString(),zipDetail.toString(),zipList,batch,"1.0","1.0",1,1 );
								//可以顧全第二方案,
								//db.execSQL("update qdetail set TR='1000'  where TR<>'1000' and BATCH='"+batch+"'");								
				}
			}
				db.close();
				csExp.close();
				
				
		  } else if(preference.getKey().equalsIgnoreCase("key_export")){
				String SAVE_FOLDER = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+"DCIM/CWBuyer" ;
				String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + "DCIM/CWBuyer"+File.separator+batch+File.separator ;
		        File myDataPath = new File(filepath);
		        if (!myDataPath.exists()) {
					Toast.makeText(MakeTransDetail.this,"查無附圖可以輸出!!", Toast.LENGTH_SHORT).show();
		        }else{
		    		File f = new File(filepath);        
		    		File files[] = f.listFiles();
		    		if (files.length>0){
			   		 	String zipFileN=myImportPath+File.separator+"cwbuyer_Pics_"+batch+".zip";
			    		//將圖檔壓縮並存在zipFileN
						try {
							int BUFFER = 2048;
							BufferedInputStream origin = null;
							FileOutputStream dest = new FileOutputStream(zipFileN);
							ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
							byte data[] = new byte[BUFFER];
							for (int i = 0; i < files.length; i++) {
								FileInputStream fi = new FileInputStream(files[i]);
								origin = new BufferedInputStream(fi, BUFFER);
								
								ZipEntry entry = new ZipEntry(files[i].toString().substring(SAVE_FOLDER.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();
						}
						
						 ArrayList<Uri> imageUris = new ArrayList<Uri>();
						 imageUris.add(Uri.parse("file://"+zipFileN)); // Add your image URIs here
						
						try{
							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..")); 			    
						} catch (Exception e) {
						// TODO Auto-generated catch block
							e.printStackTrace();
						}
		    		}else{
						Toast.makeText(MakeTransDetail.this,"查無附圖可以輸出!!", Toast.LENGTH_SHORT).show();
		    		}
		        }
			  
		  } else if(preference.getKey().equalsIgnoreCase("key_txt_output")){
			  //取得該批號所有資料,產生文字檔,CSV
			  //再透過多媒體,傳送出去
			  StringBuffer bufQ=new StringBuffer(); 
	    		bufQ.append("select a.GOODSNO,a.P0,a.SUPPLY,b.FACTNAME,b.MOBIL,a.GOODSNAME,a.COLOR,a.SIZE,a.INLIST,a.P3,a.P4,a.P5,a.SOURCENO,a.PS  from qdetail a left  join qfact b on a.SUPPLY=b.FACTNO");
				bufQ.append(" where a.BATCH='" + batch+"'");
				bufQ.append(" order by a.GOODSNO");
				SQLiteDatabase db = Utilis.getDB(MakeTransDetail.this);
				Cursor cs = db.rawQuery(bufQ.toString(), null);
				if (cs.getCount()>0){
			 		String batchFile=myImportPath+File.separator+"CW_txt_"+batch+".csv";  //預設為分色尺寸
                    File file=new File(batchFile);
					  String sepa="\r\n";
					  String sTxtCsv="商品編號;原幣;供應商;名稱;電話;商品描述;顏色;尺寸;件數;批發價;網購價;零售價;來源編號;備註"+sepa; 
					while(cs.moveToNext()){
						for (int i=0;i<12;i++){
						sTxtCsv+=(cs.getString(i)+";");
						}
						sTxtCsv+=(cs.getString(12)+sepa);
					}
					db.close();
					cs.close();
					BufferedWriter bw;
					try {
						bw = new BufferedWriter(new FileWriter(batchFile));
	                    if (sTxtCsv !=null && sTxtCsv.length()>0)
	                    { bw.write(sTxtCsv); }
	                    bw.close();
	                    SystemClock.sleep(1000);
	                    if (file.exists()){
	                    	//開始打開多媒體,選擇匯出
	            	    	Intent send = new Intent(Intent.ACTION_SEND);
	            	    	send.setType("image/jpeg");
	            		    String uriText;
	            		    Uri U=Uri.parse("file://"+batchFile);  //重要的範例
	            		    //uriText = "https://www.google.com/cloudprint/addpublicprinter.html?printerid=bb160853-6274-0f65-eb1f-34ae2c9ed6e1&key=19901109";
	            		    uriText = "請選擇多媒體匯出(ANDFTP匯到伺服器)";
	            		    send.putExtra(Intent.ACTION_SENDTO,uriText);
	            		    send.putExtra(Intent.EXTRA_STREAM,U);
	            		    startActivity(Intent.createChooser(send, uriText));
	                    	
	                    }
	                    
					
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
		
	    		

			  
		  } else if(preference.getKey().equalsIgnoreCase("key_import10")){
			  //@@須考慮匯入的日期_對話窗 讓USER決定
			  //呼叫雲端_UPDATE
			  //也因著確認 指定某一門市 而 出貨
			  StartImport(0); //無條件 產生一份廠商進貨單
			  if (Utilis.getIni(MakeTransDetail.this, "SYS","DEPT_SEND", 1).equalsIgnoreCase("0")){
				  listdept=getdeptList(1);
				  if(listdept.length>0)  showImport1Dialog();
			  }
			  
		  } else if(preference.getKey().equalsIgnoreCase("key_bprint4070")){//
		          try
		          { 
		            // 在這裡寫上要背景執行的程式片段 
		            // 為了明顯看見效果，以暫停3秒作為示範 
		            //sleep(3000);
					  makeBarcode("1",batch,mKind);
		          }
		          catch (Exception e)
		          {
		            e.printStackTrace();
		          }
		  } else if(preference.getKey().equalsIgnoreCase("key_bprint4580")){
		          try
		          { 
		            // 在這裡寫上要背景執行的程式片段 
		            // 為了明顯看見效果，以暫停3秒作為示範 
		            //sleep(3000);
					  makeBarcode("2",batch,mKind);
		          }
		          catch (Exception e)
		          {
		            e.printStackTrace();
		          }
		  } else if(preference.getKey().equalsIgnoreCase("key_bprint3525")){//
		          try
		          { 
		            // 在這裡寫上要背景執行的程式片段 
		            // 為了明顯看見效果，以暫停3秒作為示範 
		            //sleep(3000);
					  makeBarcode("3",batch,mKind);
		          }
		          catch (Exception e)
		          {
		            e.printStackTrace();
		          }
		  } else if(preference.getKey().equalsIgnoreCase("key_bprint3530")){
		          try
		          { 
		            // 在這裡寫上要背景執行的程式片段 
		            // 為了明顯看見效果，以暫停3秒作為示範 
		            //sleep(3000);
					  makeBarcode("4",batch,mKind);
		          }
		          catch (Exception e)
		          {
		            e.printStackTrace();
		          }
		      
		  } else if(preference.getKey().equalsIgnoreCase("key_barcodesetup")){	
			  showBeCode();
		  
		  } else if(preference.getKey().equalsIgnoreCase("key_socketsetup")){
				LayoutInflater factory = LayoutInflater.from(MakeTransDetail.this);
			    final View v1 = factory.inflate(R.layout.socketbar01, null);
			    final EditText edtIp = (EditText) v1.findViewById(R.id.edtip);
			    final EditText edtPort = (EditText) v1.findViewById(R.id.edtport);
			    edtIp.setText(barStr[1]);
			    edtPort.setText(barStr[2]);
			    new AlertDialog.Builder(MakeTransDetail.this).setTitle("設定條碼機IP:"+Utilis.getStringSet(MakeTransDetail.this, PrefKey.BAR_IP, "127.0.0.1")).setView(v1).setNeutralButton("OK", new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int which) {
			          try{ 
					      File file = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+ "/cwbuyer/para/ini.sdb");
					      SQLiteDatabase dbc = SQLiteDatabase.openOrCreateDatabase(file, null);
					      
					      StringBuffer mySqlBuf = new StringBuffer();
							mySqlBuf.append("update  system ");
							
							mySqlBuf.append(" set T2='"+edtIp.getText().toString()+"'");
							mySqlBuf.append(" ,T3='"+edtPort.getText().toString()+"'");
							mySqlBuf.append(" where _ID=" +1551 );
							dbc.execSQL(mySqlBuf.toString());			      
							
						dbc.close();
					}catch(Exception e){
							e.printStackTrace();
					}

			    	  

			    	  //原先改為update ini.sdb
			    	  //Utilis.setStringSet(MakeTransDetail.this, PrefKey.BAR_IP, edtIp.getText().toString());
			    	  //Utilis.setStringSet(MakeTransDetail.this, PrefKey.BAR_PORT, edtPort.getText().toString());
			      }
			    }).setCancelable(false).show();
		  }

		  
	    return true;
	  }

	public void showImport2Dialog(){
		if (dataSend[0].equalsIgnoreCase("0")){
			AlertDialog.Builder sortDlg = new AlertDialog.Builder(MakeTransDetail.this);
	        sortDlg.setTitle("請選擇匯入門市採購新品 或 返回")
	        .setSingleChoiceItems(listdept, 0, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int item) {
	            	mChoice = item;
	            }
	        }) 
	        .setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) { //確認
		        	String [] deptlist = listdept[mChoice].split(",");  //只是批號
					  aPswd=deptlist[4];
					  aFtp=deptlist[5];
					  aBase=deptlist[6];
					  aIP=deptlist[7];
		        	cloudselect();
	            }
	          })
	        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) { //取消

	            }
	          }).show();
			
		}else {
			  aIP=Utilis.getIni(MakeTransDetail.this, "SYS", "IMPORT",1);
			  aFtp=Utilis.getIni(MakeTransDetail.this, "SYS", "IMPORT",4);
			  aPswd=Utilis.getIni(MakeTransDetail.this, "SYS", "IMPORT",5);
			  aBase=Utilis.getIni(MakeTransDetail.this, "SYS", "IMPORT",2);
			  cloudselect();
			
		}
	}		

	  
		public void showImport1Dialog(){
			AlertDialog.Builder sortDlg = new AlertDialog.Builder(MakeTransDetail.this);
	        sortDlg.setTitle("請選擇匯入門市(出貨單) 或 返回")
	        .setSingleChoiceItems(listdept, 0, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int item) {
	            	mChoice = item;
	            }
	        }) 
	        .setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) { //確認
	            	
		        	String [] deptlist = listdept[mChoice].split(",");  //只是批號
		        	cust_no=deptlist[0];
		        	cust_name=deptlist[1];
		        	cust_tradetype=Utilis.toInt(deptlist[2]);
		        	cust_discount=Utilis.toInt(deptlist[3]);
					StartImport(1);
	            }
	          })
	        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) { //取消

	            }
	          }).show();
			
		}
		
		public String[] getdeptList(int tmode){
			String[] lists=null;
			StringBuffer lst=new StringBuffer();
			SQLiteDatabase db = Utilis.getDB(MakeTransDetail.this);
			String SQLL="select CUSTNO,CUSTNAME,TRADETYPE,DISCOUNT,MOBIL,EMAIL,MSN,ADDRESS from qcust where TR='20' order by CUSTNO";
			if (tmode==1) SQLL="select CUSTNO,CUSTNAME,TRADETYPE,DISCOUNT,MOBIL,EMAIL,MSN,ADDRESS from qcust where TR='20' and CUSTNO<>'"+deptStr[5]+"' order by CUSTNO";
			Cursor cs=db.rawQuery(SQLL , null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				for (int xx=0;xx<cs.getCount();xx++){
					lst.append(cs.getString(0)+","+cs.getString(1)+","+cs.getString(2)+","+cs.getString(3)+","+cs.getString(4)+","+cs.getString(5)+","+cs.getString(6)+","+cs.getString(7)+";");
					cs.moveToNext();
				}
			}
			db.close();
			cs.close();
			
			lists=lst.toString().split(";");
			if(lists.length<=0){
				Toast.makeText(MakeTransDetail.this,"查無門市的資料!!", Toast.LENGTH_SHORT).show();
				return null;
			}else{
				Toast.makeText(MakeTransDetail.this,"門市的資料!!"+lst.toString(), Toast.LENGTH_SHORT).show();
				return lists;
			}
		}

		
	  private void StartImport(int mode){
		  //mode==0 製作廠商進貨單
		  //mode==1 製作門市出貨單
			  String mFormdate=DateUtil.getCurrentDateDb();
				SQLiteDatabase db = Utilis.getDB(MakeTransDetail.this);
				Cursor csExp = null;
				//直接將採購單(批號)產生一張廠商進貨單
		        StringBuffer bufQ = new StringBuffer();
				bufQ.append("select * from qdetail");
				bufQ.append(" where BATCH='" + batch+"'");
				bufQ.append(" order by BATCH , MID");
				csExp = db.rawQuery(bufQ.toString(), null);
				int Atot=0;
				int Asum=0;
				int Tsum=0;
				int mic=0;
				int inc=0;
				String bBatch="";
				String bKind="20";
				if (mode==0){ //產生廠商進貨單號
					bBatch=deptStr[0]+deptStr[1]+"V1"+batch;
					bKind="10";
				} else //產生門市出貨單號
					bBatch=deptStr[0]+deptStr[1]+"V2"+cust_no+batch;
				//轉入進貨單的規則AA1batch
				//應詢問是否確定將本採購單自動產生一張進貨單
				//確認後,應先刪除QHEAD QITEMS 以批號為單號
				
				if (csExp != null) {
					if (csExp.getCount() > 0) {
					csExp.moveToFirst();
						boolean hadH=false;
						int hadI=0;
						Cursor csH= db.rawQuery("select FORMNO from qhead where (EMPNAME='"+batch+"' or FORMNO='"+bBatch+"') and QKIND='"+bKind+"'", null);
						//在廠商進貨找到批號所匯入的,且有可能不是本機的單號
						//也可能因為多機同時批號匯入,引發重覆配貨,而有多筆
						if (csH.getCount()>0) {
							hadH=true;
							//不管是哪台機號,產生多張單,一次性刪除單的明細
							String SQL="delete from qitems where (HANDNO='"+batch+"' or FORMNO='"+bBatch+"') and QKIND ='"+bKind+"'";
							db.execSQL(SQL);
							
							while (csH.moveToNext()){
							hadI+=1;
								if (hadI>1) { //表示第二筆之後的單據都要刪除
									ContentValues valueH = new ContentValues();
									//也要讓QHEAD 因也存入
									String[] args = {csH.getString(0),bKind};
									valueH.put("TR", "Y2");
									valueH.put("ISCONFIRM", "N");
									valueH.put("ISCHECK", "N");
									db.update(TbName.QHEAD, valueH,"FORMNO=? and QKIND=?", args);
								}else if (mode==0) bBatch=csH.getString(0);
							}
						}
						csH.close();
						
								for (int i = 0; i < csExp.getCount(); i++) {
								//貨品明細編號需透過回圈讀取顏色尺寸的組合
								String colornS=(String)csExp.getString(csExp.getColumnIndex("COLORNO"));
								String[] arrayColorNo = colornS.split("，"); //如此可以得到有幾個顏色代號
								String colorS=(String)csExp.getString(csExp.getColumnIndex("COLOR"));
								String[] arrayColor = colorS.split("，");//如此可以得到有幾個顏色名稱
								String sizeS=(String)csExp.getString(csExp.getColumnIndex("SIZE"));
		//						sizeS.replace(',', ';');
								String[] arraySize = sizeS.split(","); //如此可以得到有幾個尺寸
								String inlistT=(String)csExp.getString(csExp.getColumnIndex("INLIST"));
		//						inlistT.replace(',', ';');
								String[] arrayInlistT = inlistT.split("，"); //如此可以得到有幾組數字
								int colort=arrayColorNo.length;
								
								for (int ji=0;ji<colort;ji++){ //逐一讀取顏色代號,顏色名稱
									String[] arrayInlistS=arrayInlistT[ji].split(","); //取得各組明細數量
									for (int jk=0;jk<arrayInlistS.length;jk++) { //逐一讀取尺寸
									if (Utilis.toInt(arrayInlistS[jk])!=0){	//@@20131030增設檢查數量不為0者	
										ContentValues value = new ContentValues();
										value.put("TR", bKind);   
										value.put("ID",0);
										//童裝批發 段數 
										value.put("ORDDATE",csExp.getString(csExp.getColumnIndex("UNIT")));										
										value.put("QKIND",bKind );  
										value.put("HANDNO",batch);
										if (csExp.getString(csExp.getColumnIndex("GOODSNO"))!=null) value.put("GOODSNO",csExp.getString(csExp.getColumnIndex("GOODSNO")));
										if (csExp.getString(csExp.getColumnIndex("SOURCENO"))!=null) value.put("SOURCENO",csExp.getString(csExp.getColumnIndex("SOURCENO")));
										value.put("GOODSNOS",csExp.getString(csExp.getColumnIndex("GOODSNO"))+"-"+arrayColorNo[ji]+"-"+arraySize[jk]);
										//GOODSTYPE須先換回文字
										int gtype = csExp.getInt(csExp.getColumnIndex("GOODSTYPE"));  //代號需轉換為文字
							        	int index = mTypeIdList.indexOf(gtype);
							        	if(index >= 0){	value.put("GOODSTYPE",mTypeList.get(index));	}
							        	else {
							        		value.put("GOODSTYPE",csExp.getString(csExp.getColumnIndex("GOODSTYPE")));
							        	}																			
										value.put("GOODSNAME",csExp.getString(csExp.getColumnIndex("GOODSNAME")));
										value.put("COLORS",csExp.getString(csExp.getColumnIndex("COLOR")));
										value.put("SIZES",csExp.getString(csExp.getColumnIndex("SIZE")));//去掉前後雙引號
										value.put("COLOR",arrayColorNo[ji]);
										value.put("SIZE",arraySize[jk]);
										value.put("UNIT1",arrayColor[ji]);
										value.put("UNIT2",colornS);
										if (mode==0){ 
											value.put("UNIT10",arrayInlistS[jk]); 
											value.put("UNIT20",0); 
											value.put("UNIT30",0); 
											value.put("UNIT40",0); 
										}else{ 
											value.put("UNIT20",arrayInlistS[jk]);
											value.put("UNIT10",0); 
											value.put("UNIT30",0); 
											value.put("UNIT40",0); 
										}
										if (Utilis.toInt(arrayInlistS[jk])>0) {inc=inc+Utilis.toInt(arrayInlistS[jk]);} else {mic=mic+Utilis.toInt(arrayInlistS[jk]);}
										value.put("SUPPLY",csExp.getString(csExp.getColumnIndex("SUPPLY")));
											if (mode==0) {
												cust_no=csExp.getString(csExp.getColumnIndex("SUPPLY"));
												cust_name=csExp.getString(csExp.getColumnIndex("SUPPLY"));
											}
										value.put("USER",cust_no);
										value.put("USERNAME",cust_name);
										value.put("BATCH",batch);
										value.put("FORMNO",bBatch);  
										value.put("RATE",csExp.getString(csExp.getColumnIndex("BILLRATE")));
										value.put("P0",csExp.getString(csExp.getColumnIndex("P0")));
										value.put("P1",csExp.getString(csExp.getColumnIndex("P1")));
										value.put("P2",csExp.getString(csExp.getColumnIndex("P2")));
										value.put("P3",csExp.getString(csExp.getColumnIndex("P3")));
										value.put("P4",csExp.getString(csExp.getColumnIndex("P4")));
										value.put("P5",csExp.getString(csExp.getColumnIndex("P5")));

										value.put("PIC",csExp.getString(csExp.getColumnIndex("PIC")));
										value.put("SEASON",csExp.getString(csExp.getColumnIndex("SEASON")));
										int gcountry = csExp.getInt(csExp.getColumnIndex("COUNTRY"));  //代號需轉換為文字
							        	int cindex = mCountryIdList.indexOf(gcountry);
							        	if(cindex >= 0){	value.put("COUNTRY",mCountryList.get(cindex));}
							        	else {
							        		value.put("COUNTRY",csExp.getString(csExp.getColumnIndex("COUNTRY")));
							        	}																			
										value.put("EMPID",csExp.getString(csExp.getColumnIndex("UNIT1"))); //櫃員統計要用 EMPNAME
										value.put("YEAR",csExp.getString(csExp.getColumnIndex("UNIT2")));
										value.put("CREATEDATETIME",DateUtil.getSystemTime().substring(2,12)); 
										value.put("FORMDATE",mFormdate);
										 int sUnitpri=0;
										if (mode==0){
											cust_discount=100;
											sUnitpri=csExp.getInt(csExp.getColumnIndex("P0"));
											cust_tradetype=0;
										} else {
											sUnitpri=csExp.getInt(csExp.getColumnIndex("P"+cust_tradetype));
										}
										 value.put("DISCOUNT",cust_discount); //預設為100.0折數
										 value.put("UNITPRICE",""+sUnitpri);
										 value.put("TRADETYPE",""+cust_tradetype); //交易方式
										 value.put("ACOST",Utilis.toInt(csExp.getString(csExp.getColumnIndex("P1")))*Utilis.toInt(arrayInlistS[jk]));
										 value.put("SUBPRICE",sUnitpri*Utilis.toInt(arrayInlistS[jk])*cust_discount/100);
										 Atot=Atot+Utilis.toInt(arrayInlistS[jk]);
										 Asum=Asum+sUnitpri*Utilis.toInt(arrayInlistS[jk])*cust_discount/100;
										 Tsum=Tsum+Utilis.toInt(csExp.getString(csExp.getColumnIndex("P1")))*Utilis.toInt(arrayInlistS[jk]);
										 value.put("RATEPRICE",sUnitpri*Utilis.toInt(arrayInlistS[jk])*cust_discount/100);
										value.put("PS","配");
										value.put("ISCONFIRM","Y");
										value.put("ISCHECK","N");
										value.put("DEPTNO",deptStr[5]);
										db.insert(TbName.QITEMS, null, value);
										//完成了QITEMS存檔後
									}	
									}
								}
						csExp.moveToNext();
								}
								//製作一張單頭
								csExp.moveToFirst();
								ContentValues value = new ContentValues();
								String mID=DateUtil.getSystemTime().substring(2,12);
								if (hadH)
									value.put("TR", "Y1");
								else 
									value.put("TR", bKind);
								
								value.put("ID", mID);
								value.put("QKIND",bKind );
								value.put("FORMNO",bBatch);
								if (mic<0){
									value.put("HANDNO","+"+inc+""+mic);
								}else {
									value.put("HANDNO","+"+inc);
								}
								value.put("CREATEDATETIME",DateUtil.getSystemTime().substring(2,12));
								value.put("FORMDATE",mFormdate);
								value.put("ISCONFIRM","Y");
								value.put("ISCHECK","N");
								value.put("ISLIST","");
								value.put("TRADETYPE",cust_tradetype);			
								value.put("EMPID",csExp.getString(csExp.getColumnIndex("UNIT1")));
								value.put("EMPNAME",batch);
								value.put("BILLRATE",csExp.getString(csExp.getColumnIndex("BILLRATE")));
								value.put("USER",cust_no);
								value.put("USERNAME",cust_name);
								value.put("DEPTNO",deptStr[5]);
								value.put("ATOT",Atot);
								value.put("ASUM",Asum);
								value.put("BSUM",Asum);
								value.put("FINEDATE","");
								value.put("ORDDATE","");
								value.put("CASH",0);
								value.put("CARD",0);
								value.put("ORDCASH",0);
								value.put("ORDCARD",0);
								value.put("DISMONEY",0);
								value.put("TURESUM",Tsum);
								value.put("COSTS",Tsum);
								value.put("BANKNO","1");
								value.put("BANKNAME",deptStr[0]+deptStr[1]);
								value.put("ATM",0);
								value.put("ATMDATE","");
								value.put("TRCASH",0);
								value.put("PS","");
								value.put("PS1","");
								value.put("PS2",csExp.getString(csExp.getColumnIndex("UNIT1")));
								if (hadH){
									String[] args = {bBatch,bKind};
									db.update(TbName.QHEAD, value,"FORMNO=? and QKIND=?", args);
									if (mode==0){
						        		Toast.makeText(MakeTransDetail.this, "採購單: "+bBatch+"  已異動廠商進貨單!", Toast.LENGTH_SHORT).show();
									}else{
						        		Toast.makeText(MakeTransDetail.this, "採購單: "+bBatch+"  已異動門市出貨單!", Toast.LENGTH_SHORT).show();
									}
								}else{
									db.insert(TbName.QHEAD, null, value);
									if (mode==0){
						        		Toast.makeText(MakeTransDetail.this, "採購單: "+bBatch+"  已新增廠商進貨單!", Toast.LENGTH_SHORT).show();
									}else{
						        		Toast.makeText(MakeTransDetail.this, "採購單: "+bBatch+"  已新增門市出貨單!", Toast.LENGTH_SHORT).show();
									}
								}
								db.execSQL("update qdetail set TR='1000'  where TR not like  '1006' and BATCH='"+batch+"'");
								
				}
			}
				db.close();
				csExp.close();
    			DBCloud.aa1_aa0_update_HI(this);
	}
	  
	  private void cloudselect(){
			SQLiteDatabase db = Utilis.getDB(MakeTransDetail.this);
			Cursor csExp = null;
//			String eacherO="";
//			應開始命名所要存的 /cwbuyer/cwbuyer_trans_888168.csv"		
	        StringBuffer bufQ = new StringBuffer();
	        if (Make01==1){
				bufQ.append("select * from qdetail");
				bufQ.append(" where BATCH='" + batch+"' and GOODSNO='"+mUser+"'");
				bufQ.append(" order by BATCH , MID limit 1");
	        }else if (Make01==0){
				bufQ.append("select * from qdetail");
				bufQ.append(" where BATCH='" + batch+"'");
				bufQ.append(" order by BATCH , MID");
	        }else if (Make01==9){
				bufQ.append("select * from qdetail");
				bufQ.append(" where BATCH>'' and GOODSNO>'' and GOODSTYPE>'' and SUPPLY>''  and SOURCENO>'' ");
				bufQ.append(" order by BATCH , MID ");
	        }
			csExp = db.rawQuery(bufQ.toString(), null);
			String sepa=";";
			StringBuffer sPrice = new StringBuffer();
			StringBuffer zipList =new StringBuffer();
			StringBuffer zipDetail =new StringBuffer();
			if (csExp != null) {
				if (csExp.getCount() > 0) {																
				csExp.moveToFirst();
							for (int i = 0; i < csExp.getCount(); i++) {
							//貨品明細編號需透過回圈讀取顏色尺寸的組合
							String colornS=(String)csExp.getString(csExp.getColumnIndex("COLORNO"));
							String[] arrayColorNo = colornS.split("，"); //如此可以得到有幾個顏色代號
							String colorS=(String)csExp.getString(csExp.getColumnIndex("COLOR"));
							String[] arrayColor = colorS.split("，");//如此可以得到有幾個顏色名稱
							String sizeS=(String)csExp.getString(csExp.getColumnIndex("SIZE"));
	//						sizeS.replace(',', ';');
							String[] arraySize = sizeS.split(","); //如此可以得到有幾個尺寸
							String inlistT=(String)csExp.getString(csExp.getColumnIndex("INLIST"));
	//						inlistT.replace(',', ';');
							String[] arrayInlistT = inlistT.split("，"); //如此可以得到有幾組數字
							int colort=arrayColorNo.length;
							
							zipDetail.append(makeDetail(csExp));
							
							for (int ji=0;ji<colort;ji++){ //逐一讀取顏色代號,顏色名稱
								String[] arrayInlistS=arrayInlistT[ji].split(","); //取得各組明細數量
								for (int jk=0;jk<arrayInlistS.length;jk++) { //逐一讀取尺寸
									//產生貨品明細編號
									sPrice.append( "10"+sepa);
									sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("GOODSNO")))+sepa);
									sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("SOURCENO")))+sepa);
									sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("GOODSNO")))+"-");
									sPrice.append((String)DBCloud.chkStr(arrayColorNo[ji])+"-");
									sPrice.append((String)DBCloud.chkStr(arraySize[jk])+sepa);
									int gtype = csExp.getInt(csExp.getColumnIndex("GOODSTYPE"));  //代號需轉換為文字
						        	int index = mTypeIdList.indexOf(gtype);
						        	if(index >= 0){	sPrice.append((String)mTypeList.get(index)+sepa);	}
						        	else {
						        		sPrice.append(DBCloud.chkStr(csExp.getString(csExp.getColumnIndex("GOODSTYPE")))+sepa);
						        	}																			
									sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("GOODSNAME")))+sepa);
									sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("COLORNO")))+sepa);
									sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("COLOR")))+sepa);
									sPrice.append( '"'+DBCloud.chkStr(sizeS)+'"'+sepa);
									sPrice.append((String)DBCloud.chkStr(arrayColorNo[ji])+sepa);
									sPrice.append((String)DBCloud.chkStr(arrayColor[ji])+sepa);
									sPrice.append((String)DBCloud.chkStr(arraySize[jk])+sepa);
									sPrice.append((String)DBCloud.chkStr(arrayInlistS[jk])+sepa);
									sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("SUPPLY")))+sepa);
									sPrice.append( (String)DBCloud.chkStrB(csExp.getString(csExp.getColumnIndex("BATCH")))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("BILLRATE"))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P0"))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("ADDCOST"))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P1"))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P2"))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P3"))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P4"))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("P5"))+sepa);
									sPrice.append( (String)DBCloud.chkStr(csExp.getString(csExp.getColumnIndex("SEASON")))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("STATE"))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("QUALITY_ID"))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("WASH_ID"))+sepa);
									String picFileN =csExp.getString(csExp.getColumnIndex("PIC"));
									sPrice.append(picFileN+sepa);
									if(Make01==9 || picFileN == null || picFileN.length() <= 0 || picFileN.equalsIgnoreCase(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png")){;} else {
										File file = new File(picFileN);
											if (file.exists() == true) {
												if (ji==0 &&jk==0) {
													if (zipList.toString().indexOf(picFileN)<0 ) zipList.append(picFileN+"，");
												}
											}
									}
									picFileN =csExp.getString(csExp.getColumnIndex("PICTURE"));
									sPrice.append(picFileN+sepa);
									if(Make01==9 || picFileN == null || picFileN.length() <= 0 || picFileN.equalsIgnoreCase(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png")){;} else {
										File file = new File(picFileN);
											if (file.exists() == true) {
												if (ji==0 &&jk==0) {
													if (zipList.toString().indexOf(picFileN)<0 ) zipList.append(picFileN+"，");
												}
											}
									}
									int gcountry = csExp.getInt(csExp.getColumnIndex("COUNTRY"));  //代號需轉換為文字
						        	int cindex = mCountryIdList.indexOf(gcountry);
						        	if(cindex >= 0){	sPrice.append((String)mCountryList.get(cindex)+sepa);	}
						        	else {
						        		sPrice.append((String)DBCloud.chkStr(csExp.getString(csExp.getColumnIndex("COUNTRY")))+sepa);
						        	}																			
									sPrice.append((String)DBCloud.chkStr(csExp.getString(csExp.getColumnIndex("PS")))+sepa);										
									sPrice.append( (String)DBCloud.chkStr(csExp.getString(csExp.getColumnIndex("UNIT1")))+sepa);
									sPrice.append( (String)DBCloud.chkStr(csExp.getString(csExp.getColumnIndex("UNIT2")))+sepa);
									sPrice.append( (String)csExp.getString(csExp.getColumnIndex("CREATEDATETIME"))+sepa+"SSSS"+"\r\n");
								}
							}
					csExp.moveToNext();
							}
								
							//可以顧全第二方案								
							//db.execSQL("update qdetail set TR='1000'  where BATCH='"+batch+"'");
							//每產生一個STRINGBUF:sPrice 就是一份完整的文件
							saveZip(sPrice.toString(),zipDetail.toString(),zipList,batch,"1.0","1.0",1,-1 );
				}
			}
			db.close();
			csExp.close();

	  }
	  
	private void getDefaultData(){
    	SQLiteDatabase sdb = Utilis.getDB(this);
    	if(sdb != null){
			Cursor cursor = sdb.rawQuery("select * from qc_default", null);
			if(cursor != null){
				try{
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						mDefaultData = new DefaultData();
						mDefaultData.nYear = cursor.getInt(cursor.getColumnIndex("YEAR"));
						mDefaultData.employ = cursor.getString(cursor.getColumnIndex("EMPLOY"));
						mDefaultData.nBarOut = cursor.getInt(cursor.getColumnIndex("BAROUT")); //保留
						mDefaultData.nFileOut = cursor.getInt(cursor.getColumnIndex("FILEOUT")); //保留
						mDefaultData.nPrintOut = cursor.getInt(cursor.getColumnIndex("PRINTOUT")); //保留
						mDefaultData.nCa1 = cursor.getInt(cursor.getColumnIndex("CA1"));
						mDefaultData.nCa2 = cursor.getInt(cursor.getColumnIndex("CA2"));
						mDefaultData.nCa3 = cursor.getInt(cursor.getColumnIndex("CA3"));
						mDefaultData.nCb1 = cursor.getInt(cursor.getColumnIndex("CB1"));
						mDefaultData.nCb2 = cursor.getInt(cursor.getColumnIndex("CB2"));
						mDefaultData.nCb3 = cursor.getInt(cursor.getColumnIndex("CB3"));
						mDefaultData.nCc1 = cursor.getInt(cursor.getColumnIndex("CC1"));
						mDefaultData.nCc2 = cursor.getInt(cursor.getColumnIndex("CC2"));
						mDefaultData.nCc3 = cursor.getInt(cursor.getColumnIndex("CC3"));
						mDefaultData.nCd1 = cursor.getInt(cursor.getColumnIndex("CD1"));
						mDefaultData.nCd2 = cursor.getInt(cursor.getColumnIndex("CD2"));
						mDefaultData.nCd3 = cursor.getInt(cursor.getColumnIndex("CD3"));
					}
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					cursor.close();
				}
			}
			sdb.close();
    	}
    }

	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;
	}
	
	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 _ID,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++){
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						String pic = cursor.getString(cursor.getColumnIndex("PIC"));
						String name = cursor.getString(cursor.getColumnIndex("NAME"));
						mCountryIdList.add(id);
						mCountryIcon.add(pic);
						mCountryList.add(name);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}
	
	 private void showBeCode(){
			AlertDialog.Builder dialogCode = new AlertDialog.Builder(this);
			final View root = this.getLayoutInflater().inflate(R.layout.dlg_becode, null);
			ArrayAdapter<CharSequence> adapter10 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCode);
			adapter10.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner10 = (Spinner)root.findViewById(R.id.trade_10);
			spinner10.setAdapter(adapter10);
			spinner10.setSelection(mDefaultData.nCa1);
	
			ArrayAdapter<CharSequence> adapter11 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCodeLR);
			adapter11.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner11 = (Spinner)root.findViewById(R.id.trade_11);
			spinner11.setAdapter(adapter11);
			spinner11.setSelection(mDefaultData.nCa2);

			ArrayAdapter<CharSequence> adapter12 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCodeNo);
			adapter12.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner12 = (Spinner)root.findViewById(R.id.trade_12);
			spinner12.setAdapter(adapter12);
			spinner12.setSelection(mDefaultData.nCa3);

			ArrayAdapter<CharSequence> adapter20 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCode);
			adapter20.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner20 = (Spinner)root.findViewById(R.id.trade_20);
			spinner20.setAdapter(adapter20);
			spinner20.setSelection(mDefaultData.nCb1);
	
			ArrayAdapter<CharSequence> adapter21 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCodeLR);
			adapter21.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner21 = (Spinner)root.findViewById(R.id.trade_21);
			spinner21.setAdapter(adapter21);
			spinner21.setSelection(mDefaultData.nCb2);

			ArrayAdapter<CharSequence> adapter22 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCodeNo);
			adapter22.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner22 = (Spinner)root.findViewById(R.id.trade_22);
			spinner22.setAdapter(adapter22);
			spinner22.setSelection(mDefaultData.nCb3);

			ArrayAdapter<CharSequence> adapter30 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCode);
			adapter30.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner30 = (Spinner)root.findViewById(R.id.trade_30);
			spinner30.setAdapter(adapter30);
			spinner30.setSelection(mDefaultData.nCc1);
	
			ArrayAdapter<CharSequence> adapter31 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCodeLR);
			adapter31.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner31 = (Spinner)root.findViewById(R.id.trade_31);
			spinner31.setAdapter(adapter31);
			spinner31.setSelection(mDefaultData.nCc2);

			ArrayAdapter<CharSequence> adapter32 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCodeNo);
			adapter32.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner32 = (Spinner)root.findViewById(R.id.trade_32);
			spinner32.setAdapter(adapter32);
			spinner32.setSelection(mDefaultData.nCc3);

			ArrayAdapter<CharSequence> adapter40 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCode);
			adapter40.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner40 = (Spinner)root.findViewById(R.id.trade_40);
			spinner40.setAdapter(adapter40);
			spinner40.setSelection(mDefaultData.nCd1);
	
			ArrayAdapter<CharSequence> adapter41 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCodeLR);
			adapter41.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner41 = (Spinner)root.findViewById(R.id.trade_41);
			spinner41.setAdapter(adapter41);
			spinner41.setSelection(mDefaultData.nCd2);

			ArrayAdapter<CharSequence> adapter42 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, beCodeNo);
			adapter42.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
			Spinner spinner42 = (Spinner)root.findViewById(R.id.trade_42);
			spinner42.setAdapter(adapter42);
			spinner42.setSelection(mDefaultData.nCd3);
			
			dialogCode.setView(root);
			dialogCode.setTitle("暗碼設定組合表(1-4)");
			dialogCode.setPositiveButton("OK", new DialogInterface.OnClickListener() {
		          public void onClick(DialogInterface dialog, int which) {
		        	  Spinner spinner10 = (Spinner)root.findViewById(R.id.trade_10);
		        	  Spinner spinner11 = (Spinner)root.findViewById(R.id.trade_11);
		        	  Spinner spinner12 = (Spinner)root.findViewById(R.id.trade_12);
		        	  Spinner spinner20 = (Spinner)root.findViewById(R.id.trade_20);
		        	  Spinner spinner21 = (Spinner)root.findViewById(R.id.trade_21);
		        	  Spinner spinner22 = (Spinner)root.findViewById(R.id.trade_22);		        	  
		        	  Spinner spinner30 = (Spinner)root.findViewById(R.id.trade_30);
		        	  Spinner spinner31 = (Spinner)root.findViewById(R.id.trade_31);
		        	  Spinner spinner32 = (Spinner)root.findViewById(R.id.trade_32);
		        	  Spinner spinner40 = (Spinner)root.findViewById(R.id.trade_40);
		        	  Spinner spinner41 = (Spinner)root.findViewById(R.id.trade_41);
		        	  Spinner spinner42 = (Spinner)root.findViewById(R.id.trade_42);		        	  
		        	  mDefaultData.nCa1 = spinner10.getSelectedItemPosition();
		        	  mDefaultData.nCa2 = spinner11.getSelectedItemPosition();
		        	  mDefaultData.nCa3 = spinner12.getSelectedItemPosition();
		        	  mDefaultData.nCb1 = spinner20.getSelectedItemPosition();
		        	  mDefaultData.nCb2 = spinner21.getSelectedItemPosition();
		        	  mDefaultData.nCb3 = spinner22.getSelectedItemPosition();
		        	  mDefaultData.nCc1 = spinner30.getSelectedItemPosition();
		        	  mDefaultData.nCc2 = spinner31.getSelectedItemPosition();
		        	  mDefaultData.nCc3 = spinner32.getSelectedItemPosition();
		        	  mDefaultData.nCd1 = spinner40.getSelectedItemPosition();
		        	  mDefaultData.nCd2 = spinner41.getSelectedItemPosition();
		        	  mDefaultData.nCd3 = spinner42.getSelectedItemPosition();
		        	  SQLiteDatabase dbc = Utilis.getDB(MakeTransDetail.this);		        	  
		  			Cursor csc = dbc.rawQuery("select * from qc_default", null);
					csc.moveToFirst();
						ContentValues value = new ContentValues();
						value.put("CA1",mDefaultData.nCa1);				
						value.put("CA2",mDefaultData.nCa2);
						value.put("CA3",mDefaultData.nCa3);
						value.put("CB1",mDefaultData.nCb1);				
						value.put("CB2",mDefaultData.nCb2);
						value.put("CB3",mDefaultData.nCb3);
						value.put("CC1",mDefaultData.nCc1);				
						value.put("CC2",mDefaultData.nCc2);
						value.put("CC3",mDefaultData.nCc3);				
						value.put("CD1",mDefaultData.nCd1);				
						value.put("CD2",mDefaultData.nCd2);
						value.put("CD3",mDefaultData.nCd3);				
						dbc.update(TbName.QC_DEFAULT, value, "", null);
					csc.close();
					dbc.close();
		          }
			});
			
			dialogCode.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		          public void onClick(DialogInterface dialog, int which) {
		          }
				});
			dialogCode.show();
		 
	 }
	
	 private String getmCode(Cursor cursor,int check){
		 StringBuffer sPrice = new StringBuffer();
		 
		 String PR3=""+cursor.getInt(cursor.getColumnIndex("P3"));
		 if (PR3.length()==3 || PR3.length()==2)
			 PR3="0"+PR3;
		 else if (PR3.length()==1)
			 PR3="00"+PR3;
		 
		 String PR1=""+cursor.getInt(cursor.getColumnIndex("P1"));
		 if (PR1.length()==3 || PR1.length()==2)
			 PR1="0"+PR1;
		 else if (PR1.length()==1)
			 PR1="00"+PR1;
		
		String dDay="CREATEDATETIME"; if (check==1) dDay="FORMDATE";
		String dPrice=PR3+","+cursor.getString(cursor.getColumnIndex("P5"))+","+cursor.getString(cursor.getColumnIndex("P2"))+","+cursor.getString(cursor.getColumnIndex("P0"))+","+cursor.getString(cursor.getColumnIndex("SUPPLY"))+","+cursor.getString(cursor.getColumnIndex(dDay)).substring(2, 4)+cursor.getString(cursor.getColumnIndex(dDay)).substring(5, 7)+cursor.getString(cursor.getColumnIndex(dDay)).substring(8)+","+cursor.getString(cursor.getColumnIndex("P4"))+","+PR1;
		String[] arrayW = dPrice.split(",");

			if (mDefaultData.nCa1>0 && mDefaultData.nCa2>0){
				if (arrayW[mDefaultData.nCa1-1].length()<(mDefaultData.nCa3+mDefaultData.nCa2-1)){
					sPrice.append(arrayW[mDefaultData.nCa1-1]); }
				else {
					sPrice.append(arrayW[mDefaultData.nCa1-1].substring(mDefaultData.nCa2-1, mDefaultData.nCa3-1+mDefaultData.nCa2));
				}
			}
			
			if (mDefaultData.nCb1>0 && mDefaultData.nCb2>0){
				if (arrayW[mDefaultData.nCb1-1].length()<(mDefaultData.nCb3+mDefaultData.nCb2-1)){
					sPrice.append(arrayW[mDefaultData.nCb1-1]); }
				else {
					sPrice.append(arrayW[mDefaultData.nCb1-1].substring(mDefaultData.nCb2-1, mDefaultData.nCb3-1+mDefaultData.nCb2));
				}
			}	
			
			if (mDefaultData.nCc1>0 && mDefaultData.nCc2>0){
				if (arrayW[mDefaultData.nCc1-1].length()<(mDefaultData.nCc3+mDefaultData.nCc2-1)){
					sPrice.append(arrayW[mDefaultData.nCc1-1]); }
				else {
					sPrice.append(arrayW[mDefaultData.nCc1-1].substring(mDefaultData.nCc2-1, mDefaultData.nCc3-1+mDefaultData.nCc2));
				}
			}	

			if (mDefaultData.nCd1>0 && mDefaultData.nCd2>0){
				if (arrayW[mDefaultData.nCd1-1].length()<(mDefaultData.nCd3+mDefaultData.nCd2-1)){
					sPrice.append(arrayW[mDefaultData.nCd1-1]); }
				else {
					sPrice.append(arrayW[mDefaultData.nCd1-1].substring(mDefaultData.nCd2-1, mDefaultData.nCd3-1+mDefaultData.nCd2));
				}
			}
		return sPrice.toString(); 
	 }

	 private String makeDetail(Cursor cursorAlbun){
		StringBuffer zipDetail =new StringBuffer();
		String sepa=";";
		
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("TR"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("MID"))+sepa);
		zipDetail.append(DBCloud.chkStrB( cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY")))+sepa);
		zipDetail.append(DBCloud.chkStrB( cursorAlbun.getString(cursorAlbun.getColumnIndex("COUNTRY")))+sepa);
		zipDetail.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("SOURCENO")))+sepa);
		zipDetail.append(DBCloud.chkStrB( cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")))+sepa);
		zipDetail.append(DBCloud.chkStrB( cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSTYPE")))+sepa);
		zipDetail.append(DBCloud.chkStrB( cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNAME")))+sepa);
		zipDetail.append( (deptStr[0]+deptStr[1])+sepa);
		zipDetail.append(DBCloud.chkStr( cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT2")))+sepa);
		zipDetail.append( DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT")))+sepa);
		zipDetail.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("BATCH")))+sepa);
		zipDetail.append(cursorAlbun.getString(cursorAlbun.getColumnIndex("BILL"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("BILLRATE"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("ADDCOST"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("P0"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("P1"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("P2"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("P3"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("P4"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("P5"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("SEASON"))+sepa);
		zipDetail.append(DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("PS")))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("CREATEDATETIME"))+sepa);
		zipDetail.append( cursorAlbun.getString(cursorAlbun.getColumnIndex("STATE"))+sepa);
		//圖檔路徑需處理
		//將超大的影像縮小到210*280
		
		String picFileN =cursorAlbun.getString(cursorAlbun.getColumnIndex("PIC"));
		zipDetail.append(picFileN+sepa);						
		picFileN =cursorAlbun.getString(cursorAlbun.getColumnIndex("PICTURE"));
		zipDetail.append(picFileN+sepa);						
		
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("QUALITY_ID"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("WASH_ID"))+sepa);
		zipDetail.append( (String)DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("COLORNO")))+sepa);
		zipDetail.append( (String)DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("COLOR")))+sepa);
		zipDetail.append( (String)DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("SIZE")))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("INLIST"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("IMPO"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("IMPOS"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("OUTPO"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("OUTPOS"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("SPOS"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("SPOSS"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("IM_OUTSTK"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("IM_POSSTK"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("ORD"))+sepa);
		zipDetail.append( (String)cursorAlbun.getString(cursorAlbun.getColumnIndex("ACCOUNT")));
		zipDetail.append(sepa+"SSSS"+"\r\n");
			
		 
		return zipDetail.toString();	
	 }

	private void makeBarcode(String ID,String search,String sMode){
		nCount=0;
		String sizeSS="";
		String colSS="";
		String colNaSS="";
		String sepa="\r\n";
		SQLiteDatabase db = Utilis.getDB(MakeTransDetail.this);
		Cursor cursorAlbun = null;
		StringBuffer sPriceB = new StringBuffer();
        StringBuffer bufQ = new StringBuffer();
//		應開始命名所要存的 /cwbuyer/cwbuyer_trans_888168.csv"
	if (sMode.equalsIgnoreCase("0")){ //原始的
		bufQ.append("select * from qdetail");
		bufQ.append(" where BATCH='" + search+"'");
		bufQ.append(" order by BATCH , MID");
		cursorAlbun = db.rawQuery(bufQ.toString(), null);

			if (cursorAlbun.getCount() > 0) {																
			cursorAlbun.moveToFirst();
				for (int i = 0; i < cursorAlbun.getCount(); i++) {
				//貨品明細編號需透過回圈讀取顏色尺寸的組合
				String colornS=(String)cursorAlbun.getString(cursorAlbun.getColumnIndex("COLORNO"));
				String[] arrayColorNo = colornS.split("，"); //如此可以得到有幾個顏色代號
				if (arrayColorNo.length>4){
					colSS=arrayColorNo[0]+","+arrayColorNo[1]+","+arrayColorNo[2]+","+arrayColorNo[3]+"~"+arrayColorNo[arrayColorNo.length-1];
				}else 
					colSS=colornS;
				
				String colorS=(String)cursorAlbun.getString(cursorAlbun.getColumnIndex("COLOR"));
				String[] arrayColor = colorS.split("，");//如此可以得到有幾個顏色名稱
				if (arrayColor.length>4){
					colNaSS=arrayColor[0]+","+arrayColor[1]+"~"+arrayColor[arrayColor.length-1];
				}else 
					colNaSS=colorS;
				
				String sizeS=(String)cursorAlbun.getString(cursorAlbun.getColumnIndex("SIZE"));
				String[] arraySize = sizeS.split(","); //如此可以得到有幾個尺寸
				if (arraySize.length>4){
					sizeSS=arraySize[0]+","+arraySize[1]+","+arraySize[2]+","+arraySize[3]+"~"+arraySize[arraySize.length-1];
				}else 
					sizeSS=sizeS;
				
				String inlistT=(String)cursorAlbun.getString(cursorAlbun.getColumnIndex("INLIST"));
//				inlistT.replace(',', ';');
				String[] arrayInlistT = inlistT.split("，"); //如此可以得到有幾組數字
				int colort=arrayColorNo.length;
				
				for (int ji=0;ji<colort;ji++){ //逐一讀取顏色代號,顏色名稱
					String[] arrayInlistS=arrayInlistT[ji].split(","); //取得各組明細數量
					for (int jk=0;jk<arrayInlistS.length;jk++) { //逐一讀取尺寸
						//產生貨品明細編號
					 if (Utilis.toInt(arrayInlistS[jk])>0){ //有數量才要輸出	
						 int nUnit=cursorAlbun.getInt(cursorAlbun.getColumnIndex("UNIT"));
						 if (nUnit>1 && (Utilis.toInt(arrayInlistS[jk]) % nUnit)==0){//表示有段數且整除者,以手為單位
							 arrayInlistS[jk]=""+Utilis.toInt(arrayInlistS[jk])/nUnit;
						 }
						sPriceB.append("^KF"+ID+sepa);
						sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")))+sepa);
						sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("SOURCENO")))+sepa);
						sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")))+"-");
						sPriceB.append( arrayColorNo[ji]+"-");
						sPriceB.append( arraySize[jk]+sepa);
						sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNAME")))+sepa);
						sPriceB.append( colSS+sepa);
						sPriceB.append( colNaSS+sepa);
						sPriceB.append( sizeSS+sepa);
						sPriceB.append( arrayColorNo[ji]+sepa);
						sPriceB.append( arrayColor[ji]+sepa);
						sPriceB.append( arraySize[jk]+sepa);
						sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY")))+sepa);
						sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("BATCH")))+sepa);
						sPriceB.append( DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("P0")))+sepa);
						sPriceB.append( DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("P4")))+sepa);//原先為P4
						sPriceB.append( DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("P5")))+sepa);
						sPriceB.append( season[cursorAlbun.getInt(cursorAlbun.getColumnIndex("SEASON"))]+sepa);
						sPriceB.append( DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT")))+sepa);
						
						String Quality[]=getQuality(cursorAlbun.getString(cursorAlbun.getColumnIndex("QUALITY_ID")))	;
						for (int s=0;s<6;s++)	sPriceB.append(Quality[s]+sepa);
						
						int gcountry = cursorAlbun.getInt(cursorAlbun.getColumnIndex("COUNTRY"));  //代號需轉換為文字
			        	int cindex = mCountryIdList.indexOf(gcountry);
			        	if(cindex >= 0){
			        		sPriceB.append(DBCloud.chkStrB(mCountryList.get(cindex))+sepa);	
			        	}else {
			        		sPriceB.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("COUNTRY")))+sepa);
			        	}																			
						sPriceB.append(DBCloud.chkStrB(getmCode(cursorAlbun,0))+sepa);  //暗碼
						sPriceB.append( DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT2")))+sepa);
						sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("CREATEDATETIME")))+sepa);
						sPriceB.append("E"+sepa);
						int printn=Utilis.toInt(arrayInlistS[jk]);
						if (nbar>1) printn=(printn+(nbar-1))/nbar;
						sPriceB.append("~P"+String.valueOf(printn)+sepa);
						//sPriceB.append("~P"+arrayInlistS[jk]+sepa);
						nCount=nCount+printn;
							if (nCount>30){
						          try
						          { 
										outBarcode(sPriceB.toString(),ID);
										Toast.makeText(MakeTransDetail.this,sPriceB.toString() , Toast.LENGTH_SHORT).show();										
										nCount=0;
										Thread.sleep(5000);
										sPriceB.delete(0, sPriceB.toString().length());
						          }
						          catch (Exception e)
						          {
						            e.printStackTrace();
						          }
							}
					 }	
				    }
				}
				cursorAlbun.moveToNext();
			}
				if (nCount>0){
			          try
			          { 
							outBarcode(sPriceB.toString(),ID);
							Toast.makeText(MakeTransDetail.this,sPriceB.toString() , Toast.LENGTH_SHORT).show();
							nCount=0;
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
				}
		}	
	} else {//iMode!=0
		bufQ.append("select * from qitems");
		bufQ.append(" where FORMNO='" + search+"' and QKIND='"+sMode+"'");
		bufQ.append(" order by CREATEDATETIME");
		cursorAlbun = db.rawQuery(bufQ.toString(), null);

		if (cursorAlbun != null) {
			if (cursorAlbun.getCount() > 0) {																
			cursorAlbun.moveToFirst();
			  for (int i = 0; i < cursorAlbun.getCount(); i++) {
				//貨品明細編號需透過回圈讀取顏色尺寸的組合
				if (Utilis.toInt(cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT"+sMode.substring(0, 1)+"0")))>0){	
					sPriceB.append("^KF"+ID+sepa);
					int nUnit=cursorAlbun.getInt(cursorAlbun.getColumnIndex("ORDDATE"));
					if (nUnit==0) nUnit=1;
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")))+sepa);
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("SOURCENO")))+sepa);
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNOS")))+sepa);
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNAME")))+sepa);
					
					String colornS=(String)cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT2"));
					String[] arrayColorNo = colornS.split("，"); //如此可以得到有幾個顏色代號
					if (arrayColorNo.length>4){
						colSS=arrayColorNo[0]+","+arrayColorNo[1]+","+arrayColorNo[2]+","+arrayColorNo[3]+"~"+arrayColorNo[arrayColorNo.length-1];
					}else 
						colSS=colornS;
					
					String colorS=(String)cursorAlbun.getString(cursorAlbun.getColumnIndex("COLORS"));
					String[] arrayColor = colorS.split("，");//如此可以得到有幾個顏色名稱
					if (arrayColor.length>4){
						colNaSS=arrayColor[0]+","+arrayColor[1]+"~"+arrayColor[arrayColor.length-1];
					}else 
						colNaSS=colorS;
					
					String sizeS=(String)cursorAlbun.getString(cursorAlbun.getColumnIndex("SIZES"));
					String[] arraySize = sizeS.split(","); //如此可以得到有幾個尺寸
					if (arraySize.length>4){
						sizeSS=arraySize[0]+","+arraySize[1]+","+arraySize[2]+","+arraySize[3]+"~"+arraySize[arraySize.length-1];
					}else 
						sizeSS=sizeS;

					sPriceB.append(colNaSS+sepa);
					sPriceB.append(colNaSS+sepa);
					sPriceB.append( sizeSS+sepa);
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("COLOR")))+sepa);
					sPriceB.append( DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT1")))+sepa);
					sPriceB.append( DBCloud.chkStr(cursorAlbun.getString(cursorAlbun.getColumnIndex("SIZE")))+sepa);
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY")))+sepa);
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("BATCH")))+sepa);
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("P0")))+sepa);
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("P4")))+sepa);  //P4
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("P5")))+sepa);
					sPriceB.append( season[cursorAlbun.getInt(cursorAlbun.getColumnIndex("SEASON"))]+sepa);
					sPriceB.append(""+nUnit+sepa);
					
					String Quality[]=getQuality("1")	;  //未來可能需要時,要參QDETAIL
					for (int s=0;s<6;s++)	sPriceB.append(""+Quality[s]+sepa);
					//成份
	        		sPriceB.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("COUNTRY")))+sepa);
					sPriceB.append(DBCloud.chkStrB(getmCode(cursorAlbun,1))+sepa);  //暗碼
					sPriceB.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("YEAR")))+sepa);
					sPriceB.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("FORMDATE")))+sepa);
					sPriceB.append("E"+sepa);

					int printn=cursorAlbun.getInt(cursorAlbun.getColumnIndex("UNIT"+sMode.substring(0, 1)+"0"));
					 if (nUnit>1 && (printn % nUnit)==0){//表示有段數且整除者,以手為單位
						 printn=printn/nUnit;
					 }
					if (nbar>1) printn=(printn+(nbar-1))/nbar;
					sPriceB.append("~P"+String.valueOf(printn)+sepa);
					nCount=nCount+Utilis.toInt(cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT"+sMode.substring(0, 1)+"0")));
						if (nCount>30){
						          try
						          { 
										outBarcode(sPriceB.toString(),ID);
										Toast.makeText(MakeTransDetail.this,sPriceB.toString() , Toast.LENGTH_SHORT).show();
										sPriceB.delete(0, sPriceB.toString().length());
										nCount=0;
										Thread.sleep(5000);
						          }
						          catch (Exception e)
						          {
						            e.printStackTrace();
						          }
						}						          
					}
					cursorAlbun.moveToNext();
			  }
				if (nCount>0){
			          try
			          { 
							outBarcode(sPriceB.toString(),ID);
							Toast.makeText(MakeTransDetail.this,sPriceB.toString() , Toast.LENGTH_SHORT).show();
							sPriceB.delete(0, sPriceB.toString().length());
							nCount=0;
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
					
				}
			 }
		}
		
	}
			//每產生一個STRINGBUF:sPrice 就是一份完整的文件
				db.close();
				cursorAlbun.close();
	 }

	 
 private boolean outBarcode( String sendText, String nmode){
     boolean Succed=false;
			
			String address = barStr[1];// 連線的ip
			int port =Utilis.toInt(barStr[2]);// 連線的port
		   
			if (nmode.equalsIgnoreCase("4")){
			   address = Utilis.getIni(this,"SYS", "DEV", 5);
			   port =Utilis.toInt(Utilis.getIni(this,"SYS", "DEV", 6));
			}
			 InetAddress serverAddr = null;
	        SocketAddress sc_add = null;
	        Socket socket = new Socket();

			 try {
				 serverAddr = InetAddress.getByName(address);
				 sc_add= new InetSocketAddress(serverAddr,port);
					 socket.connect(sc_add,5000);
					 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
					 byte data[] = new String(sendText.getBytes("UTF8")).getBytes("BIG5");
	                    SystemClock.sleep(500);
					 out.write(data, 0, data.length);
	                    SystemClock.sleep(500);
	                 out.flush();

					 Toast.makeText(MakeTransDetail.this, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
					 Succed=true;
			 } catch (UnknownHostException e) {
				 Toast.makeText(MakeTransDetail.this, "InetAddress物件建立失敗!!", Toast.LENGTH_LONG).show();
			 } catch (SocketException e) {
				 Toast.makeText(MakeTransDetail.this, "Socket 連結失敗!!", Toast.LENGTH_LONG).show();
			 } catch(IOException e) {
				 Toast.makeText(MakeTransDetail.this, "InetAddress物件建立失敗!!", Toast.LENGTH_LONG).show();
			 } finally{
				 try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					 Toast.makeText(MakeTransDetail.this, "socket關閉失敗", Toast.LENGTH_LONG).show();				 
					e.printStackTrace();
				}				 
			 }
			 
	return Succed;
 }

	 private String[] getQuality(String ID){
			String quality[] = {" "," "," "," "," "," "};
		SQLiteDatabase db = Utilis.getDB(MakeTransDetail.this);
		Cursor cs = null;
		String SQLask = "select * from qc_quality where _ID='"+ID+"'";
		cs = db.rawQuery(SQLask, null);
			if (cs.getCount() > 0) {																
				cs.moveToFirst();
				for (int i=0;i<6;i++){
					if (cs.getString(i+1)==null || cs.getString(i+1).length()==0)
						quality[i]=" ";
					else	
						if ((i%2)==1)
							quality[i]=cs.getString(i+1)+"%";
						else
							quality[i]=cs.getString(i+1);
				}
			} 
		db.close();
		cs.close();
		return quality; 
	 }
 
	 private void saveZip(String sPrice,String zipDetail,StringBuffer zipList,String iUser,String iMin,String iMax,int count,int tmode ){

			SQLiteDatabase db = Utilis.getDB(MakeTransDetail.this);
			Cursor csDept = null;

		 StringBuffer qdeptTxt=new StringBuffer();
		 String batchFile=null;
		 String DetailFile=null;
		 String zipFileN=null;
		 String IsZipOK=null;
		 String qdeptN=null;
		 String[] Recv=new String[1];
		 String[] Recvcc=new String[1];

		 if (tmode<2) {		
		 		batchFile=myImportPath+File.separator+"cwbuyer_transs_"+batch+".csv";  //預設為分色尺寸
		 		zipFileN=myImportPath+File.separator+"cwbuyer_transs_"+batch+".zip";
		 		qdeptN="cwbuyer_transs_"+batch+".zip";
		 		if (tmode==0){ 
		 			batchFile=myImportPath+File.separator+"cwbuyer_trans_"+batch+".csv"; //預設為不分色尺寸
		 			zipFileN=myImportPath+File.separator+"cwbuyer_trans_"+batch+".zip";
		 			qdeptN="cwbuyer_trans_"+batch+".zip";
		 		}
		 		Cursor fdept=db.rawQuery("select _ID from qdept where DEPTNAME='"+qdeptN+"'", null);
		 		if (fdept.getCount()>0){
		 			fdept.moveToFirst();
		 			db.execSQL(" update qdept set TRADTYPE='0' where _ID='"+fdept.getString(0)+"'");
		 		} else {
					db.execSQL("insert into qdept values ("+null+",'"+iUser+"','"+qdeptN+"','0',"+iMin+" ,"+iMax+")");
		 		}
		 		IsZipOK=myImportPath+File.separator+"tr_"+deptStr[5]+".txt";
				DetailFile=myImportPath+File.separator+"cwbuyer_detail_"+batch+".csv";

				csDept=db.rawQuery("select * from qdept where DEPTNAME like '%"+"trans"+"%' order by DEPTNAME  desc limit 50", null);
				if (csDept.getCount()>0){
					csDept.moveToFirst();
					for (int i=0;i<csDept.getCount();i++){
						qdeptTxt.append(csDept.getString(csDept.getColumnIndex("DEPTNAME"))+";"+csDept.getString(csDept.getColumnIndex("TRADTYPE"))+"\r\n");
						csDept.moveToNext();
					}
				}
				
				 Recv[0]=dataSend[1];
				 Recvcc[0]=dataSend[2];
		 }
			
			        File myFile = new File(batchFile); //其目的是為了產生一個新檔案或資料夾
			        File myFile1 = new File(DetailFile);
			        File myFile2 = new File(IsZipOK);
					BufferedWriter bw;
						try {
							bw = new BufferedWriter(new FileWriter(myFile));
		                     if (sPrice !=null && sPrice.length()>0)
		                     { bw.write(sPrice); }
		                     bw.close();
		                     
		                     bw = new BufferedWriter(new FileWriter(myFile1));
		                     if (zipDetail !=null && zipDetail.length()>0)
		                     { bw.write(zipDetail); }
		                     bw.close();
		                     
		                     bw = new BufferedWriter(new FileWriter(myFile2));
		                     if (qdeptTxt.toString() !=null && qdeptTxt.toString().length()>0)
		                     { bw.write(qdeptTxt.toString()); }
		                     bw.close();
							
		                     
		                     //呼叫壓縮

		                     	zipList.append(IsZipOK);
		                     	if (sPrice.length()>0) zipList.append("，"+batchFile);
		                     	if (zipDetail.length()>0) zipList.append("，"+DetailFile);		                     	
								String[] arrayZipF =  zipList.toString().split("，");
								Utilis.toZipF(this,arrayZipF, zipFileN);
		      			   
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						
					if (count==1) {  //只有一筆需傳送著	
						//@@雲端帶入tmode=-1 只要網路OK,則雲端程序
						if (tmode==-1){
							
		 					final String serverFile =zipFileN.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
							final File localFile = new File(zipFileN);
			        		Toast.makeText(MakeTransDetail.this, localFile+"已完成傳送到"+serverFile, Toast.LENGTH_SHORT).show();
									
								        	success=false;
											try {
												success=DBCloud.ftpUpdateFile(MakeTransDetail.this,aIP, 21,aFtp, aPswd, serverFile, localFile);												
											} catch (IOException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
									         finally
									        {

								        	  if (success){
													Log.i("DOWNLOAD", "上傳成功");
													//帶入 3g001 ,20123,
													//呼叫 PHP 進一步解壓縮zip檔
													//並轉入雲端qdetail 維護Q10
													if (Utilis.haveInternet(MakeTransDetail.this) && of_line!=0){  //有網路的狀態且非單機
														StringBuffer bfstr = new StringBuffer();
														StringBuffer bfstrF = new StringBuffer();
															bfstr.append(aBase).append(";");
															bfstrF.append("UID").append(";");  //3g001
															bfstr.append(batch).append(";");  //批號3G01
															bfstrF.append("BATCH").append(";");
															bfstr.append(Utilis.getIni(MakeTransDetail.this, "SYS", "YEAR",1)).append(Utilis.getIni(MakeTransDetail.this, "SYS", "YEAR",2)).append(";");
															bfstrF.append("QYEARS").append(";");  //20123  mDefaultData.employ
															if (Make01==1)
																bfstr.append(mUser).append(";");
															else
																bfstr.append(deptStr[0]+deptStr[1]).append(";");

															bfstrF.append("QEMP").append(";");
															bfstr.append(aIP).append(";");
															bfstrF.append("AIP").append(";");  //3g001
															bfstr.append(deptStr[0]+deptStr[1]);
															bfstrF.append("QDEPT");  //3g001
//															Log.i("DOWNLOAD_2", "呼叫執行緒PHP");
														Thread t = new Thread(new DBCloud.sendPostRunnableQC(MakeTransDetail.this,bfstr.toString(),bfstrF.toString(),10));
														t.start();
														
										    			DBCloud.aa1_aa0_qfact(this);
													}
								        	  	}else {
													Log.i("DOWNLOAD", "上傳失敗");											
								        	  	}
									        }
							
						}else{
							try{	
								Intent send = new Intent(Intent.ACTION_SEND);
				    		    Uri U=Uri.parse("file://"+zipFileN);  //重要的範例
				    		    
				       		    send.putExtra(Intent.EXTRA_EMAIL,Recv);
				        		    send.putExtra(Intent.EXTRA_SUBJECT, "CWBuyerPos銷售王,遠端傳送資料壓縮檔!正在傳送中.........");
				        		    send.putExtra(Intent.EXTRA_TEXT, "(下載)收到壓縮檔後,請一定要即時完成匯入資料的工作\n\n留言:");
				        		    send.putExtra(Intent.EXTRA_STREAM,U);
				        		    send.setType("message/rfc822");    		    
				        		    startActivity(Intent.createChooser(send, getResources().getString(R.string.app_name)+"!訊息傳送中心"));
				        		Toast.makeText(MakeTransDetail.this, batchFile+"已完成傳送的程序!", Toast.LENGTH_SHORT).show();
						 		db.execSQL("update qdept set TRADTYPE='1' where DEPTNAME='"+qdeptN+"'");	
							} catch (Exception e) {
							// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}     
					}
					
					 db.close();
					 csDept.close();
					 
					 Utilis.DeleteFile(batchFile);
					 Utilis.DeleteFile(DetailFile);
	 }
	 
}