package com.cwbuyer.lib;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import org.apache.http.conn.util.InetAddressUtils;

import com.cwbuyer.format.PItemData;
import com.cwbuyer.main.APos.PItemKind;
import com.pwbuyer.main.R;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

public class PosUtilis {
	
	public static StringBuffer getPrintKind(Context cnt,int selectPaper){
		String sepa="\r\n";
		StringBuffer sPrintB= new StringBuffer();
		sPrintB.append("^QXXXX,0,0"+sepa);
		if (selectPaper==3 || selectPaper==4) sPrintB.append("^W80"+sepa); else if (selectPaper==5 || selectPaper==6) sPrintB.append("^W100"+sepa); else  sPrintB.append("^W56"+sepa);
		sPrintB.append("^H8"+sepa+"^P1"+sepa+"^S4"+sepa+"^AD"+sepa+"^C1"+sepa+"^R0"+sepa+"~Q+0"+sepa
		+"^O0"+sepa+"^D0"+sepa+"^E11"+sepa+"~R20"+sepa+"^L"+sepa+"Dy2-me-dd"+sepa+"Th:m:s"+sepa);

		return sPrintB;
	}

	@SuppressWarnings("unused")
	public static void startPrint(Context cnt,StringBuffer sPrintB,int Loca ){
		if (sPrintB.toString().length()>0){
//			final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(cnt, "SYS", "YEAR",7);	
			String lenS="0000"+(int)(Loca/7.2);
			sPrintB.replace(2, 6,lenS.substring(lenS.length()-4,lenS.length()));
			sPrintB.append("E\r\n");
	        boolean Succed=false;
			String address=null;
			int port=0;
			int success=1;
			   address = PosUtilis.getIni(cnt, "SYS","BAR_IP", 4);// 連線的ip
			   port =toInt(PosUtilis.getIni(cnt, "SYS","BAR_IP", 5));// 連線的port
				 InetAddress serverAddr = null;
			        SocketAddress sc_add = null;
			        Socket socket = new Socket();
						 try {
							 serverAddr = InetAddress.getByName(address);
							 sc_add= new InetSocketAddress(serverAddr,port);
								 socket.connect(sc_add,5000);
								 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
								 byte data[] = new String(sPrintB.toString().getBytes("UTF8")).getBytes("BIG5");
				                    SystemClock.sleep(500);
								 out.write(data, 0, data.length);
				                    SystemClock.sleep(500);
				                 out.flush();
								// socket.close();
								 Toast.makeText(cnt, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
								 Succed=true;
						 } catch (UnknownHostException e) {
							 success=0;
						 } catch (SocketException e) {
							 success=0;
						 } catch(IOException e) {
							 success=0;
						 } finally{
							 try {
									socket.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}				 
							 }
			}
		
		
	}
		
	
	public static void startPostPrint(Context cnt,String CustNo,String[] compStr ){
		SQLiteDatabase db = Utilis.getDB(cnt);
		StringBuffer sPrintB =new StringBuffer();
		Cursor cs=db.rawQuery("select CUSTNO,CUSTNAME,ADDRESS,MOBIL from qcust where CUSTNO='"+CustNo+"'", null);
		sPrintB.delete(0, sPrintB.toString().length());
		String sepa="\r\n";
		
		if (cs.getCount()>0) {
			cs.moveToFirst();
			sPrintB.append("^QXXXX,0,0"+sepa);
			 if (PosUtilis.toInt(compStr[8])<=2) sPrintB.append("^W56"); else sPrintB.append("^W80");				
			 sPrintB.append(sepa+"^H8"+sepa+"^P1"+sepa+"^S4"+sepa+"^AD"+sepa+"^C1"+sepa+"^R0"+sepa+"~Q+0"+sepa
			+"^O0"+sepa+"^D0"+sepa+"^E11"+sepa+"~R20"+sepa+"^L"+sepa+"Dy2-me-dd"+sepa+"Th:m:s"+sepa);
			 if (PosUtilis.toInt(compStr[8])<=2){ //W56				 
				sPrintB.append("AZ,424,96,3,3,0,1,"+cs.getString(2)+"-"+cs.getString(3)+" 收"+sepa);
				sPrintB.append("AZ,320,98,6,6,0,1,"+cs.getString(0)+"-"+cs.getString(1)+" 收"+sepa);
				sPrintB.append("AZ,96,266,3,3,0,1,"+compStr[0]+"/"+compStr[3]+"寄"+sepa);
				sPrintB.append("E"+sepa);
			 }else{ //W80
				sPrintB.append("AZ,570,96,3,3,0,1,"+cs.getString(2)+sepa);
				sPrintB.append("AZ,490,96,3,3,0,1,"+cs.getString(3)+" 收"+sepa);
				sPrintB.append("AZ,360,98,6,6,0,1,"+cs.getString(0)+"-"+cs.getString(1)+" 收"+sepa);
				sPrintB.append("AZ,120,266,3,3,0,1,"+compStr[0]+"/"+compStr[3]+"寄"+sepa);
				sPrintB.append("E"+sepa);
			 }
		}
		db.close();
		cs.close();
		
		if (sPrintB.toString().length()>0) PosUtilis.startPartPrint(cnt,sPrintB,1800 );
	}
	
	@SuppressWarnings("unused")
	public static void startPartPrint(Context cnt,StringBuffer sPrintB,int Loca ){
		if (sPrintB.toString().length()>0){
//			final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(cnt, "SYS", "YEAR",7);	
			String lenS="0000"+(int)(Loca/7.9);
			sPrintB.replace(2, 6,lenS.substring(lenS.length()-4,lenS.length()));
			sPrintB.append("E\r\n");
	        boolean Succed=false;
			String address=null;
			int port=0;
			int success=1;
			   address = PosUtilis.getIni(cnt, "SYS","BAR_IP", 4);// 連線的ip
			   port =toInt(PosUtilis.getIni(cnt, "SYS","BAR_IP", 5));// 連線的port
				 InetAddress serverAddr = null;
			        SocketAddress sc_add = null;
			        Socket socket = new Socket();
						 try {
							 serverAddr = InetAddress.getByName(address);
							 sc_add= new InetSocketAddress(serverAddr,port);
								 socket.connect(sc_add,5000);
								 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
								 byte data[] = new String(sPrintB.toString().getBytes("UTF8")).getBytes("BIG5");
				                    SystemClock.sleep(500);
								 out.write(data, 0, data.length);
				                    SystemClock.sleep(500);
				                 out.flush();
								// socket.close();
								 Toast.makeText(cnt, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
								 Succed=true;
						 } catch (UnknownHostException e) {
							 success=0;
						 } catch (SocketException e) {
							 success=0;
						 } catch(IOException e) {
							 success=0;
						 } finally{
							 try {
									socket.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}				 
						 }
			}
		
		
	}
		
	public static void openCashDraw(Context cnt){
		String address=null;
		int port=0;
		   address = PosUtilis.getIni(cnt, "SYS","BAR_IP", 6);// 連線的ip
		   port =toInt(PosUtilis.getIni(cnt, "SYS","BAR_IP", 7));// 連線的port

	 InetAddress serverAddr = null;
        SocketAddress sc_add = null;
        Socket socket = new Socket();

			 try {
				 serverAddr = InetAddress.getByName(address);
				 sc_add= new InetSocketAddress(serverAddr,port);
					 socket.connect(sc_add,2000);
					 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
					 byte data[] = new String(((char)27+"p"+(char)0+(char)100+(char)250).getBytes("UTF8")).getBytes("BIG5");
					 out.write(data, 0, data.length);
					 Toast.makeText(cnt, "錢櫃開啟了!!", Toast.LENGTH_LONG).show();

			 } catch (UnknownHostException e) {

			 } catch (SocketException e) {
				 Toast.makeText(cnt, "錢櫃連線失敗!!", Toast.LENGTH_LONG).show();
			 } catch(IOException e) {
				 Toast.makeText(cnt, "關鍵檔案開啟失敗!!", Toast.LENGTH_LONG).show();
			 } finally{
				 try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				 
			 }
	}

	public static int toInt(String number){
		try{
			if(number == null || number.length() <= 0){
				return 0;
			}else{
				try{
					if (number.indexOf("%")>0) number=number.substring(0,number.indexOf("%"));
					if (number.indexOf(".")>0) number=number.substring(0,number.indexOf("."));
					return Integer.valueOf(number.trim());
				}catch(Exception e){
					e.printStackTrace();
					return 0;
				}
			}
		}catch(Exception e){
			return 0;
		}
	}
	
	//尋找一張存單 目前為了 留貨轉銷貨mMode=2 before go to GalleryViewO
	public static String getFno(Context context,String User,String msKind,int custOrFact){
		//custOrFact 0.cust 1.fact
		String msFno="";
		PItemData datax = new PItemData(); //##格式化需考量內容增刪
		String[] deptStr =Utilis.getIni(context,"SYS","DEPT",9).split("!&!");
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cursorC=null;
		datax.mUser=User;
		if (custOrFact==0)
			cursorC=db.rawQuery("select CUSTNAME,TRADETYPE,DISCOUNT from qcust where CUSTNO='"+User+"'",null);
		else
			cursorC=db.rawQuery("select FACTNAME,TRADETYPE,DISCOUNT from qfact where FACTNO='"+User+"'",null);
		
		if (cursorC.getCount()>0){
			cursorC.moveToFirst();
			datax.mUsername=cursorC.getString(0);
			datax.nTrade=cursorC.getInt(1);
			datax.dDiscount=cursorC.getDouble(2);
		}		
		cursorC.close();

		int NisEmpty=0;  //0.真空單 1.已存在的暫存單 2.
		Cursor cs = null;
		Cursor csi =null;
		StringBuffer mySqlBuf = new StringBuffer();
		mySqlBuf.append("select FORMNO from qhead");
		mySqlBuf.append(" where TR<>'Y2' and USER='"+User+"' and ISCONFIRM='N' and ISCHECK='N' and FORMNO like '"+(deptStr[0]+deptStr[1]+msKind.substring(0,1)+DateUtil.getCurrentYearFormat1().substring(0, 2))+"%'");
		mySqlBuf.append(" order by ATOT desc LIMIT 1");
		//先搜尋是否有,暫存單
		cs = db.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){ //That it
			cs.moveToFirst();
			msFno=cs.getString(0);
			NisEmpty=2;
		}else{
			mySqlBuf.delete(0,mySqlBuf.toString().length());
			mySqlBuf.append("select FORMNO,HANDNO from qhead");
			mySqlBuf.append(" where TR<>'Y2' and ISCONFIRM='N' and ISCHECK='N' and FORMNO like '"+(deptStr[0]+deptStr[1]+msKind.substring(0,1)+DateUtil.getCurrentYearFormat1().substring(0, 2))+"%'");
			mySqlBuf.append(" and ATOT=0 and ASUM=0 and CASH=0 and CARD=0 and ORDCASH=0 and ORDCARD=0 and ATM=0");			
			mySqlBuf.append(" order by FORMNO desc LIMIT 10");  //找有否空單,消化
			Cursor csf = db.rawQuery(mySqlBuf.toString(), null);
			if (csf.getCount()>0) { //表示有空單可沿用,但要求證
				while (csf.moveToNext()) {
					String mFno=csf.getString(cs.getColumnIndex("FORMNO"));
					mySqlBuf.delete(0,mySqlBuf.toString().length());
					mySqlBuf.append("select FORMNO from qitems");
					mySqlBuf.append(" where FORMNO ='"+mFno+"'");
					csi=db.rawQuery(mySqlBuf.toString(), null);
					if (csi==null || csi.getCount()<=0){
						NisEmpty=1;
						msFno=mFno;
						break;
					}
					   csi.close();
				 }  
			} csf.close();
		}
		cs.close();
		
		if (NisEmpty==2){
			db.close();
			return msFno;
		}	
		if (NisEmpty==0)	msFno = getNFormno(context,db,msKind.substring(0,1)); //新單號 以門市代號2+機號1+單別1+年1,做為流水號的基礎
		String FormD=DateUtil.getCurrentDate();  //2012-10-22
		int Ttime=toInt(DateUtil.getSystemTime().substring(8, 10));  //取得目前幾點
		if (Ttime<=5)  FormD = DateUtil.addDate(FormD, -1);
		FormD = FormD.replace("/", "-");
    	datax.mTR=msKind;  //視為新的空單到存入都OK
    	datax.nID=0;
    	datax.mDeptno =deptStr[0];
    	datax.mIslist = deptStr[1]; //機號    	
    	datax.mFormdate=FormD;
    	datax.mIsconfirm="N";
    	datax.mIscheck="N";
    	datax.mEmpid=PosUtilis.getIni(context,"INIH","EMPID",(toInt(msKind)/10)); //預設櫃員代號
    	datax.mEmpname=PosUtilis.getIni(context,"INIH","EMPNAME",(toInt(msKind)/10)); //櫃員名稱
    	datax.mBankno=PosUtilis.getIni(context,"INIH","BANK",(toInt(msKind)/10));
    	datax.mBankname=deptStr[0]+deptStr[1];
    	datax.dRate=Utilis.toDouble(PosUtilis.getIni(context,"INIH","BANKRATE",(toInt(msKind)/10))); //交易的匯率
    	datax.mFno=msFno;
		datax.mHandno="+0";	//理論上是貨品明細"+5 -1"
		datax.mOrddate="";	//KEYIN
		datax.mFinedate="";	//KEYIN
 		datax.dOrdcash=0;	//KEYIN
		datax.dOrdcard=0;	//KEYIN
		datax.dCash=0;			//KEYIN
		datax.dCard=0;			//KEYIN
		datax.dAtot=0;  		//總件數	<--來自於ITEMS的統計累加 UNIT10 20 30 40 等１不同單據
		datax.dAsum=0; 		//應收		<--來自於ITEMS的統計累加 SUBPRICE
		datax.dBsum=0; 		//實收 		<--使用者的強制輸入
		datax.dCosts=0; 		//總成本 <--來自於ITEMS的統計累加 ACOST
		datax.dTuresum=0;	//換算匯率後的實際金額 edBsum*edRate
		datax.dDismoney=0;//折讓=應收-實收
		datax.dAtm=0;
		datax.dTrcash=0;
		datax.mhPs="";
		datax.mhPs1="";
		datax.mhPs2="";
		datax.dInc=0;
		datax.dMic=0;
		
		ContentValues value = new ContentValues();
		
		value.put("TR", msKind);
		value.put("QKIND", msKind);
		value.put("FORMNO", msFno);
		value.put("HANDNO", datax.mHandno);
		
		value.put("FORMDATE", datax.mFormdate);
		value.put("CREATEDATETIME", DateUtil.getSystemTime().substring(2,14));
		//@@@
		value.put("ISCONFIRM", datax.mIsconfirm);
		value.put("ISCHECK", datax.mIscheck);

		value.put("EMPID", datax.mEmpid);
		value.put("EMPNAME", datax.mEmpname);
		value.put("USER", datax.mUser);
		value.put("USERNAME", datax.mUsername);
		value.put("TRADETYPE", datax.nTrade);
		value.put("DEPTNO", datax.mDeptno);
		value.put("ID", "0"); // 
		value.put("ISLIST", "");
		value.put("ORDCASH", 0);
		value.put("ORDCARD", 0);
		value.put("CASH", 0);
		value.put("CARD", 0);
		value.put("ATOT", 0);
		value.put("ORDDATE", "");
		value.put("FINEDATE","");
		value.put("ASUM",0);
		value.put("BSUM",0);
		value.put("BILLRATE",0);
		value.put("TURESUM",0);
		value.put("DISMONEY",0);
		value.put("ATM",0);
		value.put("TRCASH",0);
		value.put("ATMDATE","");
		value.put("PS","");
		value.put("PS1","");
		value.put("PS2","");

		value.put("BANKNO",datax.mBankno);
		value.put("BANKNAME",datax.mBankname);
		
		if (NisEmpty==0){
			db.insert(TbName.QHEAD, null, value);
		} else {
			String[] args = {msFno};
			db.update(TbName.QHEAD, value,"FORMNO=? ", args);
		}
		
		db.close();
		return msFno;
	}

	public static String getNFormno(Context context,SQLiteDatabase db,String formf){
		int flowNumber = 0;
		String msFno=PosUtilis.getIni(context,"SYS","DEPT",1)+PosUtilis.getIni(context,"SYS","DEPT",2)+formf+DateUtil.getCurrentYearFormat1().substring(0, 2);
		try{
			Cursor cursor = db.rawQuery("select FORMNO from " + TbName.QHEAD + " where FORMNO like '"+msFno+"%' order by FORMNO DESC limit 1", null);
			if(cursor != null){
				try{
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						flowNumber = toInt(cursor.getString(cursor.getColumnIndex("FORMNO")).substring(msFno.length()))+1;
					}
				}catch(Exception e){
					e.printStackTrace();
				}
				cursor.close();
			}else{ //新的開始單號
				flowNumber=1;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return msFno+Utilis.formatFlow(flowNumber);
	}
	
	
	
	@SuppressWarnings("unused")
	public static void printDayOf20213031(Context context,String theDay,int Mode){
		//全珈 除了所有的出貨單以及所有各門市銷貨單入金等等
		//總結的規劃,印製在下方
		//出貨單清單
		int PrintOK=0;
		String SQL2021H=" select DEPTNO,USER,USERNAME,FORMNO,HANDNO,BSUM from QHEAD"+ 
		" where FORMDATE='"+theDay+"' and ISCONFIRM='Y' and (QKIND='20' or QKIND='21')"+
		" order by FORMNO";
		//銷貨單清單
		String SQL3031H="select DEPTNO,USER,USERNAME,FORMNO,HANDNO,BSUM,CASH,CARD,ATM,TRCASH,DISMONEY from QHEAD"+ 
		" where FORMDATE='"+theDay+"' and ISCONFIRM='Y' and (QKIND='30' or QKIND='31')"+
		" order by DEPTNO,FORMNO";
		//出貨單總結 總出貨 件數 金額 總退貨 件數 金額
		String SQLTOT2021P="select sum(SUBPRICE),sum(UNIT20) from QITEMS where FORMDATE='"+theDay+"' and QKIND='20' and ISCONFIRM='Y' and UNIT20>0";
		String SQLTOT2021M="select sum(SUBPRICE),sum(UNIT20) from QITEMS where FORMDATE='"+theDay+"' and QKIND='20' and ISCONFIRM='Y' and UNIT20<0";
		//銷貨總結 放在QHEAD
		String SQLTOT3031="select sum(BSUM),sum(ATOT),sum(CASH),sum(CARD),sum(ATM),sum(TRCASH),sum(DISMONEY) from QHEAD"+
		" where FORMDATE='"+theDay+"' and (QKIND='30' or QKIND='31') and ISCONFIRM='Y'";
		
		String compStr[]=Utilis.getIni(context,"USER","COMPANY",9).split("!&!");
		
		
		
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor csh=null; 
		
		String sepa="\r\n";
		StringBuffer sPrintB = new StringBuffer();
		sPrintB.append("^QXXXX,0,0"+sepa);
		int Loca=0;
		if (Utilis.toInt(compStr[8])<3){												
			sPrintB.append("^W56"+sepa);
		}else{
			sPrintB.append("^W80"+sepa);
		}
		sPrintB.append("^H8"+sepa+"^P1"+sepa+"^S4"+sepa+"^AD"+sepa+"^C1"+sepa+"^R0"+sepa+"~Q+0"+sepa
		+"^O0"+sepa+"^D0"+sepa+"^E11"+sepa+"~R20"+sepa+"^L"+sepa+"Dy2-me-dd"+sepa+"Th:m:s"+sepa);
		Loca=Loca+30;
		Loca=Loca+2;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+compStr[0]+" "+theDay+" 出貨.銷貨.結帳.總結單"+sepa);
		Loca=Loca+21;  //
		sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
		
		csh=db.rawQuery(SQL2021H, null);
		if (csh.getCount()>0){
			PrintOK=1;			
			Loca=Loca+45;sPrintB.append("AZ,15,"+Loca+",1,1,0,0,專櫃代號/名稱    出貨單號      件數       金額 "+sepa);
			Loca=Loca+12;  //
			sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
			while (csh.moveToNext()){
				Loca=Loca+50;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+csh.getString(1)+sepa);
				sPrintB.append("AZ,90,"+Loca+",1,2,0,0,"+csh.getString(2)+sepa);
				sPrintB.append("AZ,220,"+Loca+",1,2,0,0,"+csh.getString(3)+sepa);
				sPrintB.append("AZ,385,"+Loca+",1,2,0,0,"+csh.getString(4)+sepa);
				sPrintB.append("AZ,515,"+Loca+",1,2,0,0,"+csh.getString(5)+sepa);
			}//印完出貨清單
			Loca=Loca+35;  //
			sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
		}
		
		csh=db.rawQuery(SQLTOT2021P, null);
		if (csh.getCount()>0){
			PrintOK=1;			
			csh.moveToFirst();
			Loca=Loca+50;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,出貨小計: "+csh.getString(0)+sepa);
			sPrintB.append("AZ,385,"+Loca+",1,2,0,0,"+csh.getString(1)+" 件"+sepa);
		}		
		csh=db.rawQuery(SQLTOT2021M, null);
		if (csh.getCount()>0){
			PrintOK=1;			
			csh.moveToFirst();
			Loca=Loca+50;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,退貨小計: "+csh.getString(0)+sepa);
			sPrintB.append("AZ,385,"+Loca+",1,2,0,0,"+csh.getString(1)+" 件"+sepa);
		}		
		Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
		Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
		Loca=Loca+21;  //
		
		csh=db.rawQuery(SQL3031H, null);
		if (csh.getCount()>0){
			PrintOK=1;			
			Loca=Loca+45;sPrintB.append("AZ,15,"+Loca+",1,1,0,0,專櫃代號/名稱    銷貨單號      件數       金額 "+sepa);
			Loca=Loca+12;  //
			sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
			while (csh.moveToNext()){
				Loca=Loca+50;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+csh.getString(1)+sepa);
				sPrintB.append("AZ,90,"+Loca+",1,2,0,0,"+csh.getString(2)+sepa);
				sPrintB.append("AZ,220,"+Loca+",1,2,0,0,"+csh.getString(3)+sepa);
				sPrintB.append("AZ,385,"+Loca+",1,2,0,0,"+csh.getString(4)+sepa);
				sPrintB.append("AZ,515,"+Loca+",1,2,0,0,"+csh.getString(5)+sepa);
				String printS="";
				//CASH,CARD,ATM,TRCASH,DISMONEY
				if (csh.getDouble(6)!=0) printS+="入金:"+Math.round(csh.getDouble(6))+" / "; 
				if (csh.getDouble(7)!=0) printS+="票卡:"+Math.round(csh.getDouble(7))+" / "; 
				if (csh.getDouble(8)!=0) printS+="匯款:"+Math.round(csh.getDouble(8))+" / "; 
				if (csh.getDouble(9)!=0) printS+="代運:"+Math.round(csh.getDouble(9))+" / "; 
				if (csh.getDouble(10)!=0) printS+="折讓:"+Math.round(csh.getDouble(10)); 
				//可以因為沒有金額,而省略列印
				if (printS.length()>0){
					Loca=Loca+50;sPrintB.append("AZ,50,"+Loca+",1,1,0,0,"+printS+sepa);
				}
			}//印完銷貨清單
			Loca=Loca+30;  //
			sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
		}
		//兩種清冊已印完 //如下總結
		csh=db.rawQuery(SQLTOT3031, null);
		if (csh.getCount()>0){
			PrintOK=1;
			int stabx=20;int staby=50;
			//select sum(BSUM),sum(ATOT),sum(CASH),sum(CARD),sum(ATM),sum(TRCASH),sum(DISMONEY)
			csh.moveToFirst();
			Loca=Loca+staby;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,銷貨小計: "+Math.round(csh.getDouble(0))+sepa);
			sPrintB.append("AZ,385,"+Loca+",1,2,0,0,"+Math.round(csh.getDouble(1))+" 件"+sepa);
			if (csh.getDouble(2)!=0){
				Loca=Loca+staby;sPrintB.append("AZ,"+stabx+","+Loca+",1,2,0,0,現金: "+Math.round(csh.getDouble(2))+sepa);
				stabx=385;staby=0;
			}
			if(csh.getDouble(3)!=0){
				Loca=Loca+staby;sPrintB.append("AZ,"+stabx+","+Loca+",1,2,0,0,票卡: "+Math.round(csh.getDouble(3))+sepa);
				if (stabx==20) {stabx=385;staby=0;} else {stabx=20;staby=50;}
			}
			if(csh.getDouble(4)!=0){
				Loca=Loca+staby;sPrintB.append("AZ,"+stabx+","+Loca+",1,2,0,0,匯款: "+Math.round(csh.getDouble(4))+sepa);
				if (stabx==20) {stabx=385;staby=0;} else {stabx=20;staby=50;}
			}
			if(csh.getDouble(5)!=0){
				Loca=Loca+staby;sPrintB.append("AZ,"+stabx+","+Loca+",1,2,0,0,代墊: "+Math.round(csh.getDouble(5))+sepa);
				if (stabx==20) {stabx=385;staby=0;} else {stabx=20;staby=50;}
			}
			if(csh.getDouble(6)!=0){
				Loca=Loca+staby;sPrintB.append("AZ,"+stabx+","+Loca+",1,2,0,0,折讓: "+Math.round(csh.getDouble(6))+sepa);
			}
		}		
		Loca=Loca+21;  //
		sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
		Loca=Loca+40;  //
		
