package com.cwbuyer.main;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
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 com.cwbuyer.adapter.MyAdapter1;
import com.cwbuyer.format.EMode;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.QHis;
import com.cwbuyer.lib.QRep_02;
import com.cwbuyer.lib.Qsms_one;
import com.cwbuyer.lib.Utilis;
import com.pwbuyer.main.R;

import android.app.Activity;
import android.app.AlertDialog;
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.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
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.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;


public class Qfactff extends Activity {
	/** Called when the activity is first created. */
	private final String[] tradeStr =Utilis.getIni(this,"SYS","TRADENAME",9).split("!&!");

	private final int RESULT_QFACT=7777; 		//
	private final int RESULT_GALLERYO=5566; 		//GALLERY 
	
	String mKind =null; //單別 1020304050
	String mDept=Utilis.getIni(this, "SYS", "DEPT", 6);
	StringBuffer Bufstr= new StringBuffer();
	private String sepa="\r\n";
	private final String[] pKind=Utilis.getIni(this,"SYS","CKIND",9).split("!&!");
	int nKind=10; //單別 1020304050
	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	int aPart=0;//0總倉 1門市
	private String[] MenuOpt ={ "畫面的廠商資料", "所有的廠商資料","返回" };

	public interface QFactfMode{
		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_new;
	private Button mBtn_exit;
	String SD_PATH =android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
	String pathName="/cwbuyer";	
	int mMode = EMode.EDIT;
	int mCountryId = 0;
	int nMode = EMode.EDIT;
	int records =0;
	String myFilePath = SD_PATH+pathName+"/fact_report.csv";

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

	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_QFACT:
			{
				if (resultCode == RESULT_OK) {
					if(dataR.getIntExtra("qfact_modify",0)==1){
			        	edno=dataR.getStringExtra("qfact_key");						
						if (nMode==EMode.GET ) {//找到而且馬上返回
				        	Intent intentS = new Intent();
				        	intentS.putExtra("qfact_key",edno);
				        	//@@@intentS.putExtra("qfact_kind",nKind);
				        	Qfactff.this.setResult(RESULT_OK,intentS);
						    finish();
						}else {   
						//讓畫面重新整理
							Toast.makeText(Qfactff.this, "傳回的廠商代號:"+edno, Toast.LENGTH_SHORT).show();							
							SQLiteDatabase db = Utilis.getDB(this);
							Cursor maincs = null;
							StringBuffer mySqlBuf = new StringBuffer();
							mySqlBuf.append("select * from qfact  where state<>'2'");
								mySqlBuf.append(" and FACTNO='"+edno+"' order by FACTNO LIMIT 300");
							
							maincs = db.rawQuery(mySqlBuf.toString(), null);
									if (maincs.getCount() > 0) {
										 updateListView(this,maincs);
									}
							maincs.close();
							db.close();
						break;				
					}					
				}	
				}
				break;
			}
		case RESULT_GALLERYO:break;
		}	
    }
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.custf);
		
		nKind = 10;
		mKind=""+nKind;
		nMode = getIntent().getIntExtra("mode", EMode.EDIT);
		mCountryId = getIntent().getIntExtra("countryid", 0);
		
//		nMode = getIntent().getIntExtra("qfactf_mode", QFactfMode.NORMAL); //0普 1查 2查返
		edno= getIntent().getStringExtra("qfact_key"); //所要查詢的項目 這是一個重要的關鍵值
		aPart=0;//1門市 0總倉

		LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout_main);
		linearLayout.setBackgroundResource(R.drawable.picbg);		
		
//		交易價別方式設定 **千萬不可在陣列中一開始就使用轉址參考型別 LINE_51
		setTitle(getResources().getText(R.string.app_name).toString()+pKind[(nKind/10)-1]+"流覽");
