package com.cwbuyer.main;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
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.adapter.MyAdapter1;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.GalleryViewC;
import com.cwbuyer.lib.CustActivity;
import com.cwbuyer.lib.GalleryViewO;
import com.cwbuyer.lib.PosUtilis;
import com.cwbuyer.lib.PrefKey;
import com.cwbuyer.lib.QHis;
import com.cwbuyer.lib.QRep_02;
import com.cwbuyer.lib.Qsms_one;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.main.APos.PItemKind;
import com.cwbuyer.main.QCust.QCustMode;
import com.pwbuyer.main.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint({ "HandlerLeak", "InflateParams" })
@SuppressWarnings("unused")
public class QCustff extends Activity {
	/** Called when the activity is first created. */
	static final private int MENU_ADD = Menu.FIRST; // 新增會員
	static final private int MENU_SMS = Menu.FIRST + 1; // 群組視為同一組Menu
	static final private int MENU_MAIL = Menu.FIRST + 2;
	static final private int MENU_QCUSTF = Menu.FIRST + 3;
	static final private int MENU_LISTALL = Menu.FIRST + 4;
	static final private int MENU_MAP = Menu.FIRST + 5;
	private String[] compStr =Utilis.getIni(this,"USER","COMPANY",9).split("!&!");
	
	//交易價別方式 千萬不可以在第一時間就以 getResources().getText(R.string.str.....)方式帶入
	private final String[] tradeStr =Utilis.getIni(this,"SYS","TRADENAME",9).split("!&!");
	private static int PSWD=0;
	public ProgressDialog myDialog = null;  	

	private final int RESULT_QCUST=5555; 		//
	private final int RESULT_GALLERYO=5566; 		//GALLERY 
	
	String mKind =null; //單別 1020304050
	int reportMode=1;
	private String sepa="\r\n";
	private final String[] pKind=Utilis.getIni(this,"SYS","CKIND",9).split("!&!");
	private final String[] backout =Utilis.getIni(this,"SYS","BACKOUT",9).split("!&!");
	private final String[] deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");
	private final String[] dept_sendStr =Utilis.getIni(this,"SYS","DEPT_SEND",9).split("!&!");
	private String[] MenuOpt ={ "畫面的資料", "所有的會員資料(含交易業績件數)", "未結清的會員資料", "[列印]未結清的會員資料","返回" };
	private String[] Menu40Opt ={ "畫面的資料", "所有的櫃員資料(含交易業績件數)", "未結清的櫃員資料", "[列印]未結清的櫃員資料","返回" };
	private String[] Menu20Opt ={ "畫面的資料","返回" };
	String mDept=deptStr[0];
	//String mBankname=deptStr[0]+deptStr[1];
	int nKind=0; //單別 1020304050
	int isOutput=0;
	StringBuffer Bufstr= new StringBuffer();
	int Loca=0;
	int Lgap=230;
	
	protected static final int REFRESH_DATA = 0x00000001;
	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	int mCloud=Utilis.toInt(dept_sendStr[3]);
	String clouds="http://"+Utilis.getIni(this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(this, "SYS", "IMPORT", 2)+File.separator;
	int ORS=Utilis.toInt(dept_sendStr[5]);
	String uriAPI1=clouds+"getweb_bsum.php";
	String uriAPIrep=clouds+"getweb_bsumreport.php";
	String ResultAum="";
	String eds2="0";
	
	int aPart=0;//0總倉 1門市
	int bPart=0;//1各門市會員不同步 0同步 
	public interface QCustfMode{
		int NORMAL = 0;  //常態
		int SEARCH= 1; 	//外部程式進來時,需帶著查詢的KEY值
		int SEARCHEDGOBACK =2;
	}
	
	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<Integer> mCountryIdList = new ArrayList<Integer>();
	private ArrayList<String> mCountryIcon = new ArrayList<String>();	
	
	private List<HashMap<String, Object>> main_list = null;	
	private ListView mListView;
 	private MyAdapter1 mMyAdapter;
	private ImageButton mImageBt_search;
	private ImageButton mImageBt_callback;
	private Button mBtn_photo;
	private Button mBtn_sms;
	private Button mBtn_email;
	private Button mBtn_new;
	private Button mBtn_exit;
	String SD_PATH =android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
	String pathName="/CWBuyer/cualbun";	
	String myFilePath = SD_PATH+pathName+"/cust_report.csv";
	int nMode = QCustfMode.NORMAL;
	int records =0;

	private int intItemSelected=-1;
	private EditText edSearch01;
    private String edno;
    private String edna;

	Bundle bundle;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent dataR) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, dataR);
		
		switch(requestCode){
		
		case RESULT_QCUST:
			{
				if (resultCode == RESULT_OK) {
					if(dataR.getIntExtra("qcust_modify",0)==1){
			        	edno=dataR.getStringExtra("qcust_key");						
						if (nMode==QCustfMode.SEARCHEDGOBACK ) {//找到而且馬上返回
				        	Intent intentS = new Intent();
				        	intentS.putExtra("qcust_key",edno);
				        	intentS.putExtra("qcust_kind",nKind);
				        	QCustff.this.setResult(RESULT_OK,intentS);
						    finish();
						}else {   
						//讓畫面重新整理
							Toast.makeText(QCustff.this, "傳回的客戶代號:"+edno, Toast.LENGTH_SHORT).show();							
							SQLiteDatabase db = Utilis.getDB(this);
							Cursor maincs = null;
							StringBuffer mySqlBuf = new StringBuffer();
							mySqlBuf.append("select * from qcust  where state<>'2' and TR='"+mKind+"'");
							if (nKind==31 ) mySqlBuf.append(" and DEPTNO='"+mDept+"'");
								mySqlBuf.append(" and CUSTNO='"+edno+"' order by CUSTNO LIMIT 3000");
							
							maincs = db.rawQuery(mySqlBuf.toString(), null);
									if (maincs.getCount() > 0) {
										 updateListView(this,maincs);
									}
							maincs.close();
							db.close();
						break;				
					}					
				}	
				}
				break;
			}
		case RESULT_GALLERYO:
			DBCloud.aa0_aa1_auto_HI(this,nKind);
			break;
		}	
    }
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.custf);
		PSWD=Utilis.toInt(deptStr[4]);
		nKind = getIntent().getIntExtra("qcustf_qkind", APos.PItemKind.TR30); //單別 這是一個重要的關鍵值
		mKind=""+((nKind/10)*10);
		//nKind=31 但是  mKind='30' 因為 qcust_table TR=30 通稱會員 
		nMode = getIntent().getIntExtra("qcustf_mode", QCustfMode.NORMAL); //0普 1查 2查返
		edno= getIntent().getStringExtra("qcustf_key"); //所要查詢的項目 這是一個重要的關鍵值
		mDept= getIntent().getStringExtra("pos_dept"); //所要查詢的項目 這是一個重要的關鍵值
		//Toast.makeText(QCustff.this, "門市銷貨單__"+mDept, Toast.LENGTH_SHORT).show();							
		if (!deptStr[0].equalsIgnoreCase(deptStr[5])) aPart=1;//1門市 0總倉
		
		if (mDept!=null && !mDept.equalsIgnoreCase("AAP")){
				if (aPart==1){
					
					//2019-04-07 針對門市的門市轉貨單
					if (nKind==21)
						mDept=deptStr[0];
					//2019-04-07 針對門市的門市轉貨單
					
					else if (nKind!=31) //員工,門市 一律為總倉
						mDept=deptStr[5];
					else //會員
						if (mDept!=null && mDept.equalsIgnoreCase("SOS")) mDept=deptStr[0];
				}else{
					if (mDept!=null && mDept.equalsIgnoreCase("SOS")) mDept=deptStr[5];
				}
			if (backout[6].equalsIgnoreCase("1"))
				bPart=1;//0預設同步 1.啟動批發會員指定門市
			else bPart=0;
		}else{//總倉盤點時專用
			aPart=0;mDept=deptStr[5];
        	Intent intentS = new Intent();
        	intentS.putExtra("qcust_key",mDept);
        	intentS.putExtra("qcust_kind",mKind);
        	QCustff.this.setResult(RESULT_OK,intentS);
        	finish();
			
		}
//		交易價別方式設定 **千萬不可在陣列中一開始就使用轉址參考型別 LINE_51
		if (dept_sendStr[4].equalsIgnoreCase("1")) tradeStr[2]=tradeStr[3];
		//歷史價  TRADENAME
		
		setTitle(getResources().getText(R.string.app_name).toString()+pKind[(nKind/10)-1]+"流覽");
