package com.cwbuyer.lib;

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.Calendar;
import java.util.LinkedList;
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.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.cwbuyer.code.CodeList;
import com.cwbuyer.code.CodeMode;
import com.cwbuyer.format.EMode;
import com.cwbuyer.format.IDateDialog;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.lib.DateUtil;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.main.QCustff;
import com.pwbuyer.main.R;

@SuppressLint("InflateParams")
public class AMacc<deptDataMacc> extends Activity{

	private static int nPicDegree =0;
	private final int ITEM_MACC = 1002;
	private final int CAPTURE = 1010;
	private final int TPICTURE = 1009;
	private final int RESULT_QEMPFF = 8888;		//交易員檔回傳口令
	private final int RESULT_QDEPTNO = 7777;  //門市檔回傳口令
	private int mMode = EMode.ADD; //0結算 1收支
	private int maddedit = 0; //0新增 1編輯
	private String aFORMDATE="";
	private String oFORMDATE="";
	private String aFORMNO="";
	private String oFORMNO="";
	private String aCTIME="";
	private String aDEPTNO="";  //門市代號
	private String oDEPTNO="";  //門市代號
	private String aDEPTNAME="";  //門市名稱
	@SuppressWarnings("unused")
	private String oDEPTNAME="";  //門市代號
	boolean sd=false;
	
	private int apart=0; //0總倉 1門市
	private int modify=0; //0查詢 1已修改
	private int mYear=1990;
	private int mMonth=11;
	private int mDay=9;

	private LinkedList<deptDataMacc> mDeptAccList = null;
	private String[] mAccDept;

	private int mSpinnerDept = 0; // 帳戶
	
	DatePicker dp1;
	//chkMacc(FORMDATE,FORMNO,DEPTNO,DEVISE,apart,addedit,mode){

	private static class deptDataMacc{
		public String dept_no="AA";
		public String dept_name="Compay";
	}
	
	public class MAccData {
		public String acc_tr;
		public int id=0;
		public String acc_qkind="80";
		public String acc_formno="";						//btn_fno
		public String acc_formdate="";					//btn_date
		public String acc_ctime="";	
		public String acc_utime="";
		public String acc_isconfirm="Y";
		public String acc_qatype="結算";				//btn_atype
		public String acc_qnom="0000";				//btn_anom
		public String acc_qnoi="";
		public String acc_ps="";								//edit_psmacc
		public double acc_mout=0;						//edit_mout
		public double acc_minto=0;						//edit_minto
		public double acc_mbefore=0;					//edit_before
		public double acc_mbalance=0;				//edit_balance
		public double acc_mbetween=0;				//edit_between
		public double acc_mafter=0;						//edit_after
		public String acc_deptno="AA";				//btn_deptno
		public String acc_deptname="/總公司";	//btn_deptname
		public String acc_devise="1";
		public String acc_atmno="";
		public String acc_atmname="";
		public String acc_atmdate="";
		public String acc_empid="A11";				//btn_empid
		public String acc_empname="A11";			//btn_empname
		public String acc_pic="drawable/icon";	//edpic
		public String acc_bankname=mBankn;	
	}
	private int rotationInDegrees=0;
	String edpic="drawable/icon";
	MAccData mData = null;
	
	//	0單機 1On_line 2.Off_line
	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	String mUid=Utilis.getIni(this, "SYS", "IMPORT", 2);  //ex:3g001
	private String[] deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");
	String mBankn=deptStr[0]+deptStr[1];
	String msFno=mBankn+"8"+DateUtil.getCurrentYearFormat1().substring(0, 2);
	
	ImageView OutPhoto = null;
	Uri mImageCaptureUri = null;
	private String mImagePath = null;
	
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR", 8);
	public final  String SAVE_FOLDER = filepath + File.separator;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		String OutPhotoURI;
		super.onActivityResult(requestCode, resultCode, data);
		