		db.close();
		csh.close();
		
		sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+" 印製:"+DateUtil.getCurrentTime()+sepa);
		Loca=Loca+30;  //
		
		if (sPrintB.toString().length()>0 && PrintOK==1){
			String lenS="0000"+(int)(Loca/7.32);
			sPrintB.replace(2, 6,lenS.substring(lenS.length()-4,lenS.length()));
			sPrintB.append("E"+sepa);
			
			String address=null;
			int port=0;
			int success=1;
			
			   address = Utilis.getIni(context, "SYS","BAR_IP", 4);// 連線的ip
			   port =Utilis.toInt(Utilis.getIni(context, "SYS","BAR_IP", 5));// 連線的port
				 InetAddress serverAddr = null;
			        SocketAddress sc_add = null;
			        Socket socket = null;
						 try {
							 serverAddr = InetAddress.getByName(address);
							 sc_add= new InetSocketAddress(serverAddr,port);
								 socket = new Socket();
								 socket.connect(sc_add,2000);
								 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
								 byte data[] = new String(sPrintB.toString().getBytes("UTF8")).getBytes("BIG5");
								 out.write(data, 0, data.length);
								 Toast.makeText(context, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();

						 } catch (UnknownHostException e) {
							 success=0;
						 } catch (SocketException e) {
							 success=0;
						 } catch(IOException e) {
							 success=0;
						 } finally{
							 try {
									socket.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}				 
							 }
						 
			}
		
	}
	