//未來以TR 判斷可為 10廠商 20門市 30會員 40櫃員
		edSearch01 = (EditText) findViewById(R.id.edSearch2);
		//edSearch01.clearFocus();
		mListView = (ListView) findViewById(R.id.mylistView1);
		mImageBt_search = (ImageButton) findViewById(R.id.imageButton21);
		mImageBt_callback = (ImageButton) findViewById(R.id.imageButton22);
		mBtn_photo = (Button) findViewById(R.id.btn_photo);
		mBtn_sms = (Button) findViewById(R.id.btn_sms);
		mBtn_email = (Button) findViewById(R.id.btn_email);
		mBtn_new = (Button) findViewById(R.id.btn_new);
		mBtn_exit = (Button) findViewById(R.id.btn_exit);
		
		//將鍵盤收起來
		
		getCountryData(this);		
		
        SQLiteDatabase db = Utilis.getDB(this);
		Cursor maincs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		
	if (nMode==QCustfMode.NORMAL){ //常態
//		 InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//	      m.hideSoftInputFromWindow(edSearch01.getWindowToken(), 0);               		

		mySqlBuf.append("select * from qcust");
		mySqlBuf.append(" where state<>'2'");
		if ((nKind==31 || nKind==30) && bPart==1) mySqlBuf.append(" and DEPTNO='"+mDept+"'");
		//2019-04-07 門市轉貨單 不得選擇總倉 有完成測試
		if (nKind==21 || ((aPart==0 && nKind==20) && !edno.equalsIgnoreCase("AA") )) mySqlBuf.append( " and  CUSTNO<>'"+mDept+"'  and CUSTNO<>'"+deptStr[5]+"'"); 
		mySqlBuf.append( " and TR='"+mKind+"'  order by CUSTNO LIMIT 3000");
		//Toast.makeText(QCustff.this, "客戶SQL"+mySqlBuf.toString(), Toast.LENGTH_SHORT).show();							
		maincs = db.rawQuery(mySqlBuf.toString(), null);
					if (maincs.getCount() > 0) {
						 updateListView(this,maincs);
							maincs.close();
							db.close();
					} else {
						maincs.close();
						db.close();
						callQcust(0);
					}
					
	}else{ //外部程式進來,先行查詢
		edSearch01.setText(edno);
		searched();
		edSearch01.setText("");
		
	}
	db.close();
	if (maincs !=null) maincs.close();
	