//未來以TR 判斷可為 10廠商 20門市 30會員 40櫃員
		
		edSearch01 = (EditText) findViewById(R.id.edSearch2);
		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_new = (Button) findViewById(R.id.btn_new);
		mBtn_exit = (Button) findViewById(R.id.btn_exit);
		
		getCountryData(this);		
		
		StringBuffer mySqlBuf = new StringBuffer();
		
	if (nMode==EMode.EDIT){ //常態
//		 InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//	      m.hideSoftInputFromWindow(edSearch01.getWindowToken(), 0);               		
        SQLiteDatabase db = Utilis.getDB(this);
		Cursor maincs = null;
 		mySqlBuf.append("select * from qfact WHERE  STATE<>'2'");
		if (mCountryId!=0) mySqlBuf.append(" and COUNTRY='"+mCountryId+"'" );
		mySqlBuf.append(" order by FACTNO LIMIT 300" );
			
		maincs = db.rawQuery(mySqlBuf.toString(), null);
					if (maincs.getCount() > 0) {
						 updateListView(this,maincs);
					} else {
							Intent intent = new Intent();
							intent.putExtra("mode", EMode.ADD);						
							intent.putExtra("factno", edno);
							intent.setClass(Qfactff.this, AddCompany.class);
							startActivityForResult(intent, RESULT_QFACT);			
					}
					maincs.close();
					db.close();
					
	}else{ //外部程式進來,先行查詢
		edSearch01.setText(edno);
		searched();
		edSearch01.setText("");
	}
