package BWP.MobileSale.BreedLog;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

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

import BWP.MobileSale.LoginedActivity;
import BWP.MobileSale.R;
import BWP.MobileSale.BranchOrder.BranchOrderEditActivity;
import BWP.MobileSale.Return.ReturnSetUserProfileActivity;
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.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class BreedLogEditActivity extends LoginedActivity {

	static final int RequestCode_Open = 3;
	Long mBillID;
	private boolean mEnableSave = true;
	private RpcObject mDmo;
	Button btnNew, btnSave;
	Spinner spinnerAccount, spinnerFactory, spinnerBatch, spinnerCage;
	TextView tvDate;
	EditText txtDeadGong, txtDeadMu, txtTaoTaiGong, txtTaoTaiMu, txtEatTime,
			txtDrinkWater;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.breedlog_edit);
		try {
			initSpinners();
		} catch (JsonRpcException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		btnNew = (Button) findViewById(R.id.breedlog_edit_btnnew);
		btnNew.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				mBillID = (long) 0;
				finish();
				Intent intent = new Intent();
				intent.putExtra("ID", mBillID);
				intent.setClass(BreedLogEditActivity.this,
						BreedLogEditActivity.class);
				startActivity(intent);
				// startActivityIfNeeded(intent,
				// BreedLogEditActivity.RequestCode_Open);

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

					getFromUi();

					saveTask.execute();
				} catch (Exception e) {
					DialogUtil.Alert(BreedLogEditActivity.this, e.getMessage());

				}
			}
		});

		txtDeadGong = (EditText) findViewById(R.id.breedlog_edit_deadgong);
		txtDeadMu = (EditText) findViewById(R.id.breedlog_edit_deadmu);
		txtTaoTaiGong = (EditText) findViewById(R.id.breedlog_edit_taotaigong);
		txtTaoTaiMu = (EditText) findViewById(R.id.breedlog_edit_taotaimu);
		txtEatTime = (EditText) findViewById(R.id.breedlog_edit_eattime);
		txtDrinkWater = (EditText) findViewById(R.id.breedlog_edit_drinkwater);
		tvDate = (TextView) findViewById(R.id.breedlog_edit_date);

		tvDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {

					public void onDateSet(DatePicker datePicker, int year,
							int month, int day) {
						Calendar calendar = Calendar.getInstance();
						calendar.set(year, month, day);
						Date date = DateTimeUtil.RemoveTime(calendar.getTime());
						tvDate.setText(DateTimeUtil.FormatDate(date));
						// mDmo.setDate("Date", date);
						// applyToUI();
					}

				};
				String dateStr = tvDate.getText().toString();
				Calendar calendar = DateTimeUtil.SafeParseCalendar(dateStr);

				new DatePickerDialog(BreedLogEditActivity.this,
						onDateSetListener, calendar.get(Calendar.YEAR),
						calendar.get(Calendar.MONTH), calendar
								.get(Calendar.DAY_OF_MONTH)).show();

			}
		});

		Intent intent = getIntent();
		mBillID = intent.getLongExtra("ID", 0);
		if (mBillID == 0) {
			Calendar c = Calendar.getInstance();

			tvDate.setText(DateTimeUtil.FormatDate(c.getTime()));
		}

		initBillTask.execute();

		//

	}

	List<String> listAccount, listFactory, listBatch, listCage;
	Dictionary<String, Long> tableAccount, tableFactory, tableBatch, tableCage;

	// =new Hashtable<String,Long>();
	private void initSpinners() throws JsonRpcException {
		spinnerAccount = (Spinner) findViewById(R.id.breedlog_edit_account);
		tableAccount = new Hashtable<String, Long>();
		listAccount = new ArrayList<String>();
		listAccount.add("");
		String method = "/Hatch/BreedingPoultry/Rpcs/MobileBreedLogRpc/LoadAccountintUnit";
		DFDataTable table = RpcFacade.rpcCall(method);
		List<RpcObject> rows = table.getRows();
		for (RpcObject rpcObject : rows) {
			String name = rpcObject.getString("Name");
			Long id = rpcObject.getLong("ID");
			listAccount.add(name);
			tableAccount.put(name, id);
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				BreedLogEditActivity.this,
				android.R.layout.simple_spinner_item, listAccount);
		spinnerAccount.setAdapter(adapter);

		// 養殖場
		spinnerFactory = (Spinner) findViewById(R.id.breedlog_edit_factory);
		tableFactory = new Hashtable<String, Long>();
		listFactory = new ArrayList<String>();
		listFactory.add("");
		method = "/Hatch/BreedingPoultry/Rpcs/MobileBreedLogRpc/LoadBreedFactory";
		table = RpcFacade.rpcCall(method);
		rows = table.getRows();
		for (RpcObject rpcObject : rows) {
			String name = rpcObject.getString("Name");
			Long id = rpcObject.getLong("ID");
			listFactory.add(name);
			tableFactory.put(name, id);
		}
		adapter = new ArrayAdapter<String>(BreedLogEditActivity.this,
				android.R.layout.simple_spinner_item, listFactory);
		spinnerFactory.setAdapter(adapter);
		//

		spinnerBatch = (Spinner) findViewById(R.id.breedlog_edit_batch);
		tableBatch = new Hashtable<String, Long>();
		listBatch = new ArrayList<String>();
		listBatch.add("");
		method = "/Hatch/BreedingPoultry/Rpcs/MobileBreedLogRpc/LoadBatch";
		table = RpcFacade.rpcCall(method);
		rows = table.getRows();
		for (RpcObject rpcObject : rows) {
			String name = rpcObject.getString("Name");
			Long id = rpcObject.getLong("ID");
			listBatch.add(name);
			tableBatch.put(name, id);
		}
		adapter = new ArrayAdapter<String>(BreedLogEditActivity.this,
				android.R.layout.simple_spinner_item, listBatch);
		spinnerBatch.setAdapter(adapter);

		spinnerCage = (Spinner) findViewById(R.id.breedlog_edit_cage);
		tableCage = new Hashtable<String, Long>();
		listCage = new ArrayList<String>();
		listCage.add("");
		method = "/Hatch/BreedingPoultry/Rpcs/MobileBreedLogRpc/LoadBreederCage";
		table = RpcFacade.rpcCall(method);
		rows = table.getRows();
		for (RpcObject rpcObject : rows) {
			String name = rpcObject.getString("Name");
			Long id = rpcObject.getLong("ID");
			listCage.add(name);
			tableCage.put(name, id);
		}
		adapter = new ArrayAdapter<String>(BreedLogEditActivity.this,
				android.R.layout.simple_spinner_item, listCage);
		spinnerCage.setAdapter(adapter);

	}

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

				// method = "/Sale/Sale/Rpcs/MobileOrderRpc/EnableCheck";
				// result = RpcFacade.rpcCall(method, mBillID);
				// mEnableCheck = result.getBoolean();

			} else {
				mDmo = RpcObject
						.create("/Hatch/BreedingPoultry/BO/MobileBreedLog");
			}
			return null;
		}

		@Override
		protected void successUI() {
			mEnableSave = mDmo.getNamedValue("BillState").getValue() == 0;
			// mEnableDelete = mDmo.getNamedValue("BillState").getValue() == 0;
			// initControls();
			applyToUI();
		}

	};

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

			if (mBillID > 0) {
				String method = "/Hatch/BreedingPoultry/Rpcs/MobileBreedLogRpc/Update";
				RpcFacade.rpcCall(method, mDmo);
			} else {
				String method = "/Hatch/BreedingPoultry/Rpcs/MobileBreedLogRpc/Insert";
				mBillID = RpcFacade.rpcCall(method, mDmo);
			}

			return null;
		}

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

	};

	// @Override
	// protected void onActivityResult(int requestCode, int resultCode, Intent
	// intent) {
	// super.onActivityResult(requestCode, resultCode, intent);
	// if (resultCode != Activity.RESULT_OK) {
	// return;
	// }
	//
	// switch (requestCode) {
	// case RequestCode_SelectBuyer:
	// ReceiveSelectBuyerResult(intent);
	// break;
	// case RequestCode_SelectGoods:
	// ReceiveSelectGoodsResult(intent);
	// break;
	// case RequestCode_EditDetail:
	// ReceiveEditDetail(intent);
	// break;
	// case RequestCode_SelectRemark:
	// ReceiveSelectRemarkResult(intent);
	// break;
	// case RequestCode_SelectSaleOutStore:
	// ReceiveSelectSaleOutStore(intent);
	// break;
	//
	// }
	// }

	private void getFromUi() {

		mDmo.setLong("AccountingUnit_ID",
				tableAccount.get((String) spinnerAccount.getSelectedItem()));
		mDmo.setLong("BreedFactory_ID",
				tableFactory.get((String) spinnerFactory.getSelectedItem()));
		mDmo.setLong("Batch_ID",
				tableBatch.get((String) spinnerBatch.getSelectedItem()));
		mDmo.setLong("BreederCage_ID",
				tableCage.get((String) spinnerCage.getSelectedItem()));

		setIntValue("DeadGong", txtDeadGong);
		setIntValue("DeadMu", txtDeadMu);
		setIntValue("TaoTaiGong", txtTaoTaiGong);
		setIntValue("TaoTaiMu", txtTaoTaiMu);

		mDmo.setString("EatSiLiaoDate", txtEatTime.getText().toString());
		mDmo.setDecimal("DrinkWater", getDecimalValue(txtEatTime));
		try {
			mDmo.setDate("Date",
					DateTimeUtil.ParseDate(tvDate.getText().toString()));
		} catch (ParseException e) {
			DialogUtil.Alert(BreedLogEditActivity.this, "请选择日期");

		}
	}

	void setIntValue(String key, EditText et) {
		if (!StringUtil.IsNullOrEmpty(et.getText().toString())) {
			mDmo.setInt(key, Integer.parseInt(et.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 applyToUI() {
		if (mDmo == null) {
			DialogUtil.Alert(BreedLogEditActivity.this, "当前可编辑的对象为空");
			finish();
			return;
		}

		if (mBillID > 0) {
			this.setTitle(String.format("%s-养殖日志单No.%s(%s)",
					getString(R.string.app_name), mBillID,
					mDmo.getNamedValue("BillState")));

			spinnerAccount.setSelection(listAccount.indexOf(mDmo
					.getString("AccountingUnit_Name")));
			spinnerFactory.setSelection(listFactory.indexOf(mDmo
					.getString("BreedFactory_Name")));
			spinnerBatch.setSelection(listBatch.indexOf(mDmo
					.getString("Batch_Name")));
			spinnerCage.setSelection(listCage.indexOf(mDmo
					.getString("BreederCage_Name")));

			getIntValue("DeadGong", txtDeadGong);
			getIntValue("DeadMu", txtDeadMu);
			getIntValue("TaoTaiGong", txtTaoTaiGong);
			getIntValue("TaoTaiMu", txtTaoTaiMu);
			getIntValue("DeadGong", txtDeadGong);

			txtEatTime.setText(mDmo.getString("EatSiLiaoDate"));
			if (mDmo.getDecimal("DrinkWater") != null) {
				txtDrinkWater.setText(mDmo.getDecimal("DrinkWater").toString());
			}
			tvDate.setText(DateTimeUtil.FormatDate(mDmo.getDate("Date")));
		}

	}

	void getIntValue(String key, EditText et) {
		if (mDmo.getInt(key) != null) {
			et.setText(mDmo.getInt(key).toString());
		}
	}

}
