package BWP.MobileSale.BranchOrder;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

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

import BWP.MobileSale.LoginedActivity;
import BWP.MobileSale.R;
import BWP.MobileSale.Util.CallableTask;
import BWP.MobileSale.Util.DateTimeUtil;
import BWP.MobileSale.Util.DialogUtil;
import BWP.MobileSale.Util.StringUtil;
import BWP.MobileSale.Util.ViewOnClickTask;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class BranchOrderEditActivity extends LoginedActivity {

	long mBillId;
	private RpcObject mDmo;
	private BigDecimal loadShijiFaHuo = BigDecimal.ZERO;
	private BigDecimal loadBenRiXiaoShou = BigDecimal.ZERO;
	private BigDecimal loadSunHao = BigDecimal.ZERO;
	static final int RequestCode_Open = 3; // 打开单据
	boolean isUnCheck = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.branchorder_edit);
		Intent intent = getIntent();
		mBillId = intent.getLongExtra("ID", 0);
		initBillTask.execute();
	}

	CallableTask initBillTask = new CallableTask(this, "读取数据中...") {

		@Override
		public Object call() throws Exception {
			if (mBillId > 0) {
				String method = "/Sale/BranchOrder/Rpcs/MobileBranchOrderRpc/Load";
				mDmo = RpcFacade.rpcCall(method, mBillId);
				isUnCheck = mDmo.getNamedValue("BillState").getValue() == 0;

			} else {
				DialogUtil.AlertAndFinish(BranchOrderEditActivity.this,
						"没有传入单据号");
			}

			return null;
		}

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

	};

	private void setVisibility() {

		if (isUnCheck) {
			return;
		}
		btnSave.setVisibility(View.GONE);

	}

	Button btnSave, btnReturn;
	TextView tvBuyername, tvDeptname, tvBilldate, tvTodaymoney, tvLeftmoney;
	TextView tvSunhaolv, tvSunhao, tvShijifahuo, tvTodaysale,
			tvYestodayleftmoney, tvloadBoxNumber, remainMoney;

	EditText etTiaohuo, etYinhangshuaka, etTihuojuan, etFanli, etJiesuandan,
			etXianjin, etBenrijine, etZhidanren, etZhaiyao, etChuzhika,
			etchangkuan, youhuijuan, huiyuanka, returnBoxNumber,
			emptyBoxNumber;
	EditText etWx, etZfb, etDzdp, etNuomi, etShoukuanka;
	EditText etChangduan, etMeituanWaimai, etBaiduWaimai, etEleme;
	private void initControls() {

		initTextView();
		initEditText();

		btnReturn = (Button) findViewById(R.id.branchorder_btnreturn);
		btnReturn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		btnSave = (Button) findViewById(R.id.branchorder_btnsave);
		btnSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					getFromUi();
					saveTask.execute();

				} catch (Exception e) {
					DialogUtil.Alert(BranchOrderEditActivity.this,
							e.getLocalizedMessage());
				}

			}
		});

	}

	ViewOnClickTask saveTask = new ViewOnClickTask(this, "保存中...") {
		public Object call() throws Exception {

			if (mBillId > 0) {
				String method = "/Sale/BranchOrder/Rpcs/MobileBranchOrderRpc/Update";
				RpcFacade.rpcCall(method, mDmo);
			}
			return null;
		}

		@Override
		protected void successUI() {
			DialogUtil.AutoHiddenAlert(BranchOrderEditActivity.this, "保存成功");
			finish();
			Intent intent = new Intent();
			intent.putExtra("ID", mBillId);
			intent.setClass(BranchOrderEditActivity.this,
					BranchOrderEditActivity.class);
			startActivityIfNeeded(intent,
					BranchOrderEditActivity.RequestCode_Open);
		}

	};

	private BigDecimal getDecimalValue(TextView view) {
		if (StringUtil.IsNullOrEmpty(view.getText().toString())) {
			return BigDecimal.ZERO;
		} else {
			return new BigDecimal(view.getText().toString());
		}

	}

	private BigDecimal getDecimalValue(EditText view) {

		if (StringUtil.IsNullOrEmpty(view.getText().toString())) {
			return BigDecimal.ZERO;
		} else {
			return new BigDecimal(view.getText().toString());
		}

	}

	private void getFromUi() {
		// 实际发货
		mDmo.setMoney("RealityLoadMoney", getDecimalValue(tvShijifahuo));

		// 损耗
		mDmo.setMoney("LossMoney", getDecimalValue(tvSunhao));

		// 本日销售
		mDmo.setMoney("TodaySaleMoney", getDecimalValue(tvTodaysale));

		// 调货
		mDmo.setMoney("AdjustMoney", getDecimalValue(etTiaohuo));

		// 银行刷卡
		mDmo.setMoney("BankCard", getDecimalValue(etYinhangshuaka));

		// 提货券
		mDmo.setMoney("GetGoodsTicket", getDecimalValue(etTihuojuan));

		// 返利
		mDmo.setMoney("ReturnMoney", getDecimalValue(etFanli));

		// 结算单
		mDmo.setMoney("StatPayMoney", getDecimalValue(etJiesuandan));

		// 现金
		mDmo.setMoney("ReadyMoney", getDecimalValue(etXianjin));
		mDmo.setMoney("WxMoney", getDecimalValue(etWx));
		mDmo.setMoney("ZfbMoney", getDecimalValue(etZfb));
		mDmo.setMoney("DzdpMoney", getDecimalValue(etDzdp));

		mDmo.setMoney("Nuomi", getDecimalValue(etNuomi));
		mDmo.setMoney("Shoukuanka", getDecimalValue(etShoukuanka));
		mDmo.setMoney("Changduan", getDecimalValue(etChangduan));		
		mDmo.setMoney("MeituanWaimai", getDecimalValue(etMeituanWaimai));
		mDmo.setMoney("BaiduWaimai", getDecimalValue(etBaiduWaimai));
		mDmo.setMoney("Eleme", getDecimalValue(etEleme));			
		// 本日余额
		mDmo.setMoney("TodayLeftMoney", getDecimalValue(etBenrijine));

		// 储值卡
		mDmo.setMoney("MoneyCard", getDecimalValue(etChuzhika));

		// 长款
		mDmo.setMoney("LongMoney", getDecimalValue(etchangkuan));

		// 会员卡
		mDmo.setMoney("MembershipCard", getDecimalValue(huiyuanka));

		// 优惠券
		mDmo.setMoney("Coupons", getDecimalValue(youhuijuan));

		// 空箱数
		mDmo.setMoney("EmptyBoxNumber", getDecimalValue(emptyBoxNumber));

		// 发货箱数
		mDmo.setMoney("LoadBoxNumber", getDecimalValue(tvloadBoxNumber));

		// 留货金额
		mDmo.setMoney("RemainGoodsMoney", getDecimalValue(remainMoney));

		// 退货箱数
		mDmo.setMoney("ReturnBoxNumber", getDecimalValue(returnBoxNumber));

		// 制单人
		mDmo.setString("CreateBillUser", etZhidanren.getText().toString());

		// 摘要
		mDmo.setString("Remark", etZhaiyao.getText().toString());

	}

	private void initTextView() {
		tvBuyername = (TextView) findViewById(R.id.branchorder_buyername);
		tvDeptname = (TextView) findViewById(R.id.branchorder_deptname);
		tvBilldate = (TextView) findViewById(R.id.branchorder_billdate);
		// tvYesterdaymoney = (TextView)
		// findViewById(R.id.branchorder_yesterdaymoney);// 昨日余额
		tvTodaymoney = (TextView) findViewById(R.id.branchorder_todaymoney);// 本日发货
		tvLeftmoney = (TextView) findViewById(R.id.branchorder_leftmoney);// 摊点剩货
		tvSunhaolv = (TextView) findViewById(R.id.branchorder_sunhaolv);
		tvSunhao = (TextView) findViewById(R.id.branchorder_sunhao);
		tvShijifahuo = (TextView) findViewById(R.id.branchorder_shijifahuo);
		tvTodaysale = (TextView) findViewById(R.id.branchorder_todaysale);
		tvYestodayleftmoney = (TextView) findViewById(R.id.branchorder_yestodayleftmoney);// 昨日余额
		tvloadBoxNumber = (TextView) findViewById(R.id.branchorder_edit_LoadBoxNumber);
		remainMoney = (TextView) findViewById(R.id.branchorder_edit_RemainMoney);
	}

	private void initEditText() {
		etTiaohuo = (EditText) findViewById(R.id.branchorder_edit_tiaohuo);
		if (!mDmo.getBoolean("IsOrNotEditAdjustMoney")) {
			etTiaohuo.setEnabled(false);
		} else {
			etTiaohuo.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					// System.out.println("onTextChanged---s="+s+"-start="+start+"-before="+before+"-count="+count);
					if (etTiaohuo.hasFocus()) {
						try {
							if (s == null
									|| StringUtil.IsNullOrEmpty(s.toString())
									|| s.toString().equals("-")
									|| s.toString().equals("+")) {
								if (loadShijiFaHuo != BigDecimal.ZERO) {
									tvShijifahuo.setText(loadShijiFaHuo
											.toString());
								}
								if (loadSunHao != BigDecimal.ZERO) {
									tvSunhao.setText(loadSunHao.toString());
								}
								if (loadBenRiXiaoShou != BigDecimal.ZERO) {
									tvTodaysale.setText(loadBenRiXiaoShou
											.toString());
								}
								return;
							}

							BigDecimal 本日发货 = BigDecimal.ZERO;
							if (!StringUtil.IsNullOrEmpty(tvTodaymoney
									.getText().toString())) {
								本日发货 = new BigDecimal((String) tvTodaymoney
										.getText()).setScale(2,
										BigDecimal.ROUND_HALF_UP);
							}

							BigDecimal 昨日余额 = BigDecimal.ZERO;
							if (!StringUtil.IsNullOrEmpty(tvYestodayleftmoney
									.getText().toString())) {
								昨日余额 = new BigDecimal(
										(String) tvYestodayleftmoney.getText())
										.setScale(2, BigDecimal.ROUND_HALF_UP);
							}

							BigDecimal 实际发货 = new BigDecimal(s.toString())
									.add(昨日余额).add(本日发货)
									.setScale(2, BigDecimal.ROUND_HALF_UP);

							// 实际发货
							tvShijifahuo.setText(""
									+ 实际发货.setScale(2, BigDecimal.ROUND_HALF_UP));
							// 损耗
							BigDecimal 损耗 = BigDecimal.ZERO;
							if (!StringUtil.IsNullOrEmpty(tvSunhaolv.getText()
									.toString())) {
								损耗 = (new BigDecimal(tvTodaymoney.getText()
										.toString()).add(new BigDecimal(
										etTiaohuo.getText().toString())))
										.multiply(new BigDecimal(tvSunhaolv
												.getText().toString()));
								;
								tvSunhao.setText(损耗.setScale(2,
										BigDecimal.ROUND_HALF_UP).toString());
							}
							// 本日销售
							BigDecimal 摊点剩货 = BigDecimal.ZERO;
							if (!StringUtil.IsNullOrEmpty(tvLeftmoney.getText()
									.toString())) {
								摊点剩货 = new BigDecimal(tvLeftmoney.getText()
										.toString());
							}
							BigDecimal 本日库存额 = BigDecimal.ZERO;
							if (!StringUtil.IsNullOrEmpty(etBenrijine.getText()
									.toString())) {
								本日库存额 = new BigDecimal(etBenrijine.getText()
										.toString());
							}
							BigDecimal 本日销售 = 实际发货
									.subtract(摊点剩货)
									.subtract(
											损耗.setScale(2,
													BigDecimal.ROUND_HALF_UP))
									.subtract(本日库存额);
							tvTodaysale.setText(本日销售.setScale(2,
									BigDecimal.ROUND_HALF_UP).toString());

						} catch (Exception e) {
							DialogUtil.Alert(BranchOrderEditActivity.this,
									e.getMessage());
						}
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					// System.out.println("beforeTextChanged---s="+s+"-start="+start+"-after="+after+"-count="+count);
				}

				@Override
				public void afterTextChanged(Editable s) {
					// System.out.println("afterTextChanged---s="+s);
				}
			});
		}
		etYinhangshuaka = (EditText) findViewById(R.id.branchorder_edit_yinhangshuaka);
		etTihuojuan = (EditText) findViewById(R.id.branchorder_edit_tihuojuan);
		etFanli = (EditText) findViewById(R.id.branchorder_edit_fanli);
		etJiesuandan = (EditText) findViewById(R.id.branchorder_edit_jiesuandan);
		etXianjin = (EditText) findViewById(R.id.branchorder_edit_xianjin);
		etDzdp = (EditText) findViewById(R.id.branchorder_edit_dzdp);	
		etWx = (EditText) findViewById(R.id.branchorder_edit_wx);
		etZfb = (EditText) findViewById(R.id.branchorder_edit_zfb);			

		etNuomi = (EditText) findViewById(R.id.branchorder_edit_Nuomi);	
		etShoukuanka = (EditText) findViewById(R.id.branchorder_edit_Shoukuanka);
		etChangduan = (EditText) findViewById(R.id.branchorder_edit_Changduan);			
		etMeituanWaimai = (EditText) findViewById(R.id.branchorder_edit_MeituanWaimai);	
		etBaiduWaimai = (EditText) findViewById(R.id.branchorder_edit_BaiduWaimai);
		etEleme = (EditText) findViewById(R.id.branchorder_edit_Eleme);	
		
		if (!mDmo.getBoolean("CanEditNuomi")) {
			etNuomi.setEnabled(false);
		}
		if (!mDmo.getBoolean("CanEditShoukuanka")) {
			etShoukuanka.setEnabled(false);
		}
		if (!mDmo.getBoolean("CanEditChangduan")) {
			etChangduan.setEnabled(false);
		}
		if (!mDmo.getBoolean("CanEditMeituanWaimai")) {
			etMeituanWaimai.setEnabled(false);
		}
		if (!mDmo.getBoolean("CanEditBaiduWaimai")) {
			etBaiduWaimai.setEnabled(false);
		}
		if (!mDmo.getBoolean("CanEditEleme")) {
			etEleme.setEnabled(false);
		}
		
		if (!mDmo.getBoolean("CanEditReadyMoney")) {
			etXianjin.setEnabled(false);
		}		
		if (!mDmo.getBoolean("CanEditWxMoney")) {
			etWx.setEnabled(false);
		}		
		if (!mDmo.getBoolean("CanEditZfbMoney")) {
			etZfb.setEnabled(false);
		}		
		if (!mDmo.getBoolean("CanEditDzdpMoney")) {
			etDzdp.setEnabled(false);
		}		
		if (!mDmo.getBoolean("CanEditBankCard")) {
			etYinhangshuaka.setEnabled(false);
		}		
		if (!mDmo.getBoolean("CanEditGetGoodsTicket")) {
			etTihuojuan.setEnabled(false);
		}		
 
		etBenrijine = (EditText) findViewById(R.id.branchorder_edit_benrijine);
		if (!mDmo.getBoolean("IsOrNotEditTodayLeftMoney")) {
			etBenrijine.setEnabled(false);
		}
		etZhidanren = (EditText) findViewById(R.id.branchorder_edit_zhidanren);
		etZhaiyao = (EditText) findViewById(R.id.branchorder_edit_zhaiyao);
		etChuzhika = (EditText) findViewById(R.id.branchorder_edit_chuzhika);
		etchangkuan = (EditText) findViewById(R.id.branchorder_edit_changkuan);
		huiyuanka = (EditText) findViewById(R.id.branchorder_edit_huiyuanka);
		youhuijuan = (EditText) findViewById(R.id.branchorder_edit_youhuijuan);
		returnBoxNumber = (EditText) findViewById(R.id.ranchorder_edit_ReturnBoxNumber);
		emptyBoxNumber = (EditText) findViewById(R.id.branchorder_edit_EmptyBoxNumber);
		
		if (!mDmo.getBoolean("CanEditMoneyCard")) {
			etChuzhika.setEnabled(false);
		}		
		if (!mDmo.getBoolean("CanEditLongMoney")) {
			etchangkuan.setEnabled(false);
		}		
		if (!mDmo.getBoolean("CanEditMembershipCard")) {
			huiyuanka.setEnabled(false);
		}

		if (!mDmo.getBoolean("CanEditCoupons")) {
			youhuijuan.setEnabled(false);
		}
		
		
		
	}

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

		this.setTitle(String.format("门店日结No.%s", mBillId));
		tvBuyername.setText(mDmo.getString("Buyer_Name"));
		tvDeptname.setText(mDmo.getString("Dept_Name"));
		// tvBilldate.setText(DateTimeUtil.FormatDate(mDmo.getDate("BillDate")));

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(mDmo.getDate("BillDate"));
		calendar.add(Calendar.DATE, 0);
		try {
			Date date = DateTimeUtil.ParseDate(DateTimeUtil
					.FormatDate(calendar));
			tvBilldate.setText(DateTimeUtil.FormatDate(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		if (mDmo.getMoney("TodayLoadMoney") != null) {
			tvTodaymoney.setText(mDmo.getMoney("TodayLoadMoney").toString());
		}
		if (mDmo.getMoney("LeftMoney") != null) {
			tvLeftmoney.setText(mDmo.getMoney("LeftMoney").toString());
		}

		if (mDmo.getDecimal("LossRate") != null) {
			tvSunhaolv.setText(mDmo.getDecimal("LossRate").toString());
		}
		if (mDmo.getMoney("LossMoney") != null) {
			tvSunhao.setText(mDmo.getMoney("LossMoney").toString());
			loadSunHao = mDmo.getMoney("LossMoney");
		}
		if (mDmo.getMoney("RealityLoadMoney") != null) {
			tvShijifahuo.setText(mDmo.getMoney("RealityLoadMoney").toString());
			loadShijiFaHuo = mDmo.getMoney("RealityLoadMoney");
		}
		if (mDmo.getMoney("TodaySaleMoney") != null) {
			tvTodaysale.setText(mDmo.getMoney("TodaySaleMoney").toString());
			loadBenRiXiaoShou = mDmo.getMoney("TodaySaleMoney");

		}
 
		if (mDmo.getMoney("YesterdayLeftMoney") != null) {
			tvYestodayleftmoney.setText(mDmo.getMoney("YesterdayLeftMoney")
					.toString());
		}

		if (mDmo.getMoney("AdjustMoney") != null) {
			etTiaohuo.setText(mDmo.getMoney("AdjustMoney").toString());
		}
		if (mDmo.getMoney("BankCard") != null) {
			etYinhangshuaka.setText(mDmo.getMoney("BankCard").toString());
		}
		if (mDmo.getMoney("GetGoodsTicket") != null) {
			etTihuojuan.setText(mDmo.getMoney("GetGoodsTicket").toString());
		}
		if (mDmo.getMoney("ReturnMoney") != null) {
			etFanli.setText(mDmo.getMoney("ReturnMoney").toString());
		}
		if (mDmo.getMoney("StatPayMoney") != null) {
			etJiesuandan.setText(mDmo.getMoney("StatPayMoney").toString());
		}
		if (mDmo.getMoney("ReadyMoney") != null) {
			etXianjin.setText(mDmo.getMoney("ReadyMoney").toString());
		}
		if (mDmo.getMoney("WxMoney") != null) {
			etWx.setText(mDmo.getMoney("WxMoney").toString());
		}		
		if (mDmo.getMoney("ZfbMoney") != null) {
			etZfb.setText(mDmo.getMoney("ZfbMoney").toString());
		}	
		if (mDmo.getMoney("DzdpMoney") != null) {
			etDzdp.setText(mDmo.getMoney("DzdpMoney").toString());
		}	

		if (mDmo.getMoney("Nuomi") != null) {
			etNuomi.setText(mDmo.getMoney("Nuomi").toString());
		}		
		if (mDmo.getMoney("Shoukuanka") != null) {
			etShoukuanka.setText(mDmo.getMoney("Shoukuanka").toString());
		}	
		if (mDmo.getMoney("Changduan") != null) {
			etChangduan.setText(mDmo.getMoney("Changduan").toString());
		}
		if (mDmo.getMoney("MeituanWaimai") != null) {
			etMeituanWaimai.setText(mDmo.getMoney("MeituanWaimai").toString());
		}		
		if (mDmo.getMoney("BaiduWaimai") != null) {
			etBaiduWaimai.setText(mDmo.getMoney("BaiduWaimai").toString());
		}	
		if (mDmo.getMoney("Eleme") != null) {
			etEleme.setText(mDmo.getMoney("Eleme").toString());
		}		
		
		if (mDmo.getMoney("TodayLeftMoney") != null) {
			etBenrijine.setText(mDmo.getMoney("TodayLeftMoney").toString());
		}
		if (mDmo.getMoney("MoneyCard") != null) {
			etChuzhika.setText(mDmo.getMoney("MoneyCard").toString());
		}
		if (mDmo.getMoney("LongMoney") != null) {
			etchangkuan.setText(mDmo.getMoney("LongMoney").toString());
		}
		if (mDmo.getMoney("Coupons") != null) {
			youhuijuan.setText(mDmo.getMoney("Coupons").toString());
		}
		if (mDmo.getMoney("MembershipCard") != null) {
			huiyuanka.setText(mDmo.getMoney("MembershipCard").toString());
		}
		if (mDmo.getMoney("LoadBoxNumber") != null) {
			tvloadBoxNumber.setText(mDmo.getMoney("LoadBoxNumber").toString());
		}
		if (mDmo.getMoney("RemainGoodsMoney") != null) {
			remainMoney.setText(mDmo.getMoney("RemainGoodsMoney").toString());
		}
		if (mDmo.getMoney("ReturnBoxNumber") != null) {
			returnBoxNumber
					.setText(mDmo.getMoney("ReturnBoxNumber").toString());
		}
		if (mDmo.getMoney("EmptyBoxNumber") != null) {
			emptyBoxNumber.setText(mDmo.getMoney("EmptyBoxNumber").toString());
		}
		etZhidanren.setText(mDmo.getString("CreateBillUser"));
		etZhaiyao.setText(mDmo.getString("Remark"));

	}

}