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 android.annotation.SuppressLint;
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.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.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.code.CodeList;
import com.cwbuyer.code.CodeMode;
import com.cwbuyer.format.DefaultData;
import com.cwbuyer.format.EMode;
import com.cwbuyer.format.FactData;
import com.cwbuyer.lib.Calculator;
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.pwbuyer.main.R;

//廠商資料編輯頁面
@SuppressLint("InflateParams")
@SuppressWarnings("unused")
public class AddCompany  extends Activity{
	private int COUNTRY_CODE = 1001;
	private int mMode = 0;
	private String mFactNo = null;
//	private LinkedList<FactData> mList = new LinkedList<FactData>();
	private FactData mData = null;
	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<String> mCountryIcon = new ArrayList<String>();
	private ArrayList<Integer> mCountryId = new ArrayList<Integer>();
	String edpic=""; //該會員圖片檔名(含全路徑)記憶區
	private int rotationInDegrees=0;
	private static int nPicDegree =0;

	Bitmap mBitmap=null;
	
	// DatePicker Use
	//private int mStartYear = 0;
	//private int mStartMonth = 0;
	//private int mStartDay = 0;
	
	//private int mEndYear = 0;
	//private int mEndMonth = 0;
	//private int mEndDay = 0;
	
	private static final String[] mTradeTypes = new String[]{"外幣","成本","中盤","批發","網購","零售"};
	
	ImageView OutPhoto = null;
	Uri mImageCaptureUri = null;
	private String mImagePath = null;
    public static final int PHOTOHRAPH = 1009;// 拍照  
    public static final int PHOTOZOOM = 2; // 缩放  
    public static final int PHOTORESOULT = 3;// 结果  
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR", 8);
	