		switch (requestCode){
			case ITEM_MACC:
			{
				if (resultCode == RESULT_OK) {				
					mData.acc_qnom=data.getStringExtra("QNOM");
					mData.acc_qatype=data.getStringExtra("QNOM_TXT");
					((Button)findViewById(R.id.btn_anom)).setText(mData.acc_qnom);
					((Button)findViewById(R.id.btn_atype)).setText(mData.acc_qatype);
				}				

				break;
			}
			
			case RESULT_QEMPFF:
			{
				if (resultCode == RESULT_OK) {				
					String aKey=data.getStringExtra("qcust_key");
					if (!mData.acc_empid.equalsIgnoreCase(aKey)){
						SQLiteDatabase db = Utilis.getDB(AMacc.this);
						Cursor cs = db.rawQuery("select CUSTNO,CUSTNAME from qcust where CUSTNO='"+aKey+"' and TR='40'", null);
						if (cs.getCount()>0){
							cs.moveToFirst();
							mData.acc_empid=aKey;
							mData.acc_empname=cs.getString(1);
							modify=1;
							Toast.makeText(AMacc.this, aKey+"已成功更新櫃員", Toast.LENGTH_SHORT).show();
							((Button)findViewById(R.id.btn_empid)).setText(mData.acc_empid);
							((Button)findViewById(R.id.btn_empname)).setText(mData.acc_empname);
							
						}
						cs.close();
						db.close();
					}
				}
				break;
			}
			case RESULT_QDEPTNO:
			{
				if (resultCode == RESULT_OK) {				
					String aKey=data.getStringExtra("qcust_key");
					if (!mData.acc_empid.equalsIgnoreCase(aKey)){
						SQLiteDatabase db = Utilis.getDB(AMacc.this);
						Cursor cs = db.rawQuery("select CUSTNO,CUSTNAME from qcust where CUSTNO='"+aKey+"' and TR='20'", null);
						if (cs.getCount()>0){
							cs.moveToFirst();
							mData.acc_deptno=aKey;
							mData.acc_deptname=cs.getString(1);
							aDEPTNO=aKey;
							modify=1;
							Toast.makeText(AMacc.this, oDEPTNO+"已成功更新門市"+aKey, Toast.LENGTH_SHORT).show();
							((Button)findViewById(R.id.btn_deptno)).setText(mData.acc_deptno);
							((Button)findViewById(R.id.btn_deptname)).setText(mData.acc_deptname);
						}
						cs.close();
						db.close();
					}
				}
				break;
			}
			case CAPTURE:
			{
				if (resultCode == RESULT_OK) // 相本
				{
		 	    		edpic=filepath +File.separator+"AMacc_"+ String.valueOf(DateUtil.getSystemTime())+ ".jpg";
			    		
			    		Bitmap mBitmap=null;Bitmap bitmap=null;
			            Uri selectedImageUri = data.getData();
			            
			            if (Build.VERSION.SDK_INT < 19) {
			            	OutPhotoURI = getPath(selectedImageUri);
			            	mBitmap = Utilis.getScaleBitmap(OutPhotoURI, 210, 280);
							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 )
						{
							mImagePath = edpic;
							OutPhoto.setImageBitmap(mBitmap);
						}
				}
				break;
			}
			case TPICTURE:
			{
				 if (resultCode == RESULT_OK) // 照相
					{
						if (data != null) {
							try {
								Bundle extras = data.getExtras();
								if (extras != null) {
									OutPhotoURI = mImageCaptureUri.getPath();
									Bitmap bitmap=null;
									OutPhotoURI = mImageCaptureUri.getPath();
									bitmap = Utilis.getLimitBitmap(
									mImageCaptureUri.getPath(), 80,80);
									if (bitmap != null) {
										ExifInterface exif = new ExifInterface(OutPhotoURI);
										int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
										int rotationInDegrees = exifToDegrees(rotation);
										Matrix matrix = new Matrix();
										matrix.preRotate(rotationInDegrees);
										Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, 80, 80, matrix, true);
										mImagePath = OutPhotoURI;
										//OutPhoto.setScaleType(ScaleType.FIT_XY);
										OutPhoto.setImageBitmap(adjustedBitmap);
									}
								}
							} catch (Exception e) {

							}
						} else {
							try {
								OutPhotoURI = mImageCaptureUri.getPath();
								Bitmap bitmap = Utilis
										.getLimitBitmap(OutPhotoURI, 80, 80);
								if (bitmap != null) {
									Matrix matrix = new Matrix();
									ExifInterface exif = new ExifInterface(OutPhotoURI);
									int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
									int rotationInDegrees = exifToDegrees(rotation);
									
									matrix.preRotate(rotationInDegrees);
									Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
										mImagePath = OutPhotoURI;
										//OutPhoto.setScaleType(ScaleType.FIT_XY);
										OutPhoto.setImageBitmap(adjustedBitmap);
									ByteArrayOutputStream stream = new ByteArrayOutputStream();
									adjustedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// (0 - 100)压缩文件

							        FileOutputStream fos = null;
									try {
											fos = new FileOutputStream(mImagePath);
									} catch (FileNotFoundException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									
									try {
										adjustedBitmap.compress(CompressFormat.JPEG, 100, fos);
										fos.close();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							} catch (Exception e) {
							}
							
							try {
								OutPhotoURI = mImageCaptureUri.getPath();
								Bitmap bitmap = Utilis.getLimitBitmap(
										mImageCaptureUri.getPath(), 80, 80);
								if (bitmap != null) {
									mImagePath = OutPhotoURI;
									edpic=mImagePath;
									OutPhoto.setImageBitmap(bitmap);
								}
							} catch (Exception e) {
							}
						}
					}
				 break;
			}
		}
			
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fmacc);
		setTitle("收支結算");
		
		aFORMDATE = getIntent().getStringExtra("FORMDATE");
		aFORMNO = getIntent().getStringExtra("FORMNO");
		aDEPTNO=getIntent().getStringExtra("DEPTNO");
		aDEPTNAME=getIntent().getStringExtra("DEPTNAME");
		aCTIME=getIntent().getStringExtra("CTIME");
		apart=getIntent().getIntExtra("PART",0);
		maddedit = getIntent().getIntExtra("ADDEDIT", EMode.ADD);
		mMode = getIntent().getIntExtra("MODE", 0); //0結算 1支出

		OutPhoto = (ImageView)findViewById(R.id.imageV1);
		
		nPicDegree =Utilis.toInt(Utilis.getIni(this, "SYS", "BACKOUT", 8)); // 圖片旋轉角度預設
		//MAccData Ddata =new MAccData();
		if (mMode==0)//結算畫面
			((LinearLayout)findViewById(R.id.linearLayouti)).setVisibility(View.GONE);
		else	
			((LinearLayout)findViewById(R.id.linearLayoutm)).setVisibility(View.GONE);
		
		boolean iniData=false;
		if(maddedit == EMode.EDIT){//編輯 (是明確的)
			iniData = getData(aDEPTNO,aFORMDATE,aCTIME);
			if(iniData==false)	 finish();
			//收支 結算 共用
			((Button)findViewById(R.id.btn_fno)).setText(mData.acc_formno);
			((Button)findViewById(R.id.btn_date)).setText(mData.acc_formdate);
			((Button)findViewById(R.id.btn_atype)).setText(mData.acc_qatype);
			((Button)findViewById(R.id.btn_anom)).setText(mData.acc_qnom);
			((Button)findViewById(R.id.btn_deptno)).setText(mData.acc_deptno);
			((Button)findViewById(R.id.btn_deptname)).setText(mData.acc_deptname);
			((Button)findViewById(R.id.btn_empid)).setText(mData.acc_empid);
			((Button)findViewById(R.id.btn_empname)).setText(mData.acc_empname);
			((EditText)findViewById(R.id.edit_psmacc)).setText(mData.acc_ps);
			if (mMode!=0){	
				((Button)findViewById(R.id.ibtn_title)).setText("[收支] 登記表   [按我可以開錢櫃]");
				((Button)findViewById(R.id.btn_date)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_atype)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_anom)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_deptno)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_deptname)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_empid)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_empname)).setOnClickListener(new MenuClick());
				((EditText)findViewById(R.id.edit_out)).setText(""+mData.acc_mout);
				((EditText)findViewById(R.id.edit_into)).setText(""+mData.acc_minto);
				
				((EditText)findViewById(R.id.edit_out)).addTextChangedListener(watcherPrice);
				((EditText)findViewById(R.id.edit_into)).addTextChangedListener(watcherPrice);
			}else{
				
				((Button)findViewById(R.id.btn_date)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_atype)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_anom)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_deptno)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_deptname)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_empid)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_empname)).setOnClickListener(new MenuClick());
	
				((Button)findViewById(R.id.ibtn_title)).setText("[結算] 登記表   [按我可以開錢櫃]");
				((EditText)findViewById(R.id.edit_mout)).setText(""+mData.acc_mout);
				((EditText)findViewById(R.id.edit_minto)).setText(""+mData.acc_minto);
				((EditText)findViewById(R.id.edit_before)).setText(""+mData.acc_mbefore);
				((EditText)findViewById(R.id.edit_balance)).setText(""+mData.acc_mbalance);
				((EditText)findViewById(R.id.edit_between)).setText(""+mData.acc_mbetween);
				((EditText)findViewById(R.id.edit_after)).setText(""+mData.acc_mafter);
				
				((EditText)findViewById(R.id.edit_mout)).addTextChangedListener(watcherPrice);
				((EditText)findViewById(R.id.edit_minto)).addTextChangedListener(watcherPrice);
				((EditText)findViewById(R.id.edit_before)).addTextChangedListener(watcherPrice);
				((EditText)findViewById(R.id.edit_balance)).addTextChangedListener(watcherPrice);
				((EditText)findViewById(R.id.edit_between)).addTextChangedListener(watcherPrice);
			}            	
			OutPhoto.setImageDrawable(Utilis.getResourceImage(this, mData.acc_pic));
			OutPhoto.setOnClickListener(new MenuClick());
		
		} else {//新增 結算 或 收支表
			//如果為結算表 新增 務必 通過 [門市預設]總倉() 選擇門市
			//日期[預設今日] 選擇日期 確認
			//可以是 [[新增][編輯]][返回]
			if (mMode ==0){
				mDeptAccList = getDeptList.getDeptData(this);
				if (mDeptAccList.size() > 0) {
					mAccDept = new String[mDeptAccList.size()];
					for (int i = 0; i < mDeptAccList.size(); i++) {
						mAccDept[i] = mDeptAccList.get(i).dept_no+"/"+mDeptAccList.get(i).dept_name;
					}
					
				} else {
					mAccDept = new String[] { "無/無" };
				}
	
				chkDateDeptno();
			}else{
				iniHead();
			}
		}
				
				((Button)findViewById(R.id.ibtn_title)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_saveacc)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_exitacc)).setOnClickListener(new MenuClick());
				
	}
	
	
	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;    
	 }

	class MenuClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int id = v.getId();
			Utilis.runVibrate(AMacc.this);
			//門市異動
			//櫃員異動
			//日期異動
			//數值欄位異動 製作異動公式
			switch(id){
				case R.id.btn_atype:
				case R.id.btn_anom:
				{
					if (mMode!=0){
						Intent intent = new Intent();
						intent.setClass(AMacc.this, CodeList.class);
						intent.putExtra("code_mode", CodeMode.MACC);
						intent.putExtra("edit_mode", 1);
						AMacc.this.startActivityForResult(intent, ITEM_MACC);
					}
					break;
				}
				case R.id.btn_deptno:
				{
					//只有在 總倉 及 收支 才可以 選擇門市
					if (apart==0 && (mMode!=0 && maddedit == EMode.ADD)){
						Intent intent = new Intent();
						intent.putExtra("qcustf_qkind",20 ); //這是櫃員基本檔是為了交易員
						intent.putExtra("qcustf_mode", 0);
						intent.putExtra("qcustf_key", "");					
						intent.putExtra("pos_dept",Utilis.getIni(AMacc.this,"SYS","DEPT",6));					
						intent.setClass(AMacc.this, QCustff.class);
						
						startActivityForResult(intent, RESULT_QDEPTNO);
					}
					break;
				}
				case R.id.btn_deptname:
				{
					if (apart==0 && (mMode!=0 && maddedit == EMode.ADD)){
						Intent intent = new Intent();
						intent.putExtra("qcustf_qkind",20 ); //這是櫃員基本檔是為了交易員
						intent.putExtra("qcustf_mode", 0);
						intent.putExtra("qcustf_key", "");					
						intent.putExtra("pos_dept",Utilis.getIni(AMacc.this,"SYS","DEPT",6));					
						intent.setClass(AMacc.this, QCustff.class);
						
						startActivityForResult(intent, RESULT_QDEPTNO);
					}
					break;
				}
				case R.id.btn_empid:
				{
					Intent intent = new Intent();
					intent.putExtra("qcustf_qkind", 40); //這是櫃員基本檔是為了交易員
					intent.putExtra("qcustf_mode", 0);
					intent.putExtra("qcustf_key", "");					
					intent.putExtra("pos_dept",Utilis.getIni(AMacc.this,"SYS","DEPT",6));					
					intent.setClass(AMacc.this, QCustff.class);
					
					startActivityForResult(intent, RESULT_QEMPFF);
				
					break;
				}
				case R.id.btn_empname:
				{
					Intent intent = new Intent();
					intent.putExtra("qcustf_qkind", 40); //這是櫃員基本檔是為了交易員
					intent.putExtra("qcustf_mode", 0);
					intent.putExtra("qcustf_key", "");					
					intent.putExtra("pos_dept",Utilis.getIni(AMacc.this,"SYS","DEPT",6));					
					intent.setClass(AMacc.this, QCustff.class);
					
					startActivityForResult(intent, RESULT_QEMPFF);
				
					break;
				}
				case R.id.btn_date:
				{
					if (mMode!=0 && maddedit == EMode.ADD){
						mYear=Utilis.toInt(mData.acc_formdate.substring(0, 4));
						mMonth=Utilis.toInt(mData.acc_formdate.substring(5, 7));
						mDay=Utilis.toInt(mData.acc_formdate.substring(8, 10));
						Calendar c = Calendar.getInstance();
							c.set(Calendar.YEAR, mYear);
							c.set(Calendar.MONTH, mMonth - 1);
							c.set(Calendar.DAY_OF_MONTH, mDay);
							
							DateUtil.showDateDialog(AMacc.this, "請輸入正確交易日期", c, new IDateDialog(){
							@Override
							public void onDateDialogFinish(String date, int year, int month, int day) {
								if (!mData.acc_formdate.equalsIgnoreCase(date)){
									mData.acc_formdate=date;
									aFORMDATE=date;
									//但是 oFORMDATE不變
									modify=1;
					    			Toast.makeText(AMacc.this,oFORMDATE+"單據日期已改為:"+aFORMDATE, Toast.LENGTH_SHORT).show();				            		
									((Button)findViewById(R.id.btn_date)).setText(mData.acc_formdate);
									//@@@這時候在稍後存入時,update 的依據 還有 CTIME 可以使用
									//重要的是,需要修正兩個 結算表
								}
							}
						});
					} 					

					break;
				}
				case R.id.imageV1:
				{
					DialogUtilis.showDialog(AMacc.this, "請選擇以下功能", -1, new String[]{"拍照","相本"}, new IDialog(){
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch(pos){
								case 0: // 拍照
									eventImgCapture();
									break;
								case 1: // 相本
									eventImgFile();
									break;
							}
						}
					});
					break;
				}
				case R.id.ibtn_title:
					//可以強制打開錢櫃
					//但是需要徵詢是否收入支出 需要輸入
					//或強迫存入一筆 資料 [開櫃]
					 if (Utilis.toInt(Utilis.getIni(AMacc.this, "SYS","BAR_IP", 7))==9600 || Utilis.toInt(Utilis.getIni(AMacc.this, "SYS","BAR_IP", 7))==9100) 
						 Utilis.openCashDraw(AMacc.this);
					 else 
			    		Toast.makeText(AMacc.this, "電子錢櫃,尚未連結,無法開櫃", Toast.LENGTH_SHORT).show();
					
				break;
				case R.id.btn_saveacc:
						if (saveData()){
						modify=1;
			        	Intent intentS = new Intent();
			        	intentS.putExtra("QMacc_modify",modify);
			        	AMacc.this.setResult(RESULT_OK,intentS);
			        	finish();
						}else{
				    		Toast.makeText(AMacc.this, "好像收支類別,尚未輸入!!", Toast.LENGTH_SHORT).show();
						}
						
					break;
				case R.id.btn_exitacc:
					modify=1;
		        	Intent intentE = new Intent();
		        	intentE.putExtra("QMacc_modify",modify);
		        	AMacc.this.setResult(RESULT_CANCELED,intentE);
		        	finish();
					break;
			}
		}
	}
	
	public String getPath(Uri uri) {
        if( uri == null ) {
            return null;
        }
        String[] projection = { MediaStore.Images.Media.DATA };
        @SuppressWarnings("deprecation")
		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 TextWatcher watcherPrice = new TextWatcher(){  
        @Override  
        public void afterTextChanged(Editable s) {  
        }  
        @Override  
        public void beforeTextChanged(CharSequence s, int start, int count,  
                int after) {  
        }  
        @Override  
        public void onTextChanged(CharSequence s, int start, int before,  
                int count) {
        	
        if(mMode==0){	
        	mData.acc_mout=Utilis.toDouble(((EditText)findViewById(R.id.edit_mout)).getText().toString());
        	mData.acc_minto=Utilis.toDouble(((EditText)findViewById(R.id.edit_minto)).getText().toString());
        	mData.acc_mbefore=Utilis.toDouble(((EditText)findViewById(R.id.edit_before)).getText().toString());
        	mData.acc_mbalance=Utilis.toDouble(((EditText)findViewById(R.id.edit_balance)).getText().toString());
        	mData.acc_mbetween=Utilis.toDouble(((EditText)findViewById(R.id.edit_between)).getText().toString());
        	mData.acc_mafter=mData.acc_mbefore+mData.acc_mbetween+mData.acc_mbalance+mData.acc_minto-mData.acc_mout;
        	
        	((EditText)findViewById(R.id.edit_after)).setText(""+mData.acc_mafter);
			
    		Toast.makeText(AMacc.this, "結算表_運算成功"+mData.acc_mafter, Toast.LENGTH_SHORT).show();
        }else{
        	mData.acc_mout=Utilis.toDouble(((EditText)findViewById(R.id.edit_out)).getText().toString());
        	mData.acc_minto=Utilis.toDouble(((EditText)findViewById(R.id.edit_into)).getText().toString());
        	
    		Toast.makeText(AMacc.this, ""+mData.acc_mout+"收支表_運算成功"+mData.acc_minto, Toast.LENGTH_SHORT).show();
        }

        }  
    };

    public void chkDateDeptno(){
		new AlertDialog.Builder(AMacc.this).setTitle("請選擇要結算的日期&門市)")
		.setView(makeDateDialog())
		.setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	aFORMDATE = "" + mYear + "-" + Utilis.formatDate(mMonth) + "-" + Utilis.formatDate(mDay);
            	//檢查結算的日期門市不可存在,否則提示,不可以再新增 結算單
        		SQLiteDatabase db = Utilis.getDB(AMacc.this);
     			sd=true;
     			Cursor cs = db.rawQuery("select distinct FORMNO from qmacc where FORMDATE='"+aFORMDATE+"'  and DEPTNO='"+aDEPTNO+"' and QNOM='0000'",null); 
				if(cs.getCount() > 0){
					cs.moveToFirst();
					sd=false;
		    		Toast.makeText(AMacc.this, "結算日期及門市已存在,不可新增,請重新選擇...", Toast.LENGTH_SHORT).show();
				}
				cs.close();
				db.close();
				if (sd) iniHead(); else {
					modify=0;
		        	Intent intentS = new Intent();
		        	intentS.putExtra("QMacc_modify",modify);
		        	AMacc.this.setResult(RESULT_CANCELED,intentS);
		        	finish();
				}
            }
            }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
					modify=0;
		        	Intent intentS = new Intent();
		        	intentS.putExtra("QMacc_modify",modify);
		        	AMacc.this.setResult(RESULT_CANCELED,intentS);
		        	finish();
	            }
	          }).show();
    }


