package com.cwbuyer.lib;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class DBCloud {
	
	protected static final int REFRESH_DATA = 0x00000001;
	
private static void mainTain_qc(final Context context,Cursor cs,String gUid,final String uriAPI){
	//將QC_xxx 的每一筆rec_data 放入陣列後,傳送到雲端,一筆一筆的,透過qc_color_ninsert.php insert or update MySQL
	if (cs.getCount()>0){
		while (cs.moveToNext()){
			final StringBuffer bfstr = new StringBuffer();
			final StringBuffer bfstrF = new StringBuffer();
				bfstr.append(gUid).append(";");
				bfstrF.append("UID").append(";");
			for(int x=0;x<cs.getColumnCount()-1;x++){
				bfstr.append(cs.getString(x)).append(";");
				bfstrF.append(cs.getColumnName(x)).append(";");
			}
				bfstr.append(cs.getString(cs.getColumnCount()-1));
				bfstrF.append(cs.getColumnName(cs.getColumnCount()-1));
			          try
			          { 
			  			Thread t = new Thread(new sendPostRunnable1(context,bfstr.toString(),bfstrF.toString(),uriAPI));
						t.start();
						//Thread.sleep(2000);  
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			          }
		}
	}
}

//3g001,Q1-Q30,Local_(SYS,ALBUN,n)LAST_DAY
private static void download_qc(final Context context,String gUid,String Id,String UPD,final String uriAPI){
		final StringBuffer bfstr = new StringBuffer();
		final StringBuffer bfstrF = new StringBuffer();
			bfstr.append(gUid).append(";");
			bfstrF.append("UID").append(";");
			bfstr.append(Id).append(";");
			bfstrF.append("ID").append(";");
			bfstr.append(UPD);
			bfstrF.append("LUPDATE");
			Toast.makeText(context, gUid+"<==GUID==Id==>"+Id+"<==Id==UPD==>"+UPD, Toast.LENGTH_LONG).show();					
		          try
		          { 
		  			Thread t = new Thread(new sendPostRunnable1(context,bfstr.toString(),bfstrF.toString(),uriAPI));
					t.start();
					//Thread.sleep(2000);
		          }
		          catch (Exception e)
		          {
		            e.printStackTrace();
		          }
		          finally
		          {
		          }
}

	//此處針對 QC_xxxx Q1~Q7 發展出的雲端 _ninsert && _del 
	public static class  sendPostRunnableQC implements Runnable
	{
		String []bfstrs;
		String []bfstrFs;
		String uriAPI=null;
		Context context;
		int work=0;
		String tableName=null;
		//1-7 insert or edit   8 delete uriAPI
		
		// 建構子，設定要傳的字串
		public ProgressDialog myDialog = null;
		public sendPostRunnableQC(Context context,String bfstrs,String bfstrFs,int work)
		{
			String []fields=bfstrs.split(";");
			String []fieldFs=bfstrFs.split(";");
			this.bfstrs=fields;
			this.bfstrFs=fieldFs;
			this.context=context;
			this.work=work;  //
			if (work==21) myDialog = ProgressDialog.show(context,"資料下載中.....","請稍候.............",true);//		setAutoRotationMode();			  
			
		}

		@Override
		public void run()
		{
			
			switch (work){
			case 1:	tableName="qc_country";	break;
			case 2:	tableName="qc_type"; break;
			case 3:	tableName="qc_color"; break;
			case 4:	tableName="qc_size"; break;
			case 5:	tableName="qc_defpri"; break;
			case 6:	tableName="qc_quality"; break;
			case 7:	tableName="qc_wash"; break;
			case 8:	tableName="qc_macc"; break;
			case 0:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"qc_each_del.php";break;
			case 10:	uriAPI="http://"+bfstrs[4]+File.separator+bfstrs[0]+File.separator+"aa1_aa0_batch_qdetail_n.php";break;
			case 11:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa0_aa1_auto_qdetail_n.php";break;
			case 9:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa1_aa0_hi_update_n.php";break;
			case 12:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa0_aa1_auto_hi_n.php";break;
			case 13:	uriAPI="http://"+"www.cwbuyer.net"+File.separator+"3g001"+File.separator+"user_regist.php";break;
			case 14:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa0_aa1_auto_qmacc.php";break;
			case 15:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa1_aa0_qmacc_update.php";break;
			case 21:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa0_aa1_dn_hi.php";break;
			case 16:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa0_aa1_auto_chk.php";break;
			case 17:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa1_aa0_qfact.php";break;
			case 18:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa0_aa1_auto_qfact.php";break;			
			case 19:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa1_aa0_qcust.php";break;
			case 20:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa0_aa1_auto_qcust.php";break;			
			case 22:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"socket_barprint.php";break;			
			case 23:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa1_addmaccs_table.php";break;			
			case 24:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa1_aa0_pan_update.php";break;			
			case 25:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"cw_maintain_171030.php";break;			
			case 26:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa1_addpandn_table.php";break;			
			case 27:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"cw_maintain_171114.php";break;			
			case 29:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa1_addppri_table.php";break;			
			case 44:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa1_add44_index.php";break;			
			case 50:	uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"aa0_aa1_auto_hi_orny_n.php";break;
			case 69:	tableName="qc_ppri"; break;
			}
			
			if ((work>0 && work<=8) || work==69)	 uriAPI="http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+tableName+"_ninsert.php";
			
			Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI);

	        String result = sendPostDataToInternetQC(bfstrs,bfstrFs);
			//未來可以因著不同的result而創建各式的mHandler1~n
			//1-8 視為代碼設定 相關 insert update delete
			//也可以 10-n 著手不同的資料維護 而引發不同的mHander
			mHandlerQC.obtainMessage(REFRESH_DATA, result).sendToTarget();
			
			if (work==21) myDialog.dismiss();

		}

		private String sendPostDataToInternetQC(String[] bfstrs,String[] bfstrFs)
		{

			/* 建立HTTP Post連線 */
			HttpPost httpRequest = new HttpPost(uriAPI);
			/*
			 * Post運作傳送變數必須用NameValuePair[]陣列儲存
			 */
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for(int x=0;x<bfstrs.length;x++){
				params.add(new BasicNameValuePair(bfstrFs[x], bfstrs[x]));
			}
			try {
				/* 發出HTTP request(請求) */
				httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				/* 取得HTTP response(回傳) */
				HttpResponse httpResponse = new DefaultHttpClient()
						.execute(httpRequest);
				/* 若狀態碼為200 ok */
				if (httpResponse.getStatusLine().getStatusCode() == 200)
				{
					/* 取出回應字串 */
					String strResult = EntityUtils.toString(httpResponse
							.getEntity());
					// 回傳回應字串
					//Log.i("DOWNLOAD_3", "呼叫執行緒PHP___"+strResult);					
					return strResult;
				}else{
					//Log.i("DOWNLOAD_31===", ""+httpResponse.getStatusLine().getStatusCode());					
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			//Log.i("DOWNLOAD_3", "呼叫執行緒PHP後___失敗");			
			return null;
		}

		Handler mHandlerQC = new Handler()
		{
			@SuppressWarnings("unused")
			@Override
			public  void handleMessage(Message msg)
			{
				String Hresult=null;
				//Log.i("DOWNLOAD_5_mHandlerQC===", ""+Hresult);						
				
				switch (msg.what)
				{
				// 顯示網路上抓取的資料
				case REFRESH_DATA:
					if (msg.obj instanceof String) 
						Hresult = (String) msg.obj;
					if (Hresult != null ){
						String mBankn=Utilis.getIni(context, "SYS", "DEPT",1)+Utilis.getIni(context, "SYS", "DEPT",2);//門市代號+機號		

						// work 1-8	可能為新增或編輯
					//解讀echo 關鍵在(insert or update)_tablename 所有寫入的欄位 
					//"new_qc_size_ID=".$id; 範例
						//Log.i("DOWNLOAD_5_mHandlerQC===", ""+Hresult);						
							if (((work>0 && work <=8) || work==69) && Hresult.indexOf(tableName)>0){
								SQLiteDatabase db = Utilis.getDB(context);
								Cursor cs =db.rawQuery("select * from "+tableName, null);
								ContentValues value = new ContentValues();
								if (Hresult.indexOf("new_")>=0){  //須將SERVER產生的新ID置入_ID
									bfstrs[1]=Hresult.substring(Hresult.lastIndexOf("_")+4);
								}

					    		for (int xx=1;xx<=cs.getColumnCount();xx++){
									value.put(bfstrFs[xx],bfstrs[xx]);
								}
								if (Hresult.indexOf("new_")>=0){  //表示新增
									long result = db.insert(tableName, null, value);
							    	if(result > 0){
							    		Toast.makeText(context, "新增資料成功", Toast.LENGTH_SHORT).show();
							    	}else{
							    		Toast.makeText(context, "新增資料失敗", Toast.LENGTH_SHORT).show();
							    	}
									
								}else if (Hresult.indexOf("edit")>=0){  //表示編輯
						    		String[] args = {bfstrs[1]};
									int success = db.update(tableName, value,
											"_ID=?", args);
									if(success > 0){
										Toast.makeText(context, "修改資料成功", Toast.LENGTH_SHORT).show();
									}else{
										Toast.makeText(context, "修改資料失敗", Toast.LENGTH_SHORT).show();
									}
									
								}

								cs.close();
								db.close();
							} else if (work==10 ){  //完成雲端qdetail_INPUT
								//暫不使用
								//Log.i("DOWNLOAD_4_mHandlerQC===", Hresult.toString());
							} else if (work==13 ){  //完成user_qcust_UPDATE
								//檢查LOCAL端 日期是否在使用日期範圍
								if (Hresult.toString().indexOf("/")>0)
								{
					        		  Utilis.putIni(context, "INIH", "SW_REPLUS",Hresult.toString() ,8 );  //回傳正確操作日期
								}
								
							} else if (work==9 ){  //完成雲端qhead qitems update後
								
								//須要將QHEAD TR改成'Y0' (isconfirm='Y' or ischeck='Y')
								if (Hresult.indexOf("update_hi_")>=0){//如果SERVER傳回,成功的更新  "update_hi_130820110011
									SQLiteDatabase db = Utilis.getDB(context);
									db.execSQL("delete from qhead where TR='Y2'");
									db.close();
									db = Utilis.getDB(context);
									db.execSQL("update qhead set TR='Y0' where (TR <>'Y0' or TR IS NULL) and (ISCONFIRM='Y' or ISCHECK='Y') ");
									db.close();
								}
								//Log.i("DOWNLOAD_4_mHandlerQC===", Hresult.toString());
	
							} else if (work==17){  //完成雲端qfact update後
								
								//須要將QFACT STATE 改成'0' "new_qfact__"+
								if (Hresult.indexOf("new_qfact_")>=0){//如果SERVER傳回,成功的更新  "update_hi_130820110011
									SQLiteDatabase db = Utilis.getDB(context);
									db.execSQL("delete from qfact where `STATE` = '2'");
									db.close();
									db = Utilis.getDB(context);
									db.execSQL("update qfact set `STATE`='0' where ((`STATE` NOT LIKE '0') or (`STATE` IS NULL))");
									db.close();
								}
								//Log.i("DOWNLOAD_17_mHandlerQC===", Hresult.toString());
							} else if (work==19){  //完成雲端qcust update後
								//須要將QCUST STATE 改成'0' "new_qcust__"+
								if (Hresult.indexOf("new_qcust_")>=0){//如果SERVER傳回,成功的更新  "update_hi_130820110011
									SQLiteDatabase db = Utilis.getDB(context);
									db.execSQL("delete from qcust where `STATE` = '2'");
									db.close();
									db = Utilis.getDB(context);
									db.execSQL("update qcust set `STATE`='0' where ((`STATE` NOT LIKE '0') or (`STATE` IS NULL))");
									db.close();
								}
								//Log.i("DOWNLOAD_19_mHandlerQC===", Hresult.toString());

							} else if (work==11){  //完成雲端qdetail_download後
								String Tnow =DateUtil.getSystemTime().substring(2, 12);
								if (Hresult.indexOf("cwbuyer_qdetail_auto_")>=0){ 	
									String  AutoFile=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"cwbuyer_qdetail_auto_"+Utilis.getIni(context,"SYS","DEPT",1)+Utilis.getIni(context,"SYS","DEPT",2)+".csv";
									String ServerT=Hresult.substring(Hresult.indexOf("cwbuyer_qdetail_auto_")+21);
									final File localFile = new File(AutoFile);
									final String serverFile =AutoFile.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
						        	boolean success=false;
									try {
										success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFile, localFile);												
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							          finally
							        {
								     try{
							        	  if (success){ //表示已存入LOCAL端
							        		  //將LOCAL更新UPDATE_TNOW

							        		  if (localFile.exists()){  //檔案存在
							        			  SQLiteDatabase db = Utilis.getDB(context);
							      					String encodout = "UTF8";
													StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
													StringBuffer ftpPic= new StringBuffer();
													FileInputStream fis = new FileInputStream(localFile);
													InputStreamReader isr = new InputStreamReader(fis, encodout);
													Reader in = new BufferedReader(isr);
													int isDel=0;
													int ch;
													
													db.beginTransaction();
												try{
													while ((ch = in.read()) > -1) {
														buffers.append((char)ch);
														if(buffers.toString().indexOf("SSSS\r\n")>0){
															String fields=buffers.toString().substring(0,buffers.toString().length()-2);
															String[] arrayField = fields.toString().split(";");
															if (arrayField.length==45){	
																Cursor cs=db.rawQuery("select * from qdetail where  BATCH='"+arrayField[11]+ "'  and GOODSNO='"+arrayField[5]+ "'",null);
																//if (cs.getCount()>0)	db.execSQL("delete from qdetail where BATCH='"+arrayField[11]+ "'  and GOODSNO='"+arrayField[5]+ "'");
																if (cs.getCount()>0) isDel=1; else isDel=0;
																ContentValues valueF = new ContentValues();
																if (arrayField[25].indexOf("/cwbuyer/")>0){
																	String chg=arrayField[25].replace(arrayField[25].substring(0, arrayField[25].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
																	arrayField[25]=chg;
																			final String serverFile1 =arrayField[25].replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
																			if (ftpPic.toString().indexOf("\r\n"+serverFile1.substring(14)+"\r\n")<0)
																			ftpPic.append(serverFile1.substring(14)+"\r\n");//製作SERVER圖片路徑,一次性的ZIP後,取回解壓縮
																}
																if (arrayField[26].indexOf("/cwbuyer/")>0){
																	String chg=arrayField[26].replace(arrayField[26].substring(0, arrayField[26].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
																	arrayField[26]=chg;
																	
																			final String serverFile1 =arrayField[26].replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
																			if (ftpPic.toString().indexOf("\r\n"+serverFile1.substring(14)+"\r\n")<0)
																			ftpPic.append(serverFile1.substring(14)+"\r\n");//製作SERVER圖片路徑,一次性的ZIP後,取回解壓縮
																}
																for(int ij=2;ij<(arrayField.length-1);ij++){ //將qdetail存入
																	valueF.put(cs.getColumnName(ij),arrayField[ij]) ;
																}
																if (cs.getCount()>0){
																	String[] argsi = {arrayField[11],arrayField[5]};
																	db.update("qdetail", valueF,"BATCH=? and GOODSNO=?", argsi);
																	db.execSQL("update qitems set P0='"+arrayField[15]+"',"
																		+ "P1='"+arrayField[16]+"', P2='"+arrayField[17]+"',"
																		+ "P3='"+arrayField[18]+"',P4='"+arrayField[19]+"',"
																		+ "P5='"+arrayField[20]+"',"
																		+ "SOURCENO='"+arrayField[4]+"',"
																		+ "GOODSNAME='"+arrayField[7]+"',"
																		+ "UNIT2='"+arrayField[29]+"',"
																		+ "COLORS='"+arrayField[30]+"',"
																		+ "SIZES='"+arrayField[31]+"'"
																		+ " where GOODSNO='"+arrayField[5]+"'");
																	//@@@觸發修正所有qitems所有P0-P5
																}else{
																	db.insert("qdetail", null, valueF);
																}	
																cs.close();
															}																	
															buffers.delete(0, buffers.toString().length()	);	
														}
													}
													
													in.close();  //
										            db.setTransactionSuccessful();
												}
												catch(Exception e){
												}
												finally{
												          db.endTransaction();
												}
													
												db.close();
												//將字串傳入SERVER .php 進行ZIP壓縮後 一次性的以FTP 取回
													if (ftpPic.toString().length()>0){
														aa0_aa1_auto_pic_n(context,ftpPic.toString());
													}
												}
							        		  Utilis.putIni(context, "SYS", "AUPDATE",ServerT ,1 );//ServerTime_Update
							        		  }  //end success
							        	} catch (Exception e) {
							        		  Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
							        	}
								    }
								} //end work11
				        		  Utilis.putIni(context, "SYS", "SEASON",Tnow ,2 );  //確保能夠還原可以再度同步

							} else if (work==12){  //完成雲端QHEAD & QITEMS_download後
								String Tnow =DateUtil.getSystemTime().substring(2, 12);
								//Utilis.putIni(context, "SYS", "SEASON",Tnow ,3 );
								if (Hresult.indexOf("aa0aa1_hi_")>=0){ 	
									String  FileH=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"AA0_"+bfstrs[1]+"_QHEAD.csv";
									String ServerT=Hresult.substring(Hresult.indexOf("aa0aa1_hi_")+10).trim();

									SQLiteDatabase db = Utilis.getDB(context);
									
									final File localFileH = new File(FileH);
									final String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
						        	boolean success=false;
									try {
										success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileH, localFileH);												
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							          finally
							        {
								     try{
							        	  if (success){ //表示已存入LOCAL端

							        		  if (localFileH.exists()){  //檔案存在
							      					String encodout = "UTF8";
													StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
													String[] colNames={"TR","ID","QKIND","FORMNO","HANDNO","FORMDATE","CREATEDATETIME","ISCONFIRM","ISCHECK","ISLIST","EMPID","EMPNAME","USER","USERNAME","TRADETYPE","DEPTNO"
															,"ORDCASH","ORDCARD","CASH","CARD","ATOT","ORDDATE","FINEDATE","ASUM","BSUM","BILLRATE","COSTS","TURESUM","DISMONEY","BANKNO","BANKNAME"
															,"ATM","ATMDATE","TRCASH","PS","PS1","PS2"};
													//目的只是取得QHEAD的欄位總數及欄位名稱
													FileInputStream fis = new FileInputStream(localFileH);
													InputStreamReader isr = new InputStreamReader(fis, encodout);
													Reader in = new BufferedReader(isr);
													int ch;
													
													db.beginTransaction();
													try{
														
													while ((ch = in.read()) > -1) {
														buffers.append((char)ch);
														if(buffers.toString().indexOf("SSSS\r\n")>0){
															String fields=buffers.toString().substring(0,buffers.toString().length()-2);
															String[] arrayField = fields.toString().split(";");
															if (arrayField.length==38){//PS1 PS2
																	db.execSQL("delete from qhead where FORMNO='"+arrayField[3]+"'");
																	db.execSQL("delete from qitems where FORMNO='"+arrayField[3]+"'");
																	ContentValues valueF = new ContentValues();
																//if (arrayField[0]==null || arrayField[0].equalsIgnoreCase("NULL")  || arrayField[0].equalsIgnoreCase("nu")) arrayField[0]="Y0";
																//可以省略??? 因為 <>'Y2' 一律填入 'Y0'
																if (!arrayField[0].equalsIgnoreCase("Y2")){
																	arrayField[0]="Y0";
																	for(int ij=0;ij<(arrayField.length-1);ij++){ //將qdetail存入
																		if (arrayField[ij]==null || arrayField[ij].equalsIgnoreCase("NULL") || arrayField[ij].equalsIgnoreCase("nu")) arrayField[ij]="0"; 
																		valueF.put(colNames[ij],arrayField[ij]) ;
																	}
																	db.insert("qhead", null, valueF);
																}	
																
															}																	
															buffers.delete(0, buffers.toString().length()	);	
														}
													}
													in.close();  //
										            db.setTransactionSuccessful();
												}
												catch(Exception e){
												}
												finally{
												          db.endTransaction();
												}
												}
							        		  }  //end success
							        	} catch (Exception e) {
							        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
							        		success=false;
							        	}
								    }
									String  FileI=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"AA0_"+bfstrs[1]+"_QITEMS.csv";
									final File localFileI = new File(FileI);
									final String serverFileI =FileI.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
									
									try {
										success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileI, localFileI);												
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							          finally
							        {
								     try{
							        	  if (success){ //表示已存入LOCAL端
							        		  if (localFileI.exists()){  //檔案存在
							      					String encodout = "UTF8";
													StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
													String[] colNames={
													"TR","ID","QKIND","FORMNO","HANDNO","FORMDATE","CREATEDATETIME","ISCONFIRM","ISCHECK",
												    "EMPID","EMPNAME","USER","USERNAME","TRADETYPE","DEPTNO","GOODSNO","GOODSNOS","SOURCENO",
												    "UNIT1","UNIT2","UNIT","UNITPRICE","DISCOUNT","ACOST","RATE","RATEPRICE","REALSUM","SUBPRICE",
												    "P0","P1","P2","P3","P4","P5","COLOR","SIZE","ORDDATE","FINEDATE","BATCH","SUPPLY","GOODSTYPE","GOODSNAME",
												    "COLORS","SIZES","UNIT10","UNIT20","UNIT30","UNIT40","PIC","PS","SEASON","COUNTRY","YEAR"};
													FileInputStream fis = new FileInputStream(localFileI);
													InputStreamReader isr = new InputStreamReader(fis, encodout);
													Reader in = new BufferedReader(isr);
													int ch;
													db.beginTransaction();
												try{
													while ((ch = in.read()) > -1) {
														buffers.append((char)ch);
														if(buffers.toString().indexOf("SSSS\r\n")>0){
															String fields=buffers.toString().substring(0,buffers.toString().length()-2);
															String[] arrayField = fields.toString().split(";");
															if (arrayField.length==54){
																
																ContentValues valueF = new ContentValues();
																
																if (arrayField[48].indexOf("/cwbuyer/")>0){
																	String chg=arrayField[48].replace(arrayField[48].substring(0, arrayField[48].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
																	arrayField[48]=chg;
																}
																
																for(int ij=1;ij<(arrayField.length-1);ij++){ //將qdetail存入
																	if (arrayField[ij]==null || arrayField[ij].equalsIgnoreCase("NULL") || arrayField[ij].equalsIgnoreCase("nu")) arrayField[ij]="0"; 
																	valueF.put(colNames[ij],arrayField[ij]) ;
																}
																db.insert("qitems", null, valueF);
																
															}																	
															buffers.delete(0, buffers.toString().length()	);	
														}
													}
													in.close();  //
										            db.setTransactionSuccessful();
												}
												catch(Exception e){
												}
												finally{
												          db.endTransaction();
												}
											}
						        		  }  //end success
							        	} catch (Exception e) {
							        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
							        		success=false;
							        	}
								    }
									db.close();
									if (success) Utilis.putIni(context, "SYS", "AUPDATE",ServerT ,3 );//ServerTime_Update
								}
			        			  Utilis.putIni(context, "SYS", "SEASON",Tnow , 4);  //localTime_Update
			        			  
							} else if (work==50){  //完成雲端所有留貨QHEAD & QITEMS_download後
								if (Hresult.indexOf("aa0aa1_hi_")>=0){ 	
									//Log.i("DOWNLOAD_5_mHandlerQC_ORNY===", ""+Hresult);						
									String  FileH=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"AA0_"+bfstrs[1]+"_QHEAD_ORNY.csv";

									SQLiteDatabase db = Utilis.getDB(context);
									
									final File localFileH = new File(FileH);
									final String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
						        	boolean success=false;
									try {
										success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileH, localFileH);												
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							          finally
							        {
								     try{
							        	  if (success){ //表示已存入LOCAL端

							        		  if (localFileH.exists()){  //檔案存在
							      					String encodout = "UTF8";
													StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
													String[] colNames={"TR","ID","QKIND","FORMNO","HANDNO","FORMDATE","CREATEDATETIME","ISCONFIRM","ISCHECK","ISLIST","EMPID","EMPNAME","USER","USERNAME","TRADETYPE","DEPTNO"
															,"ORDCASH","ORDCARD","CASH","CARD","ATOT","ORDDATE","FINEDATE","ASUM","BSUM","BILLRATE","COSTS","TURESUM","DISMONEY","BANKNO","BANKNAME"
															,"ATM","ATMDATE","TRCASH","PS","PS1","PS2"};
													//目的只是取得QHEAD的欄位總數及欄位名稱
													FileInputStream fis = new FileInputStream(localFileH);
													InputStreamReader isr = new InputStreamReader(fis, encodout);
													Reader in = new BufferedReader(isr);
													int ch;
													
													db.beginTransaction();
													try{
														String SQL="delete from qhead where ISCHECK='Y'";
														if (bfstrs[5].equalsIgnoreCase("0")) 
															SQL+=" and ISCONFIRM='R'";
														else if (bfstrs[5].equalsIgnoreCase("1"))
															SQL+=" and (ISCONFIRM='N' or ISCONFIRM='O')";
														else
															SQL+=" and (ISCONFIRM='N' or ISCONFIRM='O' or ISCONFIRM='R')";
														
														if (!bfstrs[2].equalsIgnoreCase(bfstrs[3])) SQL+=" and DEPTNO='"+bfstrs[2]+"'";
														if (bfstrs[4].length()>0) SQL+=" and FORMNO='"+bfstrs[4]+"'";
														
															db.execSQL(SQL);SQL=SQL.replace("qhead","qitems");
															db.execSQL(SQL);
														
													while ((ch = in.read()) > -1) {
														buffers.append((char)ch);
														if(buffers.toString().indexOf("SSSS\r\n")>0){
															String fields=buffers.toString().substring(0,buffers.toString().length()-2);
															String[] arrayField = fields.toString().split(";");
															if (arrayField.length==38){//PS1 PS2
																	ContentValues valueF = new ContentValues();
																	arrayField[0]="Y0";
																	for(int ij=0;ij<(arrayField.length-1);ij++){ //將qdetail存入
																		if (arrayField[ij]==null || arrayField[ij].equalsIgnoreCase("NULL") || arrayField[ij].equalsIgnoreCase("nu")) arrayField[ij]="0"; 
																		valueF.put(colNames[ij],arrayField[ij]) ;
																	}
																	db.insert("qhead", null, valueF);
															}																	
															buffers.delete(0, buffers.toString().length()	);	
														}
													}
													in.close();  //
										            db.setTransactionSuccessful();
												}
												catch(Exception e){
												}
												finally{
												          db.endTransaction();
												}
												}
							        		  }  //end success
							        	} catch (Exception e) {
							        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
							        		success=false;
							        	}
								    }
									String  FileI=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"AA0_"+bfstrs[1]+"_QITEMS_ORNY.csv";
									final File localFileI = new File(FileI);
									final String serverFileI =FileI.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
									
									try {
										success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileI, localFileI);												
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							          finally
							        {
								     try{
							        	  if (success){ //表示已存入LOCAL端
							        		  if (localFileI.exists()){  //檔案存在
							      					String encodout = "UTF8";
													StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
													String[] colNames={
													"TR","ID","QKIND","FORMNO","HANDNO","FORMDATE","CREATEDATETIME","ISCONFIRM","ISCHECK",
												    "EMPID","EMPNAME","USER","USERNAME","TRADETYPE","DEPTNO","GOODSNO","GOODSNOS","SOURCENO",
												    "UNIT1","UNIT2","UNIT","UNITPRICE","DISCOUNT","ACOST","RATE","RATEPRICE","REALSUM","SUBPRICE",
												    "P0","P1","P2","P3","P4","P5","COLOR","SIZE","ORDDATE","FINEDATE","BATCH","SUPPLY","GOODSTYPE","GOODSNAME",
												    "COLORS","SIZES","UNIT10","UNIT20","UNIT30","UNIT40","PIC","PS","SEASON","COUNTRY","YEAR"};
													FileInputStream fis = new FileInputStream(localFileI);
													InputStreamReader isr = new InputStreamReader(fis, encodout);
													Reader in = new BufferedReader(isr);
													int ch;
													db.beginTransaction();
												try{
													while ((ch = in.read()) > -1) {
														buffers.append((char)ch);
														if(buffers.toString().indexOf("SSSS\r\n")>0){
															String fields=buffers.toString().substring(0,buffers.toString().length()-2);
															String[] arrayField = fields.toString().split(";");
															if (arrayField.length==54){
																
																ContentValues valueF = new ContentValues();
																
																if (arrayField[48].indexOf("/cwbuyer/")>0){
																	String chg=arrayField[48].replace(arrayField[48].substring(0, arrayField[48].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
																	arrayField[48]=chg;
																}
																
																for(int ij=1;ij<(arrayField.length-1);ij++){ //將qdetail存入
																	if (arrayField[ij]==null || arrayField[ij].equalsIgnoreCase("NULL") || arrayField[ij].equalsIgnoreCase("nu")) arrayField[ij]="0"; 
																	valueF.put(colNames[ij],arrayField[ij]) ;
																}
																db.insert("qitems", null, valueF);
																
															}																	
															buffers.delete(0, buffers.toString().length()	);	
														}
													}
													in.close();  //
										            db.setTransactionSuccessful();
										            String echo="預購";
										            		if (bfstrs[5].equalsIgnoreCase("0")) echo="留貨";
										    		Toast.makeText(context, "所有"+echo+" 與 雲端資料 維護成功 !!!", Toast.LENGTH_SHORT).show();
										            
												}
												catch(Exception e){
												}
												finally{
												          db.endTransaction();
												}
											}
						        		  }  //end success
							        	} catch (Exception e) {
							        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
							        		success=false;
							        	}
								    }
									db.close();
								}
			        			  
							} else if (work==15 ){  //完成雲端qmacc update後
								
								if (Hresult.indexOf("update_qmacc_")>=0){
									SQLiteDatabase db = Utilis.getDB(context);
									db.execSQL("delete from qmacc where TR='Y2'");
									db.close();
									db = Utilis.getDB(context);
									db.execSQL("update qmacc set TR='Y0' where TR <>'Y0' or TR IS NULL ");
									db.close();
								}
								//Log.i("DOWNLOAD_15_mHandlerQC===", Hresult.toString());
	
							} else if (work==14){  //完成雲端QMAC_download後
								String Tnow =DateUtil.getSystemTime().substring(2, 12);
								if (Hresult.indexOf("aa0aa1_qmacc_")>=0){ 	
									String  FileH=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"AA0_"+bfstrs[1]+"_QMACC.csv";
									String ServerT=Hresult.substring(Hresult.indexOf("aa0aa1_qmacc_")+13).trim();

									SQLiteDatabase db = Utilis.getDB(context);
									
									final File localFileH = new File(FileH);
									final String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
						        	boolean success=false;
									try {
										success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileH, localFileH);
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							          finally
							        {
								     try{
							        	  if (success){ //表示已存入LOCAL端

							        		  if (localFileH.exists()){  //檔案存在
							      					String encodout = "UTF8";
													StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
													String[] colNames={"TR","ID","QKIND","FORMNO","FORMDATE","CTIME",
															"UTIME","ISCONFIRM","QATYPE","QNOM","QNOI","PS","MOUT","MINTO",
															"MBEFORE","MBALANCE","MBETWEEN","MAFTER","DEPTNO","DEPTNAME",
															"DEVISE","ATMNO","ATMNAME","ATMDATE","EMPID","EMPNAME","PIC","BANKNAME"};
													FileInputStream fis = new FileInputStream(localFileH);
													InputStreamReader isr = new InputStreamReader(fis, encodout);
													Reader in = new BufferedReader(isr);
													int ch;
													
													db.beginTransaction();
													try{
														
													while ((ch = in.read()) > -1) {
														buffers.append((char)ch);
														if(buffers.toString().indexOf("SSSS\r\n")>0){
															String fields=buffers.toString().substring(0,buffers.toString().length()-2);
															String[] arrayField = fields.toString().split(";");
															if (arrayField.length==29){//PS1 PS2
																	db.execSQL("delete from qmacc where DEPTNO='"+arrayField[18]+"' and FORMDATE='"+arrayField[4]+"' and CTIME='"+arrayField[5]+"'");
																	ContentValues valueF = new ContentValues();
																	if (arrayField[0]==null || arrayField[0].equalsIgnoreCase("NULL") || !arrayField[0].equalsIgnoreCase("Y2")){
																		arrayField[0]="Y0";
																		for(int ij=0;ij<(arrayField.length-1);ij++){ //將qdetail存入
																			if (arrayField[ij]==null || arrayField[ij].equalsIgnoreCase("NULL")) arrayField[ij]="0";
																			if (arrayField[26].indexOf("/cwbuyer/")>0){
																				String chg=arrayField[26].replace(arrayField[26].substring(0, arrayField[26].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
																				arrayField[26]=chg;
																						final File localFile1 = new File(arrayField[26]);
																						final String serverFile1 =arrayField[26].replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
																						try {
																							ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFile1, localFile1);
																						} catch (IOException e) {
																							// TODO Auto-generated catch block
																							e.printStackTrace();
																						}
																			}
																			valueF.put(colNames[ij],arrayField[ij]) ;
																		}
																		db.insert("qmacc", null, valueF);
																	}
															}																	
															buffers.delete(0, buffers.toString().length());	
														}
													}
													in.close();  //
										            db.setTransactionSuccessful();
												}
												catch(Exception e){
												}
												 
												finally{
												          db.endTransaction();
												}
												}
							        		  }  //end success
							        	} catch (Exception e) {
							        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
							        		success=false;
							        	}
								    }
									db.close();
									if (success) Utilis.putIni(context, "SYS", "AUPDATE",ServerT ,2 );//ServerTime_Update
								}
			        			  Utilis.putIni(context, "SYS", "SEASON",Tnow , 6);  //與廠商5.6共用
			        			  
							} else if (work==21){  //完成雲端QHEAD & QITEMS_download後
								//@@@未來進階版 應該是一筆筆檢查 異樣資料再行修正
								if (Hresult.indexOf("aa0aa1_dn_hi_")>=0){ 	
									//在SERVER上產生了  //3g001/IMPORT/20123/cwbuyer_qdetail_auto.csv
									String  FileH=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"AA0_"+bfstrs[1]+"_DN_QHEAD.csv";


									SQLiteDatabase db = Utilis.getDB(context);
									
									final File localFileH = new File(FileH);
									final String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
						        	boolean success=false;
									try {
										success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileH, localFileH);
										
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							          finally
							        {
								     try{
							        	  if (success){ //表示已存入LOCAL端

							        		  if (localFileH.exists()){  //檔案存在
							        			  //稍後的整批DATA 將以每5000筆存入
							        			  //所以應先刪除 日期範圍的QHEAD ???並如何圈住QITEMS
							        			  	String query_rsH ="";
							        			  	String delete_rsH ="";
							        			  if (bfstrs[2].equalsIgnoreCase(bfstrs[3])){ //證明是總倉
													if (!bfstrs[5].equalsIgnoreCase("1")){
														query_rsH = "SELECT FORMNO FROM qhead WHERE (FORMDATE>='"+bfstrs[6]+"' and FORMDATE<='"+bfstrs[7]+"' ) and (BANKNAME <> '"+bfstrs[1]+"') and ((ISCONFIRM='Y') or (ISCHECK='Y' and (DEPTNO='"+bfstrs[2]+"' or ISCONFIRM='N')))";
														 delete_rsH = "delete FROM qhead WHERE (FORMDATE>='"+bfstrs[6]+"' and FORMDATE<='"+bfstrs[7]+"' ) and (BANKNAME <> '"+bfstrs[1]+"') and ((ISCONFIRM='Y') or (ISCHECK='Y' and (DEPTNO='"+bfstrs[2]+"' or ISCONFIRM='N')))";
														 
														}else{ //輔助平板,不再下載其他門市的銷貨類交易檔 但是出貨轉貨要轉
															query_rsH = "SELECT FORMNO FROM qhead WHERE (FORMDATE>='"+bfstrs[6]+"' and FORMDATE<='"+bfstrs[7]+"' ) and (BANKNAME <> '"+bfstrs[1]+"') and ((ISCONFIRM='Y' and QKIND<>'31' and QKIND<>'41') or (ISCHECK='Y' and DEPTNO='"+bfstrs[2]+"'))";
															delete_rsH = "delete FROM qhead WHERE (FORMDATE>='"+bfstrs[6]+"' and FORMDATE<='"+bfstrs[7]+"' ) and (BANKNAME <> '"+bfstrs[1]+"') and ((ISCONFIRM='Y' and QKIND<>'31' and QKIND<>'41') or (ISCHECK='Y' and DEPTNO='"+bfstrs[2]+"'))";
														}	
													}else{  //否則就是門市 20131020 修正放寬改單後 需傳回當事門市異動
														query_rsH = "SELECT FORMNO FROM qhead WHERE (FORMDATE>='"+bfstrs[6]+"' and FORMDATE<='"+bfstrs[7]+"' ) and (((QKIND='20' and USER='"+bfstrs[2]+"') or (QKIND ='21' and (DEPTNO='"+bfstrs[2]+"' or USER='"+bfstrs[2]+"')) or ((QKIND='31' or QKIND ='41') and DEPTNO='"+bfstrs[2]+"'))) and (BANKNAME <> '"+bfstrs[1]+"')";
														delete_rsH = "delete  FROM qhead WHERE (FORMDATE>='"+bfstrs[6]+"' and FORMDATE<='"+bfstrs[7]+"' ) and (((QKIND='20' and USER='"+bfstrs[2]+"') or (QKIND ='21' and (DEPTNO='"+bfstrs[2]+"' or USER='"+bfstrs[2]+"')) or ((QKIND='31' or QKIND ='41') and DEPTNO='"+bfstrs[2]+"'))) and (BANKNAME <> '"+bfstrs[1]+"')";
													}
					
											 	Cursor csh=db.rawQuery(query_rsH,null);
											 	if (csh.getCount()>0){
													StringBuffer placeholders = new StringBuffer();
													StringBuffer aDelete = new StringBuffer();
						        			  		csh.moveToFirst();
						        			  		
							        			  	for(int s=0;s<csh.getCount();s++){ 
													    placeholders.append("? ,");
													   aDelete.append(csh.getString(0)+",");
													   
														if (((s%100)==0) || (s==(csh.getCount()-1))){
															 String [] flgA=aDelete.toString().substring(0,aDelete.toString().length()-1).split(",");
															String where = "FORMNO  IN (" + placeholders.toString().substring(0,placeholders.toString().length()-1) + ")";
															db.delete("qitems", where, flgA);
															if (s%500==0) Toast.makeText(context, "已進行準備進度:約"+s+"筆", Toast.LENGTH_LONG).show();
															placeholders.delete(0, placeholders.toString().length());
															aDelete.delete(0, aDelete.toString().length());
													    }
							        			  		csh.moveToNext();
							        			  	}
													 db.execSQL(delete_rsH);
											 	}
												 csh.close();
							        			  String encodout = "UTF8";
													StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
													//目的只是取得QHEAD的欄位總數及欄位名稱 @@@萬一沒有任何資料時
													String insertH=" insert into qhead  (TR,ID,QKIND,FORMNO,HANDNO,FORMDATE,CREATEDATETIME,ISCONFIRM,ISCHECK,ISLIST,EMPID,EMPNAME,USER,USERNAME,TRADETYPE,DEPTNO" +
															",ORDCASH,ORDCARD,CASH,CARD,ATOT,ORDDATE,FINEDATE,ASUM,BSUM,BILLRATE,COSTS,TURESUM,DISMONEY,BANKNO,BANKNAME" +
															",ATM,ATMDATE,TRCASH,PS,PS1,PS2 ) values ";
													FileInputStream fis = new FileInputStream(localFileH);
													InputStreamReader isr = new InputStreamReader(fis, encodout);
													Reader in = new BufferedReader(isr);
													int ch;
													db.beginTransaction();
													try{
														while ((ch = in.read()) > -1) {
															buffers.append((char)ch);
															if(buffers.toString().indexOf("),")>0){
																String ValueH=buffers.toString().substring(0,buffers.toString().indexOf("),")+1);
																
																if (ValueH.length()>0){
																	String SQLinsertH=insertH+ValueH;
																	db.execSQL(SQLinsertH);
																}
																buffers.delete(0, buffers.toString().length()	);
															}
														}
														in.close();  //
											            db.setTransactionSuccessful();
													}
													catch(Exception e){
													}
													finally{
													          db.endTransaction();
													}
												}
							        		  
												String  FileI=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"AA0_"+bfstrs[1]+"_DN_QITEMS.csv";
												final File localFileI = new File(FileI);
												final String serverFileI =FileI.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
												try {
													success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileI, localFileI);												
												} catch (IOException e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
												}
										          finally
										        {
											     try{
										        	  if (success){ //表示已存入LOCAL端
										        		  if (localFileI.exists()){  //檔案存在
										      					String encodout = "UTF8";
																StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
																String insertI=" insert into qitems  (TR,ID,QKIND,FORMNO,HANDNO,FORMDATE,CREATEDATETIME,ISCONFIRM,ISCHECK," +
																		"EMPID,EMPNAME,USER,USERNAME,TRADETYPE,DEPTNO,GOODSNO,GOODSNOS,SOURCENO," +
																		"UNIT1,UNIT2,UNIT,UNITPRICE,DISCOUNT,ACOST,RATE,RATEPRICE,REALSUM,SUBPRICE," +
																		"P0,P1,P2,P3,P4,P5,COLOR,SIZE,ORDDATE,FINEDATE,BATCH,SUPPLY,GOODSTYPE,GOODSNAME," +
																		"COLORS,SIZES,UNIT10,UNIT20,UNIT30,UNIT40,PIC,PS,SEASON,COUNTRY,YEAR ) values ";
																
																FileInputStream fis = new FileInputStream(localFileI);
																InputStreamReader isr = new InputStreamReader(fis, encodout);
																Reader in = new BufferedReader(isr);
																int ch;
																int s=0;

																db.beginTransaction();
																try{
																	while ((ch = in.read()) > -1) {
																		buffers.append((char)ch);
																		String SQLinsertI="";
																		if(buffers.toString().indexOf("'),")>0) {
																			String ValueI=buffers.toString().substring(0,buffers.toString().indexOf("'),")+2);
																			if (ValueI.length()>0){
																				String Clm[]=ValueI.split("','"); 
																				if (Clm[48].indexOf("/cwbuyer/")>0){
																					String chg=Clm[48].replace(Clm[48].substring(1, Clm[48].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
																					Clm[48]=chg;
																				}//置換正確的圖片路徑,因為每個裝置都有可能不一致
																				ValueI=Clm[0]; for(int i=1;i<Clm.length;i++) ValueI+="','"+Clm[i];
																				SQLinsertI=insertI+ValueI;
																				db.execSQL(SQLinsertI);
																				s+=1;
																				 if (s%500==0) Toast.makeText(context, "已完成進度:約"+s+"筆", Toast.LENGTH_LONG).show();
																			}
																			buffers.delete(0, buffers.toString().length()	);
																		}
																	}
																	in.close();  //
													            db.setTransactionSuccessful();
																}
																catch(Exception e){
																}
																finally{
																          db.endTransaction();
																}
															}
										        	  }
											     } catch (Exception e) {
											    	 Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
											    	 success=false;
											     }
										        }									        
							        	  }
										} catch (Exception e) {
									    	 Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
									    	 success=false;
										}
							        }
						        	  db.close();
						        	  Toast.makeText(context, "已完成所有下載雲端同步", Toast.LENGTH_LONG).show();
						        	  //end Q21
								}							  	

							} else if (work==18){ //qfact download
								String Tnow =DateUtil.getSystemTime().substring(2, 12);
								if (Hresult.indexOf("aa0_qfact")>=0){ 	
									//在SERVER上產生了  //3g001/ALBUN/20123/aa0_aa1_qfact.csv
									String mFile="aa0_"+mBankn+"_qfact.csv";
									String  AutoFile=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",6)+File.separator+mFile;
									String ServerT=Hresult.substring(Hresult.indexOf("aa0_qfact_")+10);
									final File localFile = new File(AutoFile);
									final String serverFile =AutoFile.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
									//Log.i("QFACT", ""+AutoFile+"==local__server=="+serverFile);									
									
						        	boolean success=false;
									try {
										success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFile, localFile);
										
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							          finally
							        {
								     try{
							        	  if (success){ //表示已存入LOCAL端
							        		  Utilis.putIni(context, "SYS", "AUPDATE",ServerT ,6 );//ServerTime_Update
							        		  //將LOCAL更新UPDATE_TNOW

							        		  if (localFile.exists()){  //檔案存在
							        			  SQLiteDatabase db = Utilis.getDB(context);
							      					String encodout = "UTF8";
													StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
													Cursor cs=null;
													FileInputStream fis = new FileInputStream(localFile);
													InputStreamReader isr = new InputStreamReader(fis, encodout);
													Reader in = new BufferedReader(isr);
													int ch;

													db.beginTransaction();
													try{
														while ((ch = in.read()) > -1) {
															buffers.append((char)ch);
															if(buffers.toString().indexOf("\r\n")>0){
																String fields=buffers.toString().substring(0,buffers.toString().length()-2);
																String[] arrayField = fields.toString().split(";");
																	if (arrayField.length==22){
																		if (!arrayField[18].equalsIgnoreCase("2")){
																			cs=db.rawQuery("select * from qfact where FACTNO='"+arrayField[1]+ "'",null);
																			if (cs.getCount()>0)	db.execSQL("delete from qfact where FACTNO='"+arrayField[1]+ "'");
																			
																				ContentValues valueF = new ContentValues();
																				if (arrayField[19].indexOf("/cwbuyer/")>0){
																					String chg=arrayField[19].replace(arrayField[19].substring(0, arrayField[19].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
																					arrayField[19]=chg;
																							final File localFile1 = new File(arrayField[19]);
																							final String serverFile1 =arrayField[19].replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
																							try {
																								ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFile1, localFile1);												
																							} catch (IOException e) {
																								// TODO Auto-generated catch block
																								e.printStackTrace();
																							}
																				}
																				arrayField[18]="0"; //STATE=0表示不用傳送
																				
																				for(int ij=1;ij<arrayField.length;ij++){ //將qfact存入
																					valueF.put(cs.getColumnName(ij),arrayField[ij]) ;
																				}
																				db.insert("qfact", null, valueF);
																		}else{
																			db.execSQL("delete from qfact where FACTNO='"+arrayField[1]+"'");
																		}
																	}
																buffers.delete(0, buffers.toString().length()	);	
															}
														}
														in.close();  //
											            db.setTransactionSuccessful();
													}
													catch(Exception e){
													}
													finally{
													          db.endTransaction();
													}
												cs.close();
												db.close();
												}
							        		  }  //end success
							        	} catch (Exception e) {
							        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
							        	}
								    }
								}
								Utilis.putIni(context, "SYS", "SEASON",Tnow ,6 );  //localTime_Update									
								//end work18
							} else if (work==20){ 
								String Tnow =DateUtil.getSystemTime().substring(2, 12);
								if (Hresult.indexOf("aa0_qcust")>=0){ 	
									//在SERVER上產生了  //3g001/ALBUN/20123/aa0_aa1_qcust.csv
									String mFile="aa0_"+mBankn+"_qcust.csv";
									String  AutoFile=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",6)+File.separator+mFile;
									String ServerT=Hresult.substring(Hresult.indexOf("aa0_qcust_")+10);
									final File localFile = new File(AutoFile);
									final String serverFile =AutoFile.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
									//Log.i("QCUST", ""+AutoFile+"==local__server=="+serverFile);									
						        	boolean success=false;
									try {
										success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFile, localFile);
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							          finally
							        {
								     try{
							        	  if (success){ //表示已存入LOCAL端
							        		  Utilis.putIni(context, "SYS", "AUPDATE",ServerT ,7 );//ServerTime_Update
							        		  //將LOCAL更新UPDATE_TNOW

							        		  if (localFile.exists()){  //檔案存在
							        			  SQLiteDatabase db = Utilis.getDB(context);
													Cursor cs=null;
							      					String encodout = "UTF8";
													StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文

													FileInputStream fis = new FileInputStream(localFile);
													InputStreamReader isr = new InputStreamReader(fis, encodout);
													Reader in = new BufferedReader(isr);
													int ch;
													
													db.beginTransaction();
												try{
													while ((ch = in.read()) > -1) {
														buffers.append((char)ch);
														if(buffers.toString().indexOf("\r\n")>0){
															String fields=buffers.toString().substring(0,buffers.toString().length()-2);
															String[] arrayField = fields.toString().split(";");

																if (arrayField.length==33){
																	if (!arrayField[19].equalsIgnoreCase("2")){
																		cs=db.rawQuery("select * from qcust where CUSTNO='"+arrayField[2]+ "'",null);
																		if (cs.getCount()>0) db.execSQL("delete from qcust where CUSTNO='"+arrayField[2]+ "'");
																			ContentValues valueF = new ContentValues();
																		if (arrayField[20].indexOf("/cwbuyer/")>0){
																			String chg=arrayField[20].replace(arrayField[20].substring(0, arrayField[20].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
																			arrayField[20]=chg;
																					final File localFile1 = new File(arrayField[20]);
																					final String serverFile1 =arrayField[20].replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
																					try {
																						ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFile1, localFile1);
																					} catch (IOException e) {
																						// TODO Auto-generated catch block
																						e.printStackTrace();
																					}
																		}
																		arrayField[19]="0"; //STATE=0表示不用傳送

																		
																		for(int ij=1;ij<arrayField.length;ij++){ //將qcust存入
																			valueF.put(cs.getColumnName(ij),arrayField[ij]) ;
																		}
																		db.insert("qcust", null, valueF);
																		//cs.close();
																	}else{
																		db.execSQL("delete from qcust where CUSTNO='"+arrayField[2]+"'");
																	}
																}
																buffers.delete(0, buffers.toString().length()	);	
															}																	
														}
													in.close();  //
										            db.setTransactionSuccessful();
												}
												catch(Exception e){
												}
												finally{
												          db.endTransaction();
												}
												cs.close();	
												db.close();
												}
							        		  }  //end success
							        	} catch (Exception e) {
							        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
							        	}
								    }
								}
								Utilis.putIni(context, "SYS", "SEASON",Tnow ,8 );  //localTime_Update									
							} else if (work==22 ){  //check for barprinter succeed or not
								if (Hresult.indexOf("OK")>=0)
									 Toast.makeText(context, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
								else
									 Toast.makeText(context,Hresult+"傳送失敗", Toast.LENGTH_LONG).show();
								
							} else if (work==24 ){  //完成雲端上傳q	pandn後的處置
								if (Hresult.indexOf("update_pan_")>=0){
									 Toast.makeText(context, "已成功傳送雲端!!", Toast.LENGTH_LONG).show();
										String mDBPath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"cwbuyer/data/20123/qmtrio.sdb";		 
										File fileQmtrio = new File(mDBPath);
								      	SQLiteDatabase mdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
								      	StringBuffer SQLb=new StringBuffer();
								      	SQLb.append("delete from qpandn where TR='Y1' ");
								      	SQLb.append(" and PNDNSTATE='2' ");
								      	mdb.execSQL(SQLb.toString());
								      	mdb.close();
								      	
									 
								}
								//Log.i("Update_qpandn_mHandlerQC===", Hresult.toString());
							}
					}
				}
			}
			
		};
		
	}


//針對雙向Q1~Q8 Q11 Q16同步更新
	
	public static class sendPostRunnable implements Runnable
	{
		String []bfstrs;
		String []bfstrFs;
		Context context;
		String uriAPI=null;
		int work=0;
		
		// 建構子，設定要傳的字串
		public sendPostRunnable(Context context,String bfstrs,String bfstrFs,String uriAPI,int work)
		{
			String []fields=bfstrs.split(";");
			String []fieldFs=bfstrFs.split(";");
			this.bfstrs=fields;
			this.bfstrFs=fieldFs;
			this.uriAPI=uriAPI; 
			this.context=context;
			this.work=work;
		}

		@Override
		public void run()
		{
			
			String result = sendPostDataToInternet(bfstrs,bfstrFs);
			mHandler.obtainMessage(REFRESH_DATA, result).sendToTarget();
			
		}

		private String sendPostDataToInternet(String[] bfstrs,String[] bfstrFs)
		{

			/* 建立HTTP Post連線 */

			HttpPost httpRequest = new HttpPost(uriAPI);
			/*
			 * Post運作傳送變數必須用NameValuePair[]陣列儲存
			 */
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for(int x=0;x<bfstrs.length;x++){
				params.add(new BasicNameValuePair(bfstrFs[x], bfstrs[x]));
			}
			try

			{

				/* 發出HTTP request(請求) */

				httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				/* 取得HTTP response(回傳) */
				HttpResponse httpResponse = new DefaultHttpClient()
						.execute(httpRequest);
				/* 若狀態碼為200 ok */
				if (httpResponse.getStatusLine().getStatusCode() == 200)
				{
					/* 取出回應字串 */
					String strResult = EntityUtils.toString(httpResponse
							.getEntity());
					// 回傳回應字串
					return strResult;
				}else{
					//Log.i("DOWNLOAD_31===", ""+httpResponse.getStatusLine().getStatusCode());					
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return null;
		}

		Handler mHandler = new Handler()
		{
			@Override
			public void handleMessage(Message msg)
			{
				String Hresult = "130101999999";  //為預設SERVER端出始更新日
				
				switch (msg.what)
				{
				// 顯示網路上抓取的資料
				case REFRESH_DATA:
					if (msg.obj instanceof String)
						Hresult = (String) msg.obj;
					if (Hresult != null ){
						// 傳回SERVER的update(Q1~Q8)日期
						//  由此來判讀client & server是否同步了,不同步者將會因著Id=0.update =1.download
						String [] ServerUPD=Hresult.split(";");  
						String [] ClientUPD=Utilis.getIni(context, "SYS", "ALBUN", 9).split("!&!");
						String mUid=Utilis.getIni(context, "SYS", "IMPORT", 2);
						String uriAPIpath = "http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+"/"+Utilis.getIni(context, "SYS", "IMPORT", 2);		
						//Toast.makeText(context, "雲端資料同步中....請稍候", Toast.LENGTH_LONG).show();
						
						if (ServerUPD.length==9){  //Q1-Q7 Q11 Q16
							SQLiteDatabase sdb = Utilis.getDB(context);
							Cursor scs =null;
							//Log.i("DOWNLOAD_7_mHandlerQC===", Hresult.toString()+ClientUPD.length);
							
							
							for (int xx=0;xx<ServerUPD.length;xx++){
//							int xx=0;
								
								if (!ServerUPD[xx].equalsIgnoreCase(ClientUPD[xx])){
									//表示需要Client-->Server UPDATE
								    switch(xx){
								    case 0:
								    	if (work==0){
								    		uriAPI = uriAPIpath+"/qc_country_ninsert.php";
								    		scs=sdb.rawQuery("select * from qc_country order by _ID", null);
								    	}else{
								    		uriAPI = uriAPIpath+"/qc_country_download.php";
								    	}
								    	break;
								    case 1:
								    	if (work==0){
								    		uriAPI = uriAPIpath+"/qc_type_ninsert.php";
								    		scs=sdb.rawQuery("select * from qc_type order by _ID", null);
								    	}else{
								    		uriAPI = uriAPIpath+"/qc_type_download.php";
								    	}
								    	break;
								    case 2:
								    	if(work==0){
								    		uriAPI = uriAPIpath+"/qc_color_ninsert.php";
								    		scs=sdb.rawQuery("select * from qc_color order by NO", null);
								    	}else{
								    		uriAPI = uriAPIpath+"/qc_color_download.php";
								    	}
								    	break;
								    case 3:
								    	if(work==0){
								    		uriAPI = uriAPIpath+"/qc_size_ninsert.php";
								    		scs=sdb.rawQuery("select * from qc_size order by _ID", null);
								    	}else{
								    		uriAPI = uriAPIpath+"/qc_size_download.php";
								    	}
								    	break;
								    case 4:
								    	if(work==0){
								    		uriAPI = uriAPIpath+"/qc_defpri_ninsert.php";
								    		scs=sdb.rawQuery("select * from qc_defpri order by _ID", null);
								    	}else{
								    		uriAPI = uriAPIpath+"/qc_defpri_download.php";
								    	}
								    	break;
								    case 5:
								    	if(work==0){
								    		uriAPI = uriAPIpath+"/qc_quality_ninsert.php";
								    		scs=sdb.rawQuery("select * from qc_quality order by _ID", null);
								    	}else{
								    		uriAPI = uriAPIpath+"/qc_quality_download.php";
								    	}
								    	break;
								    case 6:
								    	if(work==0){
								    		uriAPI = uriAPIpath+"/qc_wash_ninsert.php";
								    		scs=sdb.rawQuery("select * from qc_wash order by _ID", null);
								    	}else{
								    		uriAPI = uriAPIpath+"/qc_wash_download.php";
								    	}
								    	break;
								    case 7:
								    	if(work==0){
								    		uriAPI = uriAPIpath+"/qc_macc_ninsert.php";
								    		scs=sdb.rawQuery("select * from qc_macc order by _ID", null);
								    	}else{
								    		uriAPI = uriAPIpath+"/qc_macc_download.php";
								    	}
								    	break;
								    case 8:
								    	if(work==0){
								    		uriAPI = uriAPIpath+"/qc_ppri_ninsert.php";
								    		scs=sdb.rawQuery("select * from qc_ppri order by _ID", null);
								    	}else{
								    		uriAPI = uriAPIpath+"/qc_ppri_download.php";
								    	}
								    	break;
								    }
								    
								    if(work==0){ 
								    	mainTain_qc(context,scs,mUid,uriAPI);
										//Log.i("DOWNLOAD_8_mHandlerQC===", "_"+scs.getCount()+"_"+scs.getColumnCount());
								    }else{
								    	download_qc(context,mUid,""+(xx+1),ClientUPD[xx],uriAPI);
								    	Utilis.putIni(context, "SYS", "ALBUN",ServerUPD[xx] , xx+1); 
								    }
								    
								}
							}  //end _for()	
							
							if (scs!=null) scs.close();
							sdb.close();
						}
						
					}	
					break;	
				}	
			}
		};

		
	}
	
	
	@SuppressLint("HandlerLeak")
	public static class sendPostRunnable1 implements Runnable
	{
		String []bfstrs;
		String []bfstrFs;
		String uriAPI=null;
		Context context;
		
		// 建構子，設定要傳的字串
		public sendPostRunnable1(Context context,String bfstrs,String bfstrFs,String uriAPI)
		{
			String []fields=bfstrs.split(";");
			String []fieldFs=bfstrFs.split(";");
			this.bfstrs=fields;
			this.bfstrFs=fieldFs;
			this.uriAPI=uriAPI; 
			this.context=context;
		}

		@Override
		public void run()
		{
			String result = sendPostDataToInternet1(bfstrs,bfstrFs,uriAPI);
			mHandler1.obtainMessage(REFRESH_DATA, result).sendToTarget();
			
		}

		private String sendPostDataToInternet1(String[] bfstrs,String[] bfstrFs,String uriAPI)
		{

			/* 建立HTTP Post連線 */

			HttpPost httpRequest = new HttpPost(uriAPI);
			/*
			 * Post運作傳送變數必須用NameValuePair[]陣列儲存
			 */
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for(int x=0;x<bfstrs.length;x++){
				params.add(new BasicNameValuePair(bfstrFs[x], bfstrs[x]));
			}
			try

			{

				/* 發出HTTP request(請求) */

				httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				/* 取得HTTP response(回傳) */
				HttpResponse httpResponse = new DefaultHttpClient()
						.execute(httpRequest);
				/* 若狀態碼為200 ok */
				if (httpResponse.getStatusLine().getStatusCode() == 200)
				{
					/* 取出回應字串 */
					String strResult = EntityUtils.toString(httpResponse
							.getEntity());
					// 回傳回應字串
					return strResult;
				}else{
					//Log.i("DOWNLOAD_31===", ""+httpResponse.getStatusLine().getStatusCode());					
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return null;
		}
		

	//3g001,Q1-Q30,Local_(SYS,ALBUN,n)LAST_DAY
	Handler mHandler1 = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			String Hresult1 = "130101";  //為預設SERVER端出始更新日					
			switch (msg.what)
			{
			// 雲端傳回的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String)
					Hresult1 = (String) msg.obj;
				if (Hresult1 != null ){
					String [] records =Hresult1.split("\r\n");
					if (records[0].indexOf("table_")>=0){ //表示為某一個TABLE傳回DATA
						String tableName=records[0].substring(records[0].indexOf("_")+1, records[0].lastIndexOf("_"));
						//Log.i("DOWNLOAD_"+tableName, ""+Hresult1);				
						if (records.length>1){ //表示除了第一筆為TABLENAME以外,還有DATA部分
							String[] arrayField =records[1].split(";");
							SQLiteDatabase rdb = Utilis.getDB(context);
							Cursor rcs =rdb.rawQuery("select * from "+tableName, null);
							if (rcs.getColumnCount()==(arrayField.length)){  //欄位數應相符,驗證之
								rdb.execSQL("delete from "+tableName);  //刪除所有CLIENT端資料
								for (int ii=1;ii<records.length;ii++){
									arrayField =records[ii].split(";");
										ContentValues valueB = new ContentValues();

										for(int ij=0;ij<arrayField.length;ij++){ 
											valueB.put(rcs.getColumnName(ij),arrayField[ij]) ;
										}
										rdb.insert(tableName, null, valueB);
								}		
							}
							rcs.close();
							rdb.close();
						}
					}
				}
			}
		}	
	};
	
}

	public static class sendPostRunnablePic implements Runnable
	{
		String []bfstrs;
		String []bfstrFs;
		String uriAPI=null;
		Context context;
		
		// 建構子，設定要傳的字串
		public sendPostRunnablePic(Context context,String bfstrs,String bfstrFs,String uriAPI)
		{
			String []fields=bfstrs.split(";");
			String []fieldFs=bfstrFs.split(";");
			this.bfstrs=fields;
			this.bfstrFs=fieldFs;
			this.uriAPI=uriAPI; 
			this.context=context;
		}

		@Override
		public void run()
		{
			String result = sendPostDataToInternetPic(context,bfstrs,bfstrFs,uriAPI);
			mHandlerPic.obtainMessage(REFRESH_DATA, result).sendToTarget();
			
		}

		private String sendPostDataToInternetPic(Context context,String[] bfstrs,String[] bfstrFs,String uriAPI)
		{

			/* 建立HTTP Post連線 */

			HttpPost httpRequest = new HttpPost(uriAPI);
			/*
			 * Post運作傳送變數必須用NameValuePair[]陣列儲存
			 */
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for(int x=0;x<bfstrs.length;x++){
				params.add(new BasicNameValuePair(bfstrFs[x], bfstrs[x]));
			}
			try

			{

				/* 發出HTTP request(請求) */

				httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				/* 取得HTTP response(回傳) */
				HttpResponse httpResponse = new DefaultHttpClient()
						.execute(httpRequest);
				/* 若狀態碼為200 ok */
				if (httpResponse.getStatusLine().getStatusCode() == 200)
				{
					/* 取出回應字串 */
					String strResult = EntityUtils.toString(httpResponse
							.getEntity());
					// 回傳回應字串
					return strResult;
				}else{
					//Log.i("DOWNLOAD_31===", ""+httpResponse.getStatusLine().getStatusCode());					
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return null;
		}

		//3g001,Q1-Q30,Local_(SYS,ALBUN,n)LAST_DAY
		Handler mHandlerPic = new Handler()
		{
			@SuppressLint("HandlerLeak")
			@Override
			public void handleMessage(Message msg)
			{
				String HresultPic = "";  //為預設SERVER端出始更新日					
				switch (msg.what)
				{
				// 雲端傳回的資料
				case REFRESH_DATA:
					if (msg.obj instanceof String)
						HresultPic = (String) msg.obj;
//					Log.i("DOWNLOAD_Pic===", HresultPic);					
					
					if (HresultPic != null ){
						if (HresultPic.indexOf("success")>=0){ //表示為某一個TABLE傳回DATA
							//取得成功資訊後,進行ftp 傳回ZIP檔 再行解壓縮
							final String AutoFile=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"aa0_"+Utilis.getIni(context,"SYS","DEPT",1)+Utilis.getIni(context,"SYS","DEPT",2)+".zip";
							final File localFile = new File(AutoFile);

							final String serverFile =AutoFile.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
							try {
								boolean success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFile, localFile);
								
								if (success){
									//需解壓縮
									Utilis.Unzip2(AutoFile, android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7));
								}
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}												

						}
					}
				}
			}	
		};
	}
		
	

	public static void aa0_aa1_auto_qdetail_n(Context context){
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
	 		if (Utilis.haveInternet(context) && of_line!=0 && Utilis.toInt(Utilis.getIni(context, "CLOUD", "AUTO", 1))>1){
			//SERVER的時間與LOCAL時間不同調,不可混談
			String Tnow =DateUtil.getSystemTime().substring(2, 12);
			String T1=Utilis.getIni(context, "SYS", "SEASON", 1);
			String T2=Utilis.getIni(context, "SYS", "SEASON", 2);
				//也要帶到sendPostRunnableQC 更新
			if (((Utilis.toDouble(Tnow)-Utilis.toDouble(T1))>5) || (!Tnow.equalsIgnoreCase(T1) && !T2.equalsIgnoreCase("0"))){
				//確保在同一分鐘不會再度執行,或正在同步中不可執行,或超過30分鐘,才可執行
				Utilis.putIni(context, "SYS", "SEASON",""+Tnow ,1 );
				Utilis.putIni(context, "SYS", "SEASON","0" ,2 ); //表示同步中,不可以干擾或再同步一次
				StringBuffer bfstr = new StringBuffer();
				StringBuffer bfstrF = new StringBuffer();
					bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
					bfstrF.append("UID").append(";");
					bfstr.append(Utilis.getIni(context,"SYS","DEPT",1)+Utilis.getIni(context,"SYS","DEPT",2)).append(";");
					bfstrF.append("QEMP").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2)).append(";");
					bfstrF.append("QYEARS").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "AUPDATE", 1)).append(";");
					bfstrF.append("LUPDATE").append(";");
					bfstr.append(Utilis.getIni(context,"SYS","DEPT",1)+Utilis.getIni(context,"SYS","DEPT",2));
					bfstrF.append("QDEPT");
			          try
			          { 
			        	  Thread t = new Thread(new DBCloud.sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),11));
			        	  t.start();
							//Thread.sleep(2000);
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			          }
			}
	}
}	

	public static void aa0_aa1_auto_pic_n(Context context,String picStr){
			//SERVER的時間與LOCAL時間不同調,不可混談
				//確保在同一分鐘不會再度執行,或正在同步中不可執行,或超過30分鐘,才可執行
				StringBuffer bfstr = new StringBuffer();
				StringBuffer bfstrF = new StringBuffer();
					bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
					bfstrF.append("UID").append(";");
					bfstr.append(picStr).append(";");
					bfstrF.append("PICSTR").append(";");
					bfstr.append(Utilis.getIni(context,"SYS","DEPT",1)+Utilis.getIni(context,"SYS","DEPT",2)).append(";");
					bfstrF.append("PARTNOS").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2));
					bfstrF.append("QYEARS");

			          try
			          { 
							Thread t = new Thread(new DBCloud.sendPostRunnablePic(context,bfstr.toString(),bfstrF.toString(),"http://"+Utilis.getIni(context, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(context, "SYS", "IMPORT", 2)+File.separator+"getweb_pic.php"));
							t.start();
							//Thread.sleep(2000);
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			          }
	}	
	
	public static void aa0_aa1_auto_HI(Context context,int nKind){
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
		if (Utilis.haveInternet(context) && of_line!=0 && Utilis.toInt(Utilis.getIni(context, "CLOUD", "AUTO", 3))>0 ){
			//SERVER的時間與LOCAL時間不同調,不可混談
			String Tnow =DateUtil.getSystemTime().substring(2, 12);
			String T3=Utilis.getIni(context, "SYS", "SEASON", 3);
			String T4=Utilis.getIni(context, "SYS", "SEASON", 4);
			//也要帶到sendPostRunnableQC 更新
			if (((Utilis.toDouble(Tnow)-Utilis.toDouble(T3))>5) || (!Tnow.equalsIgnoreCase(T3) && !T4.equalsIgnoreCase("0")) ){
				//確保在同一分鐘不會再度執行,或正在同步中不可執行,或超過5分鐘,才可執行
				Utilis.putIni(context, "SYS", "SEASON",""+Tnow ,3 );
				Utilis.putIni(context, "SYS", "SEASON","0" ,4 );
				String mBankn=Utilis.getIni(context, "SYS", "DEPT",1)+Utilis.getIni(context, "SYS", "DEPT",2);//門市代號+機號		
				StringBuffer bfstr = new StringBuffer();
				StringBuffer bfstrF = new StringBuffer();
					bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
					bfstrF.append("UID").append(";");
					bfstr.append(mBankn).append(";");
					bfstrF.append("QDEPT").append(";");
					bfstr.append(Utilis.getIni(context,"SYS","DEPT",1)).append(";");
					bfstrF.append("DEPTNO").append(";");
					bfstr.append(Utilis.getIni(context,"SYS","DEPT",6)).append(";");
					bfstrF.append("QPART").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2)).append(";");
					bfstrF.append("QYEARS").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "TRADENAME", 8)).append(";");
					bfstrF.append("ALONE").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "AUPDATE", 3));
					bfstrF.append("LUPDATE");
			          try
			          { 
							Thread t = new Thread(new DBCloud.sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),12));
							t.start();
							//Thread.sleep(2000);
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			          }
			}
		}
	}

	public static void aa0_aa1_auto_HI_ORNY(Context context,String mFormno,String mode){//0留貨1預購 維護
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
		if (Utilis.haveInternet(context) && of_line!=0 && Utilis.toInt(Utilis.getIni(context, "CLOUD", "AUTO", 3))>0 ){
			//SERVER的時間與LOCAL時間不同調,不可混談
			//也要帶到sendPostRunnableQC 更新
				//確保在同一分鐘不會再度執行,或正在同步中不可執行,或超過5分鐘,才可執行
				String mBankn=Utilis.getIni(context, "SYS", "DEPT",1)+Utilis.getIni(context, "SYS", "DEPT",2);//門市代號+機號		
				StringBuffer bfstr = new StringBuffer();
				StringBuffer bfstrF = new StringBuffer();
					bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
					bfstrF.append("UID").append(";");
					bfstr.append(mBankn).append(";");
					bfstrF.append("QDEPT").append(";");
					bfstr.append(Utilis.getIni(context,"SYS","DEPT",1)).append(";");
					bfstrF.append("DEPTNO").append(";");
					bfstr.append(Utilis.getIni(context,"SYS","DEPT",6)).append(";");
					bfstrF.append("QPART").append(";");
					bfstr.append(mFormno).append(";");
					bfstrF.append("FORMNO").append(";");
					bfstr.append(mode).append(";");
					bfstrF.append("MODE").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2));
					bfstrF.append("QYEARS");
			          try
			          { 
							Thread t = new Thread(new DBCloud.sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),50));
							t.start();
							//Thread.sleep(2000);
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			          }
		}		
	}

	public static void aa0_aa1_auto_qmacc(Context context){
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
		if (Utilis.haveInternet(context) && of_line!=0 ){
			//SERVER的時間與LOCAL時間不同調,不可混談
			String Tnow =DateUtil.getSystemTime().substring(2, 12);
			String T4=Utilis.getIni(context, "SYS", "SEASON", 5);
			String T5=Utilis.getIni(context, "SYS", "SEASON", 6);
			//也要帶到sendPostRunnableQC 更新
			if (((Utilis.toDouble(Tnow)-Utilis.toDouble(T4))>5) || (!Tnow.equalsIgnoreCase(T4) && !T5.equalsIgnoreCase("0")) ){
				//確保在同一分鐘不會再度執行,或正在同步中不可執行,或超過30分鐘,才可執行
				Utilis.putIni(context, "SYS", "SEASON",""+Tnow ,5 );
				Utilis.putIni(context, "SYS", "SEASON","0" ,6 );
				String mBankn=Utilis.getIni(context, "SYS", "DEPT",1)+Utilis.getIni(context, "SYS", "DEPT",2);//門市代號+機號		
				StringBuffer bfstr = new StringBuffer();
				StringBuffer bfstrF = new StringBuffer();
					bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
					bfstrF.append("UID").append(";");
					bfstr.append(mBankn).append(";");
					bfstrF.append("QDEPT").append(";");
					bfstr.append(Utilis.getIni(context,"SYS","DEPT",1)).append(";");
					bfstrF.append("DEPTNO").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2)).append(";");
					bfstrF.append("QYEARS").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "AUPDATE", 2));
					bfstrF.append("LUPDATE");
			          try
			          { 
							Thread t = new Thread(new DBCloud.sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),14));
							t.start();
							//Thread.sleep(2000);
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			          }
			}
		}
	}
	
	public static void aa1_aa0_update_GVO(Context context,String aDept){
		String  FileH=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"AA0_"+aDept+"_QHEAD_GVO.csv";

		SQLiteDatabase db = Utilis.getDB(context);
		
		final File localFileH = new File(FileH);
		final String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
    	boolean success=false;
		try {
			success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileH, localFileH);												
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
          finally
        {
	     try{
        	  if (success){ //表示已存入LOCAL端

        		  if (localFileH.exists()){  //檔案存在
      					String encodout = "UTF8";
						StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
						String[] colNames={"TR","ID","QKIND","FORMNO","HANDNO","FORMDATE","CREATEDATETIME","ISCONFIRM","ISCHECK","ISLIST","EMPID","EMPNAME","USER","USERNAME","TRADETYPE","DEPTNO"
								,"ORDCASH","ORDCARD","CASH","CARD","ATOT","ORDDATE","FINEDATE","ASUM","BSUM","BILLRATE","COSTS","TURESUM","DISMONEY","BANKNO","BANKNAME"
								,"ATM","ATMDATE","TRCASH","PS","PS1","PS2"};
						//目的只是取得QHEAD的欄位總數及欄位名稱
						FileInputStream fis = new FileInputStream(localFileH);
						InputStreamReader isr = new InputStreamReader(fis, encodout);
						Reader in = new BufferedReader(isr);
						int ch;
						
						db.beginTransaction();
						try{
							
						while ((ch = in.read()) > -1) {
							buffers.append((char)ch);
							if(buffers.toString().indexOf("SSSS\r\n")>0){
								String fields=buffers.toString().substring(0,buffers.toString().length()-2);
								String[] arrayField = fields.toString().split(";");
								if (arrayField.length==38){//PS1 PS2
										db.execSQL("delete from qhead where FORMNO='"+arrayField[3]+"' and QKIND LIKE '"+arrayField[2].substring(0, 1)+"%'");
										db.execSQL("delete from qitems where FORMNO='"+arrayField[3]+"' and QKIND LIKE '"+arrayField[2].substring(0, 1)+"%'");
										ContentValues valueF = new ContentValues();
										if (arrayField[0]==null || arrayField[0].equalsIgnoreCase("null") || !arrayField[0].equalsIgnoreCase("Y2")){
											arrayField[0]="Y0";
										for(int ij=0;ij<(arrayField.length-1);ij++){ //將qhead存入
											if (arrayField[ij]==null || arrayField[ij].equalsIgnoreCase("null")) arrayField[ij]="0"; 
											valueF.put(colNames[ij],arrayField[ij]) ;
										}
										db.insert("qhead", null, valueF);
									}
								}																	
								buffers.delete(0, buffers.toString().length()	);	
							}
						}
						in.close();  //
			            db.setTransactionSuccessful();
					}
					catch(Exception e){
					 
					}
					 
					finally{
					           //finish
					          db.endTransaction();
					}
					}
        		  }  //end success
        	} catch (Exception e) {
        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
        		success=false;
        	}
	    }
		String  FileI=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7)+File.separator+"AA0_"+aDept+"_QITEMS_GVO.csv";
		final File localFileI = new File(FileI);
		final String serverFileI =FileI.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		
		try {
			success=ftpDownloadAndSaveFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileI, localFileI);												
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
          finally
        {
	     try{
        	  if (success){ //表示已存入LOCAL端
        		  if (localFileI.exists()){  //檔案存在
      					String encodout = "UTF8";
						StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
						String[] colNames={
						"TR","ID","QKIND","FORMNO","HANDNO","FORMDATE","CREATEDATETIME","ISCONFIRM","ISCHECK",
					    "EMPID","EMPNAME","USER","USERNAME","TRADETYPE","DEPTNO","GOODSNO","GOODSNOS","SOURCENO",
					    "UNIT1","UNIT2","UNIT","UNITPRICE","DISCOUNT","ACOST","RATE","RATEPRICE","REALSUM","SUBPRICE",
					    "P0","P1","P2","P3","P4","P5","COLOR","SIZE","ORDDATE","FINEDATE","BATCH","SUPPLY","GOODSTYPE","GOODSNAME",
					    "COLORS","SIZES","UNIT10","UNIT20","UNIT30","UNIT40","PIC","PS","SEASON","COUNTRY","YEAR"};
						FileInputStream fis = new FileInputStream(localFileI);
						InputStreamReader isr = new InputStreamReader(fis, encodout);
						Reader in = new BufferedReader(isr);
						int ch;
						db.beginTransaction();
					try{
							
						while ((ch = in.read()) > -1) {
							buffers.append((char)ch);
							if(buffers.toString().indexOf("SSSS\r\n")>0){
								String fields=buffers.toString().substring(0,buffers.toString().length()-2);
								String[] arrayField = fields.toString().split(";");
								if (arrayField.length==54){
									
									ContentValues valueF = new ContentValues();
									
									if (arrayField[48].indexOf("/cwbuyer/")>0){
										String chg=arrayField[48].replace(arrayField[48].substring(0, arrayField[48].indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
										arrayField[48]=chg;
									}
									
									for(int ij=1;ij<(arrayField.length-1);ij++){ //將qdetail存入
										if (arrayField[ij]==null || arrayField[ij].equalsIgnoreCase("NULL")) arrayField[ij]="0"; 
										valueF.put(colNames[ij],arrayField[ij]) ;
									}
									db.insert("qitems", null, valueF);
									
								}																	
								buffers.delete(0, buffers.toString().length()	);	
							}
						}
						in.close();  //
			            db.setTransactionSuccessful();
					}
					catch(Exception e){
					}
					finally{
					          db.endTransaction();
					}
				}
    		  }  //end success
        	} catch (Exception e) {
        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
        		success=false;
        	}
	    }
		db.close();
	}
	
	public static void aa1_aa0_update_qmacc(Context context){
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
		if (Utilis.haveInternet(context) && of_line!=0){
			//SERVER的時間與LOCAL時間不同調,不可混談
			
			String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7);	
			String mBankn=Utilis.getIni(context, "SYS", "DEPT",1)+Utilis.getIni(context, "SYS", "DEPT",2);//門市代號+機號
			
			SQLiteDatabase db = Utilis.getDB(context);
			Cursor csExp = null;
			String sepa="\r\n";

			StringBuffer bufQ= new StringBuffer();
	        bufQ.delete(0, bufQ.toString().length());
			bufQ.append("select * from qmacc");
			bufQ.append(" where TR<>'Y0'");
			bufQ.append(" order by FORMDATE,CTIME ");
			csExp = db.rawQuery(bufQ.toString(), null);
			if (csExp.getCount()>0){
				int QheadColumnCount=csExp.getColumnCount();
		 		String FileH=myImportPath+File.separator+Utilis.getIni(context, "SYS", "DEPT", 1)+Utilis.getIni(context, "SYS", "DEPT", 2)+"_aa0_QMACC.csv"; 
					String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		 		
				File hFile = new File(FileH);
				
				try{
					
						BufferedWriter bwH = new BufferedWriter(new FileWriter(hFile));					 		
						csExp.moveToFirst();
						for (int i=0;i<csExp.getCount();i++){
							for (int j=0;j<QheadColumnCount;j++){
								String mWdata=chkStrB(csExp.getString(j));
								bwH.write(mWdata+";");
							}
							bwH.write("SSSS"+sepa);
							//完成一筆QHEAD,開始取得QITEMS存入
							String LocalPath=csExp.getString(csExp.getColumnIndex("PIC"));
							if (LocalPath != null && LocalPath.indexOf("cwbuyer")>0 && LocalPath.indexOf("drawable/icon")<=0){
								String serverPath =LocalPath.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
								try {
								File pFile= new File(LocalPath);
									DBCloud.ftpUpdateFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverPath, pFile);
								} catch (IOException e) {
								// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}	

							csExp.moveToNext();
							}
						bwH.close();
			        	boolean success=false;
			        	
						try {
							success=DBCloud.ftpUpdateFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileH, hFile);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						if (success){ //如果檔案上傳成功就呼叫 PHP
						
							StringBuffer bfstr = new StringBuffer();
							StringBuffer bfstrF = new StringBuffer();
								bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
								bfstrF.append("UID").append(";");
								bfstr.append(mBankn).append(";");
								bfstrF.append("QDEPT").append(";");
								bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2));
								bfstrF.append("QYEARS");
						          try
						          { 
										Thread t = new Thread(new DBCloud.sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),15));
										t.start();
										//Thread.sleep(2000);
						          }
						          catch (Exception e)
						          {
						            e.printStackTrace();
						          }
						          finally
						          {
						          }
						} else {  //上傳更新檔案失敗
							Toast.makeText(context, "Fail", Toast.LENGTH_LONG).show();							
						}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			db.close();
			csExp.close();
		}
	}
	
	public static void aa1_aa0_pan_update(Context context,String mWho,String Ddate,String mBankn,int nDept){
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
		if (Utilis.haveInternet(context) && of_line!=0){
			//一次只傳送一張盤點單,但不限哪一種盤點單
			String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7);	
			String mDBPath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"cwbuyer/data/20123/qmtrio.sdb";		 
			File fileQmtrio = new File(mDBPath);
			SQLiteDatabase pdb = SQLiteDatabase.openOrCreateDatabase(fileQmtrio, null);
			Cursor csExp = null;
			String sepa="\r\n";

			StringBuffer bufQ= new StringBuffer();
	        bufQ.delete(0, bufQ.toString().length());
			bufQ.append("select * from qpandn");
			bufQ.append(" where USER='"+mWho+"' and PNDNADAY='"+Ddate+"' and PNDNFKIND='"+nDept+"'");
			bufQ.append(" order by PNDNADAY,USER,GOODSNO,ID ");
			csExp = pdb.rawQuery(bufQ.toString(), null);
			if (csExp.getCount()>0){
				int QheadColumnCount=csExp.getColumnCount();
		 		String FileH=myImportPath+File.separator+Utilis.getIni(context, "SYS", "DEPT", 1)+Utilis.getIni(context, "SYS", "DEPT", 2)+"_aa0_PAN.csv"; 
					String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
				File hFile = new File(FileH);
				try{
						BufferedWriter bwH = new BufferedWriter(new FileWriter(hFile));					 		
						csExp.moveToFirst();
						for (int i=0;i<csExp.getCount();i++){
							for (int j=0;j<QheadColumnCount;j++){
								String mWdata=chkStr(csExp.getString(j));
								bwH.write(mWdata+";");
							}
							bwH.write("SSSS"+sepa);
							csExp.moveToNext();
							}
						bwH.close();
			        	boolean success=false;
			        	
						try {
							success=DBCloud.ftpUpdateFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileH, hFile);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						if (success){ //如果檔案上傳成功就呼叫 PHP
						
							StringBuffer bfstr = new StringBuffer();
							StringBuffer bfstrF = new StringBuffer();
								bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
								bfstrF.append("UID").append(";");
								bfstr.append(mBankn).append(";");
								bfstrF.append("QDEPT").append(";");
								bfstr.append(mWho).append(";");
								bfstrF.append("WHO").append(";");
								bfstr.append(Ddate).append(";");
								bfstrF.append("DDATE").append(";");
								bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2));
								bfstrF.append("QYEARS");
						          try
						          { 
										Thread t = new Thread(new DBCloud.sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),24));
										t.start();
										//Thread.sleep(2000);
						          }
						          catch (Exception e)
						          {
						            e.printStackTrace();
						          }
						          finally
						          {
						          }
						} else {  //上傳更新檔案失敗
							Toast.makeText(context, "Fail", Toast.LENGTH_LONG).show();							
						}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			pdb.close();
			csExp.close();
		}
	}

	public static void aa1_aa0_update_HI(Context context){
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
		if (Utilis.haveInternet(context) && of_line!=0){
			//SERVER的時間與LOCAL時間不同調,不可混談
			
			String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",7);	
			String mBankn=Utilis.getIni(context, "SYS", "DEPT",1)+Utilis.getIni(context, "SYS", "DEPT",2);//門市代號+機號
			
			SQLiteDatabase db = Utilis.getDB(context);
			Cursor csExp = null;
			String sepa="\r\n";

			StringBuffer bufQ= new StringBuffer();
	        bufQ.delete(0, bufQ.toString().length());
			bufQ.append("select * from qhead");
			bufQ.append(" where (TR<>'Y0'  and (ISCONFIRM='Y' or ISCHECK='Y') ) or (TR='Y2')");
			bufQ.append(" order by CREATEDATETIME ");
			csExp = db.rawQuery(bufQ.toString(), null);
			if (csExp.getCount()>0){
				int QheadColumnCount=csExp.getColumnCount();
				//$fileH="IMPORT/".$qyears."/".$qdept."_aa0_qhead.csv";
				//$fileI="IMPORT/".$qyears."/".$qdept."_aa0_qitems.csv";
		 		String FileH=myImportPath+File.separator+Utilis.getIni(context, "SYS", "DEPT", 1)+Utilis.getIni(context, "SYS", "DEPT", 2)+"_aa0_qhead.csv"; 
		 		String FileI=FileH.replace("qhead","qitems");
					String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
					String serverFileI =serverFileH.replace("qhead","qitems");
		 		
				File hFile = new File(FileH);
				File iFile = new File(FileI);
				
				try{
					
						BufferedWriter bwH = new BufferedWriter(new FileWriter(hFile));					 		
						BufferedWriter bwI = new BufferedWriter(new FileWriter(iFile));
						csExp.moveToFirst();
						//@@@可以改為 into file ??? 如MySQL
						for (int i=0;i<csExp.getCount();i++){
							for (int j=0;j<QheadColumnCount;j++){
								String mWdata=chkStr(csExp.getString(j));
								bwH.write(mWdata+";");
							}
							bwH.write("SSSS"+sepa);
							//完成一筆QHEAD,開始取得QITEMS存入
							if (!csExp.getString(0).equalsIgnoreCase("Y2") ){
								Cursor csi=db.rawQuery("select * from qitems where FORMNO='"+csExp.getString(3)+"'  order by createdatetime",null);
										if (csi.getCount()>0){
											csi.moveToFirst();
											int QitemsColumnCount=csi.getColumnCount();
											for (int ii=0;ii<csi.getCount();ii++){
												for (int ij=0;ij<QitemsColumnCount;ij++){
													String mWdata=chkStr(csi.getString(ij));
													bwI.write(mWdata+";");
												}
												bwI.write("SSSS"+sepa);
												csi.moveToNext();
											}
											csi.close();
										}
							}
							csExp.moveToNext();
						}
						bwH.close();
						bwI.close();
			        	boolean success=false;
			        	
						try {
							success=DBCloud.ftpUpdateFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileI, iFile);												
							success=DBCloud.ftpUpdateFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileH, hFile);
							//先寄出QITEMS 後寄出QHEAD sucesss以QHEAD為主
							//不宜做出 判斷空檔案 即使 空檔案 也要傳出 使 SERVER端 的FILE 覆蓋為最新的
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						if (success){ //如果檔案上傳成功就呼叫 PHP
						
							StringBuffer bfstr = new StringBuffer();
							StringBuffer bfstrF = new StringBuffer();
								bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
								bfstrF.append("UID").append(";");
								bfstr.append(mBankn).append(";");
								bfstrF.append("QDEPT").append(";");
								bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2));
								bfstrF.append("QYEARS");
						          try
						          { 
										Thread t = new Thread(new DBCloud.sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),9));
										t.start();
										//Thread.sleep(2000);
						          }
						          catch (Exception e)
						          {
						            e.printStackTrace();
						          }
						          finally
						          {
						          }
						} else {  //上傳更新檔案失敗
							Toast.makeText(context, "Fail", Toast.LENGTH_LONG).show();							
						}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			db.close();
			csExp.close();
		}
	}
	
	public static void aa0_aa1_auto_qfact(Context context){
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
		if (Utilis.haveInternet(context) && of_line!=0 && Utilis.toInt(Utilis.getIni(context, "CLOUD", "AUTO", 6))>0){
			//SERVER的時間與LOCAL時間不同調,不可混談
			String Tnow =DateUtil.getSystemTime().substring(2, 12);
			//也要帶到sendPostRunnableQC 更新
			String T5=Utilis.getIni(context, "SYS", "SEASON", 5);
			String T6=Utilis.getIni(context, "SYS", "SEASON", 6);
			if (((Utilis.toDouble(Tnow)-Utilis.toDouble(T5))>5) || (!Tnow.equalsIgnoreCase(T5) && !T6.equalsIgnoreCase("0")) ){
				//距上次更新1分鐘以上
      		  Utilis.putIni(context, "SYS", "SEASON",Tnow ,5 );  //確保能夠還原可以再度同步
      		  Utilis.putIni(context, "SYS", "SEASON","0" ,6 );
				String mBankn=Utilis.getIni(context, "SYS", "DEPT",1)+Utilis.getIni(context, "SYS", "DEPT",2);//門市代號+機號		
				StringBuffer bfstr = new StringBuffer();
				StringBuffer bfstrF = new StringBuffer();
					bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
					bfstrF.append("UID").append(";");
					bfstr.append(mBankn).append(";");
					bfstrF.append("QDEPTNO").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2)).append(";");
					bfstrF.append("QYEARS").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "AUPDATE", 6));
					bfstrF.append("LUPDATE");
			          try
			          { 
							Thread t = new Thread(new sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),18));
							t.start();
							//Thread.sleep(2000);
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			          }
			}
		}
	}

	public static void user_update(Context context){
		StringBuffer bfstr = new StringBuffer();
		StringBuffer bfstrF = new StringBuffer();
			bfstr.append("3g001").append(";");
			bfstrF.append("UID").append(";");
			bfstr.append(Utilis.getIni(context, "SYS", "IMEI", 8)).append(";");
			bfstrF.append("T8").append(";");
			bfstr.append(Utilis.getIni(context, "USER", "COMPANY", 1)).append(";");
			bfstrF.append("COMPANY").append(";");
			bfstr.append(Utilis.getIni(context, "SYS", "IMEI", 3)).append(";");
			bfstrF.append("T3").append(";");
			bfstr.append(Utilis.getIni(context, "SYS", "IMEI", 4)).append(";");
			bfstrF.append("T4").append(";");
			bfstr.append(Utilis.getIni(context, "SYS", "IMEI", 7)).append(";");
			bfstrF.append("T7").append(";");
			bfstr.append(Utilis.getIni(context, "SYS", "IMEI", 5)).append(";");
			bfstrF.append("T5").append(";");
			bfstr.append(Utilis.getIni(context, "SYS", "IMEI", 6)).append(";");
			bfstrF.append("T6").append(";");
			bfstr.append(Utilis.getIni(context, "SYS", "IMEI", 1)).append(";");
			bfstrF.append("T1").append(";");
			bfstr.append(Utilis.getIni(context, "SYS", "IMEI", 2)).append(";");
			bfstrF.append("T2").append(";");
			bfstr.append(Utilis.getIni(context, "USER", "COMPANY", 3)).append(";");
			bfstrF.append("ADDRESS").append(";");
			bfstr.append(Utilis.getIni(context, "USER", "COMPANY", 2)).append(";");
			bfstrF.append("EMAIL").append(";");
			bfstr.append(Utilis.getIni(context, "SYS", "DEPT", 1)).append(";");
			bfstrF.append("DEPTNO").append(";");
			bfstr.append(Utilis.getIni(context, "SYS", "DEPT", 2)).append(";");
			bfstrF.append("DEVICENO").append(";");
			//ENDing
			bfstr.append(Utilis.getIni(context, "USER", "COMPANY", 4));
			bfstrF.append("MOBIL");
	          try
	          { 
	      		Thread t = new Thread(new DBCloud.sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),13));
	    		t.start();
					//Thread.sleep(2000);
	          }
	          catch (Exception e)
	          {
	            e.printStackTrace();
	          }
	          finally
	          {
	          }
	}	
	
	public static void aa0_aa1_auto_qcust(Context context){
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
		if (Utilis.haveInternet(context) && of_line!=0 && Utilis.toInt(Utilis.getIni(context, "CLOUD", "AUTO", 7))!=0){
			//SERVER的時間與LOCAL時間不同調,不可混談
			String Tnow =DateUtil.getSystemTime().substring(2, 12);
			//也要帶到sendPostRunnableQC 更新
			String T7=Utilis.getIni(context, "SYS", "SEASON", 7);
			String T8=Utilis.getIni(context, "SYS", "SEASON", 8);
			if (((Utilis.toDouble(Tnow)-Utilis.toDouble(T7))>5) || (!Tnow.equalsIgnoreCase(T7) && !T8.equalsIgnoreCase("0")) ){
	      		  Utilis.putIni(context, "SYS", "SEASON",Tnow ,7 );  //確保能夠還原可以再度同步
	      		  Utilis.putIni(context, "SYS", "SEASON","0" ,8 );
				String mBankn=Utilis.getIni(context, "SYS", "DEPT",1)+Utilis.getIni(context, "SYS", "DEPT",2);//門市代號+機號		
				StringBuffer bfstr = new StringBuffer();
				StringBuffer bfstrF = new StringBuffer();
					bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
					bfstrF.append("UID").append(";");
					bfstr.append(mBankn).append(";");
					bfstrF.append("QDEPTNO").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2)).append(";");
					bfstrF.append("QYEARS").append(";");
					bfstr.append(Utilis.getIni(context, "SYS", "AUPDATE", 7));
					bfstrF.append("LUPDATE");
			          try
			          { 
							Thread t = new Thread(new sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),20));
							t.start();
							//Thread.sleep(2000);
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			          }
			}
		}
	}
	
	public static void aa1_aa0_qfact(Context context){
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
		if (Utilis.haveInternet(context) && of_line!=0){
			//SERVER的時間與LOCAL時間不同調,不可混談
			String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",6);	
			String mBankn=Utilis.getIni(context, "SYS", "DEPT",1)+Utilis.getIni(context, "SYS", "DEPT",2);//門市代號+機號
			SQLiteDatabase db = Utilis.getDB(context);
			Cursor csExp = null;
			String sepa="\r\n";

			StringBuffer bufQ= new StringBuffer();
	        bufQ.delete(0, bufQ.toString().length());
			bufQ.append("select * from qfact");
			bufQ.append(" where STATE<>'0'");
			bufQ.append(" order by FACTNO");
			csExp = db.rawQuery(bufQ.toString(), null);
			if (csExp.getCount()>0){
		 		String FileH=myImportPath+File.separator+Utilis.getIni(context, "SYS", "DEPT", 1)+Utilis.getIni(context, "SYS", "DEPT", 2)+"_aa0_qfact.csv"; 
				String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		 		
				File hFile = new File(FileH);
				try{
						BufferedWriter bwH = new BufferedWriter(new FileWriter(hFile));					 		
						csExp.moveToFirst();
						
						for (int i=0;i<csExp.getCount();i++){
							for (int j=0;j<csExp.getColumnCount()-1;j++){
								String mWdata=chkStrB(csExp.getString(j));
								bwH.write(mWdata+";");
							}
							bwH.write(csExp.getString(csExp.getColumnCount()-1)+sepa);

							String LocalPath=csExp.getString(csExp.getColumnIndex("PIC"));
							if (LocalPath != null && LocalPath.indexOf("cwbuyer")>0 && LocalPath.indexOf("04.jpg")<=0){
								String serverPath =LocalPath.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
								try {
								File pFile= new File(LocalPath);
									DBCloud.ftpUpdateFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverPath, pFile);
								} catch (IOException e) {
								// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}	
							
							csExp.moveToNext();
						}
						bwH.close();
			        	boolean success=false;
			        	
						try {
							success=DBCloud.ftpUpdateFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileH, hFile);
							//先寄出QITEMS 後寄出QHEAD sucesss以QHEAD為主
							//不宜做出 判斷空檔案 即使 空檔案 也要傳出 使 SERVER端 的FILE 覆蓋為最新的
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						if (success){ //如果檔案上傳成功就呼叫 PHP
							StringBuffer bfstr = new StringBuffer();
							StringBuffer bfstrF = new StringBuffer();
								bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
								bfstrF.append("UID").append(";");
								bfstr.append(mBankn).append(";");
								bfstrF.append("QDEPTNO").append(";");
								bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2)).append(";");
								bfstrF.append("QYEARS");
						          try
						          { 
										Thread t = new Thread(new DBCloud.sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),17));
										t.start();
										//Thread.sleep(2000);
						          }
						          catch (Exception e)
						          {
						            e.printStackTrace();
						          }
						          finally
						          {
						          }
						} else {  //上傳更新檔案失敗
//							Toast.makeText(context, "", Toast.LENGTH_LONG).show();							
						}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			db.close();
			csExp.close();
		}
	}
	
	@SuppressWarnings("unused")
	public static void aa1_aa0_qcust(Context context){
		int of_line=Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3));
		if (Utilis.haveInternet(context) && of_line!=0){
			//SERVER的時間與LOCAL時間不同調,不可混談
			String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(context, "SYS", "YEAR",6);	
			String mBankn=Utilis.getIni(context, "SYS", "DEPT",1)+Utilis.getIni(context, "SYS", "DEPT",2);//門市代號+機號
			String mDeptno=Utilis.getIni(context, "SYS", "DEPT",1);
			SQLiteDatabase db = Utilis.getDB(context);
			Cursor csExp = null;
			String sepa="\r\n";

			StringBuffer bufQ= new StringBuffer();
	        bufQ.delete(0, bufQ.toString().length());
			bufQ.append("select * from qcust");
			bufQ.append(" where STATE<>'0'");
			bufQ.append(" order by CUSTNO");
			csExp = db.rawQuery(bufQ.toString(), null);
			if (csExp.getCount()>0){
		 		String FileH=myImportPath+File.separator+Utilis.getIni(context, "SYS", "DEPT", 1)+Utilis.getIni(context, "SYS", "DEPT", 2)+"_aa0_qcust.csv"; 
				String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
		 		
				File hFile = new File(FileH);
				try{
						BufferedWriter bwH = new BufferedWriter(new FileWriter(hFile));					 		
						csExp.moveToFirst();
						
						for (int i=0;i<csExp.getCount();i++){
							for (int j=0;j<csExp.getColumnCount()-1;j++){
								//@@@須檢查不好的欄位內容
								String mWdata=chkStrB(csExp.getString(j));
								bwH.write(mWdata+";");
							}
							bwH.write(csExp.getString(csExp.getColumnCount()-1)+sepa);
							
							String LocalPath=csExp.getString(csExp.getColumnIndex("PIC"));
							if (LocalPath != null && LocalPath.indexOf("cwbuyer")>0 && LocalPath.indexOf("04.jpg")<=0){
								String serverPath =LocalPath.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
								try {
								File pFile= new File(LocalPath);
									DBCloud.ftpUpdateFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverPath, pFile);
								} catch (IOException e) {
								// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}	
							csExp.moveToNext();
						}
						bwH.close();
			        	boolean success=false;
			        	
						try {
							success=DBCloud.ftpUpdateFile(context,Utilis.getIni(context, "SYS", "IMPORT",1), 21,Utilis.getIni(context, "SYS", "IMPORT",4), Utilis.getIni(context, "SYS", "IMPORT",5), serverFileH, hFile);
							//先寄出QITEMS 後寄出QHEAD sucesss以QHEAD為主
							//不宜做出 判斷空檔案 即使 空檔案 也要傳出 使 SERVER端 的FILE 覆蓋為最新的
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						if (success){ //如果檔案上傳成功就呼叫 PHP
							StringBuffer bfstr = new StringBuffer();
							StringBuffer bfstrF = new StringBuffer();
								bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
								bfstrF.append("UID").append(";");
								bfstr.append(mBankn).append(";");
								bfstrF.append("QDEPTNO").append(";");
								bfstr.append(Utilis.getIni(context, "SYS", "YEAR", 1)+Utilis.getIni(context, "SYS", "YEAR", 2)).append(";");
								bfstrF.append("QYEARS");
								
						          try
						          { 
										Thread t = new Thread(new DBCloud.sendPostRunnableQC(context,bfstr.toString(),bfstrF.toString(),19));
										t.start();
										//Thread.sleep(2000);
						          }
						          catch (Exception e)
						          {
						            e.printStackTrace();
						          }
						          finally
						          {
						          }
						} else {  //上傳更新檔案失敗
//							Toast.makeText(context, "", Toast.LENGTH_LONG).show();							
						}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			db.close();
			csExp.close();
		}
	}

	public static String chkStr(String mChkString){
		String mWdata=mChkString;
		if (mWdata!=null && mWdata.indexOf("'")>=0) mWdata=mWdata.replace("'", "");
		if (mWdata!=null && mWdata.indexOf("\r\n")>=0) mWdata=mWdata.replace("\r\n", "");
		if (mWdata!=null && mWdata.indexOf("\r")>=0) mWdata=mWdata.replace("\r", "");
		if (mWdata!=null && mWdata.indexOf("\n")>=0) mWdata=mWdata.replace("\n", "");
		if (mWdata!=null && mWdata.indexOf("\\")>=0) mWdata=mWdata.replace("\\", "");
		if (mWdata!=null && mWdata.indexOf("\"")>=0) mWdata=mWdata.replace("\"", "");
		if (mWdata!=null && mWdata.indexOf(" ")>=0) mWdata=mWdata.replace(" ", "");
		// ; 分號如何擋住
		//@@@萬一null 傳回 "" 考慮是否需要		
		//if (mWdata==null) mWdata=""; 
		return mWdata;
	}
	
	public static String chkStrB(String mChkString){
		String mWdata=mChkString;
		if (mWdata!=null && mWdata.indexOf("'")>=0) mWdata=mWdata.replace("'", "");
		if (mWdata!=null && mWdata.indexOf("\r\n")>=0) mWdata=mWdata.replace("\r\n", "");
		if (mWdata!=null && mWdata.indexOf("\r")>=0) mWdata=mWdata.replace("\r", "");
		if (mWdata!=null && mWdata.indexOf("\n")>=0) mWdata=mWdata.replace("\n", "");
		if (mWdata!=null && mWdata.indexOf("\\")>=0) mWdata=mWdata.replace("\\", "");
		if (mWdata!=null && mWdata.indexOf("\"")>=0) mWdata=mWdata.replace("\"", "");
		if (mWdata!=null && mWdata.indexOf(" ")>=0) mWdata=mWdata.replace(" ", "");
		if (mWdata!=null && mWdata.indexOf(";")>=0) mWdata=mWdata.replace(";", "");
		if (mWdata!=null && mWdata.indexOf(",")>=0) mWdata=mWdata.replace(",", "");
		if (mWdata==null || mWdata.length()==0) mWdata="";
		return mWdata;
	}
	
	//FTP 將SERVER端的FILE DOWNLOAD 且存入指定的檔案 
	public static Boolean ftpDownloadAndSaveFile(Context context,String server, int portNumber,String user, String password, String serverFile, File localFile)  throws IOException {
	    FTPClient mFtp = null;

		File entryDir = new File(localFile.getParent());
	        if (!entryDir.exists()) entryDir.mkdirs();
	        
	    //圖片檔應該或可能為雲端空間(),有可能與雲端運算不一樣的伺服器
	    //雲端資料庫也要開啟FTP 並將上傳下載的傳輸檔放置(3g001)
			  
        boolean success = false;
	    try {
	        mFtp = new FTPClient();
	        mFtp.setConnectTimeout(50000);
	        mFtp.connect(server, portNumber);
            int reply = mFtp.getReplyCode();
          	if (FTPReply.isPositiveCompletion(reply)) {
                if (mFtp.login(user, password)) {
				        mFtp.setFileType(FTP.BINARY_FILE_TYPE);
				        mFtp.enterLocalPassiveMode();
				        OutputStream outputStream = null;
				        try {
			        		if (mFtp.listFiles(serverFile).length>0){	        		
				        		outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
				        		success = mFtp.retrieveFile(serverFile, outputStream);
				        	}
				        } finally {
				            if (outputStream != null) {
				                outputStream.close();
				            }
				        }
                }
          	}
	    } finally {

	        if (mFtp != null) {
	        	mFtp.logout();
	        	mFtp.disconnect();
	        }
	    }
        return success;
	}

	public static Boolean ftpUpdateFile(Context context,String server, int portNumber,String user, String password, String serverFile, File localFile)  throws IOException {
	    FTPClient mFtp = null;
	    //圖片檔應該或可能為雲端空間(),有可能與雲端運算不一樣的伺服器
	    //雲端資料庫也要開啟FTP 並將上傳下載的傳輸檔放置(3g001)
        boolean success = false;
	    
	    try {
	        mFtp = new FTPClient();
	        mFtp.setConnectTimeout(50000);
	        mFtp.connect(server, portNumber);
            int reply = mFtp.getReplyCode();
          	if (FTPReply.isPositiveCompletion(reply)) {
                if (mFtp.login(user, password)) {
				        mFtp.setFileType(FTP.BINARY_FILE_TYPE);
				        mFtp.enterLocalPassiveMode();
				        InputStream inputStream = null;
				        try {
				        	if (localFile.exists()){
				        		inputStream = new BufferedInputStream(new FileInputStream(localFile));
				        		success = mFtp.storeFile(serverFile, inputStream);
				        	}
				        } finally {
				            if (inputStream != null) {
				                inputStream.close();
				            }
				        }
                }
          	}
	    } finally {

	        if (mFtp != null) {
	        	mFtp.logout();
	        	mFtp.disconnect();
	        }
	    }
        return success;
	}
	
}