	public final static String SAVE_FOLDER = Environment.getExternalStorageDirectory().getAbsolutePath()
			+ File.separator + "cwbuyer" + File.separator;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.company_layout);
		setTitle("廠商主檔編輯");
		
		mMode = getIntent().getIntExtra("mode", EMode.ADD);
		mFactNo = getIntent().getStringExtra("factno");
		nPicDegree =Utilis.toInt(Utilis.getIni(this, "SYS", "BACKOUT", 8)); // 拍照鏡頭角度		
		
		getCountryData(this);  // 取得國家資料
		if(mMode == EMode.EDIT){
			if(mFactNo != null){
				getData(mFactNo);
			}
		}else{
			mData = new FactData();
			DefaultData defdata = DBUtil.Default.getDefaultData(this);
			((ImageView)findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(this, defdata.strCountryPic));
			mData.country = defdata.country;
			mData.nCountry = defdata.nCountry;
			mData.deptno=Utilis.getIni(this, "SYS", "DEPT",1);
			// 設定建檔時間
			mData.time = DateUtil.getSystemTime().substring(2, 14);
			mData.empid = "1";
			mData.dDiscount=100;
			mData.nState="1";
			mFactNo = "";
			((EditText)findViewById(R.id.edit_datetime)).setText(mData.time);
			edpic = filepath +File.separator+"cu" +DateUtil.getSystemTime()+".png";
			((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_2);
		}
		
		OutPhoto = (ImageView)findViewById(R.id.img_item);
        ((RelativeLayout)findViewById(R.id.layout_img_item)).setOnClickListener(new MainClick());
		
		if(mData != null){
//			((ImageView)findViewById(R.id.img_icon)).setImageDrawable(Utilis.getResourceImage(this, mData.icon));
			if (mData.nCountry<=0) mData.nCountry=1;
			((ImageView)findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(this, mCountryIcon.get(mData.nCountry - 1)));
			((EditText)findViewById(R.id.edit_country)).setText(mData.country);
			((EditText)findViewById(R.id.edit_factno)).setText(mData.factno);
			((EditText)findViewById(R.id.edit_factname)).setText(mData.factname);
			((EditText)findViewById(R.id.edit_email)).setText(mData.email);
			((EditText)findViewById(R.id.edit_gpsla)).setText("" + mData.dGpsLA);
			((EditText)findViewById(R.id.edit_gpslo)).setText("" + mData.dGpsLO);
			((EditText)findViewById(R.id.edit_msn)).setText(mData.msn);
			((EditText)findViewById(R.id.edit_gmail)).setText(mData.gmail);
			((EditText)findViewById(R.id.edit_mobil)).setText(mData.mobile);
			((EditText)findViewById(R.id.edit_datetime)).setText(mData.time);
			((EditText)findViewById(R.id.edit_birthday)).setText(mData.birtime);
			((EditText)findViewById(R.id.edit_sale)).setText(""+mData.dDiscount);
			((EditText)findViewById(R.id.edit_address)).setText(mData.address);
			((EditText)findViewById(R.id.edit_desc)).setText(mData.desc);

			if(edpic != null && edpic.length() > 0){
				Bitmap bitmap = Utilis.getLimitBitmap(
						edpic, 320, 480);
				if (bitmap != null) {
					mImagePath = edpic;
					OutPhoto.setScaleType(ScaleType.FIT_XY);
					OutPhoto.setImageBitmap(bitmap);
				}
        	}
		}
		
		ArrayAdapter<CharSequence> adaptetTrade = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, mTradeTypes);
		adaptetTrade.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
		Spinner tradeSpinner = (Spinner)findViewById(R.id.spin_trade);
		tradeSpinner.setAdapter(adaptetTrade);
		tradeSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(@SuppressWarnings("rawtypes") AdapterView adapterView, View view,
					int position, long id) {
			}
			@SuppressWarnings("rawtypes")
			public void onNothingSelected(AdapterView arg0) {
			}
		});
		tradeSpinner.setSelection(mData.nTradetype);
		
		if (mData.empid !=null && !mData.empid.equalsIgnoreCase("0") && !mData.empid.equalsIgnoreCase("1"))
			mData.empid="1";//預設為標準價

		if(mData.empid.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);
		}
		
		((EditText)findViewById(R.id.edit_gpsla)).setOnClickListener(new NumberClick());
        ((EditText)findViewById(R.id.edit_gpslo)).setOnClickListener(new NumberClick());
		((EditText)findViewById(R.id.edit_country)).setOnClickListener(new MainClick());
       // ((EditText)findViewById(R.id.edit_datetime)).setOnClickListener(new MainClick());
        ((EditText)findViewById(R.id.edit_birthday)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.btn_save)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_new)).setOnClickListener(new MainClick());
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		String OutPhotoURI;
		if (requestCode == COUNTRY_CODE) {
			if (resultCode == RESULT_OK) {
				int id = data.getIntExtra("country_id", 0);
				String pid = data.getStringExtra("country_pic");
				String name = data.getStringExtra("country_name");
				try{
					mData.nCountry = id;
					((ImageView)findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(AddCompany.this, pid));
					((EditText)findViewById(R.id.edit_country)).setText(name);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}  
		if (requestCode == PHOTOZOOM) // 相本
		{
        	if (data != null) {
        		if (edpic==null || (edpic !=null && (edpic.indexOf("drawable/icon")==0 || edpic.indexOf("/cwbuyer/para/04.jpg")>0)))
        			edpic = filepath +File.separator+"cu" +DateUtil.getSystemTime()+".png";
        		
                Uri selectedImageUri = data.getData();
                Bitmap bitmap=null;Bitmap mBitmap=null;
                if (Build.VERSION.SDK_INT < 19) {
                	OutPhotoURI = getPath(selectedImageUri);
                	bitmap = Utilis.getScaleBitmap(OutPhotoURI, 210, 280);
                	try {
                		ExifInterface exif = new ExifInterface(OutPhotoURI);
                		int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                		mBitmap=Utilis.exifToDegrees(edpic,bitmap,rotation);
    				} 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);
        					ExifInterface exif = new ExifInterface(edpic);
        					int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        					mBitmap=Utilis.exifToDegrees(edpic,mBitmap,rotation);
        					
        				} catch (IOException e) {
        					// TODO Auto-generated catch block
        					e.printStackTrace();
        				}
                        
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                }
                
    			if (mBitmap != null)	OutPhoto.setImageBitmap(mBitmap);
    			
        	}
		}
        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)	OutPhoto.setImageBitmap(mBitmap);

		}
	}
	
	class NumberClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(AddCompany.this);