public static String getQMtrioArray(Context context,String kGoods,String kSplitColorNo,String kSplitColor,String kSplitSizes,String mDept,String mCountList , int nPart,int Mode){
		//Obj,Key,Index 都應該有值,否則返回
	String[] anames;	
	String[] anumber;
	String[] asizes;
	int  ttot[][]=new int [30][30];
	int  Otot [][]=new int [30][30];
	String returnValue="";

	if(kSplitSizes != null && kSplitSizes.length() > 0
		&& kSplitColorNo != null && kSplitColorNo.length() > 0
		&& kSplitColor != null && kSplitColor.length() > 0){
		    	
        	anumber = kSplitColorNo.split("，"); //取得各色號字串
        	anames = kSplitColor.split("，");
        	asizes = kSplitSizes.split(",");
	        	
        	if (Mode==0){
	        	for(int nRow = 0; nRow < anames.length; nRow++){
	        		String [] numberLevel1=mCountList.split("，");
	    			for(int i = 0 ; i < asizes.length; i++){
	    				String [] numberLevel2=numberLevel1[nRow].split(",");
	    					Otot[nRow][i]=Utilis.toInt(numberLevel2[i]);
	    				}
	    			}
        	}

		    	ttot =new int[(anumber.length)*3][(asizes.length)*6] ; //進銷存統計用
		    	for(int i = 0; i < (asizes.length*6);i++) for ( int j=0;j<(anumber.length)*3;j++){ttot[j][i]=0;}
				try{
			        SQLiteDatabase db = Utilis.getDB(context);		
					Cursor cs = null;
					StringBuffer mySqlBuf = new StringBuffer();

					if (nPart==0){
						mySqlBuf.append("select GOODSNO,COLOR,SIZE,ISCONFIRM,ISCHECK,QKIND,");
						mySqlBuf.append("sum(UNIT10),sum(UNIT20),sum(UNIT30),sum(UNIT40)");
						mySqlBuf.append(" from qitems");
						mySqlBuf.append(" where GOODSNO='" + kGoods+"'");
						mySqlBuf.append(" group by GOODSNO,COLOR,SIZE,ISCONFIRM,ISCHECK,QKIND");
						cs = db.rawQuery(mySqlBuf.toString(), null);
						if (cs.getCount()>0){
								while (cs.moveToNext()){  //從第一筆--最後一筆讀取
									String acol=cs.getString(cs.getColumnIndex("COLOR"));
									String asiz=cs.getString(cs.getColumnIndex("SIZE"));
									 int j=-1; for (int jj=0;jj<anumber.length;jj++) if (acol.equalsIgnoreCase(anumber[jj])) {j=jj;break;} 
									 int k=-1;for (int kk=0;kk<asizes.length;kk++) if (asiz.equalsIgnoreCase(asizes[kk])) {k=kk;break;} 
									   //顏色相符
										if (j>=0 && k>=0){
				  							if (Mode==0) ttot[j*3][k*6+3]=Otot[j][k]; //採購訂單量
				  							if (cs.getString(3).equalsIgnoreCase("Y")){  //表示 進出銷
				  								if (cs.getString(5).equalsIgnoreCase("10")){
					  								ttot[j*3][k*6]+=cs.getInt(6); //廠商進貨(進)
					  								ttot[j*3][k*6+2]+=cs.getInt(6);
					  								ttot[j*3][k*6+5]+=cs.getInt(6);
				  								}else if (cs.getString(5).equalsIgnoreCase("30") || cs.getString(5).equalsIgnoreCase("40") || cs.getString(5).equalsIgnoreCase("31") || cs.getString(5).equalsIgnoreCase("41")){ //總倉銷貨
					  								ttot[j*3][k*6+1]+=(cs.getInt(8)+cs.getInt(9)); //銷貨(銷)+
					  								ttot[j*3][k*6+2]-=(cs.getInt(8)+cs.getInt(9)); //銷貨(存)-
					  								if (cs.getString(5).equalsIgnoreCase("30") || cs.getString(5).equalsIgnoreCase("40")) ttot[j*3][k*6+5]-=(cs.getInt(8)+cs.getInt(9));
					  							}else if (cs.getString(5).equalsIgnoreCase("20")){
					  								ttot[j*3][k*6+5]-=cs.getInt(7); //出貨(存)-
					  							}
				  							}else if (cs.getString(4).equalsIgnoreCase("Y") && (cs.getString(5).equalsIgnoreCase("30") || cs.getString(5).equalsIgnoreCase("31")) ){ //預購OY NY 留貨RY
				  								if (cs.getString(3).equalsIgnoreCase("N") || cs.getString(3).equalsIgnoreCase("O")){ //預購
					  								ttot[j*3][k*6+4]+=cs.getInt(8); //銷(訂)+
					  								ttot[j*3][k*6+5]-=cs.getInt(8); //出貨(存)-
				  								}else if (cs.getString(3).equalsIgnoreCase("R")){//留貨
					  								ttot[j*3][k*6+1]+=cs.getInt(8); //銷貨(銷)+
					  								ttot[j*3][k*6+2]-=cs.getInt(8); //(存)+
					  								ttot[j*3][k*6+5]-=cs.getInt(8); //出貨(存)-
				  								}
					  						}else if (cs.getString(3).equalsIgnoreCase("N") && cs.getString(4).equalsIgnoreCase("N") && (cs.getString(5).equalsIgnoreCase("30") || cs.getString(5).equalsIgnoreCase("40"))){//
				  								ttot[j*3][k*6+1]+=(cs.getInt(8)+cs.getInt(9)); //銷貨(銷)+
				  								ttot[j*3][k*6+2]-=(cs.getInt(8)+cs.getInt(9)); //銷貨(存)-
				  								ttot[j*3][k*6+5]-=(cs.getInt(8)+cs.getInt(9)); //銷貨(存)-
					  							//暫存銷貨要視為銷貨並扣庫存
				  							}
				  						}
							}
						}
					} else { //nPart==1 門市的進銷存
						mySqlBuf.append("select GOODSNO,COLOR,SIZE,USER,QKIND,ISCONFIRM,ISCHECK,");
						mySqlBuf.append("sum(UNIT20) as SUM20,sum(UNIT30) as SUM30,sum(UNIT40) as SUM40");
						mySqlBuf.append(" from qitems where GOODSNO='" + kGoods+"' and (USER='"+mDept+"' or DEPTNO='"+mDept+"')");
						mySqlBuf.append(" group by GOODSNO,COLOR,SIZE,USER,QKIND,ISCONFIRM,ISCHECK");
						cs =null;
						cs = db.rawQuery(mySqlBuf.toString(), null);
						if (cs.getCount()>0){
							cs.moveToFirst();			
							for (int i=0;i<cs.getCount();i++){  //從第一筆--最後一筆讀取
									String acol=cs.getString(cs.getColumnIndex("COLOR"));
									String asiz=cs.getString(cs.getColumnIndex("SIZE"));
									
								for (int j=0;j<anumber.length;j++){
									if (acol.equalsIgnoreCase(anumber[j]))  { //顏色相符
				  						for (int k=0;k<asizes.length;k++){
					  						if (asiz.equalsIgnoreCase(asizes[k]))  { //尺寸相符  置入進銷存
				  							if (cs.getString(5).equalsIgnoreCase("Y")){
					  							if (cs.getString(4).equalsIgnoreCase("20") || (cs.getString(3).equalsIgnoreCase(mDept) && cs.getString(4).equalsIgnoreCase("21")) ) {  
					  								ttot[j*3][k*6]+=cs.getInt(7); //廠商進貨(進)
					  								ttot[j*3][k*6+2]+=cs.getInt(7);
					  								ttot[j*3][k*6+5]+=cs.getInt(7);
					  							} else if (cs.getString(4).equalsIgnoreCase("21") && !cs.getString(3).equalsIgnoreCase(mDept)){
					  								ttot[j*3][k*6+3]+=cs.getInt(7); //廠商進貨(進)
					  								ttot[j*3][k*6+2]-=cs.getInt(7);
					  								ttot[j*3][k*6+5]-=cs.getInt(7);
				  								} else  if (cs.getString(4).equalsIgnoreCase("31") || cs.getString(4).equalsIgnoreCase("41")){
					  								ttot[j*3][k*6+1]+=(cs.getInt(8)+cs.getInt(9)); //銷貨(銷)+
					  								ttot[j*3][k*6+2]-=(cs.getInt(8)+cs.getInt(9)); //銷貨(存)-
					  								ttot[j*3][k*6+5]-=(cs.getInt(8)+cs.getInt(9)); //銷貨(存)-
					  							}	
					  						}else if (cs.getString(4).equalsIgnoreCase("Y")){ //預購 留貨
				  								if (cs.getString(3).equalsIgnoreCase("N") || cs.getString(3).equalsIgnoreCase("O")){ //預購
					  								ttot[j*3][k*6+4]+=cs.getInt(8); //銷(訂)+
					  								ttot[j*3][k*6+5]-=cs.getInt(8); //出貨(存)-
				  								}else if (cs.getString(3).equalsIgnoreCase("R")){//留貨
					  								ttot[j*3][k*6+1]+=cs.getInt(8); //銷貨(銷)+
					  								ttot[j*3][k*6+2]-=cs.getInt(8); //(存)+
					  								ttot[j*3][k*6+5]-=cs.getInt(8); //出貨(存)-
				  								}
					  						}else if (cs.getString(3).equalsIgnoreCase("N") && cs.getString(4).equalsIgnoreCase("N") && (cs.getString(5).equalsIgnoreCase("31") || cs.getString(54).equalsIgnoreCase("41"))){//
				  								ttot[j*3][k*6+1]+=(cs.getInt(8)+cs.getInt(9)); //銷貨(銷)+
				  								ttot[j*3][k*6+2]-=(cs.getInt(8)+cs.getInt(9)); //銷貨(存)-
				  								ttot[j*3][k*6+5]-=(cs.getInt(8)+cs.getInt(9)); //銷貨(存)-
					  							//暫存銷貨要視為銷貨並扣庫存
					  						}
				  							break;
					  						}
				  						}
				  						break;
									}
								}
								cs.moveToNext();
							}
						}
						
					}
					cs.close();
					db.close();

					StringBuffer SB=new StringBuffer();
					for (int i=0;i<anumber.length;i++){
						for (int j=0;j<asizes.length;j++){
							if (Mode==0 && nPart==0) SB.append(""+ttot[i*3][j*6]+"("+ttot[i*3][j*6+3]+")").append(","); 
							else	SB.append(""+ttot[i*3][j*6]).append(",");
				  			SB.append(""+ttot[i*3][j*6+1]+"("+ttot[i*3][j*6+4]+")").append(",")
				  			.append(""+ttot[i*3][j*6+2]+"("+ttot[i*3][j*6+5]+")");
				  		if  ( j<(asizes.length-1)) {
				  			SB.append(",");
				  			}
				  		
						}
						if (i<(anumber.length-1)){	
							SB.append("，"); 
							}
					}
					
					returnValue=SB.toString();
					
				}catch(Exception e){
					e.printStackTrace();
				}
	
	} 
	    return returnValue;
}	
	
	public static String getIni(Context context,String Obj,String Key,int mode){
		//Obj,Key,Index 都應該有值,否則返回
		String value=null;		
	    try {
		      File file = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+ "/cwbuyer/para/ini.sdb");
		      SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, null);
		      
		      StringBuffer mBuf = new StringBuffer();
		      mBuf.append("select * from system where OBJ='"+Obj+"' and KEY='"+Key+"'");
		      Cursor cs = db.rawQuery(mBuf.toString(), null);
		      if (cs.getColumnCount()>0){
		    	  cs.moveToFirst();
		    	  int index = cs.getInt(cs.getColumnIndex("POINT"));
		    	  if(mode==0){ //有預設值
		    		  value=cs.getString(index+3);
		    	  } else if (mode>=1 && mode <=8){
		    		  value=cs.getString(mode+3);  //指定要求值
		    	  }else if(mode==9){ //全數帶回  
		    		  StringBuffer Buf = new StringBuffer();
		    		  Buf.append(cs.getString(cs.getColumnIndex("T1"))+",")
		    		  .append(cs.getString(cs.getColumnIndex("T2"))+",")
		    		  .append(cs.getString(cs.getColumnIndex("T3"))+",")
		    		  .append(cs.getString(cs.getColumnIndex("T4"))+",")
		    		  .append(cs.getString(cs.getColumnIndex("T5"))+",")		    		  
		    		  .append(cs.getString(cs.getColumnIndex("T6"))+",")
		    		  .append(cs.getString(cs.getColumnIndex("T7"))+",")
		    		  .append(cs.getString(cs.getColumnIndex("T8"))+",")
		    		  .append(cs.getString(cs.getColumnIndex("T9")));
		    		  value=Buf.toString();
		    	  }
		      }
		      cs.close();
		      db.close();
	    } catch (SQLException e) {
		      return null;	    	
	    }
		return value;
	}
	
	//取得LOCAL_IP_ADDRESS
	public static String getLocalIpAddress() {
		String ip=null;
	    try {
	        for (Enumeration<NetworkInterface> en = NetworkInterface
	                .getNetworkInterfaces(); en.hasMoreElements();) {
	            NetworkInterface intf = en.nextElement();
	            for (Enumeration<InetAddress> enumIpAddr = intf
	                    .getInetAddresses(); enumIpAddr.hasMoreElements();) {
	                InetAddress inetAddress = enumIpAddr.nextElement();
	                System.out.println("ip1--:" + inetAddress);
	                System.out.println("ip2--:" + inetAddress.getHostAddress());

	      // for getting IPV4 format
	      if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {

	                     ip = inetAddress.getHostAddress().toString();
	                    // return inetAddress.getHostAddress().toString();
	                    return ip;
	                }
	            }
	        }
	    } catch (Exception ex) {
	        Log.e("IP Address", ex.toString());
	    }
	    return null;
	}	
	
	@SuppressWarnings("unused")
	public static String changeItems(Context context,String aDept,String mUser,String mKey,String mGoods,String mKind,String mTime,int [] locas, int xx,int yy,int f123,int mode){
		int success=0;
		StringBuffer ServerStr=new StringBuffer();
		final String[] importStr =Utilis.getIni(context,"SYS", "IMPORT",9).split("!&!");
		final int of_line=Utilis.toInt(importStr[2]);
		 if ( of_line==0 || (Utilis.haveInternet(context) && of_line!=0)){
			//如果單機 或正常網路 才可以 GONO
			String [] locS={"O","R","N"};
			String mFno="";
			String[] deptStr =Utilis.getIni(context,"SYS","DEPT",9).split("!&!");
			int oH=0;//是否有新單單存在
			double mDiscount=0;
			double mUnitprice=0;
	    	String FormD=DateUtil.getCurrentDate();  //2012/10/22
	    	FormD = FormD.replace("/", "-");			//2012-10-22

	    	if (of_line!=0){
			ServerStr.append("updateserver;HHHH\r\n");
	    	}
			
	    	Toast.makeText(context, mKey+"__轉單正在進行中...請稍候!", Toast.LENGTH_SHORT).show();
	    	
			SQLiteDatabase db = Utilis.getDB(context);
			String SQL="";

			SQL="select  * from qitems where FORMNO='"+mKey+"'";
			if (xx==1)//1單筆 0整單
				//可能是 主貨 也可能是 明細貨品
				if (mGoods.indexOf("-")>0)
					SQL=SQL+" and GOODSNOS='"+mGoods+"' and CREATEDATETIME='"+mTime+"'";
				else
					SQL=SQL+" and GOODSNO='"+mGoods+"' and CREATEDATETIME='"+mTime+"'";
			
			
			Cursor cs=db.rawQuery(SQL, null);
			//locas[yy]==0轉預購 1轉留貨 2轉銷貨
			if (locas[yy]!=2){
				if (locas[yy]==0){//專屬單一客戶的[銷貨]轉[預購]
					mFno=aDept+"5"+mUser;  //
				}else if (locas[yy]==1){//專屬單一客戶 轉留貨單
					mFno=aDept+"6"+mUser;  //
				}
				SQL="select  FORMNO from qhead where FORMNO='"+mFno+"'";	    											
				Cursor csH=db.rawQuery(SQL, null);
				if (csH.getCount()>0){

					if (locas[yy]==0){//用意在補強 單頭的屬性
						db.execSQL("update qhead set ISCONFIRM='O',ISCHECK='Y', BANKNAME='"+deptStr[0]+deptStr[1]+"',QKIND='"+mKind+"' where FORMNO='"+mFno+"'");
					}else{
						db.execSQL("update qhead set ISCONFIRM='R',ISCHECK='Y', BANKNAME='"+deptStr[0]+deptStr[1]+"',QKIND='"+mKind+"' where FORMNO='"+mFno+"'");
					}
					Toast.makeText(context,"直接轉單!!"+mFno, Toast.LENGTH_SHORT).show();
					
				}else oH=1; //新預購留貨單
				csH.close();

			} else {//locas[yy]==2  轉入銷貨暫存單 應先查有無暫存單
				SQL="select  FORMNO from qhead where TR<>'Y2' and USER='"+mUser+"' and ISCONFIRM='N' and ISCHECK='N' and FORMNO like '"+(deptStr[0]+deptStr[1]+mKind.substring(0,1)+DateUtil.getCurrentYearFormat1().substring(0, 2))+"%' order by FORMDATE desc LIMIT 1";	    											
				Cursor csH=db.rawQuery(SQL, null);
				if (csH.getCount()>0){  //有暫存單
					csH.moveToFirst();
					mFno=csH.getString(0);
				}else{  //無暫存單,應該產生一張銷貨單頭的單號
					oH=1;
	    			mFno = Utilis.getNFormno(context,mKind.substring(0,1)); //新單號 以門市代號2+機號1+單別1+年1,做為流水號的基礎
				}
				csH.close();
			}
			int reCountH=0;
			if (cs.getCount()>0){
				reCountH=1;
					String GVOUser="";
					String GVOEmp="";
						while (cs.moveToNext()){
				    	  if (Utilis.haveInternet(context) && of_line!=0){
							StringBuffer tempStr =new StringBuffer();
							GVOUser=cs.getString(cs.getColumnIndex("USER"))+"/"+cs.getString(cs.getColumnIndex("USERNAME"));
							GVOEmp=cs.getString(cs.getColumnIndex("EMPID"))+"/"+cs.getString(cs.getColumnIndex("EMPNAME"));
							tempStr.append(cs.getString(cs.getColumnIndex("GOODSNOS"))+";");
							tempStr.append(cs.getString(cs.getColumnIndex("GOODSNAME"))+"/"+cs.getString(cs.getColumnIndex("UNIT1"))+";");
							String UNIT="UNIT"+mKind.substring(0, 1)+"0";
							int aUint=cs.getInt(cs.getColumnIndex(UNIT));
							if (locas[yy]==1){	//(左)銷預->(右)留 
								tempStr.append("0"+";");	//(銷)(預)左0
								tempStr.append(""+aUint+";"); 	//(留)右
								tempStr.append(cs.getInt(cs.getColumnIndex("DISCOUNT"))+";");
								tempStr.append(cs.getDouble(cs.getColumnIndex("UNITPRICE"))+";");
								tempStr.append("1"+";");
								tempStr.append(cs.getString(cs.getColumnIndex("CREATEDATETIME"))+";");
								tempStr.append(GVOUser+";");
								tempStr.append(cs.getString(cs.getColumnIndex("FORMDATE"))+";");
								tempStr.append(FormD+";");
								if (locas[2]==0){//本位預購
									tempStr.append(""+aUint+";");
									tempStr.append("0"+";");			//(留)右+
									tempStr.append(cs.getString(cs.getColumnIndex("FORMNO"))+";");
								}else{ 
									tempStr.append("0"+";");
									tempStr.append("0"+";");
									tempStr.append(""+";");
								}
								tempStr.append(mFno+";");
								
							}else if (locas[yy]==0 ){//(左)預<-(右)銷留
								tempStr.append(""+aUint+";");  		//(預購)左+
								tempStr.append("0"+";");					//(銷)(留)右0
								tempStr.append(cs.getInt(cs.getColumnIndex("DISCOUNT"))+";");
								tempStr.append(cs.getDouble(cs.getColumnIndex("UNITPRICE"))+";");
								tempStr.append("0"+";"); //QPOSFF
								tempStr.append(cs.getString(cs.getColumnIndex("CREATEDATETIME"))+";"); //CDT
								tempStr.append(GVOUser+";"); //USER
								tempStr.append(FormD+";");
								tempStr.append(cs.getString(cs.getColumnIndex("FORMDATE"))+";");
								tempStr.append("0"+";");  		//(預購)左+
									//(留)右- 
								if (locas[2]==1){
									tempStr.append(""+aUint+";");
									tempStr.append(mFno+";");
									tempStr.append(cs.getString(cs.getColumnIndex("FORMNO"))+";");
								}else{ 
									tempStr.append("0"+";");
									tempStr.append(mFno+";");
									tempStr.append(""+";");
								}
								
							}else{//locas[yy]==2預購 OR 留貨 轉銷貨 (左)預->(右)留
								tempStr.append("0"+";");	//(預)左
								tempStr.append("0"+";");	//(留)右0
								tempStr.append(cs.getInt(cs.getColumnIndex("DISCOUNT"))+";");
								tempStr.append(cs.getDouble(cs.getColumnIndex("UNITPRICE"))+";");
								tempStr.append("2"+";"); //QPOSFF
								tempStr.append(cs.getString(cs.getColumnIndex("CREATEDATETIME"))+";"); //CDT
								tempStr.append(GVOUser+";"); //USER
								tempStr.append(FormD+";");
								tempStr.append(FormD+";");
								if (locas[2]==0){							
									tempStr.append(""+aUint+";");	//(預)左-
									tempStr.append("0"+";");			//(留)右0
									tempStr.append(cs.getString(cs.getColumnIndex("FORMNO"))+";");
									tempStr.append(""+";");
									
								}else if (locas[2]==1){
									tempStr.append("0"+";");			//(預)左0
									tempStr.append(""+aUint+";");	//(留)右-
									tempStr.append(""+";");
									tempStr.append(cs.getString(cs.getColumnIndex("FORMNO"))+";");
								}
							}
							tempStr.append(cs.getString(cs.getColumnIndex("PIC"))+";");
							ServerStr.append(tempStr);						
							//因為後面還要加入Qitems
		 					String [] Fields=new String [cs.getColumnCount()];
							for (int r=0;r<cs.getColumnCount();r++){
							Fields[r]=cs.getString(r);
							ServerStr.append(Fields[r]+";");
							}
							ServerStr.append("\r\n");
				    	  }//絕對要Cloud && HaveInternet

							String mGoodss=cs.getString(cs.getColumnIndex("GOODSNOS"));
							String mCtime=cs.getString(cs.getColumnIndex("CREATEDATETIME"));
							mDiscount=cs.getInt(cs.getColumnIndex("DISCOUNT"));
							mUnitprice=cs.getDouble(cs.getColumnIndex("UNITPRICE"));
							SQL="select * from qitems where FORMNO='"+mFno+"' and GOODSNOS='"+mGoodss+"' and DISCOUNT="+mDiscount+" and UNITPRICE="+mUnitprice;
							Cursor csc=db.rawQuery(SQL, null);
							if (csc.getCount()>0){ //表示需要累加程序
								csc.moveToFirst();
								double aPrice=csc.getDouble(csc.getColumnIndex("UNITPRICE"));
								double aDisc=csc.getInt(csc.getColumnIndex("DISCOUNT"));
								double aCost=csc.getInt(csc.getColumnIndex("P1"));
								String aTime=csc.getString(csc.getColumnIndex("CREATEDATETIME"));
								String UNIT="UNIT"+mKind.substring(0, 1)+"0";
								int aUint=csc.getInt(csc.getColumnIndex(UNIT));
								aUint=aUint+cs.getInt(cs.getColumnIndex(UNIT));
								if (f123==0) aCost=Math.round(aUint*aCost); else aCost=Utilis.dedb(aUint*aCost, 3);
								if (f123==0) aPrice=Math.round(aUint*aPrice*aDisc/100); else aPrice=Utilis.dedb(aUint*aPrice*aDisc/100,2); 
								ContentValues value = new ContentValues();
								value.put("TR", mKind);
								value.put("QKIND", mKind);
								value.put(UNIT,aUint);
								value.put("ACOST", aCost);
								value.put("SUBPRICE", aPrice);
								if (locas[yy]==2){//轉銷貨的思考
									value.put("UNIT", 0);
								}else{//否則 轉預購留貨時
									value.put("UNIT", aUint);
								}
								String[] args = {mFno,mGoodss,""+mDiscount,""+mUnitprice,aTime};
								int success1 = db.update(TbName.QITEMS, value,"FORMNO=? and GOODSNOS=? and DISCOUNT=? and UNITPRICE=? and CREATEDATETIME=?", args);

								String[] args1 = {mKey,mGoodss,""+mDiscount,""+mUnitprice,mCtime};
								db.delete(TbName.QITEMS, "FORMNO=? and GOODSNOS=? and DISCOUNT=? and UNITPRICE=? and CREATEDATETIME=? ", args1);
								
							}else{//直接轉單
								//ISCONFIRM轉預購O留貨R ISCHECK='Y' UNIT=UNIT30 FORMNO='"+mFno
								//轉銷貨 UNIT=0 ISCHECK='N' 該會員暫存單存在否
								//原單號 新單號QHEAD先搶位
								ContentValues value = new ContentValues();
								value.put("TR", mKind);
								value.put("QKIND", mKind);
								value.put("ISCONFIRM",locS[locas[yy]]);
								value.put("FORMNO",mFno);

								String UNIT="UNIT"+mKind.substring(0, 1)+"0";
								int aUint=cs.getInt(cs.getColumnIndex(UNIT));
								if (locas[yy]==2){
									value.put("UNIT", 0);
									value.put("ISCHECK","N");
									if (f123==0) value.put("SUBPRICE", ""+Math.round(aUint*mUnitprice*mDiscount/100));
									else value.put("SUBPRICE", ""+Utilis.dedb(aUint*mUnitprice*mDiscount/100,2));
								}else{
									value.put("UNIT", aUint);
									value.put("ISCHECK","Y");
								}
								String[] args = {mKey,mGoodss,""+mDiscount,""+mUnitprice,mCtime};
								int success2 = db.update(TbName.QITEMS, value,"FORMNO=? and GOODSNOS=? and DISCOUNT=? and UNITPRICE=? and CREATEDATETIME=?", args);
							}
							csc.close();
						}
						
						if (oH!=0){//新增一個單頭檔
							SQL="select  * from qhead where FORMNO='"+mKey+"'";	    											
							Cursor csH=db.rawQuery(SQL, null);
							if (csH.getCount()>0){//COPY
								csH.moveToFirst();
								String [] Fields=new String [csH.getColumnCount()];
								//須改變 單號 
								for (int x=0;x<csH.getColumnCount();x++)
									Fields[x]=csH.getString(x);
									//修正FORMNO,ISCONFIRM,ISCHECK,TR,CASHCARDORDCASH,ORDCARD,FINEDATE,ORDDATE
								Fields[0]="Y0";
								Fields[2]=mKind;; //TR=QKIND
								Fields[3]=mFno;
								Fields[5]=FormD;
								Fields[7]=locS[locas[yy]];
								if (locas[yy]==2) Fields[8]="N"; else Fields[8]="Y";
								Fields[16]="0";Fields[17]="0";Fields[18]="0";Fields[19]="0";
								Fields[21]="";Fields[22]="";Fields[23]="0";Fields[24]="0"; //ATM TRCASH= 0
								Fields[30]=deptStr[0]+deptStr[1];
								
								ContentValues value = new ContentValues();
								for (int x=0;x<csH.getColumnCount();x++)
									value.put(csH.getColumnName(x), Fields[x]);
								
								long success3=db.insert(TbName.QHEAD, null, value);
								
							}//找不到原單頭 IMPOSSABLE
						}
						if (of_line!=0){
							ServerStr.append(";HHHH\r\n");
							Cursor h1=db.rawQuery("select * from qhead where FORMNO='"+mKey+"'", null);
							if (h1.getCount()>0){
								h1.moveToFirst();
			 					String [] Fields=new String [h1.getColumnCount()];
								for (int r=0;r<h1.getColumnCount();r++){
								Fields[r]=h1.getString(r);
								ServerStr.append(Fields[r]+";");
								}
								ServerStr.append("\r\n");
							} h1.close();
							
							Cursor h2=db.rawQuery("select * from qhead where FORMNO='"+mFno+"'", null);
							if (h2.getCount()>0){
								h2.moveToFirst();
			 					String [] Fields=new String [h2.getColumnCount()];
								for (int r=0;r<h2.getColumnCount();r++){
								Fields[r]=h2.getString(r);
								ServerStr.append(Fields[r]+";");
								}
								ServerStr.append("\r\n");
							} h1.close();
							ServerStr.append(";HHHH\r\n");
							ServerStr.append("'"+mKey+"','"+mFno+"'");						
							ServerStr.append(";HHHH\r\n");
						}
			}
			db.close();
			cs.close();
			int cloud1=reCountHead(context,mKey,FormD,mKind,f123);
			int cloud2=reCountHead(context,mFno,FormD,mKind,f123);
			//if (cloud1!=0 || cloud2!=0 ) DBCloud.aa1_aa0_update_HI(context);
			

		 }else Toast.makeText(context, "網路不正常,無法進行交易!!!!", Toast.LENGTH_SHORT).show();	        		        	
		 //網路不正常
		 
		 return ServerStr.toString(); 
	}
	
	//PosUtilis.reCountHead(QPosff.this,mKey,"",mKind,f123);

	public static int reCountHead(Context context,String mKey,String mFmDate,String mKind,int f123){  //QITEMS異動後 需維護QHEAD
		SQLiteDatabase db = Utilis.getDB(context);
		StringBuffer mySqlBuf = new StringBuffer();
		StringBuffer handNo=new StringBuffer();  //須算好 進退量 存入HandNo
		String tureTRADE="P4";
		final String[] importStr =Utilis.getIni(context,"SYS", "IMPORT",9).split("!&!");
		final int of_line=Utilis.toInt(importStr[2]);
		int success=0;
		
		//清除件數為0的資料
		db.execSQL("delete from qitems where FORMNO='"+mKey+"' and UNIT"+mKind.substring(0, 1)+"0=0 ");
		
		mySqlBuf.delete(0, mySqlBuf.toString().length());
		mySqlBuf.append("select sum(UNIT"+mKind.substring(0, 1)+"0),TRADETYPE");
		mySqlBuf.append(" from qitems where FORMNO ='" +mKey+"'")
		.append(" and QKIND ='" + mKind+"'");

		//先算出的
		String mySql=mySqlBuf.toString();
		mySqlBuf.append(" and UNIT"+mKind.substring(0, 1)+"0 >=0 group by TRADETYPE");

		
		Cursor cursory = db.rawQuery(mySqlBuf.toString(), null);									
		if (cursory.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
			cursory.moveToFirst();
			handNo.append("+"+cursory.getInt(0));
			tureTRADE="P"+cursory.getString(1);
			}
		
		cursory.close();
		
		mySqlBuf.delete(0, mySqlBuf.toString().length());
		mySqlBuf.append(mySql); //共用片段
		mySqlBuf.append(" and UNIT"+mKind.substring(0, 1)+"0 <0 group by TRADETYPE");		
		Cursor cursorz = db.rawQuery(mySqlBuf.toString(), null);									
		if (cursorz.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
			cursorz.moveToFirst();
			if (cursorz.getInt(0)<0)
			handNo.append(""+cursorz.getInt(0));
			tureTRADE="P"+cursorz.getString(1);
		}
		cursorz.close();
		
		double SUBP=0;
		double SUBQ=0;
		double SUBT=0;
		Cursor cursorw = db.rawQuery("select TRCASH,DISMONEY from qhead where FORMNO ='" + mKey+"' and QKIND ='" + mKind+"'", null);
		if (cursorw.getCount()>0){
			cursorw.moveToFirst();
			int dTrcash=Utilis.toInt(cursorw.getString(0));
			int dDismoney=Utilis.toInt(cursorw.getString(1));
			SUBQ=dTrcash-dDismoney;
		}
		cursorw.close();
		
		mySqlBuf.delete(0, mySqlBuf.toString().length());
		mySqlBuf.append("select FORMNO,sum(UNIT"+mKind.substring(0, 1)+"0) as UNITS,sum(SUBPRICE) as SUBPRIS,");
		//@@@盲點 無法算出正確的實際未折讓金額
		mySqlBuf.append("sum(ACOST) as ACOSTS,sum(UNIT"+mKind.substring(0, 1)+"0 * "+tureTRADE+") as ATURESUM from qitems")
		.append(" where FORMNO ='" + mKey+"'")
		.append(" and QKIND ='" + mKind+"'")
		.append(" group by FORMNO" );
		Cursor cursorx = db.rawQuery(mySqlBuf.toString(), null);
		
		if (cursorx.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
			ContentValues value = new ContentValues();
			cursorx.moveToFirst();
			
			int PERS=Utilis.toInt(Utilis.getIni(context,"SYS", "SDB", 8));
			if (PERS==5){
				SUBP=Math.round(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS"))/10)*10;
			}else if (PERS==1){ //無條件捨去
				SUBP=Math.floor(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS"))/10)*10;
			}else if (PERS==9){ //無條件進入
				SUBP=Math.ceil(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS"))/10)*10;
			}else{ 
				if(f123==0) SUBP=Math.round(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS")));
				else SUBP=Utilis.dedb(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS")),2);
			}
			double Atot=cursorx.getDouble(cursorx.getColumnIndex("UNITS"));
			double Costs=Math.round(cursorx.getDouble(cursorx.getColumnIndex("ACOSTS")));
			if (f123==0) Costs=Utilis.dedb(cursorx.getDouble(cursorx.getColumnIndex("ACOSTS")),3);
			if (f123==0) SUBT=Math.round(cursorx.getDouble(cursorx.getColumnIndex("ATURESUM")));
			else SUBT=Utilis.dedb(cursorx.getDouble(cursorx.getColumnIndex("ATURESUM")),2);
			
			//????為何傳入了 日期 是不用視為異動????
			//因為GalleryViewP "" 也是呼叫這裡
			if (mFmDate.length()>0){
				value.put("FORMDATE",mFmDate);
				value.put("TR","Y0");
			}else value.put("TR",mKind);
			
			value.put("ASUM",SUBP);
			value.put("BSUM",SUBP+SUBQ);
			value.put("ATOT",Atot);
			value.put("COSTS",Costs);
			value.put("HANDNO", handNo.toString());
			value.put("BANKNAME", importStr[0]+importStr[1]);

			//廠商進貨需再存入
			if (Utilis.toInt(mKind)==PItemKind.TR10){
				value.put("TURESUM",cursorx.getDouble(cursorx.getColumnIndex("ACOSTS")));
			} else{
				value.put("TURESUM",SUBT);
			}
			
			String[] args = {mKey};
			success = db.update(TbName.QHEAD, value,"FORMNO=? ", args);
			//不維護ORYN
		} else {//沒有Qitems
			Cursor csH = db.rawQuery("select * from qhead where FORMNO='" + mKey+"'", null);
			if (csH.getCount()>0){
				csH.moveToFirst();
				if (csH.getDouble(csH.getColumnIndex("ORDCASH"))!=0 || csH.getDouble(csH.getColumnIndex("ORDCARD"))!=0  || csH.getDouble(csH.getColumnIndex("CASH"))!=0 || csH.getDouble(csH.getColumnIndex("CARD"))!=0 || csH.getDouble(csH.getColumnIndex("TRCASH"))!=0 || csH.getDouble(csH.getColumnIndex("DISMONEY"))!=0){
					//因為有訂金,所以不可以清除
					String SQL="update qhead set TR='Y1',ID='1009',HANDNO='+0',ISCONFIRM='Y',ISCHECK='N',ATOT='0',ASUM=0,BSUM=0,COSTS=0 where FORMNO='" + mKey+"'";
					db.execSQL(SQL);
					if (of_line!=0 && mFmDate.length()<=1){ 
						success=2; 
						SystemClock.sleep(500);
						DBCloud.aa1_aa0_update_HI(context);
					}	
				}else if (of_line==0) {
					db.execSQL("delete from qhead where FORMNO='" + mKey+"'" );//其實存的是單號
				} else {
					if (mFmDate.length()>1){//mFmDate.length()>0 表示轉單
						db.execSQL("delete from qhead where FORMNO='" + mKey+"'" );//其實存的是單號
					}else{//QPOSFF的維護單頭
						db.execSQL("update qhead set TR='Y2',ASUM=0,ATOT=0,COSTS=0,HANDNO='+0',ISCONFIRM='N',ISCHECK='N',FINEDATE='',ORDDATE='' where FORMNO='"+mKey+"'");
						success=2; 
						SystemClock.sleep(500);
						DBCloud.aa1_aa0_update_HI(context);
					}
				}
			}
			csH.close();
		}
		db.close();
		cursorx.close();
		return success;
	}
	
	public static int mChoice=0;
	public static String [] lists;
	public static int of_line=0;
	public static void showImportDialog(final Context context,final String mKey,int nPart,int tmode){
		StringBuffer lst=new StringBuffer();
		final String[] deptStr =Utilis.getIni(context,"SYS","DEPT",9).split("!&!");
		of_line=Utilis.toInt(Utilis.getIni(context,"SYS", "IMPORT",3));
		SQLiteDatabase db = Utilis.getDB(context);
		String SQLL="select CUSTNO,CUSTNAME,TRADETYPE,DISCOUNT from qcust where TR='20' and CUSTNO<>'"+deptStr[5]+"' order by CUSTNO";
		if (tmode==1 && nPart!=0) SQLL="select CUSTNO,CUSTNAME,TRADETYPE,DISCOUNT from qcust where TR='20' and CUSTNO='"+deptStr[0]+"'";
		Cursor cs=db.rawQuery(SQLL , null);
		if (cs.getCount()>0){
			cs.moveToFirst();
			for (int xx=0;xx<cs.getCount();xx++){
				lst.append(cs.getString(0)+","+cs.getString(1)+","+cs.getString(2)+","+cs.getString(3)+";");
				cs.moveToNext();
			}
		}
		db.close();
		cs.close();
		
		lists=lst.toString().split(";");
		
		if (lists.length>0){
		AlertDialog.Builder sortDlg = new AlertDialog.Builder(context);
        sortDlg.setTitle("請選擇匯入的門市(出貨單)或  返回")
        .setSingleChoiceItems(lists, 0, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
            	mChoice = item;
            }
        }) 
        .setPositiveButton(context.getString(R.string.str_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { //確認

            	SQLiteDatabase db = Utilis.getDB(context);
	        	String [] deptlist = lists[mChoice].split(",");  //只是批號
	        	String nFno="";
	        	String nHno="";
	        	String nTT="";
	        	String nCT="";
	        	double Asum=0;
	        	double Disc=Utilis.toDouble(deptlist[3]);

	        	String QSQL="";
	        	QSQL="select * from qhead where FORMNO='"+mKey+"' and QKIND='10'";
	        	Cursor csH=db.rawQuery(QSQL,null);
	        	if (csH.getCount()>0)
	        	{//找到本廠商進貨單
	        		csH.moveToFirst();
	        		nFno=csH.getString(csH.getColumnIndex("PS2"));
	        		nHno=csH.getString(csH.getColumnIndex("HANDNO"));
	        		nTT=csH.getString(csH.getColumnIndex("ATOT"));
	        		nCT=csH.getString(csH.getColumnIndex("COSTS"));
	        		
	    			Toast.makeText(context,"找到進貨單="+mKey+" 的PS2="+nFno, Toast.LENGTH_SHORT).show();
	        		//@@@如果已存在上次的轉出貨單時,將詢問是否清除
	        		//@@@或產生另一張新的出貨單
	        		//如果這張廠商進貨單已轉出貨單,務必刪除該單
	        		//清除已轉出的門市出貨單的所有QITEMS
	        		if (nFno!=null && nFno.length()>0){
	        			
	        			QSQL="delete from qitems WHERE FORMNO='"+nFno+"'";
	        			db.execSQL(QSQL);
		    			Toast.makeText(context,"找到出貨單!!且進入刪除"+nFno, Toast.LENGTH_SHORT).show();
		        		//找到已轉出的門市出貨單頭時,應該刪除
						if (of_line==0 ){
								db.execSQL("delete from qhead where FORMNO='" + nFno+"'" );//其實存的是單號
						} else {
								db.execSQL("update qhead set TR='Y2',ID='1008',CREATEDATETIME='"+DateUtil.getSystemTime().substring(2, 14)+"',ISCONFIRM='N',ISCHECK='N' ,BANKNAME='"+deptStr[0]+deptStr[1]+"' where FORMNO='" + nFno+"'" );
						}
	        		}
	        	}

	        		nFno=Utilis.getNFormno(context,"2"); //新單號 以門市代號2+機號1+單別1+年1,做為流水號的基礎
	        		
	        		//產生一個新單號 並記得存入 原單
	        		//讀取廠商進貨單QITEMS 複製後 改 TR QKIND FORMNO FORMDATE CREATEDATETIME USER USERNAME TRADETYPE 單價 折 小計 外幣合計0 UNIT 0
	        		//製作一個新出貨單頭
	        		QSQL="update QHEAD  set PS2='"+nFno+"',TR='"+"Y1"+"' where FORMNO='"+mKey+"'";
	        		db.execSQL(QSQL);
	        		QSQL="select * from qitems where FORMNO='"+mKey+"'";
	        		Cursor csI=db.rawQuery(QSQL,null);
	        		String nFdate=DateUtil.getCurrentDateDb();
	        		String nTime=DateUtil.getSystemTime().substring(2,14);
	        		
	        		if (csI.getCount()>0){
	        			while (csI.moveToNext()){
							ContentValues valueI = new ContentValues();
							String[] arrayField =new String[53];
							for(int xx=0;xx<csI.getColumnCount();xx++){
								arrayField[xx]=csI.getString(xx);
							}	
								arrayField[0]="20";arrayField[2]="20";
								arrayField[37]=mKey; //將廠商進貨單號存入出貨FINEDATE
								arrayField[3]=nFno;
								arrayField[4]="";  //出貨單的批號,應刪除,以防配轉單刪除
								arrayField[5]=nFdate;
								arrayField[6]=nTime;
								arrayField[7]="Y";arrayField[8]="N";
								arrayField[11]=deptlist[0];arrayField[12]=deptlist[1];
								arrayField[13]=deptlist[2];arrayField[20]="0.0";
								arrayField[21]=arrayField[28+Utilis.toInt(deptlist[2])];//單價
								arrayField[45]=arrayField[44];arrayField[44]="0";//件數
								arrayField[46]="0";arrayField[47]="0";
								arrayField[26]="0.0";//外幣小計
								Asum=Asum+(Utilis.toDouble(arrayField[21])*Utilis.toInt(arrayField[45])*Disc)/100;
								arrayField[27]=""+(Utilis.toDouble(arrayField[21])*Utilis.toInt(arrayField[45])*Disc)/100;
								
							for(int xx=0;xx<csI.getColumnCount();xx++){
								valueI.put(csI.getColumnName(xx),arrayField[xx]) ;
							}
							db.insert("qitems", null, valueI);
	        			}
		        		//製作單頭	        			
						ContentValues valueH = new ContentValues();
						valueH.put("TR","20");
						valueH.put("ID","0");
						valueH.put("QKIND","20");
						valueH.put("FORMNO",nFno);
						valueH.put("HANDNO",nHno);//件數不變
						valueH.put("FORMDATE",nFdate);
						valueH.put("CREATEDATETIME",nTime);
						valueH.put("ISCONFIRM","Y");
						valueH.put("ISCHECK","N");
						valueH.put("ISLIST","N");
						valueH.put("EMPID","TTD");
						valueH.put("EMPNAME","");
						valueH.put("USER",deptlist[0]);
						valueH.put("USERNAME",deptlist[1]);
						valueH.put("TRADETYPE",deptlist[2]);
						valueH.put("DEPTNO",deptStr[5]);
						valueH.put("ORDCASH","0");						
						valueH.put("ORDCARD","0");
						valueH.put("CASH","0");
						valueH.put("CARD","0");
						valueH.put("ATM","0");
						valueH.put("TRCASH","0");
						valueH.put("PS","配");
						valueH.put("PS2",mKey);
						valueH.put("ATOT",nTT);
						valueH.put("FINEDATE","");						
						valueH.put("ORDDATE","");
						valueH.put("ASUM",Asum);
						valueH.put("BSUM",Asum);
						valueH.put("BILLRATE","0.0");
						valueH.put("COSTS",nCT);
						valueH.put("DISMONEY",0);
						valueH.put("TURESUM",0);
						valueH.put("BANKNO","1");
						valueH.put("BANKNAME",deptStr[0]+deptStr[1]);
						db.insert("qhead", null, valueH);
	        		}
	        		db.close();
	        		csH.close();
	        		csI.close();
					if (of_line==1) {
						SystemClock.sleep(500);
						DBCloud.aa1_aa0_update_HI(context);
					}
	                Toast.makeText(context, deptlist[0]+deptlist[1]+"已經成功轉入門市出貨單!!", Toast.LENGTH_SHORT).show();
            }
          })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { //取消

            }
          }).show();
		}
	}	
	
	
	
}