package com.cwbuyer.lib;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.PItemData;
import com.pwbuyer.main.R;
import com.cwbuyer.main.APos.PItemKind;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;



@SuppressLint({ "InflateParams", "HandlerLeak" })
@SuppressWarnings("unused")
public class GalleryViewO extends Activity {

//	private Gallery mGalleryGoods,mGalleryCust;
	private ImageButton mImgBtnSearch;
	private ImageButton mImgBtnRobk;
	private EditText mEdSearch;  //搜尋關鍵字
	private String compStr[]=Utilis.getIni(GalleryViewO.this,"USER","COMPANY",9).split("!&!");
	private String deptStr[]=Utilis.getIni(GalleryViewO.this,"SYS","DEPT",9).split("!&!");
	int f123=0;
	private int Loca=0;
	private int printYN=0;
	private StringBuffer sPrintB = new StringBuffer();
	private StringBuffer ServerStr = new StringBuffer();
	private String ServerRecountHead="";
	
	static ListView mListView = null;		

	static MyAdapter1 adapter1;
    private List<HashMap<String, Object>> list = null;
	
  	private LinearLayout lTableView = null;
	private LinearLayout mLayoutRoot = null;
	
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+	 File.separator + "CWBuyer"  ;
	protected static final int REFRESH_DATA = 0x00000001;
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);	
	String SD_PATH =android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
	String pathName="/CWBuyer/cualbun";	
	String myFilePath = SD_PATH+pathName+"/cu_order_keep.csv";
	String myFilePathG = SD_PATH+pathName+"/goods_order_keep.csv";
	int locations;
	//預購留貨轉銷貨 只針對單一門市
	int nKind=PItemKind.TR30; //只為會員銷貨單製作 留貨功能 
	String mKind=""+nKind;
	String mUNIT="UNIT30";
//	String Maxx=null;
	//保存商品原始資料,本區紀錄的目的是為了
	String mUser=null;
	String SQLSTD=" USER,USERNAME,GOODSNOS,GOODSNAME,PIC,ISCONFIRM,ISCHECK,FORMDATE,UNIT1,FORMNO,DISCOUNT,UNITPRICE,CREATEDATETIME ";
	String fNo=null;  //單據編號 不可變  如果保持空白 代表永遠只能查詢(決不可以新增修改)	
	String mGoods=null;
	String mColors=null;
	String mUnit2=null;
	String mSizes=null;
	String mGoodsPic=null;
	String mCountry=null;
	String mColor=null;  //單一顏色
	String mColorno=null;  //單一顏色
	String mySize=null; //單一尺寸
	double dDiscount=0;
	double dUnitprice=0;
	double dSubprice=0;
	double defDiscount=0;
	String ASK="";
	String ASKg="";
	String ASKc="";//針對Server帶上的 Qhead Qitems 條件
	private String sepa="\r\n";

	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));

	double units=0;
	int nPart=0;//0.總倉 1.門市
	static int mMode = 0;  //0mUser 1mGoods 2KeepaToSale and mUser
	int records = 0;
	int positionCust = 0;
	static int positionGoods = 0;
	String mFnR="";  //如果是 mMode==2 留貨轉銷貨 勢必帶入 銷貨單號
	String mFnO="";
	String strRes = "";
	PItemData dataH;	
	//GalleryList專用的資料陣列
	int Wheight;
	int Wwidth;
	int modify=0;  //並未修改
	int change=1; //控制recount 手動自動update 7 8
	int tableHeight=45;
	int tabless=6;
	
	Bundle bundle;
	String mBankn="";//門市代號+機號
	String mDept="";
	String BufGoodsStr=null;
	String BufUserStr=null;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (Utilis.haveInternet(GalleryViewO.this) && of_line==1){
	        SQLiteDatabase db = Utilis.getDB(GalleryViewO.this);
			Cursor cs=db.rawQuery("select FORMNO from "+TbName.QHEAD+" where TR<>'Y0' and (ISCONFIRM='Y' or ISCHECK='Y')", null);
			if (cs.getCount()>0){
				DBCloud.aa1_aa0_update_HI(GalleryViewO.this);
				Toast.makeText(GalleryViewO.this, "有單據尚未傳送到雲端,稍後再執行...", Toast.LENGTH_LONG).show();
	        	Intent intentS = new Intent();
	        	intentS.putExtra("GVPO_modify",0);
	        	GalleryViewO.this.setResult(RESULT_OK,intentS);
				finish();
			}
			db.close();
			cs.close();
		}
		
		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Wwidth = dm.widthPixels;
        Wheight = dm.heightPixels;

		setContentView(R.layout.galleryo);
		mImgBtnSearch = (ImageButton) findViewById(R.id.imageButton15);		
		mImgBtnRobk = (ImageButton) findViewById(R.id.imageButton16);
		mEdSearch =(EditText)findViewById(R.id.edSearch);
        mListView = (ListView)findViewById(R.id.list_pitems);  //將在畫面流覽的欄位們
        mListView.getLayoutParams().height=Wheight-300;
        lTableView = (LinearLayout)findViewById(R.id.tableview);
        ((Button)findViewById(R.id.btn_allyes)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_allno)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_rcount)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_save)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());
        ((EditText)findViewById(R.id.edSearch)).setOnClickListener(new MainClick());
        mImgBtnSearch.setOnClickListener(new MainClick());
        mImgBtnRobk.setOnClickListener(new MainClick());
        
    	mLayoutRoot = (LinearLayout)findViewById(R.id.root);