//			switch (id) {
//			}
			showComputer(id);
		}
	}
	
	private void showComputer(final int vid){
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		final View root = this.getLayoutInflater().inflate(R.layout.dlg_computer, null);
		Calculator calu = new Calculator(AddCompany.this, root);
		final TextView print = (TextView)root.findViewById(R.id.text_print);
		dialog.setView(root);
		dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	          public void onClick(DialogInterface dialog, int which) {
	        	  EditText edit = (EditText)AddCompany.this.findViewById(vid);
	        	  try{
	        		  String result = print.getText().toString();
	        		  if(result == null || result.length() <=0){
	        			  print.setText("0");
	        		  }else if(result.indexOf("+") > 0){
	        			  print.setText("0");
	        		  }else if(result.indexOf("-") > 0){
	        			  print.setText("0");
	        		  }else if(result.indexOf("×") > 0){
	        			  print.setText("0");
	        		  }else if(result.indexOf("÷") > 0){
	        			  print.setText("0");
	        		  }
	        		  edit.setText(print.getText().toString());
	        	  }catch(Exception e){
	        		  
	        	  }
	          }
		});
		dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	          public void onClick(DialogInterface dialog, int which) {
	          }
			});
		dialog.show();
	}
	
	class MainClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(AddCompany.this);
			switch (id) {
				case R.id.edit_country:
				{
					Intent intent = new Intent();
					intent.setClass(AddCompany.this, CodeList.class);
					intent.putExtra("code_mode", CodeMode.COUNTRY);
					intent.putExtra("edit_mode", 1);
					AddCompany.this.startActivityForResult(intent, COUNTRY_CODE);
					break;
				}
				case R.id.btn_save:
					if(saveData() == true){
			        	Intent intentS = new Intent();
						intentS.putExtra("qfact_key",mFactNo);
						intentS.putExtra("qfact_modify",1);
						AddCompany.this.setResult(RESULT_OK,intentS);
						finish();
					}
					break;
				case R.id.btn_exit:
					finish();
					break;
				case R.id.btn_new: // 相本
					eventImgFile();
					break;
				case R.id.layout_img_item:
				{
					eventImgCapture(PHOTOHRAPH);
					break;
				}
			}
		}
	}
	
	private boolean saveData(){
		String factno = DBCloud.chkStrB(((EditText)findViewById(R.id.edit_factno)).getText().toString());
		String factname =DBCloud.chkStrB( ((EditText)findViewById(R.id.edit_factname)).getText().toString());
		String email = DBCloud.chkStrB(((EditText)findViewById(R.id.edit_email)).getText().toString());
		String gpsla = ((EditText)findViewById(R.id.edit_gpsla)).getText().toString();
		String gpslo = ((EditText)findViewById(R.id.edit_gpslo)).getText().toString();
		String msn = DBCloud.chkStrB(((EditText)findViewById(R.id.edit_msn)).getText().toString());
		String gmail =DBCloud.chkStrB(((EditText)findViewById(R.id.edit_gmail)).getText().toString());
		String mobile =DBCloud.chkStrB(((EditText)findViewById(R.id.edit_mobil)).getText().toString());
		String datetime = ((EditText)findViewById(R.id.edit_datetime)).getText().toString();
		String birtime = DBCloud.chkStrB(((EditText)findViewById(R.id.edit_birthday)).getText().toString());
		String sale = DBCloud.chkStrB(((EditText)findViewById(R.id.edit_sale)).getText().toString());
		String address = DBCloud.chkStrB(((EditText)findViewById(R.id.edit_address)).getText().toString());
		String desc = ((EditText)findViewById(R.id.edit_desc)).getText().toString();
		String empid="1";
    	int checkStateId = ((RadioGroup)findViewById(R.id.group_state)).getCheckedRadioButtonId();
    	switch(checkStateId){
    	case R.id.radio_state_1:
    		empid = "0";
    		break;
    	case R.id.radio_state_2:
    		empid = "1";
    		break;
    	}
		int nTradeType = ((Spinner)findViewById(R.id.spin_trade)).getSelectedItemPosition();
		
		if(factno == null || factno.length() <= 0){
			Toast.makeText(this, "請輸入廠商編號", Toast.LENGTH_SHORT).show();
			return false;
		}
		
		if(mMode == EMode.ADD || mFactNo.equalsIgnoreCase(factno) != true){
			// 檢查看是不是有重覆的廠商編號
			if(isFactExist(factno) == true){
				Toast.makeText(this, "此廠商編號已存在，請重新命名", Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		mFactNo=factno;
		SQLiteDatabase db = Utilis.getDB(this);
		ContentValues value = new ContentValues();
		value.put("TR", 10);
		value.put("FACTNO", factno);
		value.put("FACTNAME", factname);
		value.put("MOBIL", mobile);
		value.put("EMAIL", email);
		value.put("MSN", msn);
		value.put("GMAIL", gmail);
		value.put("GPSLA", gpsla);
		value.put("GPSLO", gpslo);
		value.put("DEPTNO", mData.deptno);
		value.put("EMPID", empid);
		value.put("DISCOUNT", sale);
		value.put("ADDRESS", address);
		value.put("PS", desc);
		value.put("BANKNO", 0);
		value.put("BANKNAME", "AA0");

		if(edpic==null || edpic.length() <= 0)  	edpic=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/04.jpg";
		if(edpic.equalsIgnoreCase("drawable/icon")) edpic=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/04.jpg";
        File file= new File(edpic); if(!file.exists()) edpic=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/04.jpg";
       	 
        value.put("PIC", edpic);
		value.put("TRADETYPE", nTradeType);
		value.put("COUNTRY", mData.nCountry);
		value.put("BIRTHDAY", birtime);
    	value.put("CREATEDATETIME", DateUtil.getSystemTime().substring(2,14));
		value.put("STATE", "1");
    	
    	if(mMode == EMode.ADD){
	    	long result = db.insert(TbName.QFACT, null, value);
	    	if(result > 0){
	    		Toast.makeText(this, "存取資料成功", Toast.LENGTH_SHORT).show();
	    	}else{
	    		Toast.makeText(this, "存取資料失敗", Toast.LENGTH_SHORT).show();
	    		return false;
	    	}
    	}else{  // EDIT
    		String[] args = {mFactNo};
    		try{
				int success = db.update(com.cwbuyer.lib.TbName.QFACT, value,
						"FACTNO=?", args);
				if(success > 0){
					Toast.makeText(this, "修改資料成功", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(this, "修改資料失敗", Toast.LENGTH_SHORT).show();
					return false;
				}
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    	db.close();
    	DBCloud.aa1_aa0_qfact(this);
		return true;
	}
	
	private boolean isFactExist(String factno){
		boolean bResult = false;
		SQLiteDatabase db = Utilis.getDB(this);
		if(db != null){
			Cursor cursor = null;
			try{
				cursor = db.rawQuery("select * from qfact where factno ='" +factno + "'", null);
				if(cursor != null){
					if(cursor.getCount() > 0){
						bResult = true;
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(cursor != null){
					cursor.close();
				}
			}
			db.close();
		}
		return bResult;
	}
	
	public void getData(String factno){
		SQLiteDatabase db = Utilis.getDB(this);
		Cursor cursor = db.rawQuery("select * from qfact where factno=  '" +factno + "'", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					mData = new FactData();
//						data.id = cursor.getInt(cursor.getColumnIndex("_ID"));
					mData.nTR = cursor.getInt(cursor.getColumnIndex("TR"));
					mData.factno = cursor.getString(cursor.getColumnIndex("FACTNO"));
					mData.factname = cursor.getString(cursor.getColumnIndex("FACTNAME"));
					mData.mobile = cursor.getString(cursor.getColumnIndex("MOBIL"));
					mData.email = cursor.getString(cursor.getColumnIndex("EMAIL"));
					mData.msn = cursor.getString(cursor.getColumnIndex("MSN"));
					mData.gmail = cursor.getString(cursor.getColumnIndex("GMAIL"));
						
					mData.dGpsLA = cursor.getDouble(cursor.getColumnIndex("GPSLA"));
					mData.dGpsLO = cursor.getDouble(cursor.getColumnIndex("GPSLO"));
						
					mData.deptno = cursor.getString(cursor.getColumnIndex("DEPTNO"));
					mData.empid = cursor.getString(cursor.getColumnIndex("EMPID"));
					mData.dDiscount = cursor.getDouble(cursor.getColumnIndex("DISCOUNT"));
						
					mData.address = cursor.getString(cursor.getColumnIndex("ADDRESS"));
						
					mData.desc = cursor.getString(cursor.getColumnIndex("PS"));
					mData.bankno = cursor.getString(cursor.getColumnIndex("BANKNO"));
					mData.bankname = cursor.getString(cursor.getColumnIndex("BANKNAME"));
						
					mData.nCountry = cursor.getInt(cursor.getColumnIndex("COUNTRY"));
					mData.country = mCountryList.get(mData.nCountry - 1);
						
					mData.nTradetype = cursor.getInt(cursor.getColumnIndex("TRADETYPE"));
					mData.nState = cursor.getString(cursor.getColumnIndex("STATE"));
					mData.pic = cursor.getString(cursor.getColumnIndex("PIC"));
					edpic=cursor.getString(cursor.getColumnIndex("PIC"));
					
					mData.birtime = cursor.getString(cursor.getColumnIndex("BIRTHDAY"));
					mData.time = cursor.getString(cursor.getColumnIndex("CREATEDATETIME"));
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}
	
	public void getCountryData(Context context){
		if(mCountryIcon != null){
			mCountryIcon.clear();
		}
		if(mCountryList != null){
			mCountryList.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++){
						String pic = cursor.getString(cursor.getColumnIndex("PIC"));
						String name = cursor.getString(cursor.getColumnIndex("NAME"));
						mCountryId.add(cursor.getInt(cursor.getColumnIndex("_ID")));
						mCountryIcon.add(pic);
						mCountryList.add(name);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}
	
    private void eventImgCapture(int PHOTO) {
    	Toast.makeText(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, PHOTO);
		} catch (ActivityNotFoundException e) {
			// Do nothing for now
		} catch (Exception e){
		}
	}
	
	@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 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 eventImgFile(){
        Intent intent = new Intent(); 
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Picture"),PHOTOZOOM);
	}
}
