package com.cwbuyer.main;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import com.cwbuyer.format.DefaultData;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DBUtil;
import com.cwbuyer.lib.DateUtil;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.main.ManageAccount.AccountData;
import com.pwbuyer.main.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.speech.RecognizerIntent;
import android.text.InputFilter;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("unused")
public class QCust extends Activity {
	/** Called when the activity is first created. */
	
	//交易價別方式 千萬不可以在第一時間就以 getResources().getText(R.string.str.....)方式帶入
	private static int nPicDegree =0;
	private final String[] backout =Utilis.getIni(this,"SYS","BACKOUT",9).split("!&!");
	private  final String[] tradeStr =Utilis.getIni(this,"SYS","TRADENAME",9).split("!&!");
	final Calendar  cld = Calendar.getInstance();	
	private Spinner mySpinnerCountry;
	private int rotationInDegrees=0;
	private Spinner mySpinnerBank;
	private Spinner mySpinnerTrade;
	private ArrayAdapter<String> cnItem;
	private ArrayAdapter<String> bkItem;
	private ArrayAdapter<String> tradeItem;
	Bitmap bmp;
	Bitmap mBitmap=null;
	
	ImageView imageViewFlag;
	ImageButton mImage;
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR", 8);
	public interface QCustMode{
		int SEARCH =0;
		int ADD = 1;  //常態
		int EDIT= 2; 	//外部程式進來時,需帶著查詢的KEY值
	}

	ImageView OutPhoto = null;
	int defTrade=Utilis.toInt(backout[0]);
	//0.批發 1.零售
	String[] pKind=Utilis.getIni(this,"SYS","CKIND",9).split("!&!");
	int exit = 0; // 表示還不用離開
	int mMode=QCustMode.ADD;
	Button mButton2, mButton3, mButton4, mButton5, mButton6;
	//編輯欄位
	EditText edCustno, edCustname, eddiscount, edmobil, edlo, edemail,  edla,
			edmsn, edadd, edps,edbirthday;
	//系統日期時間 及欄位
	String edcreatedate=DateUtil.getCurrentDate(); 
	String edcreatetime=DateUtil.getSystemTime().substring(2,14);
	String eddeptno="";
	String edempid="";
	int aPart=0;//0總倉 1門市
	int bPart=0;//1批發會員指定門市 0會員通用(預設)原為第二資料庫備份 
	//編輯預設欄位
	int edCountry;
	String mKind="30";
	int nKind=0;
	String mCustno="";
	String tCustno="";
	String edgmail="";
	int edbankno=0;
	String edbankname="";
	String edstate="1"; // 資料屬性 0.已送雲端 1.未送雲端 
	String edpic=""; //該會員圖片檔名(含全路徑)記憶區
	String edc1="1"; String edc2="0";String edc3="0";  //相簿三種清單
	String edm1="1"; String edm2="0";String edm3="0"; //EMAIL三種清單
	String eds1="1"; String eds2="0";String eds3="0"; //簡訊三種清單
	
	int modify=0;
	// Table資料表 這個陣列&dbHelper 所定義的陣列 各自宣告,只是結構一致 由此傳遞過去 續用的概念

	private ArrayList<Integer> mCountryIdList = new ArrayList<Integer>();	
	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<String> mCountryIcon = new ArrayList<String>();
	private LinkedList<AccountData> mAccountList = null;
	private String[] mAccount;
	private int[] mAccountid;

	private DefaultData mDefaultData = null; // 採購參數
	