//					 setupViews();
				
		
		mImageBt_callback.setOnClickListener(new ImageButton.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
		        SQLiteDatabase db = Utilis.getDB(QCustff.this);				
				Cursor cs = null;
				StringBuffer mySqlBuf = new StringBuffer();
				mySqlBuf.append("select * from qcust where state<>'2'");
				if (nMode==QCustfMode.NORMAL){
					if ((nKind==31 || nKind==30) && bPart==1) mySqlBuf.append(" and DEPTNO='"+mDept+"'");
					if (nKind==21 || (aPart==0 && nKind==20)) mySqlBuf.append( " and  CUSTNO<>'"+mDept+"'  and CUSTNO<>'"+deptStr[5]+"'"); 
					mySqlBuf.append(" and TR='"+mKind+"'  order by CUSTNO LIMIT 3000");
				}else{
					mySqlBuf.append(" and TR='"+mKind+"' and CUSTNO='"+edno+"' order by CUSTNO LIMIT 3000");
					//因為在設計總倉盤點時,無法直接帶回總倉AA
				}
				cs = db.rawQuery(mySqlBuf.toString(), null);
				if (cs.getCount() > 0) {
					intItemSelected=0;
				    updateListView(QCustff.this,cs);
				} 
				db.close();
				cs.close();

			}
		});		
		
		edSearch01.setOnKeyListener(new View.OnKeyListener() {
        	@Override
        	public boolean onKey(View v, int keyCode, KeyEvent event) {
        		if(event.getAction()== KeyEvent.ACTION_DOWN){
        		}
        	return false;
        	}
		});

    	edSearch01.addTextChangedListener(watcherSearched);

		mImageBt_search.setOnClickListener(new ImageButton.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (edSearch01.hasFocusable()==false) edSearch01.setVisibility(View.VISIBLE);
        		if (edSearch01.length()>0) {
     				searched();
            		edSearch01.setText("");
//            		setupViews();
        		}
			}
		});

	mBtn_photo.setOnClickListener(new Button.OnClickListener(){

		@Override
		public void onClick(View v) {	
			//輸出
			//暫時只寫到CSV輸出(未來開發列印,A4列印)
			//可以輸出的 mkqr 甚至含 條碼 (目錄的概念)
			if (PSWD==0){
				if (nKind==PItemKind.TR40 || nKind==PItemKind.TR41 )//櫃員通訊錄
					MenuOpt=Menu40Opt;
				if (nKind==PItemKind.TR20 || nKind==PItemKind.TR21 ) 
					MenuOpt=Menu20Opt;
				
				
			DialogUtilis.showDialog(QCustff.this, "請選擇輸出的內容", -1,
				MenuOpt , new IDialog() {
						@Override
					public void onDialogFinish(int pos, String choice) {
							
			  				SQLiteDatabase db = Utilis.getDB(QCustff.this);
				           	Bufstr.delete(0, Bufstr.toString().length());
			  				
						switch (pos) {
						case 0: 
				           	if (main_list.size()>0){
				        		for (int x=0;x<main_list.size();x++){
				    				HashMap<String, Object> mapm = main_list.get(x);
				    				edno = (String)mapm.get("tv_no");
				    				if ( mapm.get("tv_mobil").toString() !=null && mapm.get("tv_mobil").toString().length()>0 && mapm.get("tv_mobil").toString().indexOf("09")==0){
				    				Cursor cs=db.rawQuery("select ADDRESS,EMAIL,BIRTHDAY,CUSTNO from qcust where CUSTNO='"+edno+"'", null);
				    				if (cs.getCount()>0){
				    			        cs.moveToFirst();
				    			        Bufstr
				    			        .append(cs.getString(3)).append(",")
				    			        .append(mapm.get("tv_name").toString()).append(",")
				    			        .append(mapm.get("tv_mobil").toString()).append(",")
				    			        .append(cs.getString(0)).append(",")
				    			        .append(cs.getString(1)).append(",")
				    			        .append(cs.getString(2)).append("\r\n");
				    				}
				    				cs.close();
				    				}
				        		}
			        		outPut_bufStr();
				           	}
							break;
						case 1://需開闢 Cloud || Client
							if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 || nKind==PItemKind.TR40 || nKind==PItemKind.TR41 ){//門市通訊錄
							
							StringBuffer buf1= new StringBuffer();
							String headBsum="(select max(FORMDATE) from qhead where qcust.custno = qhead.user and ((qhead.ISCONFIRM='Y') "; 
							if (ORS!=2)	headBsum+=" or (qhead.ISCHECK='Y' and (qhead.ISCONFIRM='N' or qhead.ISCONFIRM='O'))))  as allsum"; else headBsum+=")) as allsum";
							headBsum+=", (select sum(BSUM) from qhead where qcust.custno = qhead.user and ((qhead.ISCONFIRM='Y') "; 
							if (ORS!=2)	headBsum+=" or (qhead.ISCHECK='Y' and (qhead.ISCONFIRM='N' or qhead.ISCONFIRM='O'))))  as allsum"; else headBsum+=")) as allsum";
							headBsum+=", (select sum(ATOT) from qhead where qcust.custno = qhead.user and ((qhead.ISCONFIRM='Y') ";
							if (ORS!=2)	headBsum+=" or (qhead.ISCHECK='Y' and (qhead.ISCONFIRM='N' or qhead.ISCONFIRM='O')))) as allsum"; else headBsum+=")) as allsum";
							
							Bufstr.delete(0, Bufstr.toString().length());
								
								buf1.append("select qcust.DEPTNO, qcust.CUSTNO,qcust.CUSTNAME,")
								.append("qcust.MOBIL,qcust.GMAIL,qcust.MSN,qcust.DISCOUNT,qcust.BIRTHDAY,qcust.EMAIL,qcust.ADDRESS,qcust.PS,"+headBsum);
								if (aPart==0)
									if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 )
										buf1.append(" from qcust where qcust.TR='30' order by qcust.DEPTNO,qcust.CUSTNO ");
									else
										buf1.append(" from qcust where qcust.TR='40' order by qcust.DEPTNO,qcust.CUSTNO ");
								else
									if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 )
										buf1.append(" from qcust where qcust.TR='30' and qcust.DEPTNO='"+deptStr[0]+"' order by qcust.DEPTNO,qcust.CUSTNO ");
									else								
										buf1.append(" from qcust where qcust.TR='40' and qcust.DEPTNO='"+deptStr[0]+"' order by qcust.DEPTNO,qcust.CUSTNO ");
								
								//雲端CLOUD 讀取 可以撈到 全部	
								if  (Utilis.haveInternet(QCustff.this) && of_line==1 && mCloud>0){
									reportMode=1;getCloudReport(buf1.toString());									
								}else{
					
									Cursor cs1=db.rawQuery(buf1.toString(), null);
									
									if (cs1.getCount()>0){
										
										if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 )
											Bufstr.append("門市;會員編號;會員名稱;手機;官網帳號;密碼;折數%;生日;電郵;地址;備註;最近交易日;累積交易;累積件數;\r\n");
										else
											Bufstr.append("門市;櫃員編號;櫃員名稱;手機;官網帳號;密碼;折數%;生日;電郵;地址;備註;最近交易日;累積交易;累積件數;\r\n");
										
										while (cs1.moveToNext()){
											for (int x=0;x<14;x++){
												if (cs1.getString(x) == null || cs1.getString(x).equalsIgnoreCase("null") || cs1.getString(x).length()==0 )
													Bufstr.append("----;");							
												else	
													Bufstr.append(cs1.getString(x)).append(";");							
											}
											Bufstr.append("\r\n");
										}
						    		outPut_bufStr();
									}
									cs1.close();
								
								}
							}	
								Bufstr.delete(0, Bufstr.toString().length());
							break;
						case 2:
							if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 || nKind==PItemKind.TR40 || nKind==PItemKind.TR41 ){//門市通訊錄
								StringBuffer buf2= new StringBuffer();
							
								Bufstr.delete(0, Bufstr.toString().length());
								buf2.append("select a.DEPTNO,a.CUSTNO,a.CUSTNAME,")
								.append("a.MOBIL,a.GMAIL,a.MSN,a.DISCOUNT,a.BIRTHDAY,a.EMAIL,a.ADDRESS,a.PS,max(b.FORMDATE),round(sum(b.BSUM)),sum(b.ATOT),");
								if (ORS!=2)
									buf2.append("round(sum(b.BSUM-b.CASH-b.CARD-b.ORDCASH-b.ORDCARD-b.ATM)) as OMONEY ");
								else
									buf2.append("round(sum(b.BSUM-b.CASH-b.CARD-b.ATM)) as OMONEY ");
										
								buf2.append(" from qcust as a left join qhead as b on a.CUSTNO=b.USER");
								buf2.append(" where substr(b.QKIND,1,1) ='"+mKind.substring(0,1)+"' and ( (b.ISCONFIRM='Y' and b.ISCHECK='N') ");
								if (ORS!=2){
									buf2.append(" or (b.ISCONFIRM='N' and b.ISCHECK='Y') )");
								}else{
									buf2.append(")");
								}
								if (mCloud==0 && aPart==1) buf2.append(" and b.DEPTNO='"+deptStr[0]+"' ");
								//如果門市 且 Local	
								buf2.append(" group by b.DEPTNO,a.CUSTNO having (OMONEY<>0) order by b.DEPTNO,a.CUSTNO ");
	
								if  (Utilis.haveInternet(QCustff.this) && of_line==1 && mCloud>0){
									reportMode=2;getCloudReport(buf2.toString());									
								}else{
									Cursor cs2=db.rawQuery(buf2.toString(), null);
									
									if (cs2.getCount()>0){
										if (mKind.substring(0,1).equalsIgnoreCase("3"))
											Bufstr.append("門市;會員編號;會員名稱;手機;官網帳號;密碼;折數%;生日;電郵;地址;備註;最近交易日;累積交易;累積件數;未結金額;\r\n");
										else
											Bufstr.append("門市;櫃員編號;櫃員名稱;手機;官網帳號;密碼;折數%;生日;電郵;地址;備註;最近交易日;累積交易;累積件數;未結金額;\r\n");
										
										while (cs2.moveToNext()){
											for (int x=0;x<15;x++){
												Bufstr.append(cs2.getString(x)).append(";");							
											}
											Bufstr.append("\r\n");
										}
						    		outPut_bufStr();
									}
									cs2.close();
								}
							}
							break;
						case 3:
							StringBuffer buf3= new StringBuffer();
							
							Bufstr.delete(0, Bufstr.toString().length());
							buf3.append("select a.DEPTNO,a.CUSTNO,a.CUSTNAME,")
							.append("a.MOBIL,a.PS,max(b.FORMDATE),round(sum(b.BSUM)),sum(b.ATOT),");
							if (ORS!=2)
								buf3.append("round(sum(b.BSUM-b.CASH-b.CARD-b.ORDCASH-b.ORDCARD-b.ATM)) as OMONEY ");
							else
								buf3.append("round(sum(b.BSUM-b.CASH-b.CARD-b.ATM)) as OMONEY ");
									
							buf3.append(" from qcust as a left join qhead as b on a.CUSTNO=b.USER");
							buf3.append(" where substr(b.QKIND,1,1) ='"+mKind.substring(0,1)+"' and ( (b.ISCONFIRM='Y' and b.ISCHECK='N') ");
							if (ORS!=2){
								buf3.append(" or (b.ISCONFIRM='N' and b.ISCHECK='Y') )");
							}else{
								buf3.append(")");
							}
							if (mCloud==0 && aPart==1) buf3.append(" and b.DEPTNO='"+deptStr[0]+"' ");
								
							buf3.append(" group by b.DEPTNO,a.CUSTNO having (OMONEY<>0) order by b.DEPTNO,a.CUSTNO ");
				
							Cursor cs3=db.rawQuery(buf3.toString(), null);
							//列印規格
							//DEPTNO 會員:CUSTNO/CUSTNAME
							//TEL:MOBIL /PS:PS
							//BSUM/ATOS/未結:
							
							if (cs3.getCount()>0){
								double noPay=0;
								StringBuffer sPrintB = new StringBuffer();
								Loca=0;
								sPrintB=PosUtilis.getPrintKind(QCustff.this,1);
								Loca=Loca+30;
								Loca=Loca+2;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,"+compStr[0]+"  未結清所有清單"+sepa);
								Loca=Loca+20;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
								Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
								Loca=Loca+15;
								while (cs3.moveToNext()){
									Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+cs3.getString(0)+" 寶號:"+cs3.getString(1)+"/"+cs3.getString(2)+sepa);
									Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+"TEL:"+cs3.getString(3)+" /PS:"+cs3.getString(4)+"/最近:"+cs3.getString(5)+sepa);
									Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+"總$:"+cs3.getDouble(6)+"/"+cs3.getDouble(7)+"件/未結:"+cs3.getDouble(8)+sepa);
									Loca=Loca+15;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,-------------------------------------------------"+sepa);
									if (Loca>2400){
										PosUtilis.startPartPrint(QCustff.this,sPrintB,Loca );
										sPrintB.delete(0, sPrintB.toString().length());
										SystemClock.sleep(2000);
										sPrintB=PosUtilis.getPrintKind(QCustff.this,1);
										Loca=0;
									}
									noPay=noPay+cs3.getDouble(8);
								}
								sPrintB.append("AZ,10,"+Loca+",1,2,0,0,-------------------------------------------------"+sepa);
								Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,"+"總未結金額$:"+noPay+sepa);
				    			Loca=Loca+50;
				    			//呼叫 開始列印 BarCodePrinter Socket
				    			PosUtilis.startPrint(QCustff.this,sPrintB,Loca );
							}
							cs3.close();
							break;
						case 4:
							break;
					}	
						db.close();		
				}
			});
							

           	if (Bufstr.toString().length()>0){
        		try {
                    Writer out = new BufferedWriter(new OutputStreamWriter(
                    	    new FileOutputStream(myFilePath), "UTF-8"));
                    	try {
                    	    out.write(Bufstr.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));
        	}
           	Bufstr.delete(0, Bufstr.toString().length());
           	
			}
		}
	});
		
	mBtn_sms.setOnClickListener(new Button.OnClickListener(){

		@Override
		public void onClick(View v) {	
				String myFilePath = SD_PATH+pathName+"/cu_albun.lst";
	            ArrayList<HashMap<String, Object>>  albun_list = new ArrayList<HashMap<String, Object>>();
	           	File myFile = new File(myFilePath); //其目的是為了產生一個新檔案或資料夾
        		for (int x=0;x<main_list.size();x++){
    				HashMap<String, Object> mapm = main_list.get(x);
    				if (mapm.get("tv_mobil").toString().indexOf("09")==0){
	                    HashMap<String, Object> mapss = new HashMap<String, Object>();                        
	               		mapss.put("eno",mapm.get("tv_no"));
	               		mapss.put("ename",mapm.get("tv_name"));                        		
	               		mapss.put("emobil", mapm.get("tv_mobil"));
	               		mapss.put("eemail",  mapm.get("tv_email"));
	               		mapss.put("ebars", "$"+mapm.get("tv_no"));                        		
	               		mapss.put("epics",  mapm.get("tv_picn"));                        		
	                    albun_list.add(mapss);
    				}
        		}
           	if (albun_list.size()>0){
        		FileOutputStream istream = null;
        		ObjectOutputStream os = null;
        		try {
        			istream = new FileOutputStream(myFilePath);
        			os = new ObjectOutputStream(istream);
                    os.writeObject(albun_list); 
        			os.close();
        			istream.close();

        		} catch (Exception e) {

        		}
				Intent intent = new Intent();
    			bundle = new Bundle();
    			bundle.putString("Qsms",myFilePath+",sms");
    			intent.setClass(QCustff.this, Qsms_one.class);
    			intent.putExtras(bundle);
    			startActivity(intent);
        	}
		}
			//原先啟動行動中心 
			// 前往sms
			//Intent intent = new Intent();				
			//intent.setClass(QCustff.this, CustActivity.class);
			//intent.putExtra("Qcustf",1);  //1sms 2email
			//intent.putExtra("Qcust_qkind", mKind); //種類10廠20門市30會員40櫃員
			//startActivity(intent);		}
	});
	
	mBtn_email.setOnClickListener(new Button.OnClickListener(){

		@Override
		public void onClick(View v) {	
				SQLiteDatabase db = Utilis.getDB(QCustff.this);
				String myFilePath = SD_PATH+pathName+"/cu_albun.lst";
	            ArrayList<HashMap<String, Object>>  albun_list = new ArrayList<HashMap<String, Object>>();
	           	File myFile = new File(myFilePath); //其目的是為了產生一個新檔案或資料夾
        		for (int x=0;x<main_list.size();x++){
    				HashMap<String, Object> mapm = main_list.get(x);
    				edno = (String)mapm.get("tv_no");
    				Cursor cs=db.rawQuery("select EMAIL from qcust where CUSTNO='"+edno+"'", null);
    				if (cs.getCount()>0){
    			        cs.moveToFirst();
    					if (cs.getString(0).length() > 0 && cs.getString(0).indexOf("@")>0 ) {
		                    HashMap<String, Object> mapss = new HashMap<String, Object>();                        
		               		mapss.put("eno",mapm.get("tv_no"));
		               		mapss.put("ename",mapm.get("tv_name"));                        		
		               		mapss.put("emobil", mapm.get("tv_mobil"));
		               		mapss.put("eemail",  cs.getString(0));
		               		mapss.put("ebars", "$"+mapm.get("tv_no"));                        		
		               		mapss.put("epics",  mapm.get("tv_picn"));                        		
		                    albun_list.add(mapss);
    					}
    				}
        		}
           	if (albun_list.size()>0){
        		FileOutputStream istream = null;
        		ObjectOutputStream os = null;
        		try {
        			istream = new FileOutputStream(myFilePath);
        			os = new ObjectOutputStream(istream);
                    if (albun_list !=null && albun_list.size()>0)
                    { os.writeObject(albun_list); }
        			os.close();
        			istream.close();

        		} catch (Exception e) {

        		}
				Intent intent = new Intent();
    			bundle = new Bundle();
    			bundle.putString("Qsms",myFilePath+",email");
    			intent.setClass(QCustff.this, Qsms_one.class);
    			intent.putExtras(bundle);
    			startActivity(intent);
    			db.close();
        	}
			
			//原先啟動行動中心 
			// 前往EMAIL
			//Intent intent = new Intent();				
			//intent.setClass(QCustff.this, CustActivity.class);
			//intent.putExtra("Qcustf",2);
			//intent.putExtra("Qcust_qkind", mKind); //種類10廠20門市30會員40櫃員
			//startActivity(intent);
		}
	});
	
	mBtn_new.setOnClickListener(new Button.OnClickListener(){

		@Override
		public void onClick(View v) {	
			// 前往新增新資料
			askPSWD(0);
		}
	});
	
	mBtn_exit.setOnClickListener(new Button.OnClickListener(){

		@Override
		public void onClick(View v) {	
			// 結束
			finish();
		}
	});
	
		
		mListView.setOnItemLongClickListener(new OnItemLongClickListener(){

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				 intItemSelected = arg2;
					HashMap<String, Object> map = main_list.get(intItemSelected);				 
			        edno = (String)map.get("tv_no");
			        /* 彈出的選單提供兩種功能（編輯、刪除） */
			        String[] dlgMenu=
			        {
			          getResources().getText(R.string.str_edit_it).toString(),
			          getResources().getText(R.string.str_del_it).toString()
			        };
			        new AlertDialog.Builder(QCustff.this)
			        .setTitle(edno)
			        .setItems(dlgMenu, mListener1)
			        .setPositiveButton(R.string.str_cancel,
			        new DialogInterface.OnClickListener()
			        {
			          public void onClick(DialogInterface dialog, int which)
			          {
			          }
			        }).show();	
				return true;  //@@20121116改 return false; 
			}
			
		});
		
		mListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			
				 intItemSelected = position;
					HashMap<String, Object> map = main_list.get(intItemSelected);				 
			        edna = (String)map.get("tv_name");
			        ResultAum="";
		        if ((nKind==30 || nKind==40 ||nKind==31 || nKind==41)  && Utilis.haveInternet(QCustff.this) && backout[0].equalsIgnoreCase("1") && of_line==1){
		        	//零售版才要啟動雲端統計會員的業績
					Toast.makeText(QCustff.this, "goto_SERVER", Toast.LENGTH_SHORT).show();
			        	getSum((String)map.get("tv_no"),""+(nKind/10)+"%");
		        }else{
		        	listDialog(map.get("tv_no").toString());
		        }			        
			}
			
		});

	}

	
	
	
	private TextWatcher watcherSearched = new TextWatcher(){  
        @Override  
        public void afterTextChanged(Editable s) {  
        }  
        @Override  
        public void beforeTextChanged(CharSequence s, int start, int count,  
                int after) {  
        }  
        @Override  
        public void onTextChanged(CharSequence s, int start, int before,  
                int count) {
				//Action_active with anykey
        		searched();
        }  
    };
	

	private OnClickListener mListener1=new DialogInterface.OnClickListener()
	  {
	    @Override
	    public void onClick(DialogInterface dialog, int which)
	    {
	      // TODO Auto-generated method stub
	      switch(which)
	      {
	        case 0:
	          /* 資料修改 記得要帶入編號 */
				askPSWD(1);
	          break;
	        case 1:
	          /* 刪除資料 */
				if (PSWD==0){
		         	if (records>=1) {
		         		if (!edno.equalsIgnoreCase("AA")){
					        String[] dlgMenu=
					        {
					          getResources().getText(R.string.str_delok).toString(),
					          getResources().getText(R.string.str_delno).toString()
					        };
					        new AlertDialog.Builder(QCustff.this)
					        .setTitle(edno)
					        .setItems(dlgMenu, mListener2)
					        .setPositiveButton(R.string.str_cancel,
					        new DialogInterface.OnClickListener()
					        {
					          public void onClick(DialogInterface dialog, int which)
					          {
					          }
					        }).show();
		         		}
		        	}
	        	}
	          break;
	      }
	    }
	  };
	
		private OnClickListener mListener2=new DialogInterface.OnClickListener()
		  {
		    @Override
		    public void onClick(DialogInterface dialog, int which)
		    {
		      // TODO Auto-generated method stub
		      switch(which)
		      {
		        case 0:{
			          /*確定刪除 */
			try{
					SQLiteDatabase db = Utilis.getDB(QCustff.this);
					if (of_line==0)
						db.execSQL("delete from qcust where CUSTNO ='" +edno + "'");
					else{
						db.execSQL("update qcust set STATE='2' where CUSTNO ='" +edno + "'");
						DBCloud.aa1_aa0_qcust(QCustff.this);
					}
					Toast.makeText(QCustff.this, "刪除資料成功", Toast.LENGTH_SHORT).show();
					
					// 更新資料*** 需讓ADAPTER 重新讀取一次,但是要記錄當下游標,再回來這個位置
					StringBuffer mySqlBuf = new StringBuffer();
					mySqlBuf.append("select * from qcust where state<>'2'");
					if (nMode==QCustfMode.NORMAL){
						if (nKind==31 || nKind==30) mySqlBuf.append(" and DEPTNO='"+mDept+"'");
						if (nKind==21 || (aPart==0 && nKind==20)) mySqlBuf.append( " and  CUSTNO<>'"+mDept+"'  and CUSTNO<>'"+deptStr[5]+"'"); 
						mySqlBuf.append(" and TR='"+mKind+"'  order by CUSTNO LIMIT 3000");
					}else{
						mySqlBuf.append(" and TR='"+mKind+"' and CUSTNO like '%"+edno+"%' order by CUSTNO LIMIT 3000");
					}
					Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
					if (cs.getCount() > 0) if (records>0) updateListView(QCustff.this,cs); 
					
					db.close();
					cs.close();
				}catch(Exception e){
					Toast.makeText(QCustff.this, "刪除資料失敗", Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
				break;
		        }
		        case 1:
		        {
		          /* 放棄刪除 */
		          break;
		        }
		      }
		    }
		  };
	
	
		  private OnClickListener mListener3=new DialogInterface.OnClickListener()
		  {
		    @SuppressWarnings("static-access")
			@Override
		    public void onClick(DialogInterface dialog, int which)
		    {
		      // TODO Auto-generated method stub
				Intent intent = new Intent();
				String myFilePath = SD_PATH+pathName+"/cu_albun.lst";
				HashMap<String, Object> map = main_list.get(intItemSelected);
	            ArrayList<HashMap<String, Object>>  albun_list = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> maps = new HashMap<String, Object>();                        
				
		        edno = (String)map.get("tv_no");
				SQLiteDatabase db = Utilis.getDB(QCustff.this);
	        	StringBuffer mBuf =new StringBuffer();
	        	StringBuffer sPrintB =new StringBuffer();
				
				mBuf.append("select * from qcust where CUSTNO='"+edno+"'");
				Cursor cs=db.rawQuery(mBuf.toString(), null);
			        cs.moveToFirst();
			        
			        String edname = cs.getString(cs.getColumnIndex("CUSTNAME"));
			        String edemail = cs.getString(cs.getColumnIndex("EMAIL"));
			        String edmobil = cs.getString(cs.getColumnIndex("MOBIL"));
			        String edaddress=cs.getString(cs.getColumnIndex("ADDRESS"));
			        String edps=cs.getString(cs.getColumnIndex("PS"));
			        eds2=cs.getString(cs.getColumnIndex("S2"));
			        String eddisc = (String)cs.getString(cs.getColumnIndex("DISCOUNT"));
				
		        cs.close();
		        db.close();
				
		      switch(which)
		      {
		        case 0: //確認傳回
		        	Intent intentS = new Intent();
		        	intentS.putExtra("qcust_key",edno);
		        	intentS.putExtra("qcust_kind",mKind);
		        	QCustff.this.setResult(RESULT_OK,intentS);
		        	finish();
		        	
		        	break; //保留給消費紀錄,商品分析,GPS定位
		          
		        case 1: //發簡訊
					if (edmobil.length() > 0 && edmobil.indexOf("09")==0 ) {
			           	//File myFile = new File(myFilePath); //其目的是為了產生一個新檔案或資料夾
	                   		maps.put("eno",map.get("tv_no"));
	                   		maps.put("ename",map.get("tv_name"));                        		
	                   		maps.put("emobil", map.get("tv_mobil"));
	                   		maps.put("eemail",  map.get("tv_email"));  //置換為地址了
	                   		maps.put("ebars", "$"+map.get("tv_no"));                        		
	                   		maps.put("epics",  map.get("tv_picn"));                        		
	                        albun_list.add(maps);
	                        
		        		FileOutputStream istream = null;
		        		ObjectOutputStream os = null;
		        		try {
		        			istream = new FileOutputStream(myFilePath);
		        			os = new ObjectOutputStream(istream);
		                    if (albun_list !=null && albun_list.size()>0)
		                    { os.writeObject(albun_list); }
		        			os.close();
		        			istream.close();

		        		} catch (Exception e) {

		        		}
		        		
		    			bundle = new Bundle();
		    			bundle.putString("Qsms",myFilePath+",sms");
		    			intent.setClass(QCustff.this, Qsms_one.class);
		    			intent.putExtras(bundle);
		    			startActivity(intent);
		        	}
		        	
		          break;
		          
		        case 2: //發電郵

					if (edemail.length() > 0 && edemail.indexOf("@")>0 ) {

			           	File myFile = new File(myFilePath); //其目的是為了產生一個新檔案或資料夾
	                   		maps.put("eno",edno );
	                   		maps.put("ename",edname  );                        		
	                   		maps.put("emobil", edmobil );
	                   		maps.put("eemail", edemail );
	                   		maps.put("ebars","" );                        		
	                   		maps.put("epics", "");                        		
	                        albun_list.add(maps);
		                        
		              if (albun_list.size()>0){ 
		        		FileOutputStream istream = null;
		        		ObjectOutputStream os = null;
		        		try {
		        			istream = new FileOutputStream(myFilePath);
		        			os = new ObjectOutputStream(istream);
		                    if (albun_list !=null && albun_list.size()>0)
		                    { os.writeObject(albun_list); }
		        			os.close();
		        			istream.close();

		        		} catch (Exception e) {

		        		}
		        		
		    			bundle = new Bundle();
		    			bundle.putString("Qsms",myFilePath+",email");
		    			intent.setClass(QCustff.this, Qsms_one.class);
		    			intent.putExtras(bundle);
		    			startActivity(intent);
		    			
		              }
					}
			          break;
		        case 3:{//消費統計
					intent.putExtra("QRep_Dept",mDept);
					intent.putExtra("QRep_02",(nKind/10)*10);// @@TR30為預設(暫時廠進貨單) 
					intent.putExtra("QRep_who","QCustff");// @@TR30為預設(暫時廠進貨單)
					intent.putExtra("QRep_user",edno);// @@TR30為預設(暫時廠進貨單)
					intent.setClass(QCustff.this,QRep_02.class);
					startActivity(intent);					
		        	
		        	break; //保留給消費紀錄,商品分析,GPS定位
		        }
		        
		        case 4:{
					intent.putExtra("QHis_kind", mKind);
					intent.putExtra("QHis_mode", 1);
					intent.putExtra("QHis_User",edno );
					intent.putExtra("QHis_Goods","" );
					intent.setClass(QCustff.this, QHis.class);
					startActivity(intent);
		        	break;
		        }
		        case 5:{ 	//預設為交易對象
		        	//會員*櫃員*門市

		        		if (nKind==40 || nKind==41){
				            Utilis.putIni(QCustff.this, "INIH", "EMPID", edno, 3);
				        	Utilis.putIni(QCustff.this, "INIH", "EMPNAME", edname, 3);
				            Utilis.putIni(QCustff.this, "INIH", "EMPID", edno, 2);
				        	Utilis.putIni(QCustff.this, "INIH", "EMPNAME", edname, 2);
				            Utilis.putIni(QCustff.this, "INIH", "EMPID", edno, 1);
				        	Utilis.putIni(QCustff.this, "INIH", "EMPNAME", edname, 1);
				        	Toast.makeText(QCustff.this, edno+"/"+edname+"  成功預設為櫃員對象", Toast.LENGTH_SHORT).show();
		        		}else{
				            Utilis.putIni(QCustff.this, "INIH", "USER", edno, nKind/10);
				        	Utilis.putIni(QCustff.this, "INIH", "USERNAME", edname, nKind/10);
				            Utilis.putIni(QCustff.this, "INIH", "DISBTN6", eddisc, nKind/10);
				        	Toast.makeText(QCustff.this, edno+"/"+edname+"  成功預設為交易對象", Toast.LENGTH_SHORT).show();
		        		}
		        	break;
		        }
		        
		        case 6:{ 	//印製條碼 需分為($會員門市廠商) (/櫃員)
		        				//第五種F5另排版面
		        	//先取得該筆資料紀錄
		        	//印製內容:$CUSTNO CUSTNAME MOBIL
					sPrintB.delete(0, sPrintB.toString().length());

					sPrintB.append("^KQCUST"+sepa);
					sPrintB.append(edno+"/"+edname+sepa);
						if (nKind!=40 && nKind!=41) //非櫃員
							sPrintB.append( "$"+edno+sepa);
						else  //櫃員 
							sPrintB.append( "/"+edno+sepa);
						
						sPrintB.append( "M:"+edmobil+sepa);
						sPrintB.append( "E: "+edemail+sepa);
						sPrintB.append( "W:"+edaddress+sepa);
						sPrintB.append( "PS:"+edps+sepa);
						sPrintB.append("E"+sepa);
						sPrintB.append("~P1"+sepa);
						
		    		   String address = Utilis.getIni(QCustff.this, "SYS","BAR_IP", 2);// 連線的ip
		    		   int port =Utilis.toInt(Utilis.getIni(QCustff.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,6000);
		    					 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(QCustff.this, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
		    			 } catch (UnknownHostException e) {
		    				 Toast.makeText(QCustff.this, "InetAddress物件建立失敗!!", Toast.LENGTH_LONG).show();
		    			 } catch (SocketException e) {
		    				 Toast.makeText(QCustff.this, "socket建立失敗", Toast.LENGTH_LONG).show();				 
		    			 } catch(IOException e) {
		    				 Toast.makeText(QCustff.this,"傳送失敗", Toast.LENGTH_LONG).show(); 
		    			 }
		        	break;
		        }
		        case 7:{//預購_留貨清單
	 				if (nKind ==30 || nKind ==31){
	    				intent.putExtra("GalleryUser",edno);
	    				intent.putExtra("GalleryGoods","");
	    				intent.putExtra("GalleryDept", mDept);
	    				intent.putExtra("GalleryASK"," and USER='"+edno+"' ");
	    				intent.putExtra("FormNo","");
	    				intent.putExtra("GalleryQKIND",""+nKind);
	    				intent.putExtra("GalleryMode",0);//0mUser 1mGoods 2KeepaToSale
						intent.setClass(QCustff.this, GalleryViewO.class);
						startActivityForResult(intent, RESULT_GALLERYO);
	 					
	 				}else if (nKind ==20 || nKind ==21){
 					// 出貨_專櫃請款單
	 				//先拉出 所有已過帳的盤點頭清單
	 				//再度確認後,直接呼叫goCloud(7),並直接輸出qadff mkqrst
						intent.putExtra("QRep_Dept",edno);
						intent.putExtra("QRep_02","31");// @@TR30為預設(暫時廠進貨單) 
						intent.putExtra("QRep_who","QCustff");// @@TR30為預設(暫時廠進貨單)
						intent.putExtra("QRep_user","Z"+edno);// @@TR30為預設(暫時廠進貨單)
						intent.setClass(QCustff.this,QRep_02.class);
						startActivity(intent);					
					}
		        	break;
		        }
		        
		        case 8:{//留貨轉銷貨
	 				if (nKind ==30 || nKind ==31){
	    				intent.putExtra("GalleryUser",edno);
	    				intent.putExtra("GalleryGoods","");
	    				intent.putExtra("GalleryDept", mDept);
	    				intent.putExtra("GalleryASK"," and USER='"+edno+"' ");
	    				intent.putExtra("GalleryQKIND",""+nKind);
	    				intent.putExtra("FormNo",PosUtilis.getFno(QCustff.this,edno,""+nKind,0));
	    				intent.putExtra("GalleryMode",2);//0mUser 1mGoods 2KeepaToSale
						intent.setClass(QCustff.this,GalleryViewO.class);
						startActivityForResult(intent, RESULT_GALLERYO);
					}
		        	break;
		        }
		        
		        case 9:{ //撥打電話
					if (edmobil.length() > 0) {
						intent.setAction(intent.ACTION_VIEW);
						intent.setData(Uri.parse("tel:" + edmobil));
						startActivity(intent);
					}
		        	
		          break;
		        }
		        case 10:{//列印名條
					PosUtilis.startPostPrint(QCustff.this,edno,compStr);
					break;
		        }
		      }
		    }
		  };
		  
		  
	int count;
	
 private void outPut_bufStr(){
   	if (Bufstr.toString().length()>0){
   		try {
            Writer out = new BufferedWriter(new OutputStreamWriter(
            	    new FileOutputStream(myFilePath), "UTF-8"));
            	try {
            	    out.write(Bufstr.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 getCloudReport(String SQL) {
	 //mode=123 如 case 123 
		StringBuffer bfstr = new StringBuffer();
		StringBuffer bfstrF = new StringBuffer();
		
			bfstr.append(Utilis.getIni(QCustff.this, "SYS", "IMPORT", 2)).append(";");
			bfstrF.append("UID").append(";");
			bfstr.append(""+reportMode).append(";");
			bfstrF.append("MODE").append(";");
			bfstr.append(mKind).append(";");
			bfstrF.append("QKIND").append(";");
			bfstr.append(SQL);
			bfstrF.append("SQLSTR");
			
			final String []fields=bfstr.toString().split(";");
			final String []fieldFs=bfstrF.toString().split(";");
			
		      myDialog = ProgressDialog.show(QCustff.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
			  
		      new Thread()
		      { 
		        public void run()
		        { 
		          try
		          { 
						HttpPost httpRequest = new HttpPost(uriAPIrep);
						// Post運作傳送變數必須用NameValuePair[]陣列儲存
						Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPIrep);
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						for(int x=0;x<fields.length;x++){
							params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
						}
						try {
							// 發出HTTP request(請求) 
							httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
							// 取得HTTP response(回傳) 
							HttpResponse httpResponse = new DefaultHttpClient()
									.execute(httpRequest);
							if (httpResponse.getStatusLine().getStatusCode() == 200)
							{
								// 取出回應字串
								String strResult = EntityUtils.toString(httpResponse	.getEntity());
								mHandlerSUMreport.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
							}
							
						} catch (Exception e)
						{
							e.printStackTrace();
						}

		          }
		          catch (Exception e)
		          {
		            e.printStackTrace();
		          }
		          finally
		          {
		            // 卸載所建立的myDialog物件。
		            myDialog.dismiss();
		          }
		        }
		      }.start(); 

	 
 }
 
 private void listDialog(String mUser){
 	if (nKind==30 || nKind==40){
 		//User==map.get("tv_no")
      	 String SQL="select sum(BSUM),(sum(CASH)+sum(ORDCASH)),(sum(CARD)+sum(ATM)+sum(ORDCARD)) from qhead where USER='"+mUser+"' and QKIND like '"+mKind.substring(0, 1)+"%' and (ISCONFIRM='Y')";
			SQLiteDatabase db = Utilis.getDB(QCustff.this);
			Cursor cs=db.rawQuery(SQL, null);		
			if (cs.getCount()>0){
				cs.moveToFirst();
				ResultAum="交易:"+cs.getInt(0)+" 現金:"+cs.getInt(1)+" 刷票:"+cs.getInt(2);
				Toast.makeText(QCustff.this, edna+":"+ResultAum, Toast.LENGTH_SHORT).show();
			}
			cs.close();
			db.close();
   	}
       String[] dlgMenu=
       {
       		getResources().getText(R.string.str_f_9).toString(),
       		getResources().getText(R.string.str_f_1).toString(),
       		getResources().getText(R.string.str_f_2).toString(),
       		getResources().getText(R.string.str_f_3).toString(),
       		getResources().getText(R.string.str_f_4).toString(),
       		getResources().getText(R.string.str_f_5).toString(),
       		getResources().getText(R.string.str_f_6).toString(),
       		getResources().getText(R.string.str_f_7).toString(),
       		getResources().getText(R.string.str_f_8).toString(),
       		getResources().getText(R.string.str_f_0).toString(),
       		getResources().getText(R.string.str_f_10).toString()
       };
       if (nKind==20 || nKind==21){
       	dlgMenu[7]="盤銷後_應收對帳單";
       	dlgMenu[8]="保留";
       }else if(nKind!=31 && nKind!=30){
       	dlgMenu[7]="保留";
       	dlgMenu[8]="保留";
       }
       
       new AlertDialog.Builder(QCustff.this)
       .setTitle(edna+"/"+ResultAum)
       .setItems(dlgMenu, mListener3)
       .setPositiveButton(R.string.str_cancel,
       new DialogInterface.OnClickListener()
       {
         public void onClick(DialogInterface dialog, int which)
         {
         }
       }).show();
	 
 }
 
 private void getSum (final String mUser ,String mKind){
	 ResultAum="";
	 String SQL="select sum(BSUM),(sum(CASH)+sum(ORDCASH)),(sum(CARD)+sum(ATM)+sum(ORDCARD)) from qhead where USER='"+mUser+"' and QKIND like '"+mKind.substring(0, 1)+"%' and (ISCONFIRM='Y')";
	 //php_"select sum(BSUM),(sum(CASH)+sum(ORDCASH)),(sum(CARD)+sum(ORDCARD)+sum(CARD)) from qhead where USER='". $user."' and QKIND like '".$qkind."' where (ISCONFIRM='Y')"
			//取得WEB 所有門市的該會員交易累計
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
			
				bfstr.append(Utilis.getIni(QCustff.this, "SYS", "IMPORT", 2)).append(";");
				bfstrF.append("UID").append(";");
				bfstr.append(mUser).append(";");
				bfstrF.append("USER").append(";");
				bfstr.append(mKind).append(";");
				bfstrF.append("QKIND").append(";");
				bfstr.append(SQL);
				bfstrF.append("SQLSTR");
				
				final String []fields=bfstr.toString().split(";");
				final String []fieldFs=bfstrF.toString().split(";");
				
			      myDialog = ProgressDialog.show(QCustff.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
				  
			      new Thread()
			      { 
			        public void run()
			        { 
			          try
			          { 
							HttpPost httpRequest = new HttpPost(uriAPI1);
							// Post運作傳送變數必須用NameValuePair[]陣列儲存
							//Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI1);
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							for(int x=0;x<fields.length;x++){
								params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
							}
							try {
								// 發出HTTP request(請求) 
								httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								// 取得HTTP response(回傳) 
								HttpResponse httpResponse = new DefaultHttpClient()
										.execute(httpRequest);
								if (httpResponse.getStatusLine().getStatusCode() == 200)
								{
									// 取出回應字串
									String strResult = EntityUtils.toString(httpResponse	.getEntity());
									mHandlerSUM1.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
								}
								
							} catch (Exception e)
							{
								e.printStackTrace();
							}

			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();

			          }
			          finally
			          {
			            // 卸載所建立的myDialog物件。
			            myDialog.dismiss();
			          }
			        }
			      }.start(); 

 }

	Handler mHandlerSUM1 = 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_2", "getweb_bsum_echo"+Hresult);
					if (Hresult.indexOf("okok")>0){
						String Sums []=Hresult.split(";");
						ResultAum="";
						if (Sums.length>3)
							ResultAum="交易:"+Sums[1]+" 現金:"+Sums[2]+" 刷票:"+Sums[3];
						Toast.makeText(QCustff.this, edna+":"+ResultAum, Toast.LENGTH_SHORT).show();
					}
				}
			}
	        String[] dlgMenu=
		        {
		        		getResources().getText(R.string.str_f_9).toString(),
		        		getResources().getText(R.string.str_f_1).toString(),
		        		getResources().getText(R.string.str_f_2).toString(),
		        		getResources().getText(R.string.str_f_3).toString(),
		        		getResources().getText(R.string.str_f_4).toString(),
		        		getResources().getText(R.string.str_f_5).toString(),
		        		getResources().getText(R.string.str_f_6).toString(),
		        		getResources().getText(R.string.str_f_7).toString(),
		        		getResources().getText(R.string.str_f_8).toString(),
		        		getResources().getText(R.string.str_f_0).toString(),
		        		getResources().getText(R.string.str_f_10).toString()
		        };
		        new AlertDialog.Builder(QCustff.this)
		        .setTitle(edna+"/"+ResultAum)
		        .setItems(dlgMenu, mListener3)
		        .setPositiveButton(R.string.str_cancel,
		        new DialogInterface.OnClickListener()
		        {
		          public void onClick(DialogInterface dialog, int which)
		          {
		          }
		        }).show();
			
		}
	};		
		

	Handler mHandlerSUMreport = 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_2", "getweb_bsumReport_echo"+Hresult);
					if (Hresult.indexOf("porting")>0){
						String Sums []=Hresult.split(";SSSS\r\n");
						if (Sums.length>1){
							Bufstr.delete(0, Bufstr.toString().length());
							if (reportMode==1){
								if (nKind==30 || nKind==31)
									Bufstr.append("門市;會員編號;會員名稱;手機;官網帳號;密碼;折數%;生日;電郵;地址;備註;最近交易日;累積交易;累積件數;\r\n");
								else
									Bufstr.append("門市;櫃員編號;櫃員名稱;手機;官網帳號;密碼;折數%;生日;電郵;地址;備註;最近交易日;累積交易;累積件數;\r\n");
							}else if (reportMode==2){
								if (nKind==30 || nKind==31)
									Bufstr.append("門市;會員編號;會員名稱;手機;官網帳號;密碼;折數%;生日;電郵;地址;備註;最近交易日;累積交易;累積件數;未結金額;\r\n");
								else	
									Bufstr.append("門市;櫃員編號;櫃員名稱;手機;官網帳號;密碼;折數%;生日;電郵;地址;備註;最近交易日;累積交易;累積件數;未結金額;\r\n");
							}
							
							Bufstr.append(Sums[1]);
							outPut_bufStr();							
						}						
					}
				}
			}
		}
	};		
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		/* menu群組ID */
		int idGroup1 = 0;

		/* The order position of the item */
		int orderItem1 = Menu.NONE;
		int orderItem2 = Menu.NONE + 1;
		int orderItem3 = Menu.NONE + 2;
		int orderItem4 = Menu.NONE + 3;
		int orderItem5 = Menu.NONE + 4;
		int orderItem6 = Menu.NONE + 5;

		/* 建立3個Menu選單 共四個參數 群組,項目序,排序,欄位名稱及圖示,注意:4版後就沒有圖示 */
		menu.add(idGroup1, MENU_ADD, orderItem1, R.string.str_manu1).setIcon(
				R.drawable.adds);
		menu.add(idGroup1, MENU_SMS, orderItem2, R.string.str_manu2).setIcon(
				R.drawable.smss);
		menu.add(idGroup1, MENU_MAIL, orderItem3, R.string.str_manu3).setIcon(
				R.drawable.emails);
		menu.add(idGroup1, MENU_QCUSTF, orderItem4, R.string.str_manu4)
				.setIcon(R.drawable.serchs);
		menu.add(idGroup1, MENU_LISTALL, orderItem5, R.string.str_manu5)
				.setIcon(R.drawable.albuns);
		menu.add(idGroup1, MENU_MAP, orderItem6, R.string.str_manu6).setIcon(
				R.drawable.gpss);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		switch (item.getItemId()) {
		case (MENU_ADD):
			//保留
			break;
		case (MENU_SMS):
			// 前往大宗簡訊			
			intent.setClass(QCustff.this, CustActivity.class);
			intent.putExtra("Qcust_qkind", mKind); //種類10廠20門市30會員40櫃員
			intent.putExtra("Qcustf", 1); //種類10廠20門市30會員40櫃員			
			startActivity(intent);
			break;
		case (MENU_MAIL):
			// 前往大宗電郵
    	  if(Utilis.haveInternet(QCustff.this)){
			intent.setClass(QCustff.this, CustActivity.class);
			intent.putExtra("Qcust_qkind", mKind); //種類10廠20門市30會員40櫃員
			intent.putExtra("Qcustf", 2); //種類10廠20門市30會員40櫃員			
			startActivity(intent);
    	  }	
			break;
		case (MENU_QCUSTF):
			// 前往快速查詢 
			intent.putExtra("GalleryCust", "0,0,0");	
			 intent.setClass(QCustff.this, GalleryViewC.class);
			 startActivity(intent);
			break;
		case (MENU_LISTALL):
			// 前往活頁相本			
			intent.setClass(QCustff.this, CustActivity.class);
			intent.putExtra("Qcust_qkind", mKind); //種類10廠20門市30會員40櫃員
			intent.putExtra("Qcustf", 0); //種類10廠20門市30會員40櫃員			
			startActivity(intent);
			break;
		case (MENU_MAP):
			/* 前往系統亂數選擇餐廳功能 */
			// intent.setClass(EX10_06.this, EX10_06_04.class);
			// startActivity(intent);
			// finish();
			break;

		}
		return super.onOptionsItemSelected(item);
	}

	private void searched(){
		//將鍵盤收起來
//  		 InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//         m.hideSoftInputFromWindow(edSearch01.getWindowToken(), 0);               		
	if (edSearch01.getText().toString().length() > 0) {
         int catched = 0;
         SQLiteDatabase db = Utilis.getDB(this);
 		Cursor cs = null;
 		StringBuffer mySqlBuf = new StringBuffer();
 		mySqlBuf.append("select * from qcust");
		mySqlBuf.append(" where TR='"+mKind+"'"); 
		if ((nKind==31 || nKind==30) && bPart==1) mySqlBuf.append(" and DEPTNO='"+mDept+"'");
		if (nKind==21 || (aPart==0 && nKind==20)) mySqlBuf.append( " and  CUSTNO<>'"+mDept+"'  and CUSTNO<>'"+deptStr[5]+"'"); 
		mySqlBuf.append(" and  CUSTNO  like '%" + edSearch01.getText().toString().trim() + "%' order by _ID DESC LIMIT 3000" );
 		cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount() > 0) {
				catched = 1;
			}

			if (catched == 0) {
				 mySqlBuf.delete(0, mySqlBuf.toString().length());
		 		mySqlBuf.append("select * from qcust");
				mySqlBuf.append(" where TR='"+mKind+"'"); 
				if ((nKind==31 || nKind==30) && bPart==1) mySqlBuf.append(" and DEPTNO='"+mDept+"'");
				if (nKind==21 || (aPart==0 && nKind==20)) mySqlBuf.append( " and  CUSTNO<>'"+mDept+"'  and CUSTNO<>'"+deptStr[5]+"'"); 
			 		mySqlBuf.append(" and BIRTHDAY  like '%" + edSearch01.getText().toString().trim() + "%' order by _ID DESC LIMIT 3000" );
		 		cs = db.rawQuery(mySqlBuf.toString(), null);
				
				if (cs.getCount() > 0) {
					catched = 1;
				}
			}
 					
 					
			if (catched == 0) {
				mySqlBuf.delete(0, mySqlBuf.toString().length());
		  		mySqlBuf.append("select * from qcust");
				mySqlBuf.append(" where TR='"+mKind+"'"); 
				if ((nKind==31 || nKind==30) && bPart==1) mySqlBuf.append(" and DEPTNO='"+mDept+"'");
				if (nKind==21 || (aPart==0 && nKind==20)) mySqlBuf.append( " and  CUSTNO<>'"+deptStr[0]+"'  and CUSTNO<>'"+deptStr[5]+"'"); 
	 			mySqlBuf.append(" and  CUSTNAME  like '%" + edSearch01.getText().toString().trim() + "%' order by _ID DESC LIMIT 3000" );
		 		cs = db.rawQuery(mySqlBuf.toString(), null);
				
				if (cs.getCount() > 0) {
					catched = 1;
				}
			}
			
			if (catched == 0) {
				 mySqlBuf.delete(0, mySqlBuf.toString().length());
		 		mySqlBuf.append("select * from qcust");
				mySqlBuf.append(" where TR='"+mKind+"'"); 
				if ((nKind==31 || nKind==30) && bPart==1) mySqlBuf.append(" and DEPTNO='"+mDept+"'");
				if (nKind==21 || (aPart==0 && nKind==20)) mySqlBuf.append( " and  CUSTNO<>'"+mDept+"'  and CUSTNO<>'"+deptStr[5]+"'"); 
	 			mySqlBuf.append(" and  MOBIL  like '%" + edSearch01.getText().toString().trim() + "%' order by _ID DESC LIMIT 3000" );
		 		cs = db.rawQuery(mySqlBuf.toString(), null);
				
				if (cs.getCount() > 0) {
					catched = 1;
				}
			}

			if (catched == 0) {
				 mySqlBuf.delete(0, mySqlBuf.toString().length());
		 		mySqlBuf.append("select * from qcust");
				mySqlBuf.append(" where TR='"+mKind+"'"); 
				if ((nKind==31 || nKind==30) && bPart==1) mySqlBuf.append(" and DEPTNO='"+mDept+"'");
				if (nKind==21 || (aPart==0 && nKind==20)) mySqlBuf.append( " and  CUSTNO<>'"+mDept+"'  and CUSTNO<>'"+deptStr[5]+"'"); 
	 			mySqlBuf.append(" and  EMAIL  like '%" + edSearch01.getText().toString().trim() + "%' order by _ID DESC LIMIT 3000" );
		 		cs = db.rawQuery(mySqlBuf.toString(), null);
				
				if (cs.getCount() > 0) {
					catched = 1;
				}
			}

			if (catched == 0) {
				 mySqlBuf.delete(0, mySqlBuf.toString().length());
		 		mySqlBuf.append("select * from qcust");
				mySqlBuf.append(" where TR='"+mKind+"'"); 
				if ((nKind==31 || nKind==30) && bPart==1) mySqlBuf.append(" and DEPTNO='"+mDept+"'");
				if (nKind==21 || (aPart==0 && nKind==20)) mySqlBuf.append( " and  CUSTNO<>'"+mDept+"'  and CUSTNO<>'"+deptStr[5]+"'"); 
				mySqlBuf.append(" and  PS  like '%" + edSearch01.getText().toString().trim() + "%' order by _ID DESC LIMIT 3000" );
		 		cs = db.rawQuery(mySqlBuf.toString(), null);
				
				if (cs.getCount() > 0) {
					catched = 1;
				}
			}
			

			records=cs.getCount();
			
			if (catched == 1) {
				if (nMode==QCustfMode.SEARCHEDGOBACK && records==1) {//找到而且馬上返回
		        	Intent intentS = new Intent();
		        	cs.moveToFirst();
		        	String SS=cs.getString(cs.getColumnIndex("CUSTNO"));
		        	intentS.putExtra("qcust_key",SS);
		        	intentS.putExtra("qcust_kind",nKind);
		        	QCustff.this.setResult(RESULT_OK,intentS);
		        	db.close();
		        	cs.close();
		        	finish();
				}else{
				updateListView(this,cs);
				}
			}
			db.close();
			cs.close();
		}
	}

	private void callQcust(int xMode){
		SQLiteDatabase db = Utilis.getDB(QCustff.this);
		db.execSQL("update QCUST set S2='0' where S2 isnull or S2='nul' or (S2<>'0' and S2<>'1')");
		db.close();
		
		Intent intent = new Intent();
		if (xMode==0)
			intent.putExtra("qcust_mode", QCustMode.ADD);
		else
			intent.putExtra("qcust_mode", QCustMode.EDIT);
			
		intent.putExtra("qcust_qkind", (nKind/10)*10);//modify
		intent.putExtra("qcust_key", edno);
		intent.putExtra("qcust_deptno", mDept);
	    
		intent.setClass(QCustff.this, QCust.class);
		startActivityForResult(intent, RESULT_QCUST);
	}
	
	private void askPSWD(final int xMode){
		if (PSWD!=0 && backout[8].equalsIgnoreCase("2")){
			String pass = Utilis.getStringSet(QCustff.this, PrefKey.PASSWORD, "");
			if (pass.length()>=3){
				LayoutInflater factory = LayoutInflater.from(QCustff.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);
			    final TextView txtWho = (TextView) v1.findViewById(R.id.TextView02);
			    final EditText edtWho = (EditText) v1.findViewById(R.id.edPswd);
			    edtReg.setText("");edtWho.setText("");
			    txtReg.setText("密碼:");txtWho.setText("櫃員編號:");
					  new AlertDialog.Builder(QCustff.this).setTitle("通關密語").setMessage("請輸入密碼及櫃員編號").setView(v1).setPositiveButton("OK", new DialogInterface.OnClickListener() {
			              public void onClick(DialogInterface dialog, int which) {
			          		String pass = Utilis.getStringSet(QCustff.this, PrefKey.PASSWORD, "").substring(0,3);
			            	  if (edtReg.getText().toString().equalsIgnoreCase(pass) && edtWho.getText().toString().length()>0){
									Toast.makeText(QCustff.this, "傳回的客戶代號:"+pass+"_"+edtReg.getText().toString(), Toast.LENGTH_SHORT).show();
									callQcust(xMode);
			            	  }              
			              }
					  }).setCancelable(false).show();
				}
		}else{
			callQcust(xMode);
		}
		  //檢查 YY
	}
	
	
	
