package com.cwbuyer.main;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
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 android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.cwbuyer.adapter.DateAdapter;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.KeySet;
import com.cwbuyer.lib.AppUtil;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DateUtil;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.PrefKey;
import com.cwbuyer.lib.QMacc;
import com.cwbuyer.lib.QRep_05;
import com.cwbuyer.lib.SQLite;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.main.APos.PItemKind;
import com.pwbuyer.main.R;

@SuppressLint("HandlerLeak")
public class MainMenu extends Activity {
	
	DateAdapter mAdapter = null;
	String mac =null;

	protected static final int REFRESH_DATA = 0x00000001;
	String uriAPI=null;
	private String uriAPIpath ="" ;
    String DATABASE_PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
	
	public ProgressDialog myDialog = null;
	String mCloud="";
	public int CWVersion=22;
	private final int RESULT_PASSWORD=1001;
	
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == RESULT_PASSWORD) {
			if (resultCode == RESULT_OK) {
				
			}else{
				finish();
			}
		}
    }
    
    public void onDestroy(){
    	super.onDestroy();
    }
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        setTitle(getString(R.string.app_name_version));
        
        ((LinearLayout)findViewById(R.id.layout_insert)).setOnClickListener(new MainClick());
        ((LinearLayout)findViewById(R.id.layout_psetting)).setOnClickListener(new MainClick());
        ((LinearLayout)findViewById(R.id.layout_csetting)).setOnClickListener(new MainClick());
        ((LinearLayout)findViewById(R.id.layout_manage)).setOnClickListener(new MainClick());
        ((LinearLayout)findViewById(R.id.layout_transfer)).setOnClickListener(new MainClick());
        ((LinearLayout)findViewById(R.id.layout_maintain)).setOnClickListener(new MainClick());
        
        ((Button)findViewById(R.id.btn_tool)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_setting)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_account)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_macc)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_clockx)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());