	//照片  相本 處理段
    public static final int NONE = 0;  
    public static final int PHOTOHRAPH = 1009;// 拍照  
    public static final int PHOTOZOOM = 2; // 缩放  
    public static final int PHOTORESOULT = 3;// 结果  
    public static final String IMAGE_UNSPECIFIED = "image/*";
    public static final int VOICE_RECOGNITION_REQUEST_CODE = 0x1008;    
	Uri mImageCaptureUri = null;	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.custmain);
		
		InputFilter[] FilterArray10 = new InputFilter[1];
    	FilterArray10[0] = new InputFilter.LengthFilter(10);
		InputFilter[] FilterArray3 = new InputFilter[1];
    	FilterArray3[0] = new InputFilter.LengthFilter(3);

    	
		nPicDegree =Utilis.toInt(backout[7]); // 拍照鏡頭角度		
		mMode=getIntent().getIntExtra("qcust_mode",QCustMode.ADD);  //1新增 2編輯 0純查詢  						
		nKind=getIntent().getIntExtra("qcust_qkind",10);//TR=10廠商20門市30會員40櫃員
		mCustno=getIntent().getStringExtra("qcust_key");//edNo
		eddeptno=getIntent().getStringExtra("qcust_deptno");//DEPTNO

		tCustno=mCustno;
		mKind=""+nKind;
		//eddeptno=Utilis.getIni(this,"SYS","DEPT",1);
		edempid=Utilis.getIni(this,"INIH","EMPID",nKind/10);
		if (!Utilis.getIni(this,"SYS","DEPT",1).equalsIgnoreCase(Utilis.getIni(this,"SYS","DEPT",6)))
			aPart=1;//1門市 0總倉
		if (Utilis.getIni(this,"SYS","BACKOUT",7).equalsIgnoreCase("1"))
			bPart=1;//0預設1.啟動批發會員指定門市
		
			if (nKind==30 && bPart==1 && (aPart==1 || (aPart==0 && !Utilis.getIni(this,"SYS","DEPT",1).equalsIgnoreCase(eddeptno))) &&  mCustno!=null && mCustno.indexOf(eddeptno)==0)
			tCustno=mCustno.substring(eddeptno.length());
		if (nKind==40){
	    	((EditText) findViewById(R.id.edCustno)).setFilters(FilterArray3);
	    	((TextView) findViewById(R.id.textView7)).setText("績效獎金%");
		}else
	    	((EditText) findViewById(R.id.edCustno)).setFilters(FilterArray10);

		//0批發 1零售 
		if (defTrade==0) defTrade=3; else defTrade=5;
		if (backout[8].equalsIgnoreCase("2")) defTrade=4;  //SHIH專用指定 預購
				
		
		
		getCountryData(this);
		getDefaultData();

		//取得帳戶的名稱 & _ID 再交給SPINNER
        mAccountList = DBUtil.CAccount.getAccountData(this);
        if(mAccountList.size() > 0){
        	mAccount = new String[mAccountList.size()];
        	mAccountid = new int[mAccountList.size()];
        	for(int i = 0; i < mAccountList.size(); i++){
        		mAccount[i] = mAccountList.get(i).strText;
        		mAccountid[i] = mAccountList.get(i).nID;
        	}
        }else{
        	mAccount = new String[]{"無"};
        	mAccountid = new int[]{0};
        }
        String pictxt="";
         if (mMode==QCustMode.EDIT){ 
 		setTitle(getResources().getText(R.string.app_name).toString()+pKind[(nKind/10)-1]+"編輯中");
         }else {
       	 setTitle(getResources().getText(R.string.app_name).toString()+pKind[(nKind/10)-1]+"新增中");	 
         }
 		
 		//也可以是會員 廠商 門市 櫃員 新增中 
         
        mImage =(ImageButton)findViewById(R.id.imageButton1);
		mButton2 = (Button) findViewById(R.id.btn_new); // 相本
		mButton3 = (Button) findViewById(R.id.btn_income); // 語音
		mButton4 = (Button) findViewById(R.id.btn_remind); // 儲存後 繼續新增下一筆
		mButton5 = (Button) findViewById(R.id.btn_save); // 儲存
		mButton6 = (Button) findViewById(R.id.btn_exit); // 取消
		
		edCustno = (EditText) findViewById(R.id.edCustno); // 編號
		edCustname = (EditText) findViewById(R.id.edCustname); // 名稱
		edbirthday = (EditText) findViewById(R.id.edBirth); // 名稱		
		eddiscount = (EditText) findViewById(R.id.eddiscount); // 折數
		edmobil = (EditText) findViewById(R.id.edmobil); // 行動
		edlo = (EditText) findViewById(R.id.edlo); // 經
		edemail = (EditText) findViewById(R.id.edemail); // 電郵
		edla = (EditText) findViewById(R.id.edla); // 緯
		edmsn = (EditText) findViewById(R.id.edmsn); // MSN
		edadd = (EditText) findViewById(R.id.edadd); // 地址
		edps = (EditText) findViewById(R.id.edps); // 備註
		
		((TextView) findViewById(R.id.dept_TV)).setText(eddeptno);
		if (nKind==30 && bPart==1 && (aPart==1 || (aPart==0 && !Utilis.getIni(this,"SYS","DEPT",1).equalsIgnoreCase(eddeptno)))) 
		((TextView) findViewById(R.id.dept_TV)).setVisibility(View.VISIBLE);			

		imageViewFlag = (ImageView) findViewById(R.id.imageB_country);
		
		mySpinnerCountry = (Spinner) findViewById(R.id.spinner_country);
		cnItem = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, mCountryList);
		cnItem.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mySpinnerCountry.setAdapter(cnItem);