//	   	mAdapter = new OItemAdapter(this);
		mListView.setAdapter(adapter1);
		mBankn=deptStr[0]+deptStr[1];
    	mUser= getIntent().getStringExtra("GalleryUser"); //就是會員
    	mGoods=getIntent().getStringExtra("GalleryGoods");
    	mDept= getIntent().getStringExtra("GalleryDept"); //就是門市
    	ASKg= getIntent().getStringExtra("GalleryASK"); //就是附帶條件
    	mFnR=getIntent().getStringExtra("FormNo");
    	mKind= getIntent().getStringExtra("GalleryQKIND"); //就是附帶條件
    	mMode=getIntent().getIntExtra("GalleryMode",2);//0mUser 1mGoods 2KeepaToSale
		nKind=Utilis.toInt(mKind);//預設 總倉
    	if (mDept.equalsIgnoreCase("SOS")) mDept=deptStr[0];

        	if (Utilis.getIni(this,"SYS","SDB",7).equalsIgnoreCase("1")) f123=1; //需要小數位
	        if (!mDept.equalsIgnoreCase(deptStr[5])){ 
	        	nPart=1;  //門市版
	        	nKind=31; //表示門市單別
	        }else{
	        	nKind=30; //總倉銷貨
	        }
        mKind=""+nKind;
		
		BufUserStr=SearchBG();
        QuerySqlUser(0);		
		/* 設定一個itemclickListener事件 */
     	mListView.setOnItemClickListener(new OnItemClickListener(){
     		@Override
     		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
     				long arg3) {
   			// TODO Auto-generated method stub
   			Utilis.runVibrate(GalleryViewO.this);
   			locations=position;
     			
			String diaLog[] ={"列印所有會員商品清冊","列印(原始所有商品)會員清冊","刪除該筆預購商品","列印客戶名條","列印客戶標籤","追蹤","放大","清除所有預購交易","清除所有留貨交易","留貨維護","預購維護","(會員)商品清冊輸出CSV","(商品)會員清冊輸出CSV","返回"};
			DialogUtilis.showDialog(GalleryViewO.this, "請選擇以下功能", -1,
			diaLog, new IDialog() {
			@Override
			public void onDialogFinish(int pos, String choice) {
			switch (pos) {
				case 0: //列印所有會員商品清冊
				{
					ASK=ASKg;
					BufUserStr=SearchByUser();
			        QuerySqlUser(1);		
	            	adapter1.notifyDataSetChanged();
	            	//printForm1();
					break;
				}
				case 1: //列印所有商品會員清冊
				{
					if (list!=null && list.size()>0){
					//if(adapter1 != null && adapter1.getCount()>0)	adapter1.list.clear();
		        	ASK=ASKg;
					BufUserStr=SearchByGoods();
					QuerySqlUser(2);
	            	adapter1.notifyDataSetChanged();
					//printForm2();											
					
					}
					break;
				}
				case 2: //需要在預購留貨mMode!=2 時,才可以操作 而且還要預購有值才可以刪除
				{
					if(mMode!=2){
					HashMap<String, Object> map = list.get(locations);
						if (Utilis.toInt(map.get("item_rcc").toString())!=0){
							 Toast.makeText(GalleryViewO.this, map.get("item_rul").toString()+map.get("item_rdl").toString()+map.get("item_rdc").toString()+map.get("item_rh1").toString(), Toast.LENGTH_LONG).show();
							 map.put("item_rcc", "0");
				            map.put("item_rcb", true);
							 list.set(locations,map);
			            	list.listIterator(locations);
			            	adapter1.notifyDataSetChanged();

						}
					}
					break;
				}
				case 3: //列印客戶名條
				{
					StringBuffer sPrintB=new StringBuffer();
					HashMap<String, Object> map = list.get(locations);
					String users=map.get("item_rdl").toString().substring(0,map.get("item_rdl").toString().indexOf("/"));
			        SQLiteDatabase db = Utilis.getDB(GalleryViewO.this);
			        Cursor cs=db.rawQuery("select * from qcust where CUSTNO='"+users+"'", null);
					if (cs.getCount()>0){
						cs.moveToFirst();
						sPrintB.append("^Q230,0,0"+sepa);
						sPrintB.append("^W56"+sepa+"^H10"+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);			
						sPrintB.append("AZ,320,98,6,6,0,1,"+users+"-"+cs.getString(cs.getColumnIndex("CUSTNAME"))+" 收"+sepa);
						sPrintB.append("AZ,424,96,2,2,0,1,"+cs.getString(cs.getColumnIndex("ADDRESS"))+"-"+cs.getString(cs.getColumnIndex("MOBIL"))+" 收"+sepa);
						sPrintB.append("AZ,96,266,3,3,0,1,"+compStr[0]+"/"+compStr[3]+"寄"+sepa);
						sPrintB.append("E"+sepa);
					
						if (sPrintB.toString().length()>0){
							String address=null;
							int port=0;
							   address = Utilis.getIni(GalleryViewO.this, "SYS","BAR_IP", 4);// 連線的ip
							   port =Utilis.toInt(Utilis.getIni(GalleryViewO.this, "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);
												 socket.close();
												 Toast.makeText(GalleryViewO.this, "已成功傳送名條到條碼機!!", Toast.LENGTH_LONG).show();
										 } catch (UnknownHostException e) {
										 } catch (SocketException e) {
										 } catch(IOException e) {
										 }
						}
					}
					cs.close();
					db.close();
					break;
				}
				case 4: //列印客戶標籤
				{
						StringBuffer sPrintB=new StringBuffer();
						HashMap<String, Object> map = list.get(locations);
						String users=map.get("item_rdl").toString().substring(0,map.get("item_rdl").toString().indexOf("/"));
				        SQLiteDatabase db = Utilis.getDB(GalleryViewO.this);
				        Cursor cs=db.rawQuery("select * from qcust where CUSTNO='"+users+"'", null);
						if (cs.getCount()>0){
							cs.moveToFirst();
							sPrintB.delete(0, sPrintB.toString().length());

							sPrintB.append("^KQCUST"+sepa);
							sPrintB.append(cs.getString(cs.getColumnIndex("CUSTNO"))+"/"+cs.getString(cs.getColumnIndex("CUSTNAME"))+sepa);
							sPrintB.append( "$"+cs.getString(cs.getColumnIndex("CUSTNO"))+sepa);
								
								sPrintB.append( "M:"+cs.getString(cs.getColumnIndex("MOBIL"))+sepa);
								sPrintB.append( "E: "+cs.getString(cs.getColumnIndex("EMAIL"))+sepa);
								sPrintB.append( "W:"+cs.getString(cs.getColumnIndex("ADDRESS"))+sepa);
								sPrintB.append( "PS:"+cs.getString(cs.getColumnIndex("PS"))+sepa);
								sPrintB.append("E"+sepa);
								sPrintB.append("~P1"+sepa);
						
							if (sPrintB.toString().length()>0){
								String address=null;
								int port=0;
								   address = Utilis.getIni(GalleryViewO.this, "SYS","BAR_IP", 2);// 連線的ip
								   port =Utilis.toInt(Utilis.getIni(GalleryViewO.this, "SYS","BAR_IP", 3));// 連線的port
									 try {
										 InetAddress serverAddr = InetAddress.getByName(address);
										 SocketAddress sc_add= new InetSocketAddress(serverAddr,port);
										 Socket 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);
											 socket.close();
											 Toast.makeText(GalleryViewO.this, "已成功傳送名條到條碼機!!", Toast.LENGTH_LONG).show();
									 } catch (UnknownHostException e) {
									 } catch (SocketException e) {
									 } catch(IOException e) {
									 }
							}
						}
						cs.close();
						db.close();
					break;
				}
				case 5:
				{//追蹤
					HashMap<String, Object> map = list.get(locations);
					String GoodsNo=map.get("item_rul").toString();
					if (GoodsNo.indexOf("-")>0) GoodsNo= GoodsNo.substring(0,GoodsNo.indexOf("-"));
					
					try{
						Intent intent = new Intent();
						intent.putExtra("QHis_kind", nKind);
						if (mMode==2) intent.putExtra("QHis_mode", 6); else intent.putExtra("QHis_mode", 5);
						intent.putExtra("QHis_User","" );
						intent.putExtra("QHis_Goods",GoodsNo);
						intent.setClass(GalleryViewO.this, QHis.class);
						startActivity(intent);
					}catch(Exception e){
						e.printStackTrace();
					}finally{
					}
					
					break;
				}
				
				case 6:
				{//放大
					HashMap<String, Object> map = list.get(locations);
					String mImagePath=map.get("item_rpic").toString();
					try{
						if (mImagePath!=null  && mImagePath.length()>10){
							Intent intent = new Intent();
							intent.setClass(GalleryViewO.this,Show_imagebig.class);
							intent.putExtra("image", mImagePath);
							startActivity(intent);
						}
					}catch(Exception e){
						e.printStackTrace();
					}finally{
					}
					
					break;
				}
				case 7:
				{//清除所有預購
				if(mMode!=2){
					//一定要總倉,並詢問是否確認,還要輸入一組專用密碼
					if (nPart==0){
						gotoAllErase(13);//0.預購 1.留貨 
					}
				}
					break;
				}
				case 8:
				{//清除所有留貨
					if(mMode!=2){
						if (nPart==0){
							gotoAllErase(15);//0.預購 1.留貨 
						}
					}
						break;
					}			
				case 9:{//留貨維護
					if (Utilis.haveInternet(GalleryViewO.this) && of_line==1)  //逾3分鐘沒有同步
					if (!Utilis.getIni(GalleryViewO.this, "SYS", "SEASON", 4).equalsIgnoreCase("0")){
						DBCloud.aa0_aa1_auto_HI_ORNY(GalleryViewO.this,"","0");//0留貨1預購 維護
						Toast.makeText(GalleryViewO.this, "留貨維護中,請稍後!!", Toast.LENGTH_SHORT).show();
					}else{//正常同步程序正在進行中,請稍後,再按[轉單]
						Toast.makeText(GalleryViewO.this, "正常同步程序正在進行中,請稍後!!", Toast.LENGTH_SHORT).show();
					}

					break;
				}
				
				case 10:{//預購維護
					if (Utilis.haveInternet(GalleryViewO.this) && of_line==1)  //逾3分鐘沒有同步
					if (!Utilis.getIni(GalleryViewO.this, "SYS", "SEASON", 4).equalsIgnoreCase("0")){
						DBCloud.aa0_aa1_auto_HI_ORNY(GalleryViewO.this,"","1");//0留貨1預購 維護
						Toast.makeText(GalleryViewO.this, "預購維護維護中,請稍後!!", Toast.LENGTH_SHORT).show();
					}else{//正常同步程序正在進行中,請稍後,再按[轉單]
						Toast.makeText(GalleryViewO.this, "正常同步程序正在進行中,請稍後!!", Toast.LENGTH_SHORT).show();
					}

					break;
				}
				case 11: //所有會員商品清冊輸出CSV
				{
					ASK=ASKg;
					BufUserStr=SearchByUser();
			        QuerySqlUser(3);		
	            	adapter1.notifyDataSetChanged();
					break;
				}
				case 12: //所有商品會員清冊輸出CSV
				{
					//if (list!=null && list.size()>0){
					//if(adapter1 != null && adapter1.getCount()>0)	adapter1.list.clear();
		        	ASK=ASKg;
					BufUserStr=SearchByGoods();
					QuerySqlUser(4);
	            	adapter1.notifyDataSetChanged();
					//}
					break;
				}
				case 13:break;
			}
			}
			});	
  			}
     	});     	
}
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
          new AlertDialog.Builder(GalleryViewO.this).setTitle(getString(R.string.str_msg)).setMessage(getString(R.string.msg_exitgalleryviewo)).setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
				int chk=0;
				if (list !=null && list.size()>0){
					for (int x=0;x<list.size();x++){
						HashMap<String, Object> map = list.get(x);
						if ((Boolean)map.get("item_rcb")==true){
							chk=1;break;
						}
					}
					if (chk==1){//對話是否確定返回
						DialogUtilis.showDialog(GalleryViewO.this, "資料已異動!!是否放棄轉單?", -1,
						new String[] { "放棄轉單", "繼續執行" }, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
								switch (pos) {
								case 0:
									if (list !=null && list.size()>0)	list.clear();
						        	Intent intentS = new Intent();
						        	intentS.putExtra("GVPO_modify",0);
						        	GalleryViewO.this.setResult(RESULT_OK,intentS);
									finish();
									break;
								case 1:break;
								}
							}
						});	
				}	}
				if (chk==0) {
					if (list !=null && list.size()>0)	list.clear();
		        	Intent intentS = new Intent();
		        	intentS.putExtra("GVPO_modify",0);
		        	GalleryViewO.this.setResult(RESULT_OK,intentS);
					finish();
					}
            }
          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
          }).show();
          return true;
        } else {
          return super.onKeyDown(keyCode, event);
        }
    }

	

	private String SearchBG(){
        StringBuffer mySqlBuf = new StringBuffer();
        if (mMode==0){//單一會員-預購<=>留貨
    		mySqlBuf.append("select"+SQLSTD+",sum(UNIT) as UNITS from "+TbName.QITEMS);
    		ASKc=" where USER='"+mUser+"' and ISCHECK='Y' and QKIND='"+mKind+"' and DEPTNO='"+mDept+"'";
    		mySqlBuf.append(ASKc+" group by"+SQLSTD+"order by GOODSNOS,FORMDATE,UNITPRICE,DISCOUNT,CREATEDATETIME,ISCONFIRM");
        }else  if (mMode==1){//單一商品-預購<=>留貨        	
    		mySqlBuf.append("select"+SQLSTD+",sum(UNIT) as UNITS from "+TbName.QITEMS);
    		ASKc=" where GOODSNO='"+mGoods+"' and ISCHECK='Y' and QKIND='"+mKind+"' and DEPTNO='"+mDept+"'";
    		mySqlBuf.append(ASKc+" group by"+SQLSTD+"order by GOODSNOS,FORMDATE,UNITPRICE,DISCOUNT,CREATEDATETIME,ISCONFIRM");
        }else if (mMode==2){//單一會員-留貨=>銷貨 單項運作
    		mySqlBuf.append("select"+SQLSTD+",sum(UNIT) as UNITS from "+TbName.QITEMS);
    		ASKc=" where USER='"+mUser+"' and  (ISCONFIRM='R' and ISCHECK='Y') and QKIND='"+mKind+"' and DEPTNO='"+mDept+"'";
    		mySqlBuf.append(ASKc+" group by"+SQLSTD+"order by GOODSNOS,FORMDATE,UNITPRICE,DISCOUNT,CREATEDATETIME,ISCONFIRM");
        }else if (mMode==3){//預購留貨_總攬	
        	ASK=ASKg;
    		mySqlBuf.append("select"+SQLSTD+",sum(UNIT) as UNITS from "+TbName.QITEMS);
    		ASKc=" where ISCHECK='Y' and QKIND='"+mKind+"'  and DEPTNO='"+mDept+"'"+ASK;
    		mySqlBuf.append(ASKc+" group by"+SQLSTD+"order by GOODSNOS,FORMDATE,USER,UNITPRICE,DISCOUNT,CREATEDATETIME,ISCONFIRM");
        }else if (mMode==4){//預購_銷貨
        	ASK=ASKg;
    		mySqlBuf.append("select"+SQLSTD+",sum(UNIT) as UNITS from "+TbName.QITEMS);
    		ASKc=" where ISCHECK='Y'  and DEPTNO='"+mDept+"' and QKIND='"+mKind+"' "+ASK;
    		mySqlBuf.append(ASKc+" group by"+SQLSTD+"order by GOODSNOS,FORMDATE,USER,UNITPRICE,DISCOUNT,CREATEDATETIME,ISCONFIRM");
        }
        
		return mySqlBuf.toString();
	}
	
	private String SearchByGoods(){
		StringBuffer mySqlBuf = new StringBuffer();
		mySqlBuf.append("select"+SQLSTD+",sum(UNIT) as UNITS from "+TbName.QITEMS);
		ASKc=" where ISCHECK='Y' and DEPTNO='"+mDept+"' and QKIND='"+mKind+"' "+ASK;
		mySqlBuf.append(ASKc+" group by"+SQLSTD+"order by GOODSNOS,FORMDATE,USER,UNITPRICE,DISCOUNT,CREATEDATETIME");
		return mySqlBuf.toString();
	}
	
	private String SearchByUser(){
		StringBuffer mySqlBuf = new StringBuffer();
		mySqlBuf.append("select"+SQLSTD+",sum(UNIT) as UNITS from "+TbName.QITEMS);
		ASKc=" where ISCHECK='Y'  and DEPTNO='"+mDept+"' and QKIND='"+mKind+"' "+ASK;
		mySqlBuf.append(ASKc+" group by"+SQLSTD+"order by USER,GOODSNOS,FORMDATE,UNITPRICE,DISCOUNT,CREATEDATETIME");
		return mySqlBuf.toString();
	}
	
	private void QuerySqlUser(int print){
		printYN=print;
		if(adapter1 != null && adapter1.getCount()>0)	adapter1.list.clear();
		list = null;
		
 		if (Utilis.haveInternet(this) && of_line!=0){
 			//還要判斷條件下的完整QITEMS SQL

			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
				bfstr.append(Utilis.getIni(this, "SYS", "IMPORT", 2)).append(";");
				bfstrF.append("UID").append(";");
			/* aa0_aa1_gvor.php
			mDept $bankname=@$_REQUEST['BANKNAME'];  	//AA1,A11
			$deptno=@$_REQUEST['DEPTNO'];  	//AA,A1
			$qpart=@$_REQUEST['QPART'];  	//總倉代號 做為 (總倉 或 門市)判斷下載的檔案內容
			$alone=@$_REQUEST['ALONE'];  //ini 7,8,9總倉是否下載其他門市銷貨資料
			$ASKc=@$_REQUEST['ASKC'];
			$ASKSQL=@$_REQUEST['ASKSQL'];
			$timelocal=@$_REQUEST['LUPDATE']; //IMPORT T4
			 */
				bfstr.append(mBankn).append(";");
				bfstrF.append("BANKNAME").append(";");
				bfstr.append(mDept).append(";");
				bfstrF.append("DEPTNO").append(";");
				bfstr.append(deptStr[5]).append(";");
				bfstrF.append("QPART").append(";");
				bfstr.append(Utilis.getIni(this, "SYS", "TRADENAME", 8)).append(";");
				bfstrF.append("ALONE").append(";");
				//bfstr.append(ASKc).append(";");
				//bfstrF.append("ASKC").append(";");
				bfstr.append(BufUserStr).append(";");
				bfstrF.append("ASKSQL").append(";");
				bfstr.append(Utilis.getIni(this, "SYS", "AUPDATE", 4));
				bfstrF.append("LUPDATE");

				final String []fields=bfstr.toString().split(";");
				final String []fieldFs=bfstrF.toString().split(";");
				
				  
			      new Thread()
			      { 
			        public void run()
			        { 
			          try
			          { 
							String uriAPI="http://"+Utilis.getIni(GalleryViewO.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(GalleryViewO.this, "SYS", "IMPORT", 2)+File.separator+"aa0_aa1_gvor.php";
							HttpPost httpRequest = new HttpPost(uriAPI);
							// Post運作傳送變數必須用NameValuePair[]陣列儲存
							Log.i("DOWNLOAD_GalleryViewOR_","VISIT_PHP="+uriAPI );
							
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							for(int x=0;x<fields.length;x++){
								params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
							}
							try {
								httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
								if (httpResponse.getStatusLine().getStatusCode() == 200)
								{
									String strResult = EntityUtils.toString(httpResponse.getEntity());
									//Log.i("DOWNLOAD_GalleryViewOR_","return_DATA="+strResult );
									mHandlerGVO.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
									
								}
							} catch (Exception e)
							{
								e.printStackTrace();
							}

			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			            // 卸載所建立的myDialog物件。
			          }
			        }
			      }.start(); /* 開始執行執行緒 */
 			
 		}else{
 	 		if (of_line==0){
		        SQLiteDatabase db = Utilis.getDB(this);
		        Cursor cs=db.rawQuery(BufUserStr, null);
		        if (cs.getCount()>0){
		        	String returnstr="aa0aa1_gvor;SSSS\r\n";
	 				while (cs.moveToNext()){
	 					for (int read=0;read<=13;read++){
	 						returnstr+=cs.getString(read)+";";
	 					}
	 					returnstr+="SSSS\r\n";
	 				}
	    			db.close();
	    			cs.close();
					showList(returnstr,2);
		        
 	 			}else{
	    			db.close();
	    			cs.close();
		        	Intent intentS = new Intent();
		        	intentS.putExtra("GVPO_modify",0);
		        	GalleryViewO.this.setResult(RESULT_OK,intentS);
	     			finish();
 	 			}
 	 		}else{//Cloud版 但是因為網路不通 拒絕作業
	        	Intent intentS = new Intent();
	        	intentS.putExtra("GVPO_modify",0);
	        	GalleryViewO.this.setResult(RESULT_OK,intentS);
     			finish();
 	 		}
 		}
	}
	
    public void showCheckBoxListViewC(String mUs,String mGo,String mGn,String mPg,String OD,String RD,int Ot,int Rt,String DISC,String UNITP,String CTIME) {

    	if (list==null) list = new ArrayList<HashMap<String, Object>>();

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("item_rul", mGo);  //貨號
            map.put("item_rcl",mGn);	//貨品名稱
           	map.put("item_rcc", ""+Ot);	//
           	map.put("item_rcr", ""+Rt);		//	
			//if (mUn.indexOf((mDept+"5"))==0 || mUn.indexOf((mDept+"6"))==0) mUn="";
			map.put("item_rdl", mUs);	//
            map.put("item_rdc", OD);
            map.put("item_rdr", RD);
           	map.put("item_rh1", ""+Ot);//左量
           	map.put("item_rh2", ""+Rt);//右量
           	map.put("item_rh3", ""+mFnO);//左單
           	map.put("item_rh4", ""+mFnR);//右單
           	map.put("item_rpic", mPg); //圖片
			map.put("item_riv",null);
            map.put("item_rcb", false);
            map.put("item_acl",DISC);	//DISCOUNT
           	map.put("item_acc", UNITP);
           	map.put("item_acr", "");
           	map.put("item_rtm", CTIME);
            list.add(map);
            adapter1 = new MyAdapter1(this, list, R.layout.list_repo,
                    new String[] { "item_rul" ,"item_rcl" ,"item_rcc" ,"item_rcr" ,"item_rdl" ,"item_rdc","item_rdr","item_rh1","item_rh2","item_rh3","item_rh4","item_rpic" ,"item_riv", "item_rcb","item_acl" ,"item_acc" ,"item_acr","item_rtm"}, new int[] {
                            R.id.item_rul,R.id.item_rcl,R.id.item_rcc,R.id.item_rcr,R.id.item_rdl,R.id.item_rdc,R.id.item_rdr,R.id.item_rh1,R.id.item_rh2,R.id.item_rh3,R.id.item_rh4,R.id.item_rpic,R.id.item_riv, R.id.item_rcb,R.id.item_acl,R.id.item_acc,R.id.item_acr ,R.id.item_rtm });
                            
            mListView.setAdapter(adapter1);
    }

    private void getPrintitle(int selectTitle){
    	if (selectTitle==0){
		Loca=30;
		Loca=Loca+2;sPrintB.append("AZ,20,"+Loca+",2,2,0,0,"+compStr[0]+sepa);
		Loca=Loca+50;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+"會員 - 預購留貨明細理貨清單"+sepa);
		Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
		Loca=Loca+5;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
    	}else if (selectTitle==1){
			Loca=30;
			Loca=Loca+2;sPrintB.append("AZ,20,"+Loca+",2,2,0,0,"+compStr[0]+sepa);
			Loca=Loca+50;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+"商品 - 預購留貨明細理貨清單"+sepa);
			Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
			Loca=Loca+5;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
       	} 
    }
    
    
    
    public static class MyAdapter1 extends BaseAdapter {
        
        private Context context = null;
        private LayoutInflater inflater = null;
        private List<HashMap<String, Object>> list = null;
        private String keyString[] = null;
        private String itemString = null; // 记录每个item中textview的值
        private Boolean itemBoolean = true;        
        private int idValue[] = null;// id值
 
        public MyAdapter1(Context context, List<HashMap<String, Object>> list,
                int resource, String[] from, int[] to) {
            this.context = context;
            this.list = list;
            keyString = new String[from.length];
            idValue = new int[to.length];
            System.arraycopy(from, 0, keyString, 0, from.length);
            System.arraycopy(to, 0, idValue, 0, to.length);
            inflater = LayoutInflater.from(context);
        }
 
        @Override
        public int getCount() {
            return list.size();
        }
 
        @Override
        public Object getItem(int arg0) {
            return list.get(arg0);
        }
 
        @Override
        public long getItemId(int arg0) {
            return 0;
        }
 
        @Override
        public View getView(int position, View view, ViewGroup arg2) {
            ViewHolder1 holder = null;
            positionGoods=position;
            if (holder == null) {
                holder = new ViewHolder1();
                if (view == null) {
                    view = inflater.inflate(R.layout.list_repo, null);
                }

                holder.rul=(TextView) view.findViewById(R.id.item_rul);
                holder.rcl=(TextView) view.findViewById(R.id.item_rcl);
                holder.rcc=(TextView) view.findViewById(R.id.item_rcc);
                holder.rcr=(TextView) view.findViewById(R.id.item_rcr);
                holder.acl=(TextView) view.findViewById(R.id.item_acl);
                holder.acc=(TextView) view.findViewById(R.id.item_acc);
                holder.acr=(TextView) view.findViewById(R.id.item_acr);
                holder.rtm=(TextView) view.findViewById(R.id.item_rtm);
                holder.rdl=(TextView) view.findViewById(R.id.item_rdl);
                holder.rdc=(TextView) view.findViewById(R.id.item_rdc);                
                holder.rdr=(TextView) view.findViewById(R.id.item_rdr);
                holder.rh1=(TextView)view.findViewById(R.id.item_rh1);
                holder.rh2=(TextView) view.findViewById(R.id.item_rh2);
                holder.rh3=(TextView) view.findViewById(R.id.item_rh3);
                holder.rh4=(TextView) view.findViewById(R.id.item_rh4);
                holder.rpic=(TextView) view.findViewById(R.id.item_rpic);
                holder.riv=(ImageView)view.findViewById(R.id.item_riv);
                holder.rcb = (CheckBox) view.findViewById(R.id.item_rcb);
                if (mMode==2){
                ((Button) view.findViewById(R.id.btn_order)).setText("留貨");
                ((Button) view.findViewById(R.id.btn_keepa)).setText("銷貨");
                }
                holder.btn_ord = (Button) view.findViewById(R.id.btn_order);
                holder.btn_keepa = (Button) view.findViewById(R.id.btn_keepa);

                view.setTag(holder);
            } else {
                holder = (ViewHolder1) view.getTag();
            }
            ViewTag viewTag = new ViewTag(
                    (Button) view.findViewById(R.id.btn_order),
                    (Button) view.findViewById(R.id.btn_keepa),
                    (CheckBox) view.findViewById(R.id.item_rcb)
            		);

            viewTag.btn1.setOnClickListener(new ItemButton_order(context, position));
            viewTag.btn2.setOnClickListener(new ItemButton_keepa(context, position));
            viewTag.cbx1.setOnClickListener(new ItemButton_chkbox(context, position));

            viewTag.btn1.setOnLongClickListener(new Button_Long_order(context, position));
            viewTag.btn2.setOnLongClickListener(new Button_Long_keepa(context, position));
            
            HashMap<String, Object> map = list.get(position);
            if (map != null) {
                itemString = (String) map.get(keyString[0]);
                holder.rul.setText(itemString);

                itemString = (String) map.get(keyString[1]);
                holder.rcl.setText(itemString);
                
                itemString = (String) map.get(keyString[2]);
                holder.rcc.setText(itemString);
                
                itemString = (String) map.get(keyString[3]);
                holder.rcr.setText(itemString);
                
                itemString = (String) map.get(keyString[4]);
                holder.rdl.setText(itemString);
                
                itemString = (String) map.get(keyString[5]);
                holder.rdc.setText(itemString);

                itemString = (String) map.get(keyString[6]);
                holder.rdr.setText(itemString);

                itemString = (String) map.get(keyString[7]);
                holder.rh1.setText(itemString);

                itemString = (String) map.get(keyString[8]);
                holder.rh2.setText(itemString);

                itemString = (String) map.get(keyString[9]);
                holder.rh3.setText(itemString);

                itemString = (String) map.get(keyString[10]);
                holder.rh4.setText(itemString);

                itemString = (String) map.get(keyString[11]);
                holder.rpic.setText(itemString);
                
               	 itemString = (String) map.get(keyString[11]);
 	                if(itemString != null && itemString.length() > 0){	                
 	                	if( itemString.indexOf("drawable/") < 0) { 
 	                		Bitmap bmp=Utilis.getLimitBitmap( itemString,60,60);
 	                		if (bmp!=null)holder.riv.setImageBitmap(bmp);
         				} else	holder.riv.setImageResource(R.drawable.m053);
    				} else	holder.riv.setImageResource(R.drawable.m053);    				
               
                itemBoolean = (Boolean)map.get(keyString[13]);
                holder.rcb.setChecked(itemBoolean);
                
                itemString = (String) map.get(keyString[14]);
                holder.acl.setText(itemString);
                
                itemString = (String) map.get(keyString[15]);
                holder.acc.setText(itemString);
                
                itemString = (String) map.get(keyString[16]);
                holder.acr.setText(itemString);
                
                itemString = (String) map.get(keyString[17]);
                holder.rtm.setText(itemString);
                
            }
            return view;
        }

        public class ViewTag {
        	Button btn1;
        	Button btn2;
        	CheckBox cbx1;
        	
            public ViewTag(Button button1, Button button2,CheckBox chkbox1) {
                this.btn1 = button1;
                this.btn2 = button2;
                this.cbx1 = chkbox1;
            }
        }

        
         private void ItemCount(Context context, int func,int position) {
            HashMap<String, Object> map = list.get(position);
            int order=Utilis.toInt(map.get(keyString[2]).toString());
            int keepa=Utilis.toInt(map.get(keyString[3]).toString());
            int success=0;;
	        	switch (func){
		        	case 0:{ //還原
 	                	map.put(keyString[2],map.get(keyString[7]).toString());
 	                	map.put(keyString[3],map.get(keyString[8]).toString());
		                success=1;
		        		break;
		        	}
		        	case 1:{ //留貨+1
		                if (order>0){
			                map.put(keyString[2],""+(order-1) );
			                map.put(keyString[3],""+(keepa+1) );
			                success=1;
		                }		        		
		        		break;
		        	}
		        	case -1:{//留貨-1
		                if (keepa>0){
		                	map.put(keyString[2],""+(order+1) );
		                	map.put(keyString[3],""+(keepa-1) );
			                success=1;
		                }		        		
		        		break;
		        	}
		        	case 99:{//ALL留貨
		                if (order>0){
		                	map.put(keyString[2],"0" );
		                	map.put(keyString[3],""+(order+keepa));
			                success=1;
		                }		        		
		        		break;
		        	}
		        	case 88:{//ALL預購
		                if (keepa>0){
		                	map.put(keyString[2],""+(order+keepa) );
		                	map.put(keyString[3],"0");
			                success=1;
		                }		        		
		        		break;
		        	}
	        	}
            	if (!map.get(keyString[2]).toString().equalsIgnoreCase(map.get(keyString[7]).toString()) & !map.get(keyString[3]).toString().equalsIgnoreCase(map.get(keyString[8]).toString()))
            		map.put(keyString[13], true);
            	else
            		map.put(keyString[13], false);
            	
                list.set(position, map);
            	list.listIterator(position);
            	adapter1.notifyDataSetChanged();
        	
        }
        //自訂按鈕監聽事件
        class ItemButton_order implements OnClickListener {
            private int position;
            ItemButton_order(Context context, int pos) {
                position = pos;
            }
			@Override
            public void onClick(View v) {
            	ItemCount(context,-1,position);
            }
        }
        
        //自訂按鈕監聽事件
        class Button_Long_order implements OnLongClickListener {
            private int position;
            Button_Long_order(Context context, int pos) {
                position = pos;
            }
			@Override
			public boolean onLongClick(View v) {
            	ItemCount(context,88,position);
            	return false;
			}
        }

        class Button_Long_keepa implements OnLongClickListener {
            private int position;
            Button_Long_keepa(Context context, int pos) {
                position = pos;
            }

			@Override
			public boolean onLongClick(View v) {
            	ItemCount(context,99,position);
				return false;
			}
        }
        
        class ItemButton_keepa implements OnClickListener {
            private int position;
            ItemButton_keepa(Context context, int pos) {
                position = pos;
            }
            public void onClick(View v) {
            	ItemCount(context,1,position);
            }
        }
        
        class ItemButton_chkbox implements OnClickListener {
            private int position;
            ItemButton_chkbox(Context context, int pos) {
                position = pos;
            }
            public void onClick(View v) {
                HashMap<String, Object> map = list.get(position);
                    		 if ((Boolean)map.get(keyString[13])==true){
                              	ItemCount(context,0,position);
                    		 }else{
                             	ItemCount(context,99,position);
                    		 }
			}
        }
 
        public class ViewHolder1 {
            public TextView rul = null;
            public TextView rcl = null;
            public TextView rcc = null;
            public TextView rcr = null;
            public TextView acl = null;
            public TextView acc = null;
            public TextView acr = null;
            public TextView rdl = null;
            public TextView rdc = null;
            public TextView rdr = null;
            public TextView rh1 = null;
            public TextView rh2 = null;
            public TextView rh3 = null;
            public TextView rh4 = null;
            public TextView rpic = null;
            public ImageView riv =null;
            public CheckBox rcb = null;
            public Button btn_ord  =null;
            public Button btn_keepa  =null;
            public TextView rtm = null;
        } 
    }

    

 	class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@Override
		public void onClick(View v) {
		int id = v.getId();
		Utilis.runVibrate(GalleryViewO.this);
		switch (id) {
		case R.id.btn_exit://返回
		{
			//先檢查有無異動
			int chk=0;
			if (list !=null && list.size()>0){
				for (int x=0;x<list.size();x++){
					HashMap<String, Object> map = list.get(x);
					if ((Boolean)map.get("item_rcb")==true){
						chk=1;break;
					}
				}
				if (chk==1){//對話是否確定返回
					DialogUtilis.showDialog(GalleryViewO.this, "資料已異動!!是否放棄轉單?", -1,
					new String[] { "放棄轉單", "繼續執行" }, new IDialog() {
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch (pos) {
							case 0:
								if (list !=null && list.size()>0)	list.clear();
					        	Intent intentS = new Intent();
					        	intentS.putExtra("GVPO_modify",0);
					        	GalleryViewO.this.setResult(RESULT_OK,intentS);
								finish();
								break;
							case 1:break;
							}
						}
					});	
			}	}
			if (chk==0) {
				if (list !=null && list.size()>0)	list.clear();
	        	Intent intentS = new Intent();
	        	intentS.putExtra("GVPO_modify",0);
	        	GalleryViewO.this.setResult(RESULT_OK,intentS);
				finish();
				}
			break;
		}
		case R.id.btn_allyes://全選
		{
			if (list !=null && list.size()>0){
				for (int x=0;x<list.size();x++){
					HashMap<String, Object> map = list.get(x);
					int keepa=Utilis.toInt(map.get("item_rh1").toString())+Utilis.toInt(map.get("item_rh2").toString());
					map.put("item_rcc", "0");
					map.put("item_rcr", ""+keepa);
					map.put("item_rcb", true);
	                list.set(x, map);
	            	list.listIterator(x);
				}
            	adapter1.notifyDataSetChanged();
			}						
			
			break;
		}
		case R.id.btn_allno://全不選
		{
			if (list !=null && list.size()>0){
				for (int x=0;x<list.size();x++){
					HashMap<String, Object> map = list.get(x);
					map.put("item_rcc", map.get("item_rh1").toString());
					map.put("item_rcr", map.get("item_rh2").toString());
					map.put("item_rcb", false);
	                list.set(x, map);
	            	list.listIterator(x);
				}
            	adapter1.notifyDataSetChanged();
			}						
			break;
		}
		case R.id.imageButton15:	//以輸入貨號查詢
			if (mMode!=2){
				ASK=" and GOODSNO LIKE '%"+mEdSearch.getText().toString()+"%' ";
				BufUserStr=SearchByGoods();
				QuerySqlUser(0);
            	adapter1.notifyDataSetChanged();
			}
			break;
		case R.id.imageButton16:	//還原
			ASK=ASKg;
			BufUserStr=SearchBG();
	        QuerySqlUser(0);		
        	adapter1.notifyDataSetChanged();
			break;
		case R.id.btn_rcount://統計
		{
			if (list !=null && list.size()>0){
				int lastO=0;
				int lastR=0;
				int thisO=0;
				int thisR=0;
				int nowO=0;
				int nowR=0;
				
				for (int x=0;x<list.size();x++){
					HashMap<String, Object> map = list.get(x);
					lastO+=Utilis.toInt(map.get("item_rh1").toString());
					lastR+=Utilis.toInt(map.get("item_rh2").toString());
					nowO+=Utilis.toInt(map.get("item_rcc").toString());
					nowR+=Utilis.toInt(map.get("item_rcr").toString());
				}
				thisO=nowO-lastO;
				thisR=nowR-lastR;
				DialogUtilis.showDialog(GalleryViewO.this, "會員:"+mUser+"預購&留貨統計一覽表", -1,
				new String[] { "上次預購_"+lastO,"上次留貨_"+lastR,"本次預購_"+thisO,"本次留貨_"+thisR,"預購尚有_"+nowO,"留貨合計_"+nowR}, new IDialog() {
					@Override
					public void onDialogFinish(int pos, String choice) {
						switch (pos) {
						case 0:
						}
					}
				});	
			}
			break;
		}
		case R.id.btn_save://轉單
		{
		//以mode==2 只有單一會員 進行 留貨轉銷貨的 可能
		//所以 mFnO 就是留貨單
		//檢查 Cloud 卻 沒有網路 處置方式
			
			int goon=0;//先檢查,是否有異動
			for (int x=0;x<list.size();x++){
				HashMap<String, Object> map = list.get(x);
				if ((Boolean)map.get("item_rcb")==true){
					goon=1;break;
				}
			}
			if (goon!=0){
				int chkSave=0;
				String needRcountHeadO="";
				String needRcountHeadR="";
	    		String FormD=DateUtil.getCurrentDate();  //2012-10-22
	    		int Ttime=Utilis.toInt(DateUtil.getSystemTime().substring(8, 10));  //取得目前幾點
				if (Ttime<=5)  FormD = DateUtil.addDate(FormD, -1);
				FormD = FormD.replace("/", "-");
				
				ServerStr.delete(0, ServerStr.toString().length());
				ServerRecountHead="";			
				ServerStr.append("updateserver;HHHH\r\n");
				if (mMode==2){//留mFnO=>銷mFnR
					//@@@關鍵問題出在 Cloud版 留貨資料在雲端
					//LOCAL無留貨資料
					SQLiteDatabase db = Utilis.getDB(GalleryViewO.this);
					String SQL="";
					mFnO=mDept+"6"+mUser;
					//mFnO 永遠是留貨單號
					//mFnR 銷貨單號 永遠是預先傳入的
					db.beginTransaction();
					try{
					for (int x=0;x<list.size();x++){
					HashMap<String, Object> map = list.get(x);
					if ((Boolean)map.get("item_rcb")==true){
						
						int lastR=(Utilis.toInt(map.get("item_rh2").toString()));//0
						int nowO=(Utilis.toInt(map.get("item_rcc").toString()));//即時留2
						int nowR=(Utilis.toInt(map.get("item_rcr").toString()));//即時銷1
						double adisc=(Utilis.toDouble(map.get("item_acl").toString()));//折
						double aunitp=(Utilis.toDouble(map.get("item_acc").toString()));//單價
						int thisR=nowR-lastR;//銷貨調整量 這裡應為本次銷貨量
						String CTIME=map.get("item_rtm").toString();
						mGoods=map.get("item_rul").toString();
						getListData(map);//ServerStr
						String[] args = {mFnO,mGoods,mUser,""+adisc,""+aunitp,CTIME};
						//優先處理留貨
						if (thisR!=0){//有銷貨時
							SQL="select * from "+TbName.QITEMS+" where FORMNO='"+mFnO+"' and GOODSNOS='"+mGoods+"' and USER='"+mUser+"' and DISCOUNT="+adisc+" and UNITPRICE="+aunitp+" and CREATEDATETIME='"+CTIME+"'";
							//先找出留貨單號該ITEMS 內容
							Cursor csc1=db.rawQuery(SQL, null);
							if (csc1.getCount()>0){ //表示找到原留貨單
								csc1.moveToFirst();
								double aCost=csc1.getDouble(csc1.getColumnIndex("P1"));
								
								ContentValues value = new ContentValues();
									csc1.moveToFirst();
				 					String [] Fields=new String [csc1.getColumnCount()];
									for (int xx=0;xx<csc1.getColumnCount();xx++)
									Fields[xx]=csc1.getString(xx);
									//將原留貨單 調整成 即時留2 nowO
									Fields[0]="Y1";
									Fields[20]=""+nowO;
									Fields[46]=""+nowO;
									Fields[23]=""+Math.round(nowO*aCost);//成本小計
									Fields[27]=""+Math.round(nowO*aunitp*adisc/100);//小計
									Fields[44]="0";Fields[45]="0";Fields[47]="0";
									for (int xx=0;xx<csc1.getColumnCount();xx++){
										value.put(csc1.getColumnName(xx), Fields[xx]);
										ServerStr.append(Fields[xx]+";");
									}
									ServerStr.append("\r\n");
									int succes=db.update(TbName.QITEMS,  value,"FORMNO=? and GOODSNOS=? and USER=? and DISCOUNT=? and UNITPRICE=? and CREATEDATETIME=?",args);
									
								ContentValues value1 = new ContentValues();
								SQL="select * from "+TbName.QITEMS+" where FORMNO='"+mFnR+"' and GOODSNOS='"+mGoods+"' and USER='"+mUser+"' and DISCOUNT="+adisc+" and UNITPRICE="+aunitp;
								Cursor csc2=db.rawQuery(SQL, null);
								if (csc2.getCount()>0){ //表示在銷貨 找到一樣的
									csc2.moveToFirst();
									 
									for (int xx=0;xx<csc2.getColumnCount();xx++)
									Fields[xx]=csc2.getString(xx);
									
									aCost=csc2.getDouble(csc2.getColumnIndex("P1"));
									String cTime=csc2.getString(csc2.getColumnIndex("CREATEDATETIME"));
									Fields[0]="Y0";
									Fields[7]="N";
									Fields[8]="N";
									Fields[20]="0"; //UNIT=0;
									Fields[46]=""+(Utilis.toInt(Fields[46])+thisR);
									Fields[23]=""+Math.round(Utilis.toInt(Fields[46])*aCost);//成本小計
									Fields[27]=""+Math.round(Utilis.toInt(Fields[46])*aunitp*adisc/100);//小計
									if (f123!=0){
										//20190121
										Fields[23]=""+Utilis.dedb(Utilis.toDouble(Fields[46])*aCost,3);//成本小計
										Fields[27]=""+Utilis.dedb(Utilis.toDouble(Fields[46])*aunitp*adisc/100,2);//小計
//										Fields[23]=""+Utilis.dedb(thisR*aCost,3);//成本小計
//										Fields[27]=""+Utilis.dedb(thisR*aunitp*adisc/100,2);//小計
									}
									Fields[44]="0";Fields[45]="0";Fields[47]="0";
									for (int xx=0;xx<csc2.getColumnCount();xx++)
										value1.put(csc2.getColumnName(xx), Fields[xx]);
									args[0] =mFnR;args[5] =cTime;
									succes=db.update(TbName.QITEMS,  value1,"FORMNO=? and GOODSNOS=? and USER=? and DISCOUNT=? and UNITPRICE=? and CREATEDATETIME=?",args);
								}else{
									//是留貨單的原始檔但是已異動的
									Fields[0]="Y0"; //TR=QKIND
									Fields[3]=mFnR;
									Fields[7]="N";
									Fields[8]="N";
									Fields[20]="0";
									Fields[46]=""+thisR;
									Fields[23]=""+Math.round(thisR*aCost);//成本小計
									Fields[27]=""+Math.round(thisR*aunitp*adisc/100);//小計
									if (f123!=0){
										Fields[23]=""+Utilis.dedb(thisR*aCost,3);//成本小計
										Fields[27]=""+Utilis.dedb(thisR*aunitp*adisc/100,2);//小計
									}
									
									Fields[44]="0";Fields[45]="0";Fields[47]="0";
									
									for (int xx=0;xx<csc1.getColumnCount();xx++)
										value1.put(csc1.getColumnName(xx), Fields[xx]);
									
									long success=db.insert(TbName.QITEMS, null, value1);
								}
								csc2.close();
								value1.clear();
							}else{//確認電腦並沒有 留貨單 應先到SERVER緊急調閱並維護該 留貨單
								if (Utilis.haveInternet(GalleryViewO.this) && of_line==1)  //逾3分鐘沒有同步
									if (!Utilis.getIni(GalleryViewO.this, "SYS", "SEASON", 4).equalsIgnoreCase("0")){
										DBCloud.aa0_aa1_auto_HI_ORNY(GalleryViewO.this,mFnO,"0");//0留貨1預購 維護
										Toast.makeText(GalleryViewO.this, "請看到留貨維護成功後,再按一次[轉單]!!", Toast.LENGTH_SHORT).show();
									}else{//正常同步程序正在進行中,請稍後,再按[轉單]
										Toast.makeText(GalleryViewO.this, "正常同步程序正在進行中,請稍後,再按[轉單]!!", Toast.LENGTH_SHORT).show();
									}
								break;
							}
							csc1.close();
						}
					}
					}
		            db.setTransactionSuccessful();
					chkSave=1;
				  }
				  catch(Exception e){
						if (Utilis.haveInternet(GalleryViewO.this) && of_line==1)  //逾3分鐘沒有同步
							
						if (!Utilis.getIni(GalleryViewO.this, "SYS", "SEASON", 4).equalsIgnoreCase("0")){
							DBCloud.aa0_aa1_auto_HI_ORNY(GalleryViewO.this,mFnO,"0");//0留貨1預購 維護
							Toast.makeText(GalleryViewO.this, "請看到留貨維護成功後,再按一次[轉單]!!", Toast.LENGTH_SHORT).show();
						}else{//正常同步程序正在進行中,請稍後,再按[轉單]
							Toast.makeText(GalleryViewO.this, "正常同步程序正在進行中,請稍後,再按[轉單]!!", Toast.LENGTH_SHORT).show();
						}
						chkSave=0;
				  }
					 
				  finally{
						db.endTransaction();
				  }
					db.close();
					needRcountHeadR=mFnR+";";
					needRcountHeadO=mFnO+";";
						//都是 唯一單號
							
				}else if (mMode<4 && mMode!=2){//就留貨預購的轉單功能
					
					SQLiteDatabase db = Utilis.getDB(GalleryViewO.this);
					String SQL="";
					
					
				  db.beginTransaction();
				  try{
					for (int x=0;x<list.size();x++){
						HashMap<String, Object> map = list.get(x);
					if ((Boolean)map.get("item_rcb")==true){
					
						int lastO=(Utilis.toInt(map.get("item_rh1").toString()));
						int lastR=(Utilis.toInt(map.get("item_rh2").toString()));
						int nowO=(Utilis.toInt(map.get("item_rcc").toString()));
						int nowR=(Utilis.toInt(map.get("item_rcr").toString()));
						int thisO=nowO-lastO;//預購調整量
						int thisR=nowR-lastR;//留貨調整量
						double adisc=Utilis.toDouble(map.get("item_acl").toString());
						double aunitp=Utilis.toDouble(map.get("item_acc").toString());//單價
						String CTIME=map.get("item_rtm").toString();
						mUser=map.get("item_rdl").toString().substring(0,map.get("item_rdl").toString().indexOf("/"));
						mFnO=map.get("item_rh3").toString();  //預購單號 可能為 多數筆 來自網路訂單 也有可能為 不存在 
						if (mFnO!=null && mFnO.length()>0){} else{mFnO=mDept+"5"+mUser;} //預設的預購單號
						mFnR=mDept+"6"+mUser;  //預設的留貨單號
						//因為轉檔既然事實,務必異動預購及留貨單據
						needRcountHeadO+=mFnO+";";
						needRcountHeadR+=mFnR+";";
						getListData(map);
						mGoods=map.get("item_rul").toString();
						String[] args = {mFnR,mGoods,mUser,""+adisc,""+aunitp,CTIME};//指定留貨單號
						int getItems=0;
						//優先處理留貨
						if (thisR!=0){//表示 留貨有 異動
								SQL="select * from "+TbName.QITEMS+" where FORMNO='"+mFnR+"' and GOODSNOS='"+mGoods+"' and USER='"+mUser+"' and DISCOUNT="+adisc+" and UNITPRICE="+aunitp+" and CREATEDATETIME='"+CTIME+"'";
								Cursor csc=db.rawQuery(SQL, null);
								if (csc.getCount()>0){ //表示該筆存在 留貨量需要累加程序
									csc.moveToFirst();
									//缺點是尚未更新的資料,送到SERVER依舊可以引用
									if (getItems==0){
										getQitemsData(csc);
										getItems=1;
									}
										int relR=thisR+csc.getInt(csc.getColumnIndex(mUNIT));
										double aPrice=csc.getDouble(csc.getColumnIndex("UNITPRICE"));
										double aDisc=csc.getDouble(csc.getColumnIndex("DISCOUNT"));
										double aCost=csc.getDouble(csc.getColumnIndex("P1"));
											aCost=Math.round(relR*aCost);
											aPrice=Math.round(relR*aPrice*aDisc/100);
										if (f123!=0){
											aCost=Utilis.dedb(relR*aCost,3);
											aPrice=Utilis.dedb(relR*aPrice*aDisc/100,2);
										}
										
										ContentValues value = new ContentValues();
										value.put("TR","Y0"); 
										value.put(mUNIT,relR);
										value.put("ACOST", aCost);
										value.put("SUBPRICE", aPrice);
										value.put("UNIT", relR);
										int success = db.update(TbName.QITEMS, value,"FORMNO=? and GOODSNOS=? and USER=? and DISCOUNT=? and UNITPRICE=? and CREATEDATETIME=?", args);
								}else{//留貨單不存在需要新增一筆留貨單,方法是
									//先找到該貨的預購單 再行複製新增到一張留貨單 更新後 
									SQL="select  * from "+TbName.QITEMS+" where FORMNO='"+mFnO+"' and GOODSNOS='"+mGoods+"' and USER='"+mUser+"' and DISCOUNT="+adisc+" and UNITPRICE="+aunitp+" and CREATEDATETIME='"+CTIME+"'";
									Cursor csc1=db.rawQuery(SQL, null);
									if (csc1.getCount()>0){ //表示需要轉單
										csc1.moveToFirst();
										if (getItems==0){
											getQitemsData(csc1);
											getItems=1;
										}//此時會因為
										int relR=thisR;
										double aPrice=csc1.getDouble(csc1.getColumnIndex("UNITPRICE"));
										double aDisc=csc1.getDouble(csc1.getColumnIndex("DISCOUNT"));
										double aCost=csc1.getDouble(csc1.getColumnIndex("P1"));
										if (f123==0){
											aCost=Math.round(relR*aCost);
											aPrice=Math.round(relR*aPrice*aDisc/100);
										}else{
											aCost=Utilis.dedb(relR*aCost,3);
											aPrice=Utilis.dedb(relR*aPrice*aDisc/100,2);
										}
											
										ContentValues value = new ContentValues();
											csc1.moveToFirst();
						 					String [] Fields=new String [csc1.getColumnCount()];
											//須改變 單號 
											for (int xx=0;xx<csc1.getColumnCount();xx++)
											Fields[xx]=csc1.getString(xx);
											
											Fields[0]="Y0";
											Fields[3]=mFnR;
											Fields[7]="R";
											Fields[8]="Y";
											Fields[20]=""+thisR;
											Fields[46]=""+thisR;
											double aPri=Utilis.toInt(Fields[21]);
											double dDisc=Utilis.toDouble(Fields[22]);
											aCost=Utilis.toInt(Fields[29]);
											if (f123==0){
												aCost=Math.round(thisR*aCost);
												aPri=Math.round(thisR*aPri*dDisc/100);
											}else{
												aCost=Utilis.dedb(thisR*aCost,3);
												aPri=Utilis.dedb(thisR*aPri*dDisc/100,2);
											}
											Fields[23]=""+aCost;//成本小計
											Fields[27]=""+aPri;//小計
											Fields[44]="0";Fields[45]="0";Fields[47]="0";
											for (int xx=0;xx<csc1.getColumnCount();xx++){
												value.put(csc1.getColumnName(xx), Fields[xx]);
											}
											long success=db.insert(TbName.QITEMS, null, value);
										}
									csc1.close();
								}
								csc.close();
						}
	
						if (thisO!=0){//預購量改變,表示需要異動預購單
							args[0] = mFnO;
									SQL="select  * from "+TbName.QITEMS+" where FORMNO='"+mFnO+"' and GOODSNOS='"+mGoods+"' and USER='"+mUser+"' and DISCOUNT="+adisc+" and UNITPRICE="+aunitp+" and CREATEDATETIME='"+CTIME+"'";
									Cursor csc=db.rawQuery(SQL, null);
								//表示該預購單 需要累加	
								if (csc.getCount()>0){ //表示找到該預購單需要累加程序
										csc.moveToFirst();
										if (getItems==0){
											getQitemsData(csc);
											getItems=1;
										}
										ContentValues value = new ContentValues();
										//mFnO=mDept+"5"+mUser;
										args[0] = mFnO;
										
										value.put("TR","Y0"); 
										value.put("ISCONFIRM","O");
										value.put("ISCHECK","Y");
										value.put("FORMNO",mFnO);
										
											int relO=thisO+csc.getInt(csc.getColumnIndex(mUNIT));
											double aPrice=csc.getDouble(csc.getColumnIndex("UNITPRICE"));
											double aDisc=csc.getDouble(csc.getColumnIndex("DISCOUNT"));
											double aCost=csc.getDouble(csc.getColumnIndex("P1"));
											if(f123==0){
												aCost=Math.round(relO*aCost);
												aPrice=Math.round(relO*aPrice*aDisc/100);
											}else{
												aCost=Utilis.dedb(relO*aCost,3);
												aPrice=Utilis.dedb(relO*aPrice*aDisc/100,2);
											}
										
										value.put(mUNIT, relO);
										value.put("UNIT", relO);
										value.put("ACOST", aCost);
										value.put("SUBPRICE", aPrice);
	
										int success = db.update(TbName.QITEMS, value,"FORMNO=? and GOODSNOS=? and USER=? and DISCOUNT=? and UNITPRICE=? and CREATEDATETIME=?", args);
								}else{  //找不到預購單 可以累加時
									if (nowO!=0){
										SQL="select  * from "+TbName.QITEMS+" where FORMNO='"+mFnR+"' and GOODSNOS='"+mGoods+"' and USER='"+mUser+"' and DISCOUNT="+adisc+" and UNITPRICE="+aunitp+" and CREATEDATETIME='"+CTIME+"'";
										 Cursor cse=db.rawQuery(SQL, null);
										if (cse.getCount()>0){ //
											ContentValues value = new ContentValues();
											cse.moveToFirst();
											if (getItems==0){
												getQitemsData(cse);
												getItems=1;
											}
						 					String [] Fields=new String [cse.getColumnCount()];
											//須改變 單號 
											for (int xx=0;xx<cse.getColumnCount();xx++)
											Fields[xx]=cse.getString(xx);
											
											Fields[0]="Y0";
											Fields[3]=mFnO;
											Fields[7]="O";
											Fields[8]="Y";
											Fields[20]=""+nowO;
											Fields[46]=""+nowO;
											double aPri=Utilis.toDouble(Fields[21]);
											double dDisc=Utilis.toDouble(Fields[22]);
											double aCost=Utilis.toDouble(Fields[29]);
											if (f123==0){
												aCost=Math.round(thisO*aCost);
												aPri=Math.round(thisO*aPri*dDisc/100);
											}else{
												aCost=Utilis.dedb(thisO*aCost,3);
												aPri=Utilis.dedb(thisO*aPri*dDisc/100,2);
											}
											Fields[23]=""+aCost;//成本小計
											Fields[27]=""+aPri;//小計
											Fields[44]="0";Fields[45]="0";Fields[47]="0";
											for (int xx=0;xx<cse.getColumnCount();xx++)
												value.put(cse.getColumnName(xx), Fields[xx]);
											
											long success=db.insert(TbName.QITEMS, null, value);
										}
										cse.close();
									}	
								}
								csc.close();
						}
						if (getItems==0) ServerStr.append("\r\n");
					}
					}
		            db.setTransactionSuccessful();
					chkSave=1;
				  }
				  catch(Exception e){
						if (Utilis.haveInternet(GalleryViewO.this) && of_line==1)  //逾3分鐘沒有同步
							if (!Utilis.getIni(GalleryViewO.this, "SYS", "SEASON", 4).equalsIgnoreCase("0")){
								DBCloud.aa0_aa1_auto_HI_ORNY(GalleryViewO.this,mFnO,"1");//0留貨1預購 維護
								Toast.makeText(GalleryViewO.this, "請看到預購維護成功後,再按一次[轉單]!!", Toast.LENGTH_SHORT).show();
							}else{//正常同步程序正在進行中,請稍後,再按[轉單]
								Toast.makeText(GalleryViewO.this, "正常同步程序正在進行中,請稍後,再按[轉單]!!", Toast.LENGTH_SHORT).show();
							}
						chkSave=0;
				  }
				  finally{
						db.endTransaction();
				  }
					db.close();
				}
			if (chkSave==1) {	
				ServerStr.append(";HHHH\r\n");
				//第二段資料建立完畢
				
				SQLiteDatabase dbH = Utilis.getDB(GalleryViewO.this);
				String SQL="";
				String hListR []=needRcountHeadR.split(";");
				String hListO []=needRcountHeadO.split(";");
				//是對稱很重要 但是會重複
				needRcountHeadR="";  //留貨單 或 銷貨單
				needRcountHeadO=""; //預購單 或 留貨單
	
				if (hListR.length>0){
					for (int y=0;y<hListR.length;y++){
						if (hListR[y].length()>0 && needRcountHeadR.indexOf((hListR[y]+";"))<0){
							//同單號不再重複維護一次
							needRcountHeadR+=hListR[y]+";";
							if (mMode!=2) ServerRecountHead+=",'"+hListR[y]+"'";						
							dbH.execSQL("delete from "+TbName.QITEMS+" where FORMNO='"+hListR[y]+"' and UNIT30<=0 ");
						//只刪除 件數為0 的 資料
							SQL="select * from "+TbName.QHEAD+" where FORMNO='"+hListR[y]+"'";	    											
							Cursor csH=dbH.rawQuery(SQL, null);
							if (csH.getCount()<=0){ //如果沒有單頭(留貨單 或 銷貨單) 需複製單頭
								//留貨單 複製 預購單  銷貨單 複製 留貨單
							SQL="select * from "+TbName.QHEAD+" where FORMNO='"+hListO[y]+"'";	    											
							csH=dbH.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);
									
									Fields[0]=Fields[2];
									Fields[3]=hListR[y];
									Fields[5]=FormD;
									if (mMode!=2){
										Fields[7]="R";
										Fields[8]="Y";
										Fields[36]="ORNY";
									}else{//轉銷貨
										Fields[7]="N";
										Fields[8]="N";
										Fields[36]="";
									}
									Fields[16]="0";Fields[17]="0";Fields[18]="0";Fields[19]="0";
									Fields[21]="";Fields[22]="";
									Fields[30]=mBankn;
									Fields[31]="0";Fields[32]="";Fields[33]="0";Fields[34]="";Fields[35]="";
									
									ContentValues value = new ContentValues();
									for (int x=0;x<csH.getColumnCount();x++){
										value.put(csH.getColumnName(x), Fields[x]);
	
										if (Fields[8].equalsIgnoreCase("Y"))
											ServerStr.append(Fields[x]+";");
									}
									long success=dbH.insert(TbName.QHEAD, null, value);
									
									if (Fields[8].equalsIgnoreCase("Y")) ServerStr.append("\r\n");
								}
							}else if (mMode!=2){
								csH.moveToFirst();
								for (int x=0;x<csH.getColumnCount();x++)
									ServerStr.append(csH.getString(x)+";");
								ServerStr.append("\r\n");
							}
							csH.close();
							reCountHeadO(dbH,hListR[y]);
	//@@@這裡尚未單頭重算,就製作ServerStr 目的只是帶著基礎資料 						
						}
					}
				}
				
				if (hListO.length>0 ){
					//非(預購轉留貨的)預購單 就是 (留貨轉銷貨的)留貨單
					for (int y=0;y<hListO.length;y++){
						if (hListO[y].length()>0 && needRcountHeadO.indexOf((hListO[y]+";"))<0){
							needRcountHeadO+=hListO[y]+";";
							ServerRecountHead+=",'"+hListO[y]+"'";						
							dbH.execSQL("delete from "+TbName.QITEMS+" where FORMNO='"+hListO[y]+"' and UNIT30<=0 ");
							
							SQL="select * from "+TbName.QHEAD+" where FORMNO='"+hListO[y]+"'";
							Cursor csH=dbH.rawQuery(SQL, null);
							if (csH.getCount()<=0){ //新預購留貨單
								//@@預購單@非對稱@留貨單@@
							SQL="select  * from "+TbName.QHEAD+" where FORMNO='"+hListR[y]+"'";
							csH=dbH.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]=Fields[2];
									Fields[3]=hListO[y];
									Fields[5]=FormD;
									
									if (mMode!=2){
										Fields[7]="O";
										Fields[8]="Y";
									}else{
										Fields[7]="R";
										Fields[8]="Y";											
									}
									Fields[16]="0";Fields[17]="0";Fields[18]="0";Fields[19]="0";
									Fields[21]="";Fields[22]="";
									Fields[30]=mBankn;
									Fields[31]="0";Fields[32]="";Fields[33]="0";Fields[34]="";Fields[35]="";
									Fields[36]="ORNY";  //以備避免顯示異樣報告
	
									
									ContentValues value = new ContentValues();
									for (int x=0;x<csH.getColumnCount();x++){
										value.put(csH.getColumnName(x), Fields[x]);
											ServerStr.append(Fields[x]+";");
									}
									long success=dbH.insert(TbName.QHEAD, null, value);
									ServerStr.append("\r\n");
		
								}
							}else{//單頭存在
								csH.moveToFirst();
								for (int x=0;x<csH.getColumnCount();x++)
									ServerStr.append(csH.getString(x)+";");
								ServerStr.append("\r\n");
							}
							csH.close();
							reCountHeadO(dbH,hListO[y]);
						}
					}
				}
				dbH.close();
		    	Toast.makeText(GalleryViewO.this, "已成功轉單!!", Toast.LENGTH_SHORT).show();
		    	//@@@雲端版 預購單留貨單 將以專案方式 維護雲端
		    	//改成以字串 直接帶上 ,我們估計量體不大
		    	//除了LIST 將改良為完整資料 足以在SERVER 儲存更新
		    	//應在SAVE:就完成字串的製作
				if (of_line!=0){
					ServerStr.append(";HHHH\r\n");
					if (ServerRecountHead.indexOf(",")==0) ServerRecountHead=ServerRecountHead.substring(1);
					if (ServerRecountHead.length()>0){
						ServerStr.append(ServerRecountHead+";HHHH\r\n");
			        	boolean success=false;
							StringBuffer bfstr = new StringBuffer();
							StringBuffer bfstrF = new StringBuffer();
								bfstr.append(Utilis.getIni(GalleryViewO.this, "SYS", "IMPORT", 2)).append("!#%");
								bfstrF.append("UID").append("!#%");
								bfstr.append(mBankn).append("!#%");
								bfstrF.append("BANKNAME").append("!#%");
								bfstr.append(mDept).append("!#%");
								bfstrF.append("DEPTNO").append("!#%");
								bfstr.append(deptStr[5]).append("!#%");
								bfstrF.append("QPART").append("!#%");
								bfstr.append("0!#%");
								bfstrF.append("ALONE").append("!#%");
								bfstr.append(""+mMode).append("!#%");
								bfstrF.append("MODE").append("!#%");
								bfstr.append(ServerStr.toString()).append("!#%");
								bfstrF.append("SERVERSTR").append("!#%");
								bfstr.append(Utilis.getIni(GalleryViewO.this, "SYS", "AUPDATE", 3)).append("!#%");
								bfstrF.append("LUPDATET3").append("!#%");
								//目的是為了減少回傳的更新
								bfstr.append(Utilis.getIni(GalleryViewO.this, "SYS", "AUPDATE", 4));
								bfstrF.append("LUPDATE");
	
								final String []fields=bfstr.toString().split("!#%");
								final String []fieldFs=bfstrF.toString().split("!#%");
								
								Log.i("DOWNLOAD_bufDtr", bfstr.toString()+"___"+bfstrF.toString());
								  
					     new Thread()
					      { 
						       public void run()
						       { 
						          try
						          { 
										String uriAPI="http://"+Utilis.getIni(GalleryViewO.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(GalleryViewO.this, "SYS", "IMPORT", 2)+File.separator+"aa1_aa0_gvor.php";
										HttpPost httpRequest = new HttpPost(uriAPI);
										Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI);
										
										List<NameValuePair> params = new ArrayList<NameValuePair>();
										for(int x=0;x<fields.length;x++)
										params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
										
										try {
											httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
											HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
											if (httpResponse.getStatusLine().getStatusCode() == 200)
											{
												String strResult = EntityUtils.toString(httpResponse.getEntity());
												mHandlerGVOB.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
											}
											
										} catch (Exception e){
											e.printStackTrace();
										}
						          }
						          catch (Exception e){
						        	  e.printStackTrace();
						          }
						       }
					      }.start(); /* 開始執行執行緒 */
					}
				}
				
				if (list !=null && list.size()>0)	list.clear();
	        	Intent intentS = new Intent();
	        	if (ServerRecountHead.length()>0) intentS.putExtra("GVPO_modify",1); else intentS.putExtra("GVPO_modify",0); 
	        	if (mMode==2){//留貨轉銷貨
	        		intentS.putExtra("FormNo",mFnR);
	        		intentS.putExtra("GalleryMode",2);
	        	}else{
	        		intentS.putExtra("FormNo","");
	        		intentS.putExtra("GalleryMode",0);
	        	}
	        	GalleryViewO.this.setResult(RESULT_OK,intentS);
				finish();
			}else{ //chkSave==0 表示QITEMS轉單沒有成功
				Toast.makeText(GalleryViewO.this, "請執行預購維護!!或留貨維護!!後,再繼續轉單!!!", Toast.LENGTH_SHORT).show();
			}
			}
			break;
			}
			}
			}
    }

 	
	Handler mHandlerGVO = new Handler()
	{
		@Override
		public  void handleMessage(Message msg)
		{
			//傳回的//upup_1-30_系統時間
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
				if (Hresult != null ){
					Log.i("DOWNLOAD_5_mHandlerQC===", ""+Hresult);						
					if (Hresult.indexOf("aa0aa1_gvor")>=0){
						String [] LineH=Hresult.split(";HHHH\r\n");
						//常態為四段式資料以 "HHHH\r\n"分隔
						//if (LineH[2].length()>0) updateQhead(LineH[2]);						
						//if (LineH[1].length()>0) updateQitems(LineH[1]);						
						//第一段為SQL_List 製作畫面 或 Chk_List用
						showList(LineH[0],0);//再顯示
					}else{
			        	Intent intentS = new Intent();
			        	intentS.putExtra("GVPO_modify",0);
			        	GalleryViewO.this.setResult(RESULT_OK,intentS);
		     			finish();
					}
				}
			}
		}
	};
	
	
	private void showList(String Data,int SCmode ){
		//也要判斷 off_line 0 1
		//SCmode=0 SERVER讀取 存入 list	(雲端版為準)
		//SCmode=1 CLIENT讀取 存入 listC	(比對更新用)
		//SCmode=2 CLIENT讀取 存入 list 	(純單機版用)
        //SQLiteDatabase db = Utilis.getDB(this);
      //" USER,USERNAME,GOODSNOS,GOODSNAME,PIC,ISCONFIRM,ISCHECK,FORMDATE,UNIT1,FORMNO,DISCOUNT,UNITPRICE,CREATEDATETIME" UNIT
      //0	1			2      3		 4	 5			6		7		8	  9		 10 	  11		12				13
		String Linea [] = Data.split("SSSS\r\n");
		//取得傳回的筆數,並驗證LOCAL的筆數是否一致,否則進一步維護預購留貨
		int recordServer=Utilis.toInt(Linea[0].substring(Linea[0].indexOf("aa0aa1_gvor")+11,Linea[0].indexOf(";")));
		Toast.makeText(GalleryViewO.this, "雲端的總筆數=="+recordServer, Toast.LENGTH_LONG).show();
		
			int Otot=0;
			int Rtot=0;
			String mUserO="";
			String mUserN="";
			String mGoodsO="";
			String mGoodsN="";
			String Ofdate="";
			String Rfdate="";
			String aFno="";
			String PicO="";
			String DISC="";
			String UNITP="";
			String oDISC="";
			String oUNITP="";
			String CTIME="";
			int aPare=0;//制式預購留貨單可以全數同列 否則獨立一列
		int records=0;
		//boolean isLast=false;
		for (int read=1;read<Linea.length;read++) {
				String [] arrayField=Linea[read].split(";");
				records+=1;
     			if (mMode!=2){//預購<=>留貨	
     				if (records==1){
//" USER,USERNAME,GOODSNOS,GOODSNAME,PIC,ISCONFIRM,ISCHECK,FORMDATE,UNIT1,FORMNO,DISCOUNT,UNITPRICE,CREATEDATETIME "
//	0	1	    	2      3		4		5		6		7		8		9	10 			11		12
     					mUserO=arrayField[0];
 						mUser=mUserO;
     					mUserN=arrayField[1];
 						mGoodsO=arrayField[2];
 						mGoodsN=arrayField[3]+"/"+arrayField[8];
 						aFno=arrayField[9];
 						DISC=arrayField[10];
 						UNITP=arrayField[11];
 						oDISC=DISC;oUNITP=UNITP;
							CTIME=arrayField[12];
 						
 						mFnR=mDept+"6"+mUser;	//純預設留貨單
 						mFnO=mDept+"5"+mUser;	//純預設預購單
 						if (arrayField[5].equalsIgnoreCase("O") || (arrayField[5].equalsIgnoreCase("N") && arrayField[6].equalsIgnoreCase("Y")))
 							mFnO=aFno; //有可能為 (6)制式預購單 或 (7)網路預購單
       						aPare=1;//首筆 不 list.Add(map);
     						PicO=arrayField[4];
							if (PicO.indexOf("/cwbuyer/")>0){
								PicO=PicO.replace(PicO.substring(0, PicO.indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
								arrayField[4]=PicO;
							}
     				}
     				
     				if (!arrayField[2].equalsIgnoreCase(mGoodsO) || !arrayField[0].equalsIgnoreCase(mUser)  || !arrayField[10].equalsIgnoreCase(oDISC) || !arrayField[11].equalsIgnoreCase(oUNITP) || !arrayField[12].equalsIgnoreCase(CTIME) || aPare==0){
     					
     					showCheckBoxListViewC(mUserO+"/"+mUserN,mGoodsO,mGoodsN,PicO,Ofdate,Rfdate,Otot,Rtot,DISC,UNITP,CTIME);
     					//歸零
     					Otot=0;Rtot=0;Ofdate="";Rfdate="";
     					mUserO=arrayField[0];
 						mUser=mUserO;
     					aFno=arrayField[9];
 						DISC=arrayField[10];
 						UNITP=arrayField[11];
 						oDISC=DISC;oUNITP=UNITP;
     					mFnO=mDept+"5"+mUser;  //不一定是 同一預購單
 						mFnR=mDept+"6"+mUser; //肯定是 同一留貨單
							CTIME=arrayField[12];
 						//單號都不是制式的 應視為一般的預購單 或網路預購單 mDept+"7"
							aPare=1;
   						//if (aFno.indexOf((mDept+"5"))<0 && aFno.indexOf((mDept+"6"))<0) aPare=0; else aPare=1;
   						
 						if (arrayField[5].equalsIgnoreCase("R"))
 							mFnR=aFno;
 						else
 							mFnO=aFno;
   						
     					mUserN=arrayField[1];
 						mGoodsO=arrayField[2];
 						mGoodsN=arrayField[3]+"/"+arrayField[8];
 						PicO=arrayField[4];
						if (PicO.indexOf("/cwbuyer/")>0){
							PicO=PicO.replace(PicO.substring(0, PicO.indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
							arrayField[4]=PicO;
						}
     					
     					if (!arrayField[5].equalsIgnoreCase("R")){
     						Otot=Utilis.toInt(arrayField[13]);
     						Ofdate=arrayField[7];
     					}else{
     						Rtot=Utilis.toInt(arrayField[13]);
     						Rfdate=arrayField[7];
     					}
     				}else{
     					aFno=arrayField[9];
							CTIME=arrayField[12];
							
 						if (arrayField[5].equalsIgnoreCase("R"))
 							mFnR=arrayField[9];
 						else
 							mFnO=arrayField[9];
 						
   						//if (aFno.indexOf((mDept+"5"))<0 && aFno.indexOf((mDept+"6"))<0) aPare=0; else aPare=1;
   						if (records!=1) aPare=0;
     					
     					if (!arrayField[5].equalsIgnoreCase("R")){
     						Otot=Otot+Utilis.toInt(arrayField[13]);
     						Ofdate=arrayField[7];
     					}else{
     						Rtot=Rtot+Utilis.toInt(arrayField[13]);
     						Rfdate=arrayField[7];
     					}
     				}
     				
     			}else {//mMode==2 留貨=>銷貨(單號是事先準備妥當,才進場)
     				//一定是 留貨轉銷貨 永遠不會 銷貨轉留貨
     					mUserO=arrayField[0];
 						mUser=mUserO;
     					mUserN=arrayField[1];
 						mGoodsO=arrayField[2];
 						mGoodsN=arrayField[3]+"/"+arrayField[8];
 						DISC=arrayField[10];
 						UNITP=arrayField[11];
 						mFnO=arrayField[9];
 						//mFnR先產生單號
   						aPare=0;//首筆 不 list.Add(map);
 						PicO=arrayField[4];
						if (PicO.indexOf("/cwbuyer/")>0){
							PicO=PicO.replace(PicO.substring(0, PicO.indexOf("/cwbuyer/")), android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
							arrayField[4]=PicO;
						}
 						Otot=Utilis.toInt(arrayField[13]);
 						Rtot=0;
 						Ofdate=arrayField[9];
 						CTIME=arrayField[12];
     					showCheckBoxListViewC(mUserO+"/"+mUserN,mGoodsO,mGoodsN,PicO,Ofdate,Rfdate,Otot,Rtot,DISC,UNITP,CTIME);
     			}
		}

		if (records>0 && mMode!=2) showCheckBoxListViewC(mUserO+"/"+mUserN,mGoodsO,mGoodsN,PicO,Ofdate,Rfdate,Otot,Rtot,DISC,UNITP,CTIME);
		
		if (printYN==1 && SCmode!=1){
			printForm1();
		} else if (printYN==2 && SCmode!=1){
			printForm2();
		} else if (printYN==3){
			printForm3();
		} else if (printYN==4){
			printForm4();
		}
		SQLiteDatabase db = Utilis.getDB(GalleryViewO.this);
		Cursor cs=db.rawQuery(BufUserStr, null);
		int recordLocal=cs.getCount();
		cs.close();
		db.close();
		if (recordServer!=recordLocal){
			//資料不一致,需維護
			DBCloud.aa0_aa1_auto_HI_ORNY(GalleryViewO.this,"","2");//0留貨1預購 維護
		}
		
	}
	
	private void updateQhead(String Data){
		String Linea [] = Data.split("SSSS\r\n");
		//每一個 Linea 陣列 表示 一筆Qitems
		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"};
		SQLiteDatabase db = Utilis.getDB(GalleryViewO.this);
		db.beginTransaction();
		try{
			for(int read=0;read<Linea.length;read++) {
				ContentValues valueF = new ContentValues();
			//還要拆解 每一個欄位
				String [] arrayField=Linea[read].split(";");
				String[] args = {arrayField[3]};
				valueF.put(colNames[0],"Y0");
				for(int ff=1;ff<arrayField.length;ff++){
					if (arrayField[ff]==null || arrayField[ff].equalsIgnoreCase("NULL") || arrayField[ff].equalsIgnoreCase("nu")) arrayField[ff]="0"; 
					valueF.put(colNames[ff],arrayField[ff]) ;
				}
				int sucUpdate = db.update(TbName.QHEAD, valueF,"FORMNO=?", args);
				if (sucUpdate==0) db.insert(TbName.QHEAD, null, valueF);
			}
            db.setTransactionSuccessful();
		}
		catch(Exception e){
		}
		finally{
          db.endTransaction();
		}
		db.close();
	}	
 	
	

	private void gotoAllErase(int mode){
		//mode13.預購 15.留貨 0.查詢維護
		final int ischk=mode;
		LayoutInflater factory = LayoutInflater.from(this);
	    final View v1 = factory.inflate(R.layout.exinput, null);
	    final TextView txtReg = (TextView) v1.findViewById(R.id.TextView01);
	    final EditText edtReg = (EditText) v1.findViewById(R.id.edtReg);
	    edtReg.setText("");

		  new AlertDialog.Builder(this).setTitle("清除所有預購留貨專用密碼").setMessage("請輸入密碼").setView(v1).setPositiveButton("OK", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
           	  if (edtReg.getText().toString().equalsIgnoreCase("888")){
      			SQLiteDatabase db = Utilis.getDB(GalleryViewO.this);
            		  
           		  if (of_line==1 && Utilis.haveInternet(GalleryViewO.this)){
          			if (ischk==13){//刪除所有預購
          				db.execSQL("update "+TbName.QHEAD+" set TR='Y2',PS2='ORNY',ID='1008',QKIND='"+mKind.substring(0, 1)+"2',CREATEDATETIME='"+DateUtil.getSystemTime().substring(2, 12)+"',ISCONFIRM='N',ISCHECK='N' ,BANKNAME='"+mBankn+"' where DEPTNO='"+mDept+"' and (ISCONFIRM='N' and ISCHECK='Y') or (ISCONFIRM='O' and ISCHECK='Y')");
          				db.execSQL("delete from "+TbName.QITEMS+" where DEPTNO='"+mDept+"' and (ISCONFIRM='N' and ISCHECK='Y') or (ISCONFIRM='O' and ISCHECK='Y')");
          			}else{//刪除所有留貨
          				db.execSQL("update "+TbName.QHEAD+" set TR='Y2',PS2='ORNY',ID='1008',QKIND='"+mKind.substring(0, 1)+"2',CREATEDATETIME='"+DateUtil.getSystemTime().substring(2, 12)+"',ISCONFIRM='N',ISCHECK='N' ,BANKNAME='"+mBankn+"' where DEPTNO='"+mDept+"' and (ISCONFIRM='R' and ISCHECK='Y')");
        				db.execSQL("delete from "+TbName.QITEMS+" where DEPTNO='"+mDept+"' and (ISCONFIRM='R' and ISCHECK='Y')");
          			}
    				DBCloud.aa1_aa0_update_HI(GalleryViewO.this);

           		  }else{
            			if (ischk==13){//刪除所有預購
            				db.execSQL("delete from "+TbName.QHEAD+" where DEPTNO='"+mDept+"' and (ISCONFIRM='N' and ISCHECK='Y') or (ISCONFIRM='O' and ISCHECK='Y')");
            				db.execSQL("delete from "+TbName.QITEMS+" where DEPTNO='"+mDept+"' and (ISCONFIRM='N' and ISCHECK='Y') or (ISCONFIRM='O' and ISCHECK='Y')");
            			}else{ //刪除所有留貨
            				db.execSQL("delete from "+TbName.QHEAD+" where DEPTNO='"+mDept+"' and ISCONFIRM='R' and ISCHECK='Y'");
            				db.execSQL("delete from "+TbName.QITEMS+" where DEPTNO='"+mDept+"' and ISCONFIRM='R' and ISCHECK='Y'");
            			}
           		  }
           		  db.close();
              }
           	  
              }
		  }).setCancelable(false).show();
	}
	
	Handler mHandlerGVOB = new Handler()
	{
		@Override
		public  void handleMessage(Message msg)
		{
			//傳回的//upup_1-30_系統時間
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
				if (Hresult != null ){
					if (Hresult.indexOf("aa1_aa0_gvo;")>0){
						String [] EchoStr=Hresult.split(";");
						Utilis.putIni(GalleryViewO.this, "SYS", "AUPDATE",EchoStr[1] ,4 );//T4_ORNY
					}else{//SERVER_UPDATE_Failure
						//確認是伺服器更新失敗 處置???
					}
				}
			}
		}
	};

	private void printForm1(){
		if (list!=null && list.size()>0){
			sPrintB=PosUtilis.getPrintKind(GalleryViewO.this,Utilis.toInt(compStr[8]));
			int LocaC=0;
			int cuOrder=0;int cuKeep=0;int cuKeepMoney=0;int cuOrderMoney=0;
			getPrintitle(0);												
			HashMap<String, Object> map = list.get(0);
			String mCust=map.get("item_rdl").toString();
			Loca=Loca+35;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+mCust+" 訂日"+map.get("item_rdc").toString()+sepa);
			sPrintB.append("BQ,440,"+Loca+",1,5,15,0,0,$"+mCust.substring(0, mCust.indexOf("/"))+sepa);
			LocaC=Loca+25;
			Loca=Loca+40;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
			for (int x=0;x<list.size();x++){
					map = list.get(x);
					if (!mCust.equalsIgnoreCase(map.get("item_rdl").toString())){
						sPrintB.append("AZ,20,"+LocaC+",1,1,0,0,"+" (訂:"+cuOrder+"件 $"+cuOrderMoney+")(留:"+cuKeep+"件 $"+cuKeepMoney+")"+sepa);
						if (Loca>2400){
							PosUtilis.startPrint(GalleryViewO.this,sPrintB,Loca );
							SystemClock.sleep(3000);
							sPrintB=PosUtilis.getPrintKind(GalleryViewO.this,Utilis.toInt(compStr[8]));
							getPrintitle(0);												
						}
						mCust=map.get("item_rdl").toString();
						Loca=Loca+25;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
						Loca=Loca+5;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
						Loca=Loca+35;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+mCust+" 訂日"+map.get("item_rdc").toString()+sepa);
						sPrintB.append("BQ,440,"+Loca+",1,5,15,0,0,$"+mCust.substring(0, mCust.indexOf("/"))+sepa);
						LocaC=Loca+25;
						Loca=Loca+40;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
						cuOrderMoney=0;cuKeepMoney=0;cuOrder=0;cuKeep=0;
					}
					Loca=Loca+15;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+map.get("item_rul").toString()+" 訂("+map.get("item_rh1").toString()+")留("+map.get("item_rh2").toString()+")"+sepa);
					Loca=Loca+50;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+map.get("item_rcl").toString()+" 訂日"+map.get("item_rdc").toString()+sepa);
					Loca=Loca+10;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
					cuOrderMoney+=(Utilis.toInt(map.get("item_rh1").toString())*Utilis.toInt(map.get("item_acl").toString())*Utilis.toInt(map.get("item_acc").toString())*0.01 );
					cuKeepMoney+=(Utilis.toInt(map.get("item_rh2").toString())*Utilis.toInt(map.get("item_acl").toString())*Utilis.toInt(map.get("item_acc").toString())*0.01 );
					cuOrder+=Utilis.toInt(map.get("item_rh1").toString());cuKeep+=Utilis.toInt(map.get("item_rh2").toString());
			}
			if (cuKeepMoney>0 || cuOrder>0 || cuKeep>0 ) sPrintB.append("AZ,20,"+LocaC+",1,1,0,0,"+" (訂:"+cuOrder+"件 $"+cuOrderMoney+")(留:"+cuKeep+"件 $"+cuKeepMoney+")"+sepa);
			if (sPrintB.toString().length()>0)
				PosUtilis.startPrint(GalleryViewO.this,sPrintB,Loca );
		}
		
	}

	private void printForm2(){
		int CountTot=0;
		int CountTotR=0;
		if (list!=null && list.size()>0){
			sPrintB=PosUtilis.getPrintKind(GalleryViewO.this,Utilis.toInt(compStr[8]));
			getPrintitle(1);												
					HashMap<String, Object> map = list.get(0);
					String mGoods=map.get("item_rul").toString()+"/"+map.get("item_rcl").toString();
					Loca=Loca+35;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+mGoods+sepa);
					Loca=Loca+15;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
			for (int x=0;x<list.size();x++){
					map = list.get(x);
					if (!mGoods.equalsIgnoreCase((map.get("item_rul").toString()+"/"+map.get("item_rcl").toString()))){
						Loca=Loca+20;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+"合計(預購件數)"+CountTot+" (已留貨件數)"+CountTotR+sepa);
						Loca=Loca+20;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
						if (Loca>2400){
							PosUtilis.startPrint(GalleryViewO.this,sPrintB,Loca );
							SystemClock.sleep(3000);
							sPrintB=PosUtilis.getPrintKind(GalleryViewO.this,Utilis.toInt(compStr[8]));
							getPrintitle(1);												
						}
						mGoods=map.get("item_rul").toString()+"/"+map.get("item_rcl").toString();
						Loca=Loca+35;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+mGoods+sepa);
						Loca=Loca+15;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
						CountTot=0;CountTotR=0;
					}
					Loca=Loca+15;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+map.get("item_rdl").toString()+" 訂("+map.get("item_rh1").toString()+")留("+map.get("item_rh2").toString()+")"+sepa);
					Loca=Loca+45;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
					CountTot=CountTot+Utilis.toInt(map.get("item_rh1").toString());
					CountTotR=CountTotR+Utilis.toInt(map.get("item_rh2").toString());
			}
			Loca=Loca+20;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+"合計(預購件數)"+CountTot+" (已留貨件數)"+CountTotR+sepa);
			Loca=Loca+20;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);

			if (sPrintB.toString().length()>0)
				PosUtilis.startPrint(GalleryViewO.this,sPrintB,Loca );
															
		}

	}
	
	private void printForm3(){
		if (list!=null && list.size()>0){
			sPrintB.delete(0, sPrintB.toString().length());
			int cuOrder=0;int cuKeep=0;int cuKeepMoney=0;int cuOrderMoney=0;
			sPrintB.append(compStr[0]+" 會員 - 預購留貨明細理貨清單"+sepa);
												
			HashMap<String, Object> map = list.get(0);
			String mCust=map.get("item_rdl").toString();
			sPrintB.append(mCust+" 訂日"+map.get("item_rdc").toString()+sepa);
			for (int x=0;x<list.size();x++){
					map = list.get(x);
					if (!mCust.equalsIgnoreCase(map.get("item_rdl").toString())){
						sPrintB.append("合計(預購:"+cuOrder+"件 $"+cuOrderMoney+")(留貨:"+cuKeep+"件 $"+cuKeepMoney+")"+sepa+sepa);
						mCust=map.get("item_rdl").toString();
						sPrintB.append(mCust+";訂日;"+map.get("item_rdc").toString()+sepa);
						cuOrderMoney=0;cuKeepMoney=0;cuOrder=0;cuKeep=0;
					}
					sPrintB.append(map.get("item_rul").toString()+";訂("+map.get("item_rh1").toString()+");留("+map.get("item_rh2").toString()+");");
					sPrintB.append(map.get("item_rcl").toString()+";訂日"+map.get("item_rdc").toString()+sepa);
					cuOrderMoney+=(Utilis.toInt(map.get("item_rh1").toString())*Utilis.toInt(map.get("item_acl").toString())*Utilis.toInt(map.get("item_acc").toString())*0.01 );
					cuKeepMoney+=(Utilis.toInt(map.get("item_rh2").toString())*Utilis.toInt(map.get("item_acl").toString())*Utilis.toInt(map.get("item_acc").toString())*0.01 );
					cuOrder+=Utilis.toInt(map.get("item_rh1").toString());cuKeep+=Utilis.toInt(map.get("item_rh2").toString());
			}
			if (cuKeepMoney>0 || cuOrder>0 || cuKeep>0 ) sPrintB.append("(合計(預購:"+cuOrder+"件  $"+cuOrderMoney+")(留貨:"+cuKeep+"件$"+cuKeepMoney+")"+sepa);
			if (sPrintB.toString().length()>0){
				
				//PosUtilis.startPrint(GalleryViewO.this,sPrintB,Loca );
        		try {
                    Writer out = new BufferedWriter(new OutputStreamWriter(
                    	    new FileOutputStream(myFilePath), "UTF-8"));
                    	try {
                    	    out.write(sPrintB.toString());
                    	} finally {
                    	    out.close();
                    	}                    
        		} catch (Exception e) {

        		}
        		
    			//進一步輸出,多媒體選擇
    	    	Intent send = new Intent(Intent.ACTION_SEND);
    	    	send.setType("image/jpeg");
    		    String uriText;
    		    Uri U=Uri.parse("file://"+myFilePath);  //重要的範例
    		    uriText = "https://www.google.com/cloudprint/addpublicprinter.html?printerid=bb160853-6274-0f65-eb1f-34ae2c9ed6e1&key=19901109";
    		    send.putExtra(Intent.ACTION_SENDTO,uriText);
    		    send.putExtra(Intent.EXTRA_STREAM,U);
    		    startActivity(Intent.createChooser(send, uriText));
				
			}	
		}
		
	}

	private void printForm4(){
		int CountTot=0;
		int CountTotR=0;
		if (list!=null && list.size()>0){
			sPrintB.delete(0, sPrintB.toString().length());
			sPrintB.append(compStr[0]+" 商品 - 預購留貨明細理貨清單"+sepa+sepa);
			
					HashMap<String, Object> map = list.get(0);
					String mGoods=map.get("item_rul").toString()+"/"+map.get("item_rcl").toString();
					sPrintB.append(mGoods+sepa);
			for (int x=0;x<list.size();x++){
					map = list.get(x);
					if (!mGoods.equalsIgnoreCase((map.get("item_rul").toString()+"/"+map.get("item_rcl").toString()))){
						sPrintB.append("合計(預購:"+CountTot+"件) (留貨"+CountTotR+"件)"+sepa+sepa);
						mGoods=map.get("item_rul").toString()+"/"+map.get("item_rcl").toString();
						sPrintB.append(mGoods+sepa);
						CountTot=0;CountTotR=0;
					}
					sPrintB.append(map.get("item_rdl").toString()+";預購;("+map.get("item_rh1").toString()+"件);留貨;("+map.get("item_rh2").toString()+"件)"+sepa);
					CountTot=CountTot+Utilis.toInt(map.get("item_rh1").toString());
					CountTotR=CountTotR+Utilis.toInt(map.get("item_rh2").toString());
			}
			sPrintB.append("合計(預購:"+CountTot+"件 ) (留貨"+CountTotR+"件)"+sepa);

			if (sPrintB.toString().length()>0){
        		try {
                    Writer out = new BufferedWriter(new OutputStreamWriter(
                    	    new FileOutputStream(myFilePathG), "UTF-8"));
                    	try {
                    	    out.write(sPrintB.toString());
                    	} finally {
                    	    out.close();
                    	}                    
        		} catch (Exception e) {

        		}
        		
    			//進一步輸出,多媒體選擇
    	    	Intent send = new Intent(Intent.ACTION_SEND);
    	    	send.setType("image/jpeg");
    		    String uriText;
    		    Uri U=Uri.parse("file://"+myFilePathG);  //重要的範例
    		    uriText = "https://www.google.com/cloudprint/addpublicprinter.html?printerid=bb160853-6274-0f65-eb1f-34ae2c9ed6e1&key=19901109";
    		    send.putExtra(Intent.ACTION_SENDTO,uriText);
    		    send.putExtra(Intent.EXTRA_STREAM,U);
    		    startActivity(Intent.createChooser(send, uriText));
				
				
			}
															
		}

	}

	private void getListData(HashMap<String, Object> map){
		ServerStr.append(map.get("item_rul")+";");
		ServerStr.append(map.get("item_rcl")+";");
		ServerStr.append(map.get("item_rcc")+";");
		ServerStr.append(map.get("item_rcr")+";");
		ServerStr.append(map.get("item_acl")+";");
		ServerStr.append(map.get("item_acc")+";");
		ServerStr.append(map.get("item_acr")+";");
		ServerStr.append(map.get("item_rtm")+";");
		ServerStr.append(map.get("item_rdl")+";");
		ServerStr.append(map.get("item_rdc")+";");
		ServerStr.append(map.get("item_rdr")+";");
		ServerStr.append(map.get("item_rh1")+";");
		ServerStr.append(map.get("item_rh2")+";");
		ServerStr.append(map.get("item_rh3")+";");
		ServerStr.append(map.get("item_rh4")+";");
		ServerStr.append(map.get("item_rpic")+";");
	}
	
	private void getQitemsData(Cursor csc){
		for (int items=0;items<52;items++)
			ServerStr.append(csc.getString(items)+";");
		ServerStr.append(csc.getString(52)+";\r\n");
		//字串結構List+Qitems_Fields(0-52=53)
	}
	
	private void reCountHeadO(SQLiteDatabase db,String mKey){  //QITEMS異動後 需維護QHEAD
		//需再補充 HANDNO 存入正負件數
		
		StringBuffer mySqlBuf = new StringBuffer();
		StringBuffer handNo=new StringBuffer();  //須算好 進退量 存入HandNo
		String FormD=DateUtil.getCurrentDate();  //2012-10-22
		int Ttime=Utilis.toInt(DateUtil.getSystemTime().substring(8, 10));  //取得目前幾點
		if (Ttime<=5)  FormD = DateUtil.addDate(FormD, -1);
		FormD = FormD.replace("/", "-");
		
		mySqlBuf.delete(0, mySqlBuf.toString().length());
		mySqlBuf.append("select sum(UNIT"+mKind.substring(0, 1)+"0)");
		mySqlBuf.append(" from "+TbName.QITEMS+" where FORMNO ='" +mKey+"'")
		.append(" and QKIND ='" + mKind+"'");
		//先算出的
		String mySql=mySqlBuf.toString();
		mySqlBuf.append(" and UNIT"+mKind.substring(0, 1)+"0 >=0 ");
		Cursor cursory = db.rawQuery(mySqlBuf.toString(), null);									
			if (cursory.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
				cursory.moveToFirst();
				handNo.append("+"+cursory.getInt(0));
			}else handNo.append("+0");
		cursory.close();
		
		mySqlBuf.delete(0, mySqlBuf.toString().length());
		mySqlBuf.append(mySql); //共用片段
		mySqlBuf.append(" and UNIT"+mKind.substring(0, 1)+"0 <0 ");		
		Cursor cursorz = db.rawQuery(mySqlBuf.toString(), null);									
		if (cursorz.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
			cursorz.moveToFirst();
			if (cursorz.getInt(0)<0)
			handNo.append(""+cursorz.getInt(0));			
		}
		cursorz.close();
		
		mySqlBuf.delete(0, mySqlBuf.toString().length());
		
		double SUBP=0;
		double SUBQ=0;
		String isCheck="";
		Cursor cursorw = db.rawQuery("select TRCASH,DISMONEY,ISCHECK from "+TbName.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));
			SUBP=dTrcash-dDismoney;
			isCheck=cursorw.getString(2);
		}
		cursorw.close();


		mySqlBuf.delete(0, mySqlBuf.toString().length());
		mySqlBuf.append("select sum(UNIT"+mKind.substring(0, 1)+"0) as UNITS,sum(SUBPRICE) as SUBPRIS,");
		mySqlBuf.append("sum(ACOST) as ACOSTS from "+TbName.QITEMS)
		.append(" where FORMNO ='" + mKey+"'")
		.append(" and QKIND ='" + mKind+"'");
		Cursor cursorx = db.rawQuery(mySqlBuf.toString(), null);
		
		if (cursorx.getCount()>0) { //必然找到該單所有ITEMS,重新統計一次
			ContentValues value = new ContentValues();
			cursorx.moveToFirst();
			double Costs=Math.round(cursorx.getDouble(cursorx.getColumnIndex("ACOSTS")));
			if (Utilis.getIni(GalleryViewO.this,"SYS", "SDB", 8).equalsIgnoreCase("5"))
				SUBQ=Math.round(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS"))/10)*10;
			else if (Utilis.getIni(GalleryViewO.this,"SYS", "SDB", 8).equalsIgnoreCase("1"))
				SUBQ=Math.floor(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS"))/10)*10;
			else if (Utilis.getIni(GalleryViewO.this,"SYS", "SDB", 8).equalsIgnoreCase("9"))
				SUBQ=Math.ceil(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS"))/10)*10;
			else
				SUBQ=Math.round(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS")));
			
			if (f123!=0) {
				SUBQ=Utilis.dedb(cursorx.getDouble(cursorx.getColumnIndex("SUBPRIS")),2);
				Costs=Utilis.dedb(cursorx.getDouble(cursorx.getColumnIndex("ACOSTS")),3);
			}
			
			double Atot=cursorx.getDouble(cursorx.getColumnIndex("UNITS"));
			
			value.put("TR","Y0");//強迫使啟動雲端資料庫
			value.put("FORMDATE",FormD);
			//修正最後異動當日期
			value.put("ASUM",SUBQ);
			value.put("BSUM",SUBP+SUBQ);
			value.put("ATOT",Math.round(Atot));
			value.put("COSTS",Math.round(Costs));
			value.put("HANDNO", handNo.toString());
			value.put("BANKNAME",mBankn);
			value.put("PS2","ORNY");
//			if (isCheck.equalsIgnoreCase("R")) value.put("FORMDATE", FormD);
			
			String[] args = {mKey,mKind};
			int success = db.update(TbName.QHEAD, value,"FORMNO=? and QKIND=?", args);
		
		} else {
			//如果遇到有收款的預購訂金,則不可以刪單
			Cursor csH = db.rawQuery("select * from "+TbName.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("ATM"))!=0  || csH.getDouble(csH.getColumnIndex("TRCASH"))!=0){
					//因為有訂金,所以不可以清除
					String SQL="update "+TbName.QHEAD+" set TR='Y1',PS2='ORNY',ID='1056',HANDNO='+0',ISCONFIRM='Y',ISCHECK='N',ATOT='0',ASUM=0,BSUM=0,COSTS=0 where FORMNO='" + mKey+"'";
					db.execSQL(SQL);
				}else if (of_line==0 ) {
					db.execSQL("delete from "+TbName.QHEAD+" where FORMNO='" + mKey+"' and QKIND LIKE '"+mKind.substring(0,1)+"%'" );//其實存的是單號
				} else {
					db.execSQL("update "+TbName.QHEAD+" set TR='Y2',PS2='ORNY',ID='1008',QKIND='"+mKind.substring(0, 1)+"2',CREATEDATETIME='"+DateUtil.getSystemTime().substring(2, 12)+"',ISCONFIRM='N',ISCHECK='N' ,BANKNAME='"+mBankn+"' where FORMNO='" + mKey+"'" );
				}
			}
			csH.close();
		}
		//db.close();
		cursorx.close();
		
 	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
	}

}