//        ((LinearLayout)findViewById(R.id.body)).setBackgroundDrawable(null);
        WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        mac = wm.getConnectionInfo().getMacAddress();
        	//檢查是否首次啟用
        	//如果INI.SDB首次啟用
        String DB_CHECK = DATABASE_PATH+File.separator+"CWBuyer";
        File myDataPath = new File(DB_CHECK);
        
        if (myDataPath.exists()){
        	if (!Utilis.getIni(this, "SYS", "IMEI", 1).equalsIgnoreCase("9999999999")){//非首次的登入
    			String imei [] =Utilis.getIni(this, "SYS", "IMEI", 9).split("!&!");
        		if(Utilis.getStringSet(this, PrefKey.BEGIN_SSGN,"").equalsIgnoreCase(PrefKey.BEGIN_SIGN)){  //首次安裝後的初步啟用
        			//應將INI中的資料存回MEMBER中
    		    	Utilis.setStringSet(MainMenu.this, PrefKey.LIMIT_TIME_FIRST,imei[4]); 
    		    	Utilis.setStringSet(MainMenu.this, PrefKey.LIMIT_TIME_LAST,imei[5]);
    		    	Utilis.setStringSet(MainMenu.this, PrefKey.BEGIN_MAC,imei[2]);
    		    	Utilis.putIni(this, "SYS", "IMEI", mac, 4);  
    		    	Utilis.setStringSet(MainMenu.this, PrefKey.BEGIN_SSGN,imei[7]);
				    Utilis.setStringSet(MainMenu.this, PrefKey.LIMIT_TIME_ZONA,imei[0]);		    
				    Utilis.setStringSet(MainMenu.this, PrefKey.LIMIT_TIME_ZONB, imei[1]);
				    Utilis.setStringSet(MainMenu.this, PrefKey.TIME_CHECK_DAY, imei[7]);
				    Utilis.setIntSet(MainMenu.this, PrefKey.PAY_STATE, 1);
        		}else{
        			//正常啟動通過的地方
        			//不過應該 檢查 DB & PREF 內容是否一致 可以防範什麼
        			if(!Utilis.getStringSet(MainMenu.this, PrefKey.LIMIT_TIME_LAST,DateUtil.getCurrentDate()).equalsIgnoreCase(imei[5]))
        			{
        				Toast.makeText(MainMenu.this, "系統已置換了,不同的資料庫,可能涉及侵權問題!!", Toast.LENGTH_SHORT).show();        				
        			}
        			Utilis.reCNT(this);
       			}
        	}else{ //首次登入這台手機的唯一序號
        		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.LIMIT_TIME_FIRST, DateUtil.getCurrentDate()), 5);
        		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.LIMIT_TIME_LAST, DateUtil.getCurrentDate()), 6);
        		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.LIMIT_TIME_ZONA, DateUtil.getCurrentDate()), 1);
        		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.LIMIT_TIME_ZONB, DateUtil.getCurrentDate()), 2);
        		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.BEGIN_MAC, DateUtil.getCurrentDate()), 3);
        		Utilis.putIni(this, "SYS", "IMEI", mac, 4);
        		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.TIME_CHECK_DAY, DateUtil.getCurrentDate()), 8);
        	}
        	
        	mAdapter = new DateAdapter(this);
		        ListView list = (ListView)findViewById(R.id.list_date);
		        list.setAdapter(mAdapter);
		        list.setOnItemClickListener(new OnItemClickListener(){
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
							long arg3) {
						// TODO Auto-generated method stub
						Utilis.runVibrate(MainMenu.this);
						Intent intent = new Intent();
						if((!Utilis.getIni(MainMenu.this,"SYS","DEPT",5).equalsIgnoreCase("0") || pos == 0 )){
							intent.putExtra(KeySet.KEY_SEARCH, KeySet.SearchMode.DAY);
						}else if(pos == 1){
							intent.putExtra(KeySet.KEY_SEARCH, KeySet.SearchMode.WEEK);
						}else {
							intent.putExtra(KeySet.KEY_SEARCH, KeySet.SearchMode.MONTH);
						}
						//@@@未來發展出 QPOSFF銷售統計 或 MANAGEITEMh採購統計
						//總公司才有的StockManage時,需指定"search_dept"一定要指定門市
						intent.putExtra("search_dept","SOS");  //空白表示全部顯示,一如原始設計
						if (!Utilis.getIni(MainMenu.this,"SYS","DEPT",1).equalsIgnoreCase(Utilis.getIni(MainMenu.this,"SYS","DEPT",6))){
							intent.putExtra("QPosff",PItemKind.TR31);//門市銷貨
						}else{
							intent.putExtra("QPosff",PItemKind.TR30);//總店銷貨
						}
						intent.setClass(MainMenu.this, QPosff.class);
						MainMenu.this.startActivity(intent);
					}
		        });
		        

	        //清理import/20123/過度檔
	        File dnPath = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"CWBuyer/IMPORT/20123");
	        if (!dnPath.exists()){
	        	dnPath.mkdirs();  //若不存在 則建立之
	        }else{
	        	File file[] = dnPath.listFiles();
				for (int i=0; i < file.length; i++)
				{
					if (file[i].getName().indexOf("buyer")>=0){
						Utilis.DeleteFile(dnPath+File.separator+file[i].getName());
					}	
				}
	        }
        	        
	       initPref();
	       
	       initDB();
	        
	
	    	// 2012/06/08
	    	String limitLast = Utilis.getStringSet(MainMenu.this, PrefKey.LIMIT_TIME_LAST, DateUtil.getCurrentDate());
	    	
	    	if(Utilis.getIntSet(this,PrefKey.PAY_STATE, 0) == 0){
				setTitle(getString(R.string.app_name_version) + "  試用期限:" + limitLast );
			}
	    	// Current  06/08 < 2012/03/08
	    	
	    	if(DateUtil.compareTime(limitLast, DateUtil.getCurrentDate()) <= 0	){
	    		if(Utilis.getIntSet(this, PrefKey.PAY_STATE, 0) == 0){
	    			setTitle(getString(R.string.app_name_version) + " 試用已到期");
	    		}
	    	}
	    	
	    		String pass = Utilis.getStringSet(this, PrefKey.PASSWORD, "");
	            if(pass != null && pass.length() > 0){
	            	// 啟動密碼保護
	            	Intent intent = new Intent();
	            	intent.setClass(this, APassword.class);
					MainMenu.this.startActivityForResult(intent,RESULT_PASSWORD);
	            }
	    		if (Utilis.getIni(this,"SYS","DEPT",5).equalsIgnoreCase("0")){
	    			((ListView)findViewById(R.id.list_date)).setVisibility(View.VISIBLE);
	    			mAdapter.refresh(this);
	    		}else
	    			((ListView)findViewById(R.id.list_date)).setVisibility(View.INVISIBLE);
	    		
        }
       }
    
    public void onResume(){
    	super.onResume();
        try {
        	
            String DB_CHECK = DATABASE_PATH+File.separator+"CWBuyer";
            File myDataPath = new File(DB_CHECK);
            
            if (!myDataPath.exists()){

     			DialogUtilis.showDialog(MainMenu.this, "警告!!系統因找不到資料庫將初始化", -1,
    				new String[] { "全新的安裝(警告:原有資料將全部遺失)", "可能太快開啟了銷售王,結束後,稍後再進場"}, new IDialog() {
    						@Override
    					public void onDialogFinish(int pos, String choice) {
    						switch (pos) {
    						case 0:
    							initZipPref(); //解壓縮(因為cwbuyer不存在)為第一優先
    							break;
    						case 1:
    							finish();
    							break;
    					}	
    				}
    			});
             	
            	//可能系統誤判為 資料夾 不存在 而引發嗎?
            	//
    		
            }else {
        	
            	if (Utilis.haveInternet(this)){  //有網路的狀態
            		if ((Utilis.toInt(Utilis.getIni(this, "SYS", "IMEI", 7)) % 66)==0){
            			DBCloud.user_update(this);
            			Utilis.reCNT(this);
	        			String DBZipPath=Utilis.copyDBtoSDCard(MainMenu.this);
	    				if (DBZipPath.length()>0){
		    			    Uri U=Uri.parse("file://"+DBZipPath);  //重要的範例
	    					Intent send = new Intent(Intent.ACTION_SEND);
	    					send.setType("image/jpeg");
	    				    String uriText = "系統將執行例行性的備份,請務必妥當保存";
	    				    send.putExtra(Intent.ACTION_SENDTO,uriText);
	    				    send.putExtra(Intent.EXTRA_STREAM,U);
	    				    startActivity(Intent.createChooser(send, uriText));
	    				}  
            		}
            		int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
					if (of_line!=0){
						String [] imp =Utilis.getIni(this, "SYS", "IMPORT", 9).split("!&!");
						uriAPIpath = "http://"+imp[0]+"/"+imp[1];
						uriAPI = uriAPIpath+"/mupdate_yn.php";
						mupdate_qc(imp[1],"0","130101");  //可以傳回server_Q1~Q7的update時間130801165959
					} 
				}
		    		if (Utilis.getIni(this,"SYS","DEPT",5).equalsIgnoreCase("0")){
		    			((ListView)findViewById(R.id.list_date)).setVisibility(View.VISIBLE);
		    			mAdapter.refresh(this);
		    		}else
		    			((ListView)findViewById(R.id.list_date)).setVisibility(View.INVISIBLE);
		    		
            }	    	
           } catch (Exception e) {
               Log.i("DB", "DB_DIR_Exception: " + e.toString());
           }
    }
    
    private void initDB(){
    	String mDBPath = Utilis.getIni(this, "SYS", "YEAR", 4);
    	SQLite db = new SQLite(this,mDBPath);
    	db.close();
		SQLiteDatabase dbm = Utilis.getDB(MainMenu.this);
        setTitle(getString(R.string.app_name_version)+"DBV."+dbm.getVersion());
        CWVersion=dbm.getVersion();
		dbm.close();
    	db = null;
    }
    
    ProgressDialog mProgress = null;

	private int mDatabaseChoice = 0;
	//第一次就寫入初始化
    private void initZipPref(){
    	
    	
			DialogUtilis.showDialog(MainMenu.this, "銷售王資料庫將初始化", -1,
			new String[] { "放棄安裝(若原有資料將保留)","[確定]銷售王將重新安裝(清除原有的資料)"}, new IDialog() {
					@Override
				public void onDialogFinish(int pos, String choice) {
					switch (pos) {
					case 0:
						finish();
						break;
					case 1:
				    	if((Utilis.getBooleanSet(MainMenu.this, "first_zip_init_preference", false) == false) ){
				    		Utilis.setBooleanSet(MainMenu.this, "first_zip_init_preference",true);
				    		final Handler handler = new Handler(){
								public void handleMessage(Message msg)
								{
									if(msg.what == 0){
									}else if(msg.what == 1){
										mProgress.dismiss();
									}
								}
						    };
						    
						    mProgress = new ProgressDialog(MainMenu.this);
							mProgress.setCancelable(false);
							mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
							mProgress.setMessage("第一次需載入資料,請稍候...");
							mProgress.show();
							
							handler.postDelayed(new Runnable(){
								public void run(){
									new Thread(){
										public void run(){
										    initPic();							
//											
										    handler.sendEmptyMessage(1);
										}
									}.start();
								}
							}, 2000);
				    	}
						break;
				}	
			}
		});
     	

    	
    }

    
    /*  洗滌圖片加到 sdcard  上 */
    @SuppressWarnings("unused")
	private void initPic() {
      String ZIP_FILENAME = "cwbuyer_img_wash";

      try {
        File myDataPath = new File(DATABASE_PATH);
        
        if (!myDataPath.exists()) {
          myDataPath.mkdirs();
        }
        
          InputStream is = getResources().openRawResource(R.raw.cwbuyer_img_wash);
          FileOutputStream fos = new FileOutputStream(myDataPath + "/" + ZIP_FILENAME);
          byte[] buffer = new byte[8192];
          int count = 0;
          while ((count = is.read(buffer)) > 0) {
            fos.write(buffer, 0, count);
          }
          fos.close();
          is.close();
          Utilis.Unzip2(myDataPath + "/" + ZIP_FILENAME, DATABASE_PATH );
          Utilis.DeleteFile(myDataPath + "/" + ZIP_FILENAME);
          
          int isError=AppUtil.initPref_err(MainMenu.this,mac,DateUtil.getCurrentDate(),1);
	  		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.LIMIT_TIME_FIRST, DateUtil.getCurrentDate()), 5);
	  		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.LIMIT_TIME_LAST, DateUtil.getCurrentDate()), 6);
	  		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.LIMIT_TIME_ZONA, DateUtil.getCurrentDate()), 1);
	  		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.LIMIT_TIME_ZONB, DateUtil.getCurrentDate()), 2);
	  		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.BEGIN_MAC, DateUtil.getCurrentDate()), 3);
	  		Utilis.putIni(this, "SYS", "IMEI", mac, 4);
	  		Utilis.putIni(this, "SYS", "IMEI", Utilis.getStringSet(MainMenu.this, PrefKey.TIME_CHECK_DAY, DateUtil.getCurrentDate()), 8);
          
          initDB();
      } catch (Exception e) {
        Log.i("DB_EXPLORE", "DB_DIR_Exception: " + e.toString());
      }
    }
    
  //如果第一次就寫入初始化
    private void initPref(){
    	
        int isError=AppUtil.initPref_err(MainMenu.this,mac,DateUtil.getCurrentDate(),0);
       	if (isError>0){
    	String ErrorMsg[]={"",
    			getString(R.string.msg_err_1day)+"(1)",
    			getString(R.string.msg_err_1day)+"(2)",
    			"使用期限不合法(3),請洽CW:0933811753客服",
    			"使用期限不合法(4),請洽CW:0933811753客服",
    			"CWBuyer(5)提醒您!!合約即將到期,如果滿意!!請按下方[設定]註冊正版軟體!!並拍註冊前碼,PO上 LINE群組,待審無誤後,即可註冊後續用",
    			"CWBuyer(6)提醒您!!合約已到期,如果滿意!!請按下方[設定]註冊正版軟體!!並拍註冊前碼,PO上 LINE群組,待審無誤後,即可註冊後續用",
    			"CWBuyer(7)提醒您!!合約已到期,如果滿意!!請按下方[設定]註冊正版軟體!!並拍註冊前碼,PO上 LINE群組,待審無誤後,即可註冊後續用",
    			"CWBuyer(8)提醒您!!合約已到期,如果滿意!!請按下方[設定]註冊正版軟體!!並拍註冊前碼,PO上 LINE群組,待審無誤後,即可註冊後續用"
    			};
		    mProgress = new ProgressDialog(this);
			mProgress.setCancelable(true);
			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgress.setMessage(ErrorMsg[isError]+"ERR="+isError);			
			mProgress.show();
       	}
       	
    }

	class MainClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			Utilis.runVibrate(MainMenu.this);
			int id = v.getId();
			switch (id) {
				case R.id.btn_setting:
				{
					Intent  intent = new Intent();
					intent.setClass(MainMenu.this, Setup.class);
					startActivity(intent);
					break;
				}
				case R.id.btn_account:
				{
					Intent  intent = new Intent();
					intent.setClass(MainMenu.this, ManageAccount.class);
					startActivity(intent);
					break;
				}
				case R.id.btn_macc:  //收支
				{
					Intent intent = new Intent();
					intent.setClass(MainMenu.this, QMacc.class);
					intent.putExtra("search_mode", KeySet.SearchMode.DAY);		
					intent.putExtra("search_group", QMacc.GroupMode.TOP1);	
					startActivity(intent);
					break;
				}	
				
				case R.id.btn_clockx:
				{
					Tclock();
					break;
				}
				case R.id.btn_exit:
				{
					new AlertDialog.Builder(MainMenu.this).setTitle(getString(R.string.str_msg)).setMessage(getString(R.string.msg_exit)).setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface dialog, int which) {
			              finish();
			            }
			          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface dialog, int which) {
			            }
			          }).show();
					break;
				}
				case R.id.layout_insert: // 銷售結帳
				{
					
					Intent  intent = new Intent();					
					intent.putExtra("search_mode",KeySet.SearchMode.ACTION);
					//總公司才有的StockManage時,需指定"search_dept"一定要指定門市
					intent.putExtra("search_dept","SOS");  //空白表示全部顯示,一如原始設計

					if (!Utilis.getIni(MainMenu.this,"SYS","DEPT",1).equalsIgnoreCase(Utilis.getIni(MainMenu.this,"SYS","DEPT",6))){
						intent.putExtra("QPosff",PItemKind.TR31);//門市銷貨
					}else {
						intent.putExtra("QPosff",PItemKind.TR30);//總店銷貨
					}
					intent.setClass(MainMenu.this, QPosff.class);
					startActivity(intent);
					
					break;
				}
				case R.id.layout_psetting: // Param==>統計分析
				{
					Intent  intent = new Intent();
					intent.setClass(MainMenu.this, AnslyManage.class);
					startActivity(intent);

					break;
				}
				case R.id.layout_csetting: // 代碼設定==>庫存管理
				{
					Intent  intent = new Intent();
					intent.setClass(MainMenu.this, StockManage.class);
					startActivity(intent);
					break;
				}
				case R.id.layout_manage: // 資料管理
				{
					Intent  intent = new Intent();
					intent.setClass(MainMenu.this, DataManage.class);
					startActivity(intent);
					break;
				}
				case R.id.layout_transfer: // 傳送接收
				{
					Intent  intent = new Intent();
					intent.setClass(MainMenu.this, TransManage.class);
					startActivity(intent);
					break;
				}
				case R.id.layout_maintain: // 系統維護
				{
					Intent  intent = new Intent();
					intent.setClass(MainMenu.this, MainTainManage.class);
					startActivity(intent);
					break;
				}
				case R.id.btn_tool:
				{
					Utilis.runVibrate(MainMenu.this);

					AlertDialog.Builder sortDlg = new AlertDialog.Builder(MainMenu.this);

			        sortDlg.setTitle(getString(R.string.dlg_backup_tool))
			        .setSingleChoiceItems(R.array.select_tool, mDatabaseChoice, new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface dialog, int item) {
			            	mDatabaseChoice = item;
			            }
			        })
			        .setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface dialog, int which) {
			            	switch(mDatabaseChoice){
				            	case 0: // 備份主要資料庫!
				            	{
				        			String DBZipPath=Utilis.copyDBtoSDCard(MainMenu.this);
				    				if (DBZipPath.length()>0){
					    			    Uri U=Uri.parse("file://"+DBZipPath);  //重要的範例
				    					Intent send = new Intent(Intent.ACTION_SEND);
				    					send.setType("image/jpeg");
				    				    String 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));
				    				}				    	    		    
				            		break;
				            	}
				            	
				            	case 1://
				            	{
				          		  try{
				        		      Intent goToMarket = null;
				        		      goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.cwbuyer.net/3G006_20123/index.php"));
				        		      startActivity(goToMarket);
				        		  }catch(Exception e){
				        			  e.printStackTrace();
				        		  }
				            		break;
				            	}
				            	case 2://TRY AGAIN
				            	{
				            		gotoMT();				            		
			        		    	break;
				            	}
				            	case 3://Download spk
				            	{
									final String serverFile =PrefKey.CWBUYER_FTPAPKNAME;
									String  AutoFile=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(MainMenu.this, "SYS", "YEAR",7)+File.separator+serverFile;
									final File localFile = new File(AutoFile);
						        	boolean success=false;
									try {
										success=DBCloud.ftpDownloadAndSaveFile(MainMenu.this,PrefKey.CWBUYER_WEB, 21,PrefKey.CWBUYER_FTPAPKUSER,PrefKey.CWBUYER_FTPAPKPSWD , serverFile, localFile);												
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}  
									finally{
										if (success== true){
											//成功下載
										}
									}
				            		/*
					    			SQLiteDatabase db = Utilis.getDB(MainMenu.this);
					    			db.setVersion(22);
			        				Toast.makeText(MainMenu.this, "目前的資料庫版本是 : "+db.getVersion(), Toast.LENGTH_SHORT).show();        				
					    			db.close();
					    			*/
				            		break;
				            	}
				            	case 4:
				            	{
				            		break;
				            	}
			            	}
			            }
			          })
			        .setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface dialog, int which) {
			            }
			          }).show();
					
				
					break;
				}
				default:
					break;
			}
		}
}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
          new AlertDialog.Builder(MainMenu.this).setTitle(getString(R.string.str_msg)).setMessage(getString(R.string.msg_exit)).setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              finish();
            }
          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
          }).show();
          return true;
        } else {
          return super.onKeyDown(keyCode, event);
        }
    }
	
	
	private void gotoMT(){
		LayoutInflater factory = LayoutInflater.from(MainMenu.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(MainMenu.this).setTitle("工程師系統維護").setMessage("請輸入密碼及重新註冊").setView(v1).setPositiveButton("OK", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
            	  if (edtReg.getText().toString().equalsIgnoreCase(DateUtil.getSystemTime().substring(2,11)+"999") && edtWho.getText().toString().indexOf("/")>0){
            	        @SuppressWarnings("unused")
						int isError=AppUtil.initPref_err(MainMenu.this,mac,edtWho.getText().toString(),1);
            	  }              
              }
		  }).setCancelable(false).show();
	}

	
	int Stat=-1;
	String aEmpID="";
	String aEmpName="";
	String theD="";
	String Ttime="";
	String TSec="";
	int work;
	String SQL="";	
	String goD="12:00";//個人上班時間值班表取
	String outD="24:00";//下班
	int sala=120;
	int radio=0;
	String [] args={"",""};
	String theT="";
	int Wday=1;
	StringBuffer bfstr = new StringBuffer();
	StringBuffer bfstrF = new StringBuffer();
	
	//String [] wekD={"日","一","二","三","四","五","六"};
	//String defD="正職日班";

	private void Tclock(){
		
 		LayoutInflater factory = LayoutInflater.from(MainMenu.this);
		final View v1 = factory.inflate(R.layout.fclock, null);
		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int Wwidth = dm.widthPixels;
        int Wheight = dm.heightPixels;
		Stat=-1;
		  theD=DateUtil.getCurrentDate();  //2012-10-22
			Ttime=DateUtil.getSystemTime().substring(8, 10);  //取得目前幾點
			TSec=DateUtil.getSystemTime().substring(10, 12);  //取得目前幾分
				if (Utilis.toInt(Ttime)<=5)  theD = DateUtil.addDate(theD, -1);
				theD = theD.replace("/", "-");
				if (Utilis.getIni(this,"SYS", "DEV", 7)!=null  && Utilis.getIni(this,"SYS", "DEV", 7).length()>0) goD=Utilis.getIni(this,"SYS", "DEV", 7);
				if (Utilis.getIni(this,"SYS", "DEV", 8)!=null  && Utilis.getIni(this,"SYS", "DEV", 8).length()>0) outD=Utilis.getIni(this,"SYS", "DEV", 8);
		
		((LinearLayout) v1.findViewById(R.id.layout_top)).getLayoutParams().height=(int )Wheight/6;
		((TextView) v1.findViewById(R.id.text_vdate)).setText(theD);
		final EditText editText = (EditText) v1.findViewById(R.id.text_who);
		if (Utilis.toInt(Ttime)>=15) {
			((RadioButton) v1.findViewById(R.id.radio1)).setChecked(true);
		}else{
			((RadioButton) v1.findViewById(R.id.radio0)).setChecked(true);
		}

		editText.setOnEditorActionListener(new OnEditorActionListener() {  
			@Override  
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
    			//當輸入員代號(ENTER)後,須檢查是否存在
				if (editText.getText().toString().length()>0){
					String Chk=editText.getText().toString().trim();
					if (Chk.indexOf("/")==0) Chk=Chk.substring(1);
	    			SQL="select distinct CUSTNO,CUSTNAME,MSN from qcust where CUSTNO='"+Chk+"' and TR='40' limit 1";
					
					if  (Utilis.haveInternet(MainMenu.this) && Utilis.toInt(Utilis.getIni(MainMenu.this, "SYS", "IMPORT", 3))==1){
						bfstr.delete(0, bfstr.toString().length());
						bfstrF.delete(0, bfstrF.toString().length());
						bfstr.append(Utilis.getIni(MainMenu.this, "SYS", "IMPORT", 2)).append(";");
						bfstrF.append("UID").append(";");
						bfstr.append(SQL);
						bfstrF.append("SQLADD");
						work=0;cloudClock( bfstr, bfstrF);
					}
		    			SQLiteDatabase db = Utilis.getDB(MainMenu.this);
		    			Cursor cs=db.rawQuery(SQL, null);
		    			if (cs.getCount()>0){
		    				cs.moveToFirst();
		    				((TextView) v1.findViewById(R.id.text_whoname)).setText(cs.getString(1));
		    				aEmpID=cs.getString(0);
		    				aEmpName=cs.getString(1);
		    				//Toast.makeText(MainMenu.this, "Who ="+cs.getString(0)+"/"+cs.getString(1), Toast.LENGTH_SHORT).show();
		    				//正式打卡時,要
		    				if (cs.getInt(2)>=0 && cs.getInt(2)<=9)  Stat=cs.getInt(2); else Stat=0;
		    			}else{
		    				Stat=-1;	aEmpID="";	aEmpName="";
		    			}
		    			db.close();
		    			cs.close();
		    			
	    			if (Stat<0)	Toast.makeText(MainMenu.this, "查無此櫃員資料,無法打卡!!"+Chk+"___loca="+Chk.indexOf("/"), Toast.LENGTH_SHORT).show();
	    			
					((TextView) v1.findViewById(R.id.text_who)).setText(aEmpID);
					((TextView) v1.findViewById(R.id.text_whoname)).setText(aEmpName);					
					
   				 	if (((RadioButton) v1.findViewById(R.id.radio2)).isChecked() && Stat>=0){
   						Intent  intent = new Intent();					
   						intent.putExtra("WHO",aEmpID);
   						intent.putExtra("WHONAME",aEmpName);
   						intent.setClass(MainMenu.this, QRep_05.class);
   						startActivity(intent);
   				 		//showClockrep();
   				 	}
   				 	  
   				 	 
				}
    			return false;  
			}
		});
		  new AlertDialog.Builder(MainMenu.this).setTitle("[刷條碼][選上下班][按打卡]"+Wwidth+"_"+Wheight).setView(v1).setNeutralButton("打卡", new DialogInterface.OnClickListener() {
		      public void onClick(DialogInterface dialog, int which) {
		    	  //按了打卡後,應檢察是否有該員,並進入資料庫檢查是否有重複打卡
		    	  if (Stat>=0){//表示有此號人物
		    		  Calendar calendar = Calendar.getInstance();
		    		  //指定日期,找出是星期幾
		    		  calendar.set(Calendar.YEAR, Integer.valueOf(theD.substring(0, 4)));
		    		  calendar.set(Calendar.MONTH, Integer.valueOf(theD.substring(5, 7))-1);
		    		  calendar.set(Calendar.DATE, Integer.valueOf(theD.substring(8, 10)));
		    		  //未來在報表時,很有用
		    		  Wday = calendar.get(Calendar.DAY_OF_WEEK);
		    		  Ttime=DateUtil.getSystemTime().substring(8, 10);  //取得目前幾點
		    		  TSec=DateUtil.getSystemTime().substring(10, 12);  //取得目前幾分

		    		  //取得執勤表當日的上下班的時刻表
		    		  SQL="select * from qemp where QEMPID='"+Stat+"' and MOBIL='"+Wday+"' and STATE='R'";
		    		  if (((RadioButton) v1.findViewById(R.id.radio0)).isChecked())
		    			  radio=0;  else  if (((RadioButton) v1.findViewById(R.id.radio1)).isChecked())
		    				  radio=1; else radio=2;
		    		  
						if  (Utilis.haveInternet(MainMenu.this) && Utilis.toInt(Utilis.getIni(MainMenu.this, "SYS", "IMPORT", 3))==1){
							
							bfstr.delete(0, bfstr.toString().length());
							bfstrF.delete(0, bfstrF.toString().length());
							
							bfstr.append(Utilis.getIni(MainMenu.this, "SYS", "IMPORT", 2)).append(";");
							bfstrF.append("UID").append(";");
							bfstr.append(aEmpID).append(";");
							bfstrF.append("EMPID").append(";");
							bfstr.append(aEmpName).append(";");
							bfstrF.append("EMPNAME").append(";");
							bfstr.append(Utilis.getIni(MainMenu.this,"SYS","DEPT",1)).append(";");
							bfstrF.append("DEPTNO").append(";");
							bfstr.append(""+radio).append(";");
							bfstrF.append("RADIO").append(";");
							bfstr.append(theD).append(";");
							bfstrF.append("TDAY").append(";");
							bfstr.append(Ttime+":"+TSec).append(";");
							bfstrF.append("TTIME").append(";");
							bfstr.append(Wday).append(";");
							bfstrF.append("WDAY").append(";");
							bfstr.append(Stat).append(";");
							bfstrF.append("SATA").append(";");
							bfstr.append(DateUtil.getSystemTime().substring(3,14)).append(";");
							bfstrF.append("WHATIME").append(";");
							bfstr.append(SQL);
							bfstrF.append("SQLADD");
							work=1;cloudClock( bfstr, bfstrF);
						}
						//不但伺服器要存入 還要LOCAL端存入
				    		  SQLiteDatabase db = Utilis.getDB(MainMenu.this);
				    		  Cursor cs=db.rawQuery(SQL, null);
				    		  //1日2一3二......7六
				    		  //取得值勤表(STATE='R')的 正確班別週幾上下班時間,並存入
				    		  if (cs.getCount()>0){
				    			  cs.moveToFirst();
				    			  goD=cs.getString(cs.getColumnIndex("GMAIL"));
				    			  outD=cs.getString(cs.getColumnIndex("PS"));
				    			  sala=cs.getInt(cs.getColumnIndex("GPSLA"));
				    		  }
						
				    		  SQL="select * from qemp where QEMPID='"+aEmpID+"' and MOBIL='"+theD+"'";
				    		  cs=db.rawQuery(SQL, null);
							  ContentValues value = new ContentValues();
				    		  if (cs.getCount()>0){//有可能是第二階段的前置作業,已建立打卡基本資料
				    			  cs.moveToFirst();
				    			  theT=cs.getString(cs.getColumnIndex("EMAIL"));//上班時分
				    			  if (radio==0){
				    				  if (theT !=null && theT.length()>0){
					  	    				Toast.makeText(MainMenu.this, "已打過卡!!不可重複喔!!", Toast.LENGTH_SHORT).show();
				    				  }else{//可以打卡
				    					  value.put("MOBIL", theD);
				    					  value.put("EMAIL", Ttime+":"+TSec);//時:分
				    					  value.put("STATE", "0");
				    					  value.put("PIC", goD);
				    					  value.put("BIRTHDAY", outD);
				    					  value.put("PS", ""+Wday);
				    					  value.put("CREATEDATETIME", DateUtil.getSystemTime().substring(3,14));
				    					  args[0]=aEmpID;	args[1]=theD;
				    					  db.update("qhead", value, "QEMPID=? and MOBIL=? ", args);
				    					  
					  	    				Toast.makeText(MainMenu.this, "打卡日期:"+theD+"時間:"+Ttime+":"+TSec+" 成功!!", Toast.LENGTH_SHORT).show();
				    					  
				    				  }
				    			  }else{//檢查下班
				    				  theT=cs.getString(cs.getColumnIndex("GMAIL"));
				    				  if (theT !=null && theT.length()>0){
				  	    				Toast.makeText(MainMenu.this, "已打過卡!!不可重複喔!!", Toast.LENGTH_SHORT).show();
				    				  }else{//可以存入
				    					  value.put("MSN", theD);
				    					  value.put("GMAIL", Ttime+":"+TSec);//時:分
				    					  value.put("STATE", "1");
				    					  value.put("PIC", goD);
				    					  value.put("BIRTHDAY", outD);
				    					  value.put("PS", ""+Wday);
				    					  value.put("CREATEDATETIME", DateUtil.getSystemTime().substring(3,14));
				    					  args[0]=aEmpID;	args[1]=theD;
				    					  db.update("qemp", value, "QEMPID=? and MOBIL=? ", args);
				    					  
					  	    				Toast.makeText(MainMenu.this, "打卡日期:"+theD+"時間:"+Ttime+":"+TSec+" 成功!!", Toast.LENGTH_SHORT).show();
				    					  
				    				  }
				    			  }
				    		  }else{//從未存入資料 INSERT
		    					  if (radio==0)
		    						  value.put("EMAIL", Ttime+":"+TSec);//時:分
		    					  else
		    						  value.put("GMAIL", Ttime+":"+TSec);//時:分
		    					  
				    			  value.put("QEMPID", aEmpID);
		    					  value.put("QEMPNAME", aEmpName);
		    					  value.put("MOBIL", theD);
		    					  value.put("GPSLA", sala);
		    					  value.put("DEPTNO", Utilis.getIni(MainMenu.this,"SYS","DEPT",1));
		    					  value.put("STATE", ""+radio);
		    					  value.put("PIC", goD);
		    					  value.put("BIRTHDAY", outD);
		    					  value.put("ADDRESS", ""+Stat);
		    					  value.put("PS", ""+Wday);
		    					  value.put("CREATEDATETIME", DateUtil.getSystemTime().substring(3,14));
		    					  db.insert("qemp", null, value);
		  	    				Toast.makeText(MainMenu.this, "打卡日期:"+theD+"時間:"+Ttime+":"+TSec+" 成功!!", Toast.LENGTH_SHORT).show();
				    		  }
				    		  cs.close();
				    		  db.close();
						
		    	  }else{
	    				Toast.makeText(MainMenu.this, "打卡失敗!!"+editText.getText().toString().trim(), Toast.LENGTH_SHORT).show();
		    	  }
		      }
		    }).setNegativeButton("報表", new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int which) {
			    	 //放棄打卡
	   				 	if (((RadioButton) v1.findViewById(R.id.radio2)).isChecked()){
	 						Intent  intent = new Intent();					
	 						intent.putExtra("WHO",aEmpID);
	 						intent.putExtra("WHONAME",aEmpName);
	 						intent.setClass(MainMenu.this, QRep_05.class);
	 						startActivity(intent);
	   				 	}
			      }
		    })
		    .show();
	}
	
	private void cloudClock(StringBuffer bfstr,StringBuffer bfstrF){
		final String []fields=bfstr.toString().split(";");
		final String []fieldFs=bfstrF.toString().split(";");
	      myDialog = ProgressDialog.show(MainMenu.this,"資料處理中.....","請稍候.............",true);			  
		  
	      new Thread()
	      { 
	        public void run()
	        { 
	          try
	          {
	        	  String uriH="http://"+Utilis.getIni(MainMenu.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(MainMenu.this, "SYS", "IMPORT", 2)+File.separator;
	        	  switch (work){
        	  		case 0:
    					uriAPI=uriH+"qrepclock00.php";
        	  			break;
        	  		case 1:
        	  			uriAPI=uriH+"qrepclock01.php";
        	  			break;
	        	  }
					HttpPost httpRequest = new HttpPost(uriAPI);
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					for(int x=0;x<fields.length;x++){
						params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
					}
					try {
						httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
						HttpResponse httpResponse = new DefaultHttpClient()
								.execute(httpRequest);
						if (httpResponse.getStatusLine().getStatusCode() == 200)
						{
							String strResult = EntityUtils.toString(httpResponse	.getEntity());
							mHandlerQRC_00.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
						}
					} catch (Exception e)
					{
						e.printStackTrace();
					}
	          }
	          catch (Exception e)
	          {
	            e.printStackTrace();
	          }
	          finally
	          {
	            // 卸載所建立的myDialog物件。
	            myDialog.dismiss();
	          }
	        }
	      }.start(); 

	}
	
  	Handler mHandlerQRC_00 = new Handler()
	{//目的是 取得 櫃員打卡的 代號 名稱 MSN='0123456789'班別
		@Override
		public  void handleMessage(Message msg)
		{
			String Hresult=null;
			switch (msg.what)
			{
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
				if (Hresult != null ){
					//Log.i("DOWNLOAD_6_mHandler_QEMP_CLOCK__00===", ""+Hresult);
					switch (work){
						case 0:
							if (Hresult.indexOf("SSSS\r\n")>2){
									String Lines[] =Hresult.split(";");
									aEmpID=Lines[1];
									aEmpName=Lines[2];
									if (Lines[3] !=null && Lines[3].length()>0)
										if (Utilis.toInt(Lines[3])<=9) Stat=Utilis.toInt(Lines[3]); else Stat=0; else Stat=0;
							}else{
			    				Stat=-1;	aEmpID="";	aEmpName="";
							}
							break;
						case 1:
							String mssg=aEmpID+"/"+aEmpName;
							if (Hresult.indexOf("insert_success_0")>=0){
								mssg=mssg+"上班打卡成功!!";
							}else if (Hresult.indexOf("insert_success_1")>=0){
								mssg=mssg+"下班打卡成功!!";
							}else if (Hresult.indexOf("goD_is_update")>=0){
								mssg=mssg+"上班補打卡成功!!好像忘了上班打卡!!";
							}else if (Hresult.indexOf("outD_is_update")>=0){
								mssg=mssg+"下班打卡成功";
							}else if (Hresult.indexOf("goD_is_update_fail")>=0){
								mssg=mssg+"上班打卡失敗,請重新打卡!!";
							}else if (Hresult.indexOf("outD_is_update_fail")>=0){
								mssg=mssg+"下班打卡失敗,請重新打卡!!";
							}else if (Hresult.indexOf("goD_is_already")>=0){
								mssg=mssg+"上班已打卡,不可以重複打卡!!";
							}else if (Hresult.indexOf("outD_is_already")>=0){
								mssg=mssg+"下班已打卡,不可以重複打卡!!";
							}
							Toast.makeText(MainMenu.this, mssg, Toast.LENGTH_SHORT).show();
							break;
					}
				}
			}
		}
	};
	
	  private 	void mupdate_qc(String gUid,String Id,String UPD){
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
				bfstr.append(gUid).append(";");
				bfstrF.append("UID").append(";");
				bfstr.append(Id).append(";");
				bfstrF.append("ID").append(";");
				bfstr.append(UPD);
				bfstrF.append("LUPDATE");
			Thread t = new Thread(new DBCloud.sendPostRunnable(this,bfstr.toString(),bfstrF.toString(),uriAPI,1));
			t.start();
}

	
	
	/**
	 *  Menu 使用
	 */
}