//		mySpinnerCountry.setSelection(mDefaultData.nCountry-1);
		mySpinnerCountry.setSelection(0);		
		
		pictxt=mCountryIcon.get(mySpinnerCountry.getSelectedItemPosition());
		if(pictxt.indexOf("drawable/") < 0) { 
			bmp=Utilis.getLimitBitmap(pictxt,30,30);
			if (bmp!=null)imageViewFlag.setImageBitmap(bmp);
			} else{ 
				imageViewFlag.setImageDrawable(Utilis.getResourceImage(this, pictxt));
			}
		
		mySpinnerBank = (Spinner) findViewById(R.id.spinner_bank);
		bkItem = new ArrayAdapter<String>(this,
		android.R.layout.simple_spinner_item, mAccount);
		bkItem.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mySpinnerBank.setAdapter(bkItem);
		mySpinnerBank.setSelection(0);
		

		mySpinnerTrade = (Spinner) findViewById(R.id.spinner_trade);
		tradeItem = new ArrayAdapter<String>(this,	android.R.layout.simple_spinner_item, tradeStr);
		tradeItem.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mySpinnerTrade.setAdapter(tradeItem);
		mySpinnerTrade.setSelection(defTrade);
		
		//將鍵盤收起來
 		 InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        m.hideSoftInputFromWindow(edCustno.getWindowToken(), 0);               		


        if (mMode==QCustMode.EDIT) { //傳入既有編號,應先查詢後,進入編輯,且限制編號欄(不可以異動)

        	//focusable="false"; 如果是編輯中,不可編輯
        	edCustno.setFocusable(false);
     		SQLiteDatabase db = Utilis.getDB(this);

        	StringBuffer buf = new StringBuffer();        
        	buf.append("Select * from '"+TbName.QCUST +"' where TR='"+mKind+"'");
			if (nKind==30 && bPart==1 && (aPart==1 || (aPart==0 && !Utilis.getIni(this,"SYS","DEPT",1).equalsIgnoreCase(eddeptno)))) buf.append(" and DEPTNO='"+eddeptno+"'");
        	buf.append(" and CUSTNO='"+mCustno+"'");
//     		mySqlBuf.append(" where CUSTNO  like '%" + mEdSearch.getText() + "%' order by _ID DESC LIMIT 300" );
			
			Cursor cs = db.rawQuery(buf.toString(), null);
			
		if	(cs.getCount()>0){			
			cs.moveToFirst();
			mKind=cs.getString(cs.getColumnIndex("TR"));	//String
			eddeptno=cs.getString(cs.getColumnIndex("DEPTNO"));
			mCustno=cs.getString(cs.getColumnIndex("CUSTNO"));
			tCustno=mCustno;
			if (nKind==30 && bPart==1 && (aPart==1 || (aPart==0 && !Utilis.getIni(this,"SYS","DEPT",1).equalsIgnoreCase(eddeptno))) &&  mCustno!=null && mCustno.indexOf(eddeptno)==0)
				tCustno=mCustno.substring(eddeptno.length());
				//if (nKind==30 && bPart==1 && aPart==1 &&  mCustno!=null && mCustno.indexOf(eddeptno)==0)
				//門市啟動了客戶編號置入門市編號
				edCustno.setText(tCustno);
				edCustname.setText(cs.getString(cs.getColumnIndex("CUSTNAME")));
				edmobil.setText(cs.getString(cs.getColumnIndex("MOBIL")));
				edemail.setText(cs.getString(cs.getColumnIndex("EMAIL")));
				edmsn.setText(cs.getString(cs.getColumnIndex("MSN")));
				edgmail=cs.getString(cs.getColumnIndex("GMAIL"));	//String
				edla.setText(cs.getString(cs.getColumnIndex("GPSLA")));
				edlo.setText(cs.getString(cs.getColumnIndex("GPSLO")));
				edempid=cs.getString(cs.getColumnIndex("EMPID"));
				eddiscount.setText(cs.getString(cs.getColumnIndex("DISCOUNT")));
				edadd.setText(cs.getString(cs.getColumnIndex("ADDRESS")));
				edps.setText(cs.getString(cs.getColumnIndex("PS")));
				edbankno=cs.getInt(cs.getColumnIndex("BANKNO"));  //ACCOUNT_ID
				edbankname=cs.getString(cs.getColumnIndex("BANKNAME")); //ACCOUNT_NAME
				
//正規化銀行名稱代號
				for (int i=0;i<mySpinnerBank.getCount();i++){
					if  (edbankname.equalsIgnoreCase(mySpinnerBank.getItemAtPosition(i).toString())){
						mySpinnerBank.setSelection(i);
						break;
					}	
				}
//需正規化國家地區
				edCountry=cs.getInt(cs.getColumnIndex("COUNTRY"));
				
				for (int i=0;i<mySpinnerCountry.getCount();i++){
					if  (edCountry==mCountryIdList.get(i)){
						mySpinnerCountry.setSelection(i);

						break;
					}
				}
				
//				mCountryIcon.get(mySpinnerBank.getSelectedItemPosition())				
//需正規化
                    if (cs.getInt(cs.getColumnIndex("TRADETYPE")) >= 0) {
                    	mySpinnerTrade.setSelection(cs.getInt(cs.getColumnIndex("TRADETYPE")));
                    }

                    
				edstate=cs.getString(cs.getColumnIndex("STATE"));
				edpic=cs.getString(cs.getColumnIndex("PIC"));
				edcreatedate=cs.getString(cs.getColumnIndex("CREATEDATE"));
				edcreatetime=cs.getString(cs.getColumnIndex("CREATETIME"));
				edbirthday.setText(cs.getString(cs.getColumnIndex("BIRTHDAY")));
				edc1=cs.getString(cs.getColumnIndex("C1"));
				edc2=cs.getString(cs.getColumnIndex("C2"));
				edc3=cs.getString(cs.getColumnIndex("C3"));
				edm1=cs.getString(cs.getColumnIndex("M1"));
				edm2=cs.getString(cs.getColumnIndex("M2"));
				edm3=cs.getString(cs.getColumnIndex("M3"));
				eds1=cs.getString(cs.getColumnIndex("S1"));
				eds2=cs.getString(cs.getColumnIndex("S2"));
				eds3=cs.getString(cs.getColumnIndex("S3"));
				
				if (eds2 !=null && !eds2.equalsIgnoreCase("0") && !eds2.equalsIgnoreCase("1"))
					eds2="0";//預設為歷史價

				if(eds2.equalsIgnoreCase("1")){
					((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_2);
				}else{
					((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_1);
				}
				
	        	if(edpic != null && edpic.length() > 0){
	        		if(edpic.indexOf("drawable/") < 0) { 
	        			bmp=Utilis.getLimitBitmap(edpic,200,300);
//						mImage.setScaleType(ScaleType.FIT_XY);	        			
	        			if (bmp!=null)mImage.setImageBitmap(bmp);
	        			} else{ 
	        				mImage.setImageDrawable(Utilis.getResourceImage(this, edpic));
	        			}
					}
	        	
			} else { //查不到編輯的會員資料,所以應即刻退出
		           db.close();
		           cs.close();
		           finish();
			}
           db.close();
           cs.close();

        } else { //單純新增 
    		// 初始化
    		ini();
        	
        }

        mySpinnerCountry.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,	int arg2, long arg3) {
						
						// 將所選mySpinner的值帶入mySpinner1中且以(arg2)為指定的位置						
						String pictxt=mCountryIcon.get(arg2);
						if(pictxt.indexOf("drawable/") < 0) { 
							bmp=Utilis.getLimitBitmap(pictxt,30,30);
							if (bmp!=null)imageViewFlag.setImageBitmap(bmp);
							} else{ 
							imageViewFlag.setImageDrawable(Utilis.getResourceImage(QCust.this, pictxt));
							}
						// 將mySpinner顯示
						arg0.setVisibility(View.VISIBLE);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
					}

				});

        mySpinnerBank.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {

						arg0.setVisibility(View.VISIBLE);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
					}

				});

        mySpinnerTrade.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						
						arg0.setVisibility(View.VISIBLE);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
					}

				});

		mButton5.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				savedata();
				if (exit==1) {
		        	Intent intentS = new Intent();
	        		tCustno=DBCloud.chkStrB(edCustno.getText().toString().trim());
		        	if (nKind==30 && bPart==1 && (aPart==1 || (aPart==0 && !Utilis.getIni(QCust.this,"SYS","DEPT",1).equalsIgnoreCase(eddeptno))) && tCustno.indexOf(eddeptno)<0){
		        		mCustno=eddeptno+tCustno;
	        		} else mCustno=tCustno;
		        	intentS.putExtra("qcust_key",mCustno);
		        	intentS.putExtra("qcust_modify",modify);
		        	QCust.this.setResult(RESULT_OK,intentS);
					
				finish();
				}

			}
		});
		
		mButton3.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
		        // TODO Auto-generated method stub
		        PackageManager pm = getPackageManager();
		        /* 查詢有無裝Google Voice Search Engine */
		        List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
		            RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		        /* 若有安裝Google Voice Search Engine */
		        if (activities.size() != 0)
		        {
		          try
		          {
		            /* 語音辨識Intent */
		            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

		            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
		                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		            /* 在辨識畫面出現的說明 */
		            intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "語音辨識");
		            //這是取得第一筆的方式
		            intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
		            
		            /* 開啟語音辨識Intent */
		            startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);

		          } catch (Exception e)
		          {
		            edps.setText("" + e.getMessage());
		          }

		        } 				
				
	  }
	});		
		
		mImage.setOnClickListener(new ImageButton.OnClickListener()  {
			
            @Override  
            public void onClick(View v) {
            	eventImgCapture();
            }  
        });  
		
		mButton2.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				eventImgFile();
			}
		});		
		
		
		mButton4.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (mMode==QCustMode.ADD) {	
				savedata();
				if (exit == 1) {
					exit=0;
					ini();
				}
				} else {
					Toast.makeText(QCust.this, "編輯中! 請使用儲存!!", Toast.LENGTH_LONG).show();
				}
			}
		});
		
		mButton6.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
		        /* 彈出的選單提供兩種功能（返回 / 繼續新增） */
			if (mMode==QCustMode.EDIT) {	
		        String[] dlgMenu=
		        {
		          getResources().getText(R.string.str_back).toString(),
		          getResources().getText(R.string.str_continue).toString()
		        };
		        new AlertDialog.Builder(QCust.this)
		        .setTitle(R.string.str_finish)
		        .setItems(dlgMenu, mListener1)
		        .setPositiveButton(R.string.str_cancel,
		        new DialogInterface.OnClickListener()
		        {
		          public void onClick(DialogInterface dialog, int which)
		          {
		          }
		        }).show();
			}
		 
	    	else {
		        String[] dlgMenu=
		        {
		          getResources().getText(R.string.str_noadd).toString(),
		          getResources().getText(R.string.str_conadd).toString()
		        };
		        new AlertDialog.Builder(QCust.this)
                .setTitle(R.string.str_inadd)		        
		        .setItems(dlgMenu, mListener1)
		        .setPositiveButton(R.string.str_cancel,
		        new DialogInterface.OnClickListener()
		        {
		          public void onClick(DialogInterface dialog, int which)
		          {
		          }
		        }).show();
				
	 	    }
		}
		});
		
	}

	// 取得預設參數
	private void getDefaultData(){
    	SQLiteDatabase db = Utilis.getDB(this);
    	if(db != null){
			Cursor cursor = db.rawQuery("select * from qc_default", null);
			if(cursor != null){
				try{
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						mDefaultData = new DefaultData();
						mDefaultData.nCountry = cursor.getInt(cursor.getColumnIndex("COUNTRY"));
						mDefaultData.dBillRate = cursor.getDouble(cursor.getColumnIndex("BILLRATE"));
						mDefaultData.batch = cursor.getString(cursor.getColumnIndex("BATCH"));
						mDefaultData.factno = cursor.getString(cursor.getColumnIndex("FACTNO"));
						mDefaultData.nItemState = cursor.getInt(cursor.getColumnIndex("STATE"));
						mDefaultData.nSourceNumber = cursor.getInt(cursor.getColumnIndex("SOURCENO"));
						mDefaultData.nItemProduct = cursor.getInt(cursor.getColumnIndex("PRODUCT"));
						mDefaultData.nItemFirst = cursor.getInt(cursor.getColumnIndex("ITEMFIRST"));
						mDefaultData.nSeason = cursor.getInt(cursor.getColumnIndex("SEASON"));
						mDefaultData.nYear = cursor.getInt(cursor.getColumnIndex("YEAR"));
						mDefaultData.employ = cursor.getString(cursor.getColumnIndex("EMPLOY"));
						mDefaultData.nAccountId = cursor.getInt(cursor.getColumnIndex("ACCOUNT"));
						mDefaultData.nHid = cursor.getString(cursor.getColumnIndex("HID"));
					}
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					cursor.close();
				}
			}
			db.close();
    	}
    }

	public void getCountryData(Context context){
		if(mCountryIcon != null) 	mCountryIcon.clear();
		if(mCountryList != null)		mCountryList.clear();
		if(mCountryIdList != null)	mCountryIdList.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{
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}
	

	
	
	
	private void savedata() {
		// TODO Auto-generated method stub
    	int checkStateId = ((RadioGroup)findViewById(R.id.group_state)).getCheckedRadioButtonId();
    	switch(checkStateId){
    	case R.id.radio_state_1:
    		eds2 = "0";
    		break;
    	case R.id.radio_state_2:
    		eds2 = "1";
    		break;
    	}
		
		tCustno=DBCloud.chkStrB(edCustno.getText().toString().trim());
       	if (nKind==30 && bPart==1 && (aPart==1 || (aPart==0 && !Utilis.getIni(QCust.this,"SYS","DEPT",1).equalsIgnoreCase(eddeptno))) && tCustno.indexOf(eddeptno)<=0){
    		mCustno=eddeptno+tCustno;
		} else mCustno=tCustno;
    	
		String f3[] ={mCustno};
		ContentValues value = new ContentValues();
		
        value.put("TR", mKind);
        value.put("CUSTNO", mCustno);
        value.put("CUSTNAME", DBCloud.chkStrB(edCustname.getText().toString().trim()));
        value.put("MOBIL", DBCloud.chkStrB(edmobil.getText().toString()));
        value.put("EMAIL", DBCloud.chkStrB(edemail.getText().toString()));
        value.put("MSN", DBCloud.chkStrB(edmsn.getText().toString()));
        value.put("GPSLO", edlo.getText().toString().trim());
        value.put("GPSLA", edla.getText().toString().trim());
        value.put("DISCOUNT", eddiscount.getText().toString().trim());
        value.put("ADDRESS", DBCloud.chkStrB(edadd.getText().toString()));
        value.put("PS", DBCloud.chkStrB(edps.getText().toString()));
//        value.put("BANKNO", edmobil.getText().toString().trim());
        value.put("BANKNAME", mAccount[mySpinnerBank.getSelectedItemPosition()]);
        value.put("BANKNO", mAccountid[mySpinnerBank.getSelectedItemPosition()]);        
        value.put("COUNTRY", mCountryIdList.get(mySpinnerCountry.getSelectedItemPosition()));
        value.put("TRADETYPE", ""+mySpinnerTrade.getSelectedItemPosition());
        value.put("STATE", "1");
        edpic=DBCloud.chkStrB(edpic);
        File file= new File(edpic);
        if(!file.exists() || edpic.length() <= 0){
        	edpic=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/04.jpg";
       	} 
        value.put("PIC", edpic);
        value.put("CREATEDATE", DateUtil.getCurrentDate());
        value.put("CREATETIME", DateUtil.getSystemTime().substring(2,14));
        value.put("BIRTHDAY", DBCloud.chkStrB(edbirthday.getText().toString()));
        //除了會員可能為 總倉或門市 而門市及櫃員 都隸屬總倉
        if (mKind.equalsIgnoreCase("30")) value.put("DEPTNO", eddeptno); else  value.put("DEPTNO",Utilis.getIni(this,"SYS","DEPT",6)); 
        value.put("EMPID", DBCloud.chkStrB(edempid));
        value.put("C1", edc1);        
        value.put("C2", edc2);
        value.put("C3", edc3);
        value.put("M1", edm1);        
        value.put("M2", edm2);
        value.put("M3", edm3);
        value.put("S1", eds1);        
        value.put("S2", eds2);
        value.put("S3", eds3);
		

	if (mMode==QCustMode.EDIT){	//就是編輯
 		SQLiteDatabase db = Utilis.getDB(this);		
		int success = db.update(com.cwbuyer.lib.TbName.QCUST, value,	"CUSTNO=?", f3);		
		modify=1;	
		exit = 1;		
		db.close();
		DBCloud.aa1_aa0_qcust(this);
		
	 } else {  //"1" 就是新增
			
			if (mCustno.length() != 0) {
		 		SQLiteDatabase db = Utilis.getDB(this);				
		      	StringBuffer buf = new StringBuffer();        
	        	buf.append("select CUSTNO from "+TbName.QCUST);
	        	buf.append(" where CUSTNO='"+mCustno+"'");
				Cursor cs = db.rawQuery(buf.toString(), null);

				if (cs.getCount()<=0) {
					/* 資料庫未找到，新增它 */
					long result = db.insert(TbName.QCUST, null, value);
					//如果是門市資料建檔,需新增一個預設會員
					if (nKind==20){
						value.remove("TR");
				        value.put("TR", "30");
				        
						value.remove("CUSTNO");
				        value.put("CUSTNO", "Z"+mCustno);
				        
						value.remove("DEPTNO");
				        value.put("DEPTNO", mCustno);
				        
						result = db.insert(TbName.QCUST, null, value);
					}
					
					Toast.makeText(QCust.this, "編號:"+mCustno+"已成功存入會員檔!!", Toast.LENGTH_LONG).show();				
					modify=1;
	                exit=1;
	                DBCloud.aa1_aa0_qcust(this);
				} else {
					// 編號已存在
					Toast.makeText(QCust.this, "編號不可重複,請新輸入", Toast.LENGTH_LONG).show();
					edCustno.setBackgroundColor(R.drawable.milk);
					exit = 0;
					// 未來可以嘗試詢問 進入該筆編輯 或重新輸入
				}
				db.close();
			} else {
				Toast.makeText(QCust.this, "編號不可留白,建議可以輸入會員的生日!", Toast.LENGTH_LONG).show();
				exit = 0;
			}
	 }
	}
	


	private static int exifToDegrees(int exifOrientation) {        
	    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } 
	    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {  return 180; } 
	    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {  return 270; }
	    return nPicDegree;    
	 }

	private void eventImgCapture() {
    	Toast.makeText(QCust.this, "相機請使用直拍", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// Wysie_Soh: Create path for temp file
		File folder = new File(filepath);
		if(folder.exists() == false){
			folder.mkdirs();
		}
		edpic=filepath +File.separator+"cu"+ String.valueOf(DateUtil.getSystemTime())
				+ ".jpg";
		File file = new File(edpic);
		
		if(file.exists() == false){
			try{
				file.createNewFile();
			}catch(Exception e){
				
			}
		}
		mImageCaptureUri = Uri.fromFile(file);

		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
		
		try {
			intent.putExtra("return-data", true);
			startActivityForResult(intent, PHOTOHRAPH);
		} catch (ActivityNotFoundException e) {
			// Do nothing for now
		} catch (Exception e){
		}
	}
	
	
	private void eventImgFile(){
        Intent intent = new Intent(); 
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Picture"),PHOTOZOOM);
	}
	
	
	
	private void ini() {
		// TODO Auto-generated method stub
		edpic = filepath +File.separator+"cu" +DateUtil.getSystemTime()+".png";
		edCustno.setText("");
		edCustname.setText("");
		eddiscount.setText("100");
		edmobil.setText("");
		edlo.setText("0.0");
		edemail.setText("");
		edla.setText("0.0");
		edmsn.setText("");
		edadd.setText("");
		edps.setText("");
		edbirthday.setText("");
		edcreatedate=DateUtil.getCurrentDate();
		edcreatetime=DateUtil.getSystemTime().substring(2,14);
		mCustno="";tCustno="";
		((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_1);
	}

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

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

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
//		Intent intent = new Intent();
//		if (from3.equalsIgnoreCase("Qcustf")){intent.setClass(QCust.this, Qcustf.class);}
//		else if (from3.equalsIgnoreCase("Qmails")){intent.setClass(QCust.this, Qmails.class);}
//		startActivity(intent);

		super.onDestroy();

	}
	
	private OnClickListener mListener1=new DialogInterface.OnClickListener()
	  {
	    @Override
	    public void onClick(DialogInterface dialog, int which)
	    {
	      // TODO Auto-generated method stub
	      switch(which)
	      {
	        case 0:
	          /* 返回 */
	        	exit=1;
	        	Intent intentS = new Intent();
        		tCustno=DBCloud.chkStrB(edCustno.getText().toString().trim());
	        	if (nKind==30 && bPart==1 && (aPart==1 || (aPart==0 && !Utilis.getIni(QCust.this,"SYS","DEPT",1).equalsIgnoreCase(eddeptno))) && tCustno.indexOf(eddeptno)<=0){
	        		mCustno=eddeptno+tCustno;
        		} else mCustno=tCustno;
	        	
	        	intentS.putExtra("qcust_key",mCustno);
	        	intentS.putExtra("qcust_modify",modify);
	        	QCust.this.setResult(RESULT_OK,intentS);
	        	
	        	finish();
	          break;
	        case 1:
	          /* 繼續新增 */
	        	exit=0;
	          break;
	      }
	    }
	  };
	  
		@SuppressWarnings("deprecation")
		public String getPath(Uri uri) {
	        if( uri == null ) {
	            return null;
	        }
	        String[] projection = { MediaStore.Images.Media.DATA };
	        Cursor cursor = managedQuery(uri, projection, null, null, null);
	        if( cursor != null ){
	            int column_index = cursor
	            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	            cursor.moveToFirst();
	            return cursor.getString(column_index);
	        }
	        return uri.getPath();
	}

		private void makePic(Bitmap bitmap) throws IOException{

			FileOutputStream fos = null;
			try {
					fos = new FileOutputStream(edpic);
						bitmap.compress(CompressFormat.JPEG, 100, fos);
						fos.close(); 
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
     	  //startActivityForResult(intent, PHOTOHRAPH);
	   @Override  
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		   String OutPhotoURI;
//	        if (resultCode == NONE)  
//	            return;  

	        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
	                && resultCode == RESULT_OK){
	        		String strRet ="";
	                  if (edadd.isFocused()) {  strRet = edadd.getText().toString();  }
	                  else  {  strRet = edps.getText().toString();  }
	                  

	                /* 取得辨識結果 */
	                ArrayList<String> results = data
	                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
	                for (int i = 0; i < results.size(); i++)
	                {
	                  strRet += results.get(i);
	                }

	                if (strRet.length() > 0)
	                {
		                  if (edadd.isFocused()) {  edadd.setText(strRet);  }
		                  else  {  edps.setText(strRet);  }

	                } 
	        	return;
	        }	        
	        
	        if (requestCode == PHOTOHRAPH) 
	        {  
				if (data != null) {
					try {
						Bundle extras = data.getExtras();
						if (extras != null) {
							Bitmap bitmap=null;
								OutPhotoURI = mImageCaptureUri.getPath();
								bitmap = Utilis.getLimitBitmap(mImageCaptureUri.getPath(), 210, 280);
							if (bitmap != null) {
								Matrix matrix = new Matrix();
								ExifInterface exif = new ExifInterface(OutPhotoURI);
								exif = new ExifInterface(OutPhotoURI);
									
								int rotation = exif.getAttributeInt(OutPhotoURI, ExifInterface.ORIENTATION_NORMAL);
								rotationInDegrees = exifToDegrees(rotation);
								matrix.preRotate(rotationInDegrees);
								Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, 210, 280, matrix, true);
								mBitmap=adjustedBitmap;
								//旋轉的測試SOURCE_CODE							
							}else{ //失敗
								mBitmap=null;	
							}
							 //eventImgCrop(OutPhotoURI);
						}
					} catch (Exception e) {
					}
				} else {
					try {
						OutPhotoURI = mImageCaptureUri.getPath();
						Bitmap bitmap = Utilis.getLimitBitmap(OutPhotoURI, 210, 280);
						if (bitmap != null) {
							
							Matrix matrix = new Matrix();
							ExifInterface exif = new ExifInterface(OutPhotoURI);
							int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
							rotationInDegrees = exifToDegrees(rotation);
							
							matrix.preRotate(rotationInDegrees);
							Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
							
							ByteArrayOutputStream stream = new ByteArrayOutputStream();
							adjustedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// (0 - 100)压缩文件
					        FileOutputStream fos = null;
							try {
									fos = new FileOutputStream(OutPhotoURI);
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							try {
								adjustedBitmap.compress(CompressFormat.JPEG, 100, fos);
								fos.close();
								mBitmap=adjustedBitmap;
								
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					} catch (Exception e) {
					}
				}
				
				if (mBitmap!=null && mBitmap.getHeight()>0 ) mImage.setImageBitmap(mBitmap);
	        }	
	        	
	        // 读取相册缩放图片  
	        if (requestCode == PHOTOZOOM) {
	    		edpic=filepath +File.separator+"cu"+ String.valueOf(DateUtil.getSystemTime())+ ".jpg";
	    		
	    		mBitmap=null;Bitmap bitmap=null;
	            Uri selectedImageUri = data.getData();
	            
	        	Toast.makeText(this, "成功"+Build.VERSION.SDK_INT, Toast.LENGTH_SHORT).show();
	            
	            if (Build.VERSION.SDK_INT < 19) {
	            	OutPhotoURI = getPath(selectedImageUri);
	            	mBitmap = Utilis.getScaleBitmap(OutPhotoURI, 210, 280);
	                //mBitmap = BitmapFactory.decodeFile(OutPhotoURI);
					try {
						ExifInterface exif = new ExifInterface(OutPhotoURI);
						int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
						rotationInDegrees = exifToDegrees(rotation);
						Matrix matrix = new Matrix();
						matrix.preRotate(rotationInDegrees);
						bitmap = Bitmap.createBitmap(mBitmap, 0, 0, 210, 280, matrix, true);
						
	    		        FileOutputStream fos = null;
	    				try {
	    						fos = new FileOutputStream(edpic);
	   	    					bitmap.compress(CompressFormat.JPEG, 100, fos);
	   	    					fos.close();
	   	    					mBitmap=bitmap;	
	    				} catch (FileNotFoundException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	            else
	            {
	                ParcelFileDescriptor parcelFileDescriptor;
	                try {
	                    parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
	                    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
	                    bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
	                    parcelFileDescriptor.close();

	    				ByteArrayOutputStream stream = new ByteArrayOutputStream();
	    				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// (0 - 100)压缩文件
	    		        FileOutputStream fos = null;
	    				try {
	    						fos = new FileOutputStream(edpic);
	    				} catch (FileNotFoundException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
	    				try {
	    					bitmap.compress(CompressFormat.JPEG, 100, fos);
	    					fos.close();
	    					mBitmap = Utilis.getScaleBitmap(edpic, 210, 280);
	    	                //mBitmap = BitmapFactory.decodeFile(OutPhotoURI);
	    					
	    					try {
	    						ExifInterface exif = new ExifInterface(edpic);
	    						int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
	    						rotationInDegrees = exifToDegrees(rotation);
	    						Matrix matrix = new Matrix();
	    						matrix.preRotate(rotationInDegrees);
	    						bitmap = Bitmap.createBitmap(mBitmap, 0, 0, 210, 280, matrix, true);

	    						try {
	    	    						fos = new FileOutputStream(edpic);
	    	   	    					bitmap.compress(CompressFormat.JPEG, 100, fos);
	    	   	    					fos.close();
	    	   	    					mBitmap=bitmap;	
	    	    				} catch (FileNotFoundException e) {
	    	    					// TODO Auto-generated catch block
	    	    					e.printStackTrace();
	    	    				}

	    					} catch (IOException e) {
	    						// TODO Auto-generated catch block
	    						e.printStackTrace();
	    					}
	    					
	    					
	    				} catch (IOException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
	                    
	                } catch (FileNotFoundException e) {
	                    e.printStackTrace();
	                } catch (IOException e) {

	                    e.printStackTrace();
	                }
	            }
				if (mBitmap!=null && mBitmap.getHeight()>0 ) mImage.setImageBitmap(mBitmap);
	        }
	   }
}