//					 setupViews();
				
		
		mImageBt_callback.setOnClickListener(new ImageButton.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
		        SQLiteDatabase db = Utilis.getDB(Qfactff.this);				
				Cursor cs = null;
				StringBuffer mySqlBuf = new StringBuffer();
				mySqlBuf.append("select * from qfact where state<>'2' order by FACTNO LIMIT 300");
				cs = db.rawQuery(mySqlBuf.toString(), null);
				if (cs.getCount() > 0) {
					intItemSelected=0;
				    updateListView(Qfactff.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_new.setOnClickListener(new Button.OnClickListener(){

		@Override
		public void onClick(View v) {	
			// 前往新增新資料
			Intent intent = new Intent();
			intent.putExtra("mode", EMode.ADD);						
			intent.putExtra("factno", edno);
			intent.setClass(Qfactff.this, AddCompany.class);
			startActivityForResult(intent, RESULT_QFACT);	
		}
	});
	
	mBtn_exit.setOnClickListener(new Button.OnClickListener(){

		@Override
		public void onClick(View v) {	
			// 結束
			finish();
		}
	});
	
	mBtn_photo.setOnClickListener(new Button.OnClickListener(){

		@Override
		public void onClick(View v) {	
		// 輸出
			DialogUtilis.showDialog(Qfactff.this, "請選擇輸出的內容", -1,
			MenuOpt , new IDialog() {
				@Override
				public void onDialogFinish(int pos, String choice) {
						
	  				SQLiteDatabase db = Utilis.getDB(Qfactff.this);
		           	Bufstr.delete(0, Bufstr.toString().length());
			  				
						switch (pos) {
						case 0: 
				           	if (main_list.size()>0){
								Bufstr.append("國家;廠商編號;廠商名稱;手機;GMAIL;MSN;折數%;電郵;地址;備註;\r\n");
				        		for (int x=0;x<main_list.size();x++){
				    				HashMap<String, Object> mapm = main_list.get(x);
				    				edno = (String)mapm.get("tv_no");
									StringBuffer buf1= new StringBuffer();
									buf1.append("select qc_country.NAME,qfact.FACTNO,qfact.FACTNAME,")
									.append("qfact.MOBIL,qfact.GMAIL,qfact.MSN,qfact.DISCOUNT,qfact.EMAIL,qfact.ADDRESS,qfact.PS");
									buf1.append(" from qfact left join qc_country on (qfact.country=qc_country._ID) where qfact.FACTNO='"+edno+"' and qfact.STATE<>2 order by qfact.COUNTRY,qfact.FACTNO ");
									
									Cursor cs1=db.rawQuery(buf1.toString(), null);
									if (cs1.getCount()>0){
										cs1.moveToFirst();
										for (int y=0;y<10;y++){
											Bufstr.append(cs1.getString(y)).append(";");
										}
										Bufstr.append("\r\n");
									}
									cs1.close();
				        		}
			        		outPut_bufStr();
				           	}
							break;
						case 1://
							StringBuffer buf1= new StringBuffer();
							Bufstr.delete(0, Bufstr.toString().length());
							buf1.append("select qc_country.NAME,qfact.FACTNO,qfact.FACTNAME,")
							.append("qfact.MOBIL,qfact.GMAIL,qfact.MSN,qfact.DISCOUNT,qfact.EMAIL,qfact.ADDRESS,qfact.PS");
							buf1.append(" from qfact left join qc_country on (qfact.country=qc_country._ID) where qfact.STATE<>2 order by qfact.COUNTRY,qfact.FACTNO ");
							
							Cursor cs1=db.rawQuery(buf1.toString(), null);
							
							if (cs1.getCount()>0){
								Bufstr.append("國家;廠商編號;廠商名稱;手機;GMAIL;MSN;折數%;電郵;地址;備註;\r\n");
								
								while (cs1.moveToNext()){
									for (int x=0;x<10;x++){
										Bufstr.append(cs1.getString(x)).append(";");
									}
									Bufstr.append("\r\n");
								}
				    		outPut_bufStr();
							}
							cs1.close();

							Bufstr.delete(0, Bufstr.toString().length());
							break;
						case 2:
							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());
           	
			}
			
	});
	
		
		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(Qfactff.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) {
				// When clicked, show a toast with the TextView text
			
				 intItemSelected = position;
					HashMap<String, Object> map = main_list.get(intItemSelected);				 
			        edno = (String)map.get("tv_name");

			        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_17).toString(),
			        		getResources().getText(R.string.str_f_18).toString(),
			        		getResources().getText(R.string.str_f_0).toString(),
			        		"列印名條"
			        };
			        new AlertDialog.Builder(Qfactff.this)
			        .setTitle(edno)
			        .setItems(dlgMenu, mListener3)
			        .setPositiveButton(R.string.str_cancel,
			        new DialogInterface.OnClickListener()
			        {
			          public void onClick(DialogInterface dialog, int which)
			          {
			          }
			        }).show();
			        
			}
			
		});

	}

	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:
	    		SQLiteDatabase db = Utilis.getDB(Qfactff.this);
    			db.execSQL("update QFACT set EMPID='1' where EMPID isnull or EMPID='nul' or (EMPID<>'0' and EMPID<>'1')");
	    		db.close();
	        	
				Intent intent = new Intent();
				intent.putExtra("mode", EMode.EDIT);						
				intent.putExtra("factno", edno);
				intent.setClass(Qfactff.this, AddCompany.class);
				startActivityForResult(intent, RESULT_QFACT);			
	          break;
	        case 1:
	          /* 刪除資料 */
         	if (records>1) {
		        String[] dlgMenu=
		        {
		          getResources().getText(R.string.str_delok).toString(),
		          getResources().getText(R.string.str_delno).toString()
		        };
		        new AlertDialog.Builder(Qfactff.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(Qfactff.this);
					if (of_line==0)
						db.execSQL("delete from qfact where FACTNO ='" +edno + "'");
					else{
						db.execSQL("update qfact set STATE='2' where FACTNO ='" +edno + "'");
						DBCloud.aa1_aa0_qfact(Qfactff.this);
					}
					Toast.makeText(Qfactff.this, "刪除資料成功", Toast.LENGTH_SHORT).show();
					
					// 更新資料*** 需讓ADAPTER 重新讀取一次,但是要記錄當下游標,再回來這個位置
					StringBuffer mySqlBuf = new StringBuffer();
					mySqlBuf.append("select * from qfact where state<>'2' order by FACTNO LIMIT 300");
					Cursor cs = db.rawQuery(mySqlBuf.toString(), null);
					if (cs.getCount() > 0) {
					if (records>0){updateListView(Qfactff.this,cs); }
					}else	{
						Intent intent = new Intent();
						intent.putExtra("mode", EMode.ADD);						
						intent.putExtra("factno", edno);
						intent.setClass(Qfactff.this, AddCompany.class);
						startActivityForResult(intent, RESULT_QFACT);			
						}
					db.close();
					cs.close();
				}catch(Exception e){
					Toast.makeText(Qfactff.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(Qfactff.this);
	        	StringBuffer mBuf =new StringBuffer();
	        	StringBuffer sPrintB =new StringBuffer();
				
				mBuf.append("select * from qfact where FACTNO='"+edno+"'");
				Cursor cs=db.rawQuery(mBuf.toString(), null);
			        cs.moveToFirst();
			        
			        String edname = (String)cs.getString(cs.getColumnIndex("FACTNAME"));
			        String edemail = (String)cs.getString(cs.getColumnIndex("EMAIL"));
			        String edmobil = (String)cs.getString(cs.getColumnIndex("MOBIL"));
			        String edaddress=(String)cs.getString(cs.getColumnIndex("ADDRESS"));
			        String edps=(String)cs.getString(cs.getColumnIndex("PS"));
				
		        cs.close();
		        db.close();
				
		      switch(which)
		      {
		        case 0: //確認傳回
						intent.putExtra("mode", EMode.ADD);						
						intent.putExtra("qfact_key", edno);
						intent.putExtra("fact_ph", edmobil);
						Qfactff.this.setResult(RESULT_OK,intent);
						finish();
		        	break; //保留給消費紀錄,商品分析,GPS定位
		          
		        case 1: //發簡訊
				 
					if (edmobil.length() > 0) {

	                   		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+",sms");
		    			intent.setClass(Qfactff.this, Qsms_one.class);
		    			intent.putExtras(bundle);
		    			startActivity(intent);
		    			
		              }
					}

		          break;
		          
		        case 2: //發電郵

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

	                   		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(Qfactff.this, Qsms_one.class);
		    			intent.putExtras(bundle);
		    			startActivity(intent);
		    			
		              }
					}
			          break;
		        case 3:{//廠商對帳單
					intent.putExtra("QRep_Dept",mDept);
					intent.putExtra("QRep_02",10); 
					intent.putExtra("QRep_who","QFactff");
					intent.putExtra("QRep_user",edno);
					intent.setClass(Qfactff.this,QRep_02.class);
					startActivity(intent);					
		        	
		        	break; 
		        }
		        
		        case 4:{//購物紀錄
					intent.putExtra("QHis_kind", mKind);
					intent.putExtra("QHis_mode", 0);
					intent.putExtra("QHis_User",edno );
					intent.putExtra("QHis_Goods","" );
					intent.setClass(Qfactff.this, QHis.class);
					startActivity(intent);
		        	break;
		        }
		        case 5:{ 	//預設為廠商交易對象
		        	//會員*櫃員*門市
				            Utilis.putIni(Qfactff.this, "INIH", "USER", edno, nKind/10);
				        	Utilis.putIni(Qfactff.this, "INIH", "USERNAME", edname, nKind/10);
				        	Toast.makeText(Qfactff.this, edno+"/"+edname+"  成功預設為交易對象", Toast.LENGTH_SHORT).show();
		        	break;
		        }
		        
		        case 6:{ 	//印製條碼 需分為($會員門市廠商) (/櫃員)
		        				//第五種F5另排版面
		        	//先取得該筆資料紀錄
		        	//印製內容:$FACTNO FACTNAME MOBIL
					sPrintB.delete(0, sPrintB.toString().length());
					sPrintB.append("^KQCUST"+sepa);
					sPrintB.append(edno+"/"+edname+sepa);
					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 batchFile=SD_PATH+Utilis.getIni(Qfactff.this, "SYS","YEAR", 6)+File.separator+"cwbuyer_barprint.txt";  //預設為分色尺寸
		    	        File myFile = new File(batchFile); //其目的是為了產生一個新檔案或資料夾

		    			BufferedWriter bw;
		    			try {
		    				bw = new BufferedWriter(new FileWriter(myFile));
		                    if (sPrintB.toString() !=null && sPrintB.toString().length()>0)
		                    { bw.write(sPrintB.toString()); }
		                    bw.close();
		    			} catch (IOException e1) {
		    				// TODO Auto-generated catch block
		    				e1.printStackTrace();
		    			}
		    	        
		    		   String address = Utilis.getIni(Qfactff.this, "SYS","BAR_IP", 2);// 連線的ip
		    		   int port =Utilis.toInt(Utilis.getIni(Qfactff.this, "SYS","BAR_IP", 3));// 連線的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(Qfactff.this, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
		    			 } catch (UnknownHostException e) {
		    				 Toast.makeText(Qfactff.this, "InetAddress物件建立失敗!!", Toast.LENGTH_LONG).show();
		    			 } catch (SocketException e) {
		    				 Toast.makeText(Qfactff.this, "socket建立失敗", Toast.LENGTH_LONG).show();				 
		    			 } catch(IOException e) {
		    				 Toast.makeText(Qfactff.this,"傳送失敗", Toast.LENGTH_LONG).show(); 
		    			 }
		        	break;
		        }
		        case 7:{ //廠商追加統計列印
/*		        	
		        	 "SELECT  qitems.[SUPPLY], qfact.[FACTNAME],qitems.[GOODSNO], qitems.[GOODSNAME], qitems.[P0]  ,sum( qitems.[UNIT10]) as INCOME,sum( qitems.[UNIT30]) as SALED, sum( qitems.[UNIT10])-sum( qitems.[UNIT30]) as STOCK, round(sum( qitems.[UNIT30]) / sum( qitems.[UNIT10])*100) as PARSON FROM qitems join qfact on qitems.[SUPPLY]=qfact.[FACTNO]"
"WHERE qitems.GOODSNO in(select DISTINCT GOODSNO from qitems where FORMDATE>'2015-01-01' ) group by  qitems.[SUPPLY], qitems.[GOODSNO], qitems.[GOODSNAME], qitems.[P0]      having sum( qitems.[UNIT10])-sum( qitems.[UNIT30])<10 and sum( qitems.[UNIT30])>10 and sum( qitems.[UNIT10])>10 and sum( qitems.[UNIT30]) / sum( qitems.[UNIT10])>=0.8 limit 100" 
*/ 
		          break;
		        }
		        
		        case 9:{ //撥打電話
					if (edmobil.length() > 0) {
						intent.setAction(intent.ACTION_VIEW);
						intent.setData(Uri.parse("tel:" + edmobil));
						startActivity(intent);
					}
		        	
		          break;
		        }
		        case 10:{//列印名條
		        	mBuf.delete(0, mBuf.toString().length());
					sPrintB.delete(0, sPrintB.toString().length());
					
						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,"+edno+"-"+edname+" 收"+sepa);
						sPrintB.append("AZ,424,96,2,2,0,1,"+edaddress+"-"+edmobil+" 收"+sepa);
						sPrintB.append("AZ,96,266,3,3,0,1,"+Utilis.getIni(Qfactff.this, "USER","COMPANY", 1)+"/"+Utilis.getIni(Qfactff.this, "USER","COMPANY", 4)+"寄"+sepa);
						sPrintB.append("E"+sepa);
					
					if (sPrintB.toString().length()>0){
						String address=null;
						int port=0;
						   address = Utilis.getIni(Qfactff.this, "SYS","BAR_IP", 4);// 連線的ip
						   port =Utilis.toInt(Utilis.getIni(Qfactff.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(Qfactff.this, "已成功傳送名條到條碼機!!", Toast.LENGTH_LONG).show();
									 } catch (UnknownHostException e) {
									 } catch (SocketException e) {
									 } catch(IOException e) {
									 }
					}
		        	
		        	
		        }
		      }
		    }
		  };
		  
		  
	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 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 qfact");
		mySqlBuf.append(" where FACTNO  like '%" + edSearch01.getText().toString().trim() + "%'" );
		if (mCountryId!=0) mySqlBuf.append(" and COUNTRY='"+mCountryId+"'" );
		mySqlBuf.append(" and STATE<>'2' order by FACTNO LIMIT 300" );
 		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 qfact");
				mySqlBuf.append(" where  FACTNAME  like '%" + edSearch01.getText().toString().trim() + "%'" );
				if (mCountryId!=0) mySqlBuf.append(" and COUNTRY='"+mCountryId+"'" );
				mySqlBuf.append(" and STATE<>'2' order by FACTNO LIMIT 300" );
		 		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 qfact");
				mySqlBuf.append(" where MOBIL  like '%" + edSearch01.getText().toString().trim() + "%'" );
				if (mCountryId!=0) mySqlBuf.append(" and COUNTRY='"+mCountryId+"'" );
				mySqlBuf.append(" and STATE<>'2' order by FACTNO LIMIT 300" );
		 		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 qfact");
				mySqlBuf.append(" where EMAIL  like '%" + edSearch01.getText().toString().trim() + "%'" );
				if (mCountryId!=0) mySqlBuf.append(" and COUNTRY='"+mCountryId+"'" );
				mySqlBuf.append(" and STATE<>'2' order by FACTNO LIMIT 300" );
		 		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 qfact");
				mySqlBuf.append(" where PS  like '%" + edSearch01.getText().toString().trim() + "%'" );
				if (mCountryId!=0) mySqlBuf.append(" and COUNTRY='"+mCountryId+"'" );
				mySqlBuf.append(" and STATE<>'2' order by FACTNO LIMIT 300" );
		 		cs = db.rawQuery(mySqlBuf.toString(), null);
				
				if (cs.getCount() > 0) {
					catched = 1;
				}
			}
			

			records=cs.getCount();
			
			if (catched == 1) {
				if (nMode==EMode.GET && records==1) {//找到而且馬上返回
		        	Intent intentS = new Intent();
		        	cs.moveToFirst();
		        	intentS.putExtra("qfact_key",cs.getString(cs.getColumnIndex("FACTNO")));
		        	Qfactff.this.setResult(RESULT_OK,intentS);
		        	db.close();
		        	cs.close();
		        	finish();
				}else{
				updateListView(this,cs);
				}
			}
			db.close();
			cs.close();
		}
	}
	
//事先整理出產地國別	
	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();
	}
	
	 @SuppressWarnings("unused")
	private void updateListView(Context context,Cursor cs)
	  {
	    /* SELECT f1[] FROM tables[0] */
	
	if (cs.getCount()>0){
		//將改為不要陣列 而用LIST取代
		int record=0;
		main_list = new ArrayList<HashMap<String, Object>>();		
		
		while (cs.moveToNext()) {

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("tv_no",cs.getString(cs.getColumnIndex("FACTNO")));
            map.put("tv_name",cs.getString(cs.getColumnIndex("FACTNAME")));
            map.put("tv_email",cs.getString(cs.getColumnIndex("ADDRESS")));
            
            map.put("tv_bankname",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);}
	}
	    
	 @Override
		protected void onResume() {
			// TODO Auto-generated method stub
			super.onResume();

			DBCloud.aa0_aa1_auto_qfact(this);
			
		}

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

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

		}
	
	    
}