//事先整理出產地國別	
	public void getCountryData(Context context){
		if(mCountryIdList != null){
			mCountryIdList.clear();
		}
		if(mCountryList != null){
			mCountryList.clear();
		} 
		
		if(mCountryIcon != null){
			mCountryIcon.clear();
		}
		
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cursor = db.rawQuery("select _ID,NAME,PIC from qc_country order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						String pic = cursor.getString(cursor.getColumnIndex("PIC"));
						String name = cursor.getString(cursor.getColumnIndex("NAME"));
						mCountryIdList.add(id);
						mCountryIcon.add(pic);
						mCountryList.add(name);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
			}
		}
		db.close();
		cursor.close();
	}
	
	 private void updateListView(Context context,Cursor cs)
	  {
	    /* SELECT f1[] FROM tables[0] */
	
	if (cs.getCount()>0){
		//將改為不要陣列 而用LIST取代
		int record=0;
		String discountS="";
 //      String keyString[] = {  "tv_no" , "tv_name", "tv_email" , "tv_bankname", "tv_mobil" ,"tv_trade" ,
//				"iv_pics" ,"iv_country","tv_ps","tv_gpsla","tv_gpslo"};
        
		main_list = new ArrayList<HashMap<String, Object>>();		
		
		while (cs.moveToNext()) {
//			Toast.makeText(QCustff.this, "成功!!"+cs.getColumnCount()+cs.getString(cs.getColumnIndex("CUSTNO")), Toast.LENGTH_SHORT).show();

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("tv_no",cs.getString(cs.getColumnIndex("CUSTNO")));
            map.put("tv_name",cs.getString(cs.getColumnIndex("CUSTNAME")));
            map.put("tv_email",cs.getString(cs.getColumnIndex("ADDRESS")));
            
            map.put("tv_bankname",cs.getString(cs.getColumnIndex("PS"))+"("+cs.getString(cs.getColumnIndex("BANKNAME"))+")");            
            map.put("tv_mobil",cs.getString(cs.getColumnIndex("MOBIL")));
            int gtrade =cs.getInt(cs.getColumnIndex("TRADETYPE"));
			map.put("tv_trade",tradeStr[gtrade]+"("+""+cs.getString(cs.getColumnIndex("DISCOUNT"))+")"+getResources().getText(R.string.str_discount) );
            map.put("iv_pics",null);
            
			int cindex = mCountryIdList.indexOf(cs.getInt(cs.getColumnIndex("COUNTRY")));
			if(cindex>=0){map.put("iv_country",mCountryIcon.get(cindex));}
			else {
				map.put("iv_country",null);
			}
            map.put("tv_picn",cs.getString(cs.getColumnIndex("PIC")));
			
			main_list.add(map);
			
			mMyAdapter = new MyAdapter1(context, main_list, 
                    new String[] { "tv_no" , "tv_name", "tv_email" , "tv_bankname", "tv_mobil" ,"tv_trade" ,
					"iv_pics" ,"iv_country","tv_picn"}, new int[] {
                            R.id.textview,R.id.textview2,R.id.textview5,R.id.textview6,R.id.textview7,R.id.textview1,R.id.imageView1,R.id.imageView2 ,0});
			mListView.setAdapter(mMyAdapter);
			record++;
		}
		mMyAdapter.notifyDataSetChanged();
	}
	 
	records=cs.getCount();
	if (intItemSelected>=0 && intItemSelected<records){
		mListView.setSelection(intItemSelected);}
	 
//		if (dbHelper != null && dbHelper.getReadableDatabase().isOpen()) {	dbHelper.close();	}

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

			DBCloud.aa0_aa1_auto_qcust(this);
			DBCloud.aa0_aa1_auto_HI(this,nKind);
			
		}

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

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

		}
	
	    
}
