package BWP.MobileSale.Approval;

import org.forks.jsonrpc.RpcFacade;
import org.forks.jsonrpc.RpcObject;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import BWP.MobileSale.LoginedActivity;
import BWP.MobileSale.MainActivity;
import BWP.MobileSale.R;
import BWP.MobileSale.Utils;
import BWP.MobileSale.Util.ActivityUtil;
import BWP.MobileSale.Util.CallableTask;
import BWP.MobileSale.Util.DialogUtil;
import BWP.MobileSale.Util.ViewOnClickTask;

public class ApprovalEditActivity extends LoginedActivity implements
		OnGestureListener {
	private GestureDetector detector;
	private ViewFlipper flipper;

	private View currentView;

	static final int RequestCode_Open = 99; // 打开单据

	private long mBillID;
	private long mNextEnableApproveBillID;
	private RpcObject mDmo;

	private boolean mEnableApprove = true;

	private TextView textViewOpinion;
	private TextView textViewApprovalContents;
	private TextView textViewApprovalRecord;

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		detector.onTouchEvent(ev);
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// Log.i("Fling", "Activity onTouchEvent!");
		return this.detector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * 监听滑动
	 */
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		// Log.i("Fling", "Fling Happened!");
		if (e1.getX() - e2.getX() > 120) {// 左滑
			this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_left_in));
			this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_left_out));
			this.flipper.showNext();
			Utils.ActivityUtil.Go(ApprovalEditActivity.this, MainActivity.class);
			finish();
			return true;
		} else if (e1.getX() - e2.getX() < -120) {// 右滑
			this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_right_in));
			this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_right_out));
			this.flipper.showPrevious();
			Utils.ActivityUtil.Go(ApprovalEditActivity.this, ApprovalListActivity.class);
			finish();
			return true;
		}
		return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	private void applyToUI() {
		if (mDmo == null) {
			DialogUtil.Alert(ApprovalEditActivity.this, "当前可编辑的对象为空");
			finish();
			return;
		}

		if (mBillID > 0) {
			this.setTitle(String.format("%s-签呈单No.%s(%s)",
					getString(R.string.app_name), mBillID,
					mDmo.getNamedValue("BillState")));
		}

		textViewOpinion.setText("");
		textViewApprovalContents.setText(mDmo.getString("ApprovalContents"));
		textViewApprovalRecord.setText(mDmo.getString("ApprovalRecord"));

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.approval_edit_flipper);

		View listView = LayoutInflater.from(this).inflate(
				R.layout.approval_list, null);
		currentView = LayoutInflater.from(this).inflate(R.layout.approval_edit,
				null);
		LinearLayout mayLayout = GetVLayoutWithBackgroud();
//		View mainView = new MainActivity().mainLayout();
		// View mainView = LayoutInflater.from(this).inflate(R.layout.main,
		// null);

		flipper = (ViewFlipper) this.findViewById(R.id.ViewFlipper1);
		flipper.addView(listView);
		flipper.addView(currentView);
		flipper.addView(mayLayout);
		flipper.showNext();
		detector = new GestureDetector(this);

		Intent intent = getIntent();
		mBillID = intent.getLongExtra("ID", 0);

		initBillTask.execute();

	}

	private LinearLayout GetVLayoutWithBackgroud(){
		LinearLayout vLayout=new LinearLayout(ApprovalEditActivity.this);
		vLayout.setOrientation(LinearLayout.VERTICAL);
		vLayout.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT));
		vLayout.setBackgroundResource(R.drawable.bg2);
		return vLayout;
	}
	
	private void initControls() {
		InitButtonAgree();
		InitButtonReject();
		InitOpinion();

		InitApprovalContents();
		InitApprovalRecord();

	}

	private void InitButtonAgree() {
		if (!mEnableApprove)
			return;

		Button buttonAgree = ActivityUtil.Find(this, R.id.ApprovalButton_Agree);
		buttonAgree.setOnClickListener(agreeTask);
	}

	private void InitButtonReject() {
		if (!mEnableApprove)
			return;

		Button buttonList = ActivityUtil.Find(this, R.id.ApprovalButton_Reject);
		buttonList.setOnClickListener(rejectTask);
	}

	private void InitOpinion() {
		textViewOpinion = ActivityUtil
				.Find(this, R.id.ApprovalEditText_Opinion);
		if (!mEnableApprove) {
			textViewOpinion.setVisibility(View.GONE);
		}
	}

	private void InitApprovalContents() {
		textViewApprovalContents = ActivityUtil.Find(this,
				R.id.ApprovalextView_ApprovalContents);
	}

	private void InitApprovalRecord() {
		textViewApprovalRecord = ActivityUtil.Find(this,
				R.id.ApprovalTextView_ApprovalRecord);
	}

	CallableTask initBillTask = new CallableTask(this, "读取单据中...") {
		public Object call() throws Exception {
			if (mBillID > 0) {
				String method = "/Breed/Approval/Rpcs/MobileApprovalRpc/Load";
				mDmo = RpcFacade.rpcCall(method, mBillID);

				method = "/Breed/Approval/Rpcs/MobileApprovalRpc/EnableApprove";
				mEnableApprove = RpcFacade.rpcCall(method);

			} else {
				mDmo = RpcObject.create("/Breed/Approval/BO/SignSubmit");
			}
			return null;
		}

		@Override
		protected void successUI() {
			initControls();
			applyToUI();
		}

	};

	ViewOnClickTask agreeTask = new ViewOnClickTask(this, "审批中...") {
		public Object call() throws Exception {
			String opinion = textViewOpinion.getText().toString();
			String method = "/Breed/Approval/Rpcs/MobileApprovalRpc/ApproveAndGetNextID";
			mNextEnableApproveBillID = RpcFacade.rpcCall(method, mBillID, opinion);
			return null;
		}

		@Override
		protected void successUI() {
			DialogUtil.AutoHiddenAlert(ApprovalEditActivity.this, "审批成功");
			finish();
			Intent intent = new Intent();
			if (mNextEnableApproveBillID > 0) {
				intent.putExtra("ID", mNextEnableApproveBillID);
				intent.setClass(ApprovalEditActivity.this,
						ApprovalEditActivity.class);
				startActivityIfNeeded(intent,
						ApprovalEditActivity.RequestCode_Open);
			} else {
				// TODO:
			}

		}
	};

	ViewOnClickTask rejectTask = new ViewOnClickTask(this, "驳回中...") {
		public Object call() throws Exception {
			String opinion = textViewOpinion.getText().toString();
			String method = "/Breed/Approval/Rpcs/MobileApprovalRpc/RejectAndGetNextID";
			mNextEnableApproveBillID = RpcFacade.rpcCall(method, mBillID, opinion);
			return null;
		}

		@Override
		protected void successUI() {
			DialogUtil.AutoHiddenAlert(ApprovalEditActivity.this, "驳回成功");
			finish();
			Intent intent = new Intent();
			if (mNextEnableApproveBillID > 0) {
				intent.putExtra("ID", mNextEnableApproveBillID);
				intent.setClass(ApprovalEditActivity.this,
						ApprovalEditActivity.class);
				startActivityIfNeeded(intent,
						ApprovalEditActivity.RequestCode_Open);
			} else {
				// TODO:
			}

		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			DialogUtil.Confirm(this, "您按了返回按钮,是否返回?", "是", "否",
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}

					});
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

}