private View makeDateDialog() {
	//View view = LayoutInflater.from(this).inflate(R.layout.search_date_macc, null, false);
	final View view = this.getLayoutInflater().inflate(R.layout.search_date_macc, null);
	Calendar c = Calendar.getInstance();
		String FormD=DateUtil.getCurrentDate();  //2012-10-22
		int Ttime=Utilis.toInt(DateUtil.getSystemTime().substring(8, 10));  //取得目前幾點
	if (Ttime<=5)  FormD = DateUtil.addDate(FormD, -1);
	mYear=Utilis.toInt(FormD.substring(0, 4));
	mMonth=Utilis.toInt(FormD.substring(5, 7));
	mDay=Utilis.toInt(FormD.substring(8, 10));
		c.set(Calendar.YEAR, mYear);
		c.set(Calendar.MONTH, mMonth - 1);
		c.set(Calendar.DAY_OF_MONTH, mDay);
	
	mSpinnerDept = getDeptIndex(mDeptAccList,aDEPTNO+"/"+aDEPTNAME);
	ArrayAdapter<CharSequence> adapterAccount = new ArrayAdapter<CharSequence>(
			this, android.R.layout.simple_spinner_item, mAccDept);
	adapterAccount.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
	Spinner account = (Spinner)view.findViewById(R.id.spinnerDept);
	account.setAdapter(adapterAccount);
	account.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
		public void onItemSelected(@SuppressWarnings("rawtypes") AdapterView adapterView, View view,
				int position, long id) {
			mSpinnerDept = position;
			String datx[]=mAccDept[mSpinnerDept].split("/");
			aDEPTNO=datx[0];
			aDEPTNAME=datx[1];
		}

		@SuppressWarnings("rawtypes")
		public void onNothingSelected(AdapterView arg0) {
		}
	});
	account.setSelection(mSpinnerDept);

	
	dp1 = (DatePicker)view.findViewById(R.id.dp1_acc);
	dp1.init(mYear, mMonth - 1, mDay, new DatePicker.OnDateChangedListener() {
		@Override
		public void onDateChanged(DatePicker view, int year,
				int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;
			aFORMDATE=mYear+"-"+mMonth+"-"+mDay;
		}
		
	});
	
	return view;
}

 	private boolean iniHead(){ //新增一筆交易[結算表]或[收支表]
 		boolean success=true;
		//既然來了 一定帶來 日期 門市 單號 
 		//但有可能單號是空白 來判斷 真新增
 		//因為總倉可以來,改變門市,日期,
 		//如果是收支表,是可以直接新增
 		//
		mData = new MAccData();
		//常態欄位
		mData.acc_bankname=mBankn;
		
		mData.acc_deptno=aDEPTNO;
		oDEPTNO=aDEPTNO;

		mData.acc_deptname=aDEPTNAME;
		oDEPTNAME=aDEPTNAME;

		mData.acc_devise=deptStr[1];

		mData.acc_formno=aFORMNO;
		oFORMNO=aFORMNO;

		mData.acc_formdate=aFORMDATE;
		oFORMDATE=aFORMDATE;

		
 		if (mMode==0){//結算表
 			mData.acc_qnom="0000";
 			mData.acc_qatype="結算";
 		}else{//收支表
 			mData.acc_qnom="";
 			mData.acc_qatype="請按我收支類別";
 		} 			

 			
 			//明明是 新增
 			//帶入的aFORMDATE="預設日期",aDEPTNO="預設門市代號"
 			//應先檢查該單號,日期,門市 是否已存在 結算表
 			//如果aFORMNO="" 表示為新單
 			
 			//又分 結算表 或 收支表
 		
			SQLiteDatabase db = Utilis.getDB(AMacc.this);
	 			Cursor cs = null;
 			if (oFORMNO.length()<=0){
	 			int flowNumber = 0;
	 			try{
	 				cs = db.rawQuery("select distinct FORMNO from qmacc where FORMNO like '"+msFno+"%' order by FORMNO desc limit 1", null);
		 			
		 			if(cs.getCount() > 0){
		 				cs.moveToFirst();
		 				flowNumber = Utilis.toInt(cs.getString(0).substring(msFno.length()))+1;
		 			}else{
		 				flowNumber=1;
		 			}
		 			mData.acc_formno=msFno+Utilis.formatFlow(flowNumber);				
					aFORMNO=mData.acc_formno;
	 			//否則為預設
				}catch(Exception e){
					success=false;
					e.printStackTrace();
					cs.close();
					db.close();
					finish();
				}finally{
				}
 			}
		modify=1; //已異動

				oFORMDATE=aFORMDATE;
				mData.acc_formdate=aFORMDATE;
				
				mData.acc_ctime=DateUtil.getSystemTime().substring(2,14);
				aCTIME=mData.acc_ctime;
				mData.acc_isconfirm="Y";
				mData.acc_empid=Utilis.getIni(this,"INIH","EMPID",3); //預設櫃員代號
				mData.acc_empname=Utilis.getIni(this,"INIH","EMPNAME",3); //櫃員名稱
				
				((Button)findViewById(R.id.btn_fno)).setText(mData.acc_formno);
				((Button)findViewById(R.id.btn_date)).setText(mData.acc_formdate);
				((Button)findViewById(R.id.btn_atype)).setText(mData.acc_qatype);
				((Button)findViewById(R.id.btn_anom)).setText(mData.acc_qnom);
				((Button)findViewById(R.id.btn_deptno)).setText(mData.acc_deptno);
				((Button)findViewById(R.id.btn_deptname)).setText(mData.acc_deptname);
				((Button)findViewById(R.id.btn_empid)).setText(mData.acc_empid);
				((Button)findViewById(R.id.btn_empname)).setText(mData.acc_empname);

			if (mMode!=0){	
				((Button)findViewById(R.id.ibtn_title)).setText("[收支] 登記表   [按我可以開錢櫃]");
				((Button)findViewById(R.id.btn_date)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_atype)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_anom)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_deptno)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_deptname)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_empid)).setOnClickListener(new MenuClick());
				((Button)findViewById(R.id.btn_empname)).setOnClickListener(new MenuClick());
				((EditText)findViewById(R.id.edit_out)).setText(""+mData.acc_mout);
				((EditText)findViewById(R.id.edit_into)).setText(""+mData.acc_minto);
				
				((EditText)findViewById(R.id.edit_out)).addTextChangedListener(watcherPrice);
				((EditText)findViewById(R.id.edit_into)).addTextChangedListener(watcherPrice);
				
			}else{//結算單
				
				getQheadSums(db);
				//會異動 Mbetween PS
				getQmaccIO(db);
				//會異動 Minto
				
    			((Button)findViewById(R.id.btn_date)).setOnClickListener(new MenuClick());
    			((Button)findViewById(R.id.btn_atype)).setOnClickListener(new MenuClick());
    			((Button)findViewById(R.id.btn_anom)).setOnClickListener(new MenuClick());
    			((Button)findViewById(R.id.btn_deptno)).setOnClickListener(new MenuClick());
    			((Button)findViewById(R.id.btn_deptname)).setOnClickListener(new MenuClick());
    			((Button)findViewById(R.id.btn_empid)).setOnClickListener(new MenuClick());
    			((Button)findViewById(R.id.btn_empname)).setOnClickListener(new MenuClick());

				((Button)findViewById(R.id.ibtn_title)).setText("[結算] 登記表   [按我可以開錢櫃]");
				((EditText)findViewById(R.id.edit_mout)).setText(""+mData.acc_mout);
				((EditText)findViewById(R.id.edit_minto)).setText(""+mData.acc_minto);
				((EditText)findViewById(R.id.edit_before)).setText(""+mData.acc_mbefore);
				((EditText)findViewById(R.id.edit_balance)).setText(""+mData.acc_mbalance);
				((EditText)findViewById(R.id.edit_between)).setText(""+mData.acc_mbetween);
				((EditText)findViewById(R.id.edit_after)).setText(""+mData.acc_mafter);
				
				((EditText)findViewById(R.id.edit_mout)).addTextChangedListener(watcherPrice);
				((EditText)findViewById(R.id.edit_minto)).addTextChangedListener(watcherPrice);
				((EditText)findViewById(R.id.edit_before)).addTextChangedListener(watcherPrice);
				((EditText)findViewById(R.id.edit_balance)).addTextChangedListener(watcherPrice);
				((EditText)findViewById(R.id.edit_between)).addTextChangedListener(watcherPrice);
			}            	
			db.close();
			
			((EditText)findViewById(R.id.edit_psmacc)).setText(mData.acc_ps);
			OutPhoto.setImageDrawable(Utilis.getResourceImage(this, mData.acc_pic));
			OutPhoto.setOnClickListener(new MenuClick());
		return success;				
 	}


	public void getQheadSums(SQLiteDatabase db){
		StringBuffer bufCategory=new StringBuffer();
		bufCategory.append("select ") //每個單日的總件數,總實應收,總成本
		.append("sum(CASH),sum(ORDCASH),sum(CARD),sum(ORDCARD),sum(ATM),sum(TRCASH)")
		.append(" from qhead where DEPTNO='")
		.append(aDEPTNO+"' and TR<>'Y2'")
		.append(" and (ISCONFIRM ='Y' and ISCHECK='N' and FINEDATE = '")
		.append(aFORMDATE).append("') or  (ISCONFIRM ='N' and ISCHECK='Y' and ORDDATE='").append(aFORMDATE).append("')");
		
			Cursor cs = db.rawQuery(bufCategory.toString(), null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				mData.acc_ps="票刷:"+cs.getDouble(2)+" 預刷:"+cs.getDouble(3)+" 匯款: "+cs.getDouble(4)+" 代墊款: "+cs.getDouble(5);
				mData.acc_mbetween=(cs.getDouble(0)+cs.getDouble(1));//當日營業現金
				//因為是 新單 所以不要 存入 而是顯示 及 稍後一起確認 存入
			}
			cs.close();
	}
	
	public void getQmaccIO(SQLiteDatabase db){
		StringBuffer bufCategory=new StringBuffer();
		bufCategory.append("select ") 
		.append("sum(MINTO),sum(MOUT)")
		.append(" from "+TbName.QMACC+" where FORMDATE = '").append(aFORMDATE)
		.append("' and DEPTNO='"+aDEPTNO+"' and QNOM<>'0000' and TR<>'Y2'");
		
		Cursor cs = db.rawQuery(bufCategory.toString(), null);
		if (cs.getCount()>0){
			cs.moveToFirst();
			mData.acc_minto=cs.getDouble(0)-cs.getDouble(1);
			//複檢 是否上當日有收支
		}
		cs.close();
	}
 	
 	
 	
	@SuppressWarnings("unused")
	private boolean saveData(){
		boolean succed=true;
		if (mData.acc_qnom.length()<=0 ) return false;
		SQLiteDatabase db = Utilis.getDB(this);
		mData.acc_tr="0";
		mData.acc_bankname=mBankn;
        mData.acc_ps=((EditText)findViewById(R.id.edit_psmacc)).getText().toString();
		
		ContentValues value = new ContentValues();
		
	    	value.put("TR", "0");
	    	value.put("ID", mData.id);
	    	value.put("QKIND", mData.acc_qkind);
	    	value.put("FORMNO", mData.acc_formno);
	    	value.put("FORMDATE", mData.acc_formdate);
	    	value.put("CTIME", mData.acc_ctime);
	    	value.put("UTIME", mData.acc_ctime);
	    	value.put("ISCONFIRM", mData.acc_isconfirm);
	    	value.put("QATYPE", mData.acc_qatype);
	    	value.put("QNOM", mData.acc_qnom);
	    	value.put("QNOI", mData.acc_qnoi);
	    	value.put("PS", mData.acc_ps);
	    	value.put("MOUT", mData.acc_mout);
	    	value.put("MINTO", mData.acc_minto);
	    	value.put("MBEFORE", mData.acc_mbefore);
	    	value.put("MBALANCE", mData.acc_mbalance);
	    	value.put("MBETWEEN", mData.acc_mbetween);
	    	value.put("MAFTER", mData.acc_mafter);
	    	value.put("DEPTNO", mData.acc_deptno);
	    	value.put("DEPTNAME", mData.acc_deptname);
	    	value.put("DEVISE", mData.acc_devise);
	    	value.put("ATMNO", mData.acc_atmno);
	    	value.put("ATMNAME", mData.acc_atmname);
	    	value.put("ATMDATE", mData.acc_atmname);
	    	value.put("EMPID", mData.acc_empid);
	    	value.put("EMPNAME", mData.acc_empname);
	    	value.put("PIC", edpic);
	    	value.put("BANKNAME", mData.acc_bankname);

	    	int success=0;
			
    		if(maddedit == EMode.ADD){
		    	long result = db.insert(TbName.QMACC, null, value);
		    	if(result > 0){
		    		Toast.makeText(this, "存取資料成功", Toast.LENGTH_SHORT).show();
		    	}else{
		    		Toast.makeText(this, "存取資料失敗", Toast.LENGTH_SHORT).show();
		    		succed =false;
		    	}
	    	}else{  // EDIT
	    		if (mMode==0){
		    		String[] args = {aDEPTNO,aFORMDATE,aCTIME,"0000"};
		    		success = db.update(TbName.QMACC, value,
						"DEPTNO=? and FORMDATE=? and CTIME=? and QNOM=?", args);
	    		}else{
		    		String[] args = {aDEPTNO,aFORMDATE,aCTIME};
		    		success = db.update(TbName.QMACC, value,
						"DEPTNO=? and FORMDATE=? and CTIME=?", args);
	    		}
				if(success > 0){
					Toast.makeText(this, "修改資料成功", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(this, "修改資料失敗", Toast.LENGTH_SHORT).show();
		    		succed =false;
				}
	    	}
    		value.clear();
    		
			if(mMode!=0){
			//收支異動時 會連動 結算表也要更新
				Cursor cs = db.rawQuery("select * from "+TbName.QMACC+" where FORMDATE='"+aFORMDATE+"'  and DEPTNO='"+aDEPTNO+"' and QNOM='0000'",null); 
				if (cs.getCount()>0){
						//表示需運算 MAFTER
						Cursor csi=db.rawQuery("select sum(MINTO)-sum(MOUT) from "+TbName.QMACC+" where FORMDATE='"+aFORMDATE+"'  and DEPTNO='"+aDEPTNO+"' and QNOM<>'0000' and TR<>'Y2'",null);
						if (csi.getCount()>0){
							csi.moveToFirst();
							double dInto=csi.getDouble(0);
					    	value.put("TR", "0");
					    	value.put("MINTO", dInto);
					    	cs.moveToFirst();
							if (cs.getDouble(cs.getColumnIndex("MBETWEEN"))!=0 && cs.getDouble(cs.getColumnIndex("MOUT"))!=0){
								double dAfter=cs.getDouble(cs.getColumnIndex("MBEFORE"))+cs.getDouble(cs.getColumnIndex("MBETWEEN"))+dInto-cs.getDouble(cs.getColumnIndex("MOUT"))+cs.getDouble(cs.getColumnIndex("MBALANCE"));
						    	value.put("MAFTER", dAfter);
							}
				    		String[] args = {aDEPTNO,aFORMDATE,"0000"};
				    		success = db.update(TbName.QMACC, value,
								"DEPTNO=? and FORMDATE=? and QNOM=?", args);
						}
					
				}else{//結算表不存在,須新增一筆
					value.clear();
			    	value.put("TR", "0");
			    	value.put("ID", mData.id);
			    	value.put("QKIND", mData.acc_qkind);
			    	value.put("FORMNO", mData.acc_formno);
			    	value.put("FORMDATE", mData.acc_formdate);
			    	value.put("CTIME", (mData.acc_ctime+1));
			    	value.put("UTIME", (mData.acc_ctime));
			    	value.put("ISCONFIRM", mData.acc_isconfirm);
			    	value.put("QATYPE", "結算");
			    	value.put("QNOM", "0000");
			    	value.put("QNOI", mData.acc_qnoi);
			    	value.put("PS", "");
			    	value.put("MOUT", 0);
			    	value.put("MINTO", (mData.acc_minto-mData.acc_mout));
			    	value.put("MBEFORE", 0);
			    	value.put("MBALANCE", 0);
			    	value.put("MBETWEEN", 0);
			    	value.put("MAFTER", 0);
			    	value.put("DEPTNO", mData.acc_deptno);
			    	value.put("DEPTNAME", mData.acc_deptname);
			    	value.put("DEVISE", mData.acc_devise);
			    	value.put("ATMNO", mData.acc_atmno);
			    	value.put("ATMNAME", mData.acc_atmname);
			    	value.put("ATMDATE", mData.acc_atmname);
			    	value.put("EMPID", mData.acc_empid);
			    	value.put("EMPNAME", mData.acc_empname);
			    	value.put("PIC", "drawable/icon");
			    	value.put("BANKNAME", mData.acc_bankname);
			    	long result = db.insert(TbName.QMACC, null, value);
				}
			}
			if (of_line==1) DBCloud.aa1_aa0_update_qmacc(AMacc.this);
			
		db.close();
		return succed;
	}
	
	public boolean getData(String gDEPTNO,String gFORMDATE,String gCTIME){
		boolean success=false;
		SQLiteDatabase db = Utilis.getDB(this);
		Cursor cursor =null;
		if (mMode==0){//結算表
			cursor = db.rawQuery("select * from "+TbName.QMACC+" where CTIME='"+aCTIME+"' and DEPTNO='"+aDEPTNO+"' and FORMDATE='"+aFORMDATE+"' and QNOM='0000'", null);
		}else{//收支表
			cursor = db.rawQuery("select * from "+TbName.QMACC+" where CTIME='"+aCTIME+"' and DEPTNO='"+aDEPTNO+"' and FORMDATE='"+aFORMDATE+"' and QNOM<>'0000'", null);
		}
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
						mData = new MAccData();
						mData.acc_tr = cursor.getString(cursor.getColumnIndex("TR"));
						mData.id = cursor.getInt(cursor.getColumnIndex("ID"));
						mData.acc_qkind = cursor.getString(cursor.getColumnIndex("QKIND"));
						
						mData.acc_formno = cursor.getString(cursor.getColumnIndex("FORMNO"));
						aFORMNO=mData.acc_formno;
						oFORMNO=aFORMNO;

						mData.acc_formdate = cursor.getString(cursor.getColumnIndex("FORMDATE"));
						aFORMDATE=mData.acc_formdate;
						oFORMDATE=aFORMDATE;

						mData.acc_ctime = cursor.getString(cursor.getColumnIndex("CTIME"));
						aCTIME=mData.acc_ctime;

						mData.acc_utime = cursor.getString(cursor.getColumnIndex("UTIME"));
						mData.acc_isconfirm = cursor.getString(cursor.getColumnIndex("ISCONFIRM"));
						mData.acc_qatype = cursor.getString(cursor.getColumnIndex("QATYPE"));
						mData.acc_qnom = cursor.getString(cursor.getColumnIndex("QNOM"));
						mData.acc_qnoi = cursor.getString(cursor.getColumnIndex("QNOI"));
						mData.acc_ps = cursor.getString(cursor.getColumnIndex("PS"));
						mData.acc_mout = cursor.getDouble(cursor.getColumnIndex("MOUT"));
						mData.acc_minto = cursor.getDouble(cursor.getColumnIndex("MINTO"));
						mData.acc_mbefore = cursor.getDouble(cursor.getColumnIndex("MBEFORE"));
						mData.acc_mbalance = cursor.getDouble(cursor.getColumnIndex("MBALANCE"));
						mData.acc_mbetween = cursor.getDouble(cursor.getColumnIndex("MBETWEEN"));
						mData.acc_mafter = cursor.getDouble(cursor.getColumnIndex("MAFTER"));

						mData.acc_deptno = cursor.getString(cursor.getColumnIndex("DEPTNO"));
						aDEPTNO=mData.acc_deptno;
						oDEPTNO=aDEPTNO;
						mData.acc_deptname = cursor.getString(cursor.getColumnIndex("DEPTNAME"));
						aDEPTNAME=mData.acc_deptname;

						mData.acc_devise = cursor.getString(cursor.getColumnIndex("DEVISE"));
						mData.acc_atmno = cursor.getString(cursor.getColumnIndex("ATMNO"));
						mData.acc_atmname = cursor.getString(cursor.getColumnIndex("ATMNAME"));
						mData.acc_atmdate = cursor.getString(cursor.getColumnIndex("ATMDATE"));
						mData.acc_empid = cursor.getString(cursor.getColumnIndex("EMPID"));
						mData.acc_empname = cursor.getString(cursor.getColumnIndex("EMPNAME"));
						mData.acc_pic = cursor.getString(cursor.getColumnIndex("PIC"));
						edpic=mData.acc_pic;				
						mData.acc_bankname = cursor.getString(cursor.getColumnIndex("BANKNAME"));
						modify=0;
						if(mMode==0){
							getQheadSums(db);
							//會異動 Mbetween PS
							getQmaccIO(db);
							//會異動 Minto
						}
						success=true;
					}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				cursor.close();
			}
		}
		db.close();
		cursor.close();
		return success;
	}
	
    private void eventImgCapture() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// Wysie_Soh: Create path for temp file
		File folder = new File( SAVE_FOLDER );
		if(folder.exists() == false){
			folder.mkdirs();
		}
		File file = new File(SAVE_FOLDER ,"AMacc_" + String.valueOf(System.currentTimeMillis())+ ".jpg");
		
		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, TPICTURE);
		} 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"),CAPTURE);
	}
	
	// Spinner 使用
	public static int getDeptIndex(LinkedList<deptDataMacc> list, String nDeptno){
		boolean bFind = false;
		int index = 0;
		try{
			for(int i = 0; i < list.size() && bFind == false; i++){
				if(list.get(i).dept_no == nDeptno){
					index = i;
					bFind = true;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return index;
	}
	
	
	private static class getDeptList{
		
		private static LinkedList<deptDataMacc> getDeptData(Context context){
			LinkedList<deptDataMacc> list = new LinkedList<deptDataMacc>();
			
			SQLiteDatabase db = Utilis.getDB(context);
			if(db != null){
				Cursor cursor = db.rawQuery("select CUSTNO,CUSTNAME from " + TbName.QCUST + " where TR='20' and STATE<>'2' order by CUSTNO", null);
				try{
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						for(int i = 0; i < cursor.getCount(); i++){
							deptDataMacc data = new deptDataMacc();
							data.dept_no=cursor.getString(0);
							data.dept_name=cursor.getString(1);
							list.add(data);
							
							cursor.moveToNext();
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					cursor.close();
				}
			}
			 db.close();
			return list;
		}
	}
	
}
