package BWP.MobileSale.Return;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;


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

import BWP.MobileSale.LoginedActivity;
import BWP.MobileSale.R;
import BWP.MobileSale.SelectBuyerActivity;
import BWP.MobileSale.SelectRemarkActivity;
import BWP.MobileSale.Util.ActivityUtil;
import BWP.MobileSale.Util.CallableTask;
import BWP.MobileSale.Util.DateTimeUtil;
import BWP.MobileSale.Util.DialogUtil;
import BWP.MobileSale.Util.OnPromptListener;
import BWP.MobileSale.Util.StringUtil;
import BWP.MobileSale.Util.ViewOnClickTask;
import BWP.widget.SelectSimpleAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;

public class ReturnEditActivity extends LoginedActivity {

	static final int RequestCode_SelectBuyer = 1;
	static final int RequestCode_SelectGoods = 2;
	static final int RequestCode_Open = 3; // 打开单据
	static final int RequestCode_EditDetail = 4;
	static final int RequestCode_SelectRemark = 5;
	static final int RequestCode_SelectSaleOutStore=6;

	private long mBillID;
	private RpcObject mDmo;
	private boolean mEnableSave = true;
	boolean mEnableDelete = false;
	boolean mEnableCheck = false;
	private TextView button_Date;
	private TextView textViewRemark;
	private ListView listView;
	private TextView textView_BuyerName;
	private TextView textView_SaleOutStore;
	private Button button_SaleOutStore;
	private TextView textViewDetailCount;
	private TextView textViewDetailNum;
	private int selectedPosition = -1;
	private int firstVisiblePosition;
	public static RpcObject EditingDetail;
	
	private static final int Option_FindDetail = 0;

	private static final int Option_ClearDetail = 1;
	
	
	CallableTask initBillTask = new CallableTask(this, "读取单据中...") {
		public Object call() throws Exception {
			if (mBillID > 0) {
				String method = "/Sale/Returns/Rpcs/MobileReturnRpc/Load";
				mDmo = RpcFacade.rpcCall(method, mBillID);

				method = "/Sale/Returns/Rpcs/MobileReturnRpc/EnableCheck";
				mEnableCheck = RpcFacade.rpcCall(method, mBillID);

			} else {
				mDmo = RpcObject.create("/Sale/Returns/BO/ReturnsRecord");
			}
			return null;
		}

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

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

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

		textView_BuyerName.setText(mDmo.getString("Buyer_Name"));

		button_Date.setText(DateTimeUtil.FormatDate(mDmo.getDate("ReturnsTime")));
		textViewRemark.setText(mDmo.getString("Remark"));
		ManyList details = mDmo.getManyList("GoodsDetails");

		BigDecimal allMoney = new BigDecimal(0);
		BigDecimal allNum = new BigDecimal(0);
		for (int i = 0; i < details.size(); i++) {
			RpcObject item = details.get(i);
			BigDecimal price = item.getMoney("Price");
			if (price == null) {
				price = new BigDecimal(0);
			}
			BigDecimal number = item.getMoney("UnitNum");
			if (number == null) {
				number = new BigDecimal(0);
			}
			allMoney = allMoney.add(price.multiply(number));
			allNum=allNum.add(number);
					
		}

		textViewDetailCount.setText(String.format("%s ￥%.2f", details.size(),
				allMoney));
		textViewDetailNum.setText(String.format("%s", allNum));

		SelectSimpleAdapter adapter = new SelectSimpleAdapter(
				ReturnEditActivity.this, details,
				R.layout.return_edit_detail_list_item, new String[] {
						"Goods_Name", "UnitNum", "Price" }, new int[] {
						R.id.Goods_Name, R.id.Number, R.id.Price });
		adapter.setSelect(selectedPosition);
		listView.setAdapter(adapter);
		if (firstVisiblePosition == -1) {
			firstVisiblePosition = details.size() - 1;
		} else if (firstVisiblePosition > details.size() - 1) {
			firstVisiblePosition = details.size() - 1;
		}
		listView.setSelection(firstVisiblePosition);
	}
	

	private void initControls() {
		// InitButtonReturn();

		InitButtonSave();

		InitButtonCheck();

		 InitButtonDelete();

		 InitListView();

		 InitRemark();

		 InitBuyer();

		 InitDate();
		 initSaleOutStore();
	}
	private void InitListView() {
		textViewDetailCount = ActivityUtil
				.Find(this, R.id.Return_TextView_DetailCount);
		textViewDetailNum=ActivityUtil.Find(this, R.id.Return_TextView_DetailNum);
		listView = ActivityUtil.Find(this, R.id.Return_ListView);
		Button selectGoods = ActivityUtil.Find(this, R.id.Return_Button_SelectGoods);
		selectGoods.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(arg0.getContext(), ReturnSelectGoodsActivity.class);
				startActivityForResult(intent, RequestCode_SelectGoods);
			}

		});

		if (!mEnableSave) {
			selectGoods.setVisibility(View.GONE);
			return;
		}
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				new AlertDialog.Builder(arg1.getContext()).setItems(
						new CharSequence[] { "删除", "取消" },
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								if (which == 0) {
									selectedPosition = -1;
									mDmo.getManyList("GoodsDetails").remove(arg2);
									applyToUI();
								}
							}

						}).show();

				return true;
			}

		});

		listView.setOnScrollListener(new OnScrollListener() {

			public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				if (arg1 == OnScrollListener.SCROLL_STATE_IDLE) {
					firstVisiblePosition = listView.getFirstVisiblePosition();
				}

			}

		});

		listView.setOnItemClickListener(new OnItemClickListener() {
				
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				
				//System.out.println("运行到我啦");
				
				selectedPosition = position;
				RpcObject result = mDmo.getManyList("GoodsDetails").get(position);
				EditingDetail = result;
				Intent intent = new Intent();
				intent.setClass(arg1.getContext(),ReturnDetailEditActivity.class);
				intent.putExtra("Position", position);

				
				intent.putExtra("Goods_Name", result.getString("Goods_Name"));
				intent.putExtra("UnitNum",StringUtil.ToString(result.getMoney("UnitNum")));
				startActivityForResult(intent, RequestCode_EditDetail);

			}

		});
	}

	private void initSaleOutStore()
	{
		textView_SaleOutStore=(TextView)findViewById(R.id.Return_TextView_SaleOutStore);
		button_SaleOutStore=(Button)findViewById(R.id.Return_Button_SaleOutStore);
		button_SaleOutStore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mDmo.getLong("Buyer_ID")==null)
				{
					new AlertDialog.Builder(ReturnEditActivity.this).setNegativeButton("先选择购货客户", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//finish();
						}
					}).setTitle("错误信息").create().show();
					return;
				}
				Intent intent=new Intent();	
				intent.putExtra("Buyer_ID", mDmo.getLong("Buyer_ID"));
				intent.setClass(ReturnEditActivity.this, SelectSaleOutStoreActivity.class);
				startActivityForResult(intent, RequestCode_SelectSaleOutStore);
				
			}
		});
	}
	
	private void InitDate() {
		button_Date = ActivityUtil.Find(this, R.id.Return_Button_Date);
		if (!mEnableSave) {
			button_Date.setHint("");
			return;
		}
		button_Date.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				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());
						mDmo.setDate("ReturnsTime", date);
						applyToUI();
					}

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

				new DatePickerDialog(arg0.getContext(), onDateSetListener,
						calendar.get(Calendar.YEAR), calendar
								.get(Calendar.MONTH), calendar
								.get(Calendar.DAY_OF_MONTH)).show();

			}

		});
	}
	private void InitBuyer() {
		textView_BuyerName = ActivityUtil.Find(this, R.id.Return_TextView_BuyerName);
		Button searchBuyerButton = ActivityUtil.FindButton(this,
				R.id.Return_Button_SelectBuyer);
		if (!mEnableSave) {
			searchBuyerButton.setVisibility(View.GONE);
			return;
		}

		searchBuyerButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(arg0.getContext(), SelectBuyerActivity.class);
				startActivityForResult(intent, RequestCode_SelectBuyer);
			}

		});
	}
	private void InitRemark() {
		if (mEnableSave) {
			textViewRemark = ActivityUtil.Find(this, R.id.Return_EditText_Remark);
			ActivityUtil.Find(this, R.id.Return_TextView_Remark).setVisibility(
					View.GONE);

			Button searchRemarkButton = ActivityUtil.FindButton(this,
					R.id.Return_Button_SelectRemark);

			searchRemarkButton.setOnClickListener(new OnClickListener() {

				public void onClick(View arg0) {
					Intent intent = new Intent();
					intent.setClass(arg0.getContext(),
							SelectRemarkActivity.class);
					startActivityForResult(intent, RequestCode_SelectRemark);
				}

			});
		} else {
			textViewRemark = ActivityUtil.Find(this, R.id.Return_TextView_Remark);
			ActivityUtil.Find(this, R.id.Return_EditText_Remark).setVisibility(
					View.GONE);
			ActivityUtil.FindButton(this, R.id.Return_Button_SelectRemark).setVisibility(
					View.GONE);
		}
	}
	private void InitButtonDelete() {
		deleteTask.setPrompt("确定要删除吗?");
		Button buttonDelete = ActivityUtil.Find(this, R.id.Return_Button_Delete);
		if (!mEnableDelete) {
			buttonDelete.setVisibility(View.GONE);
		}
		buttonDelete.setOnClickListener(deleteTask);
	}

	ViewOnClickTask deleteTask = new ViewOnClickTask(this, "删除中...") {

		public Object call() throws Exception {
			String method = "/Sale/Returns/Rpcs/MobileReturnRpc/Delete";
			RpcFacade.rpcCall(method, mBillID);
			return null;
		}

		@Override
		protected void successUI() {
			DialogUtil.Alert(ReturnEditActivity.this, "删除成功");
			Intent intent = new Intent();
			ActivityUtil.Finish(ReturnEditActivity.this, intent);

		}
	};
	
	private void InitButtonCheck() {
		Button btnCheck = ActivityUtil.FindButton(this, R.id.Return_Button_Check);
		if (!mEnableCheck) {
			btnCheck.setVisibility(View.GONE);
		}
		btnCheck.setOnClickListener(checkTask);
	}
	ViewOnClickTask checkTask = new ViewOnClickTask(this, "审核中...") {

		public Object call() throws Exception {
			String method = "/Sale/Returns/Rpcs/MobileReturnRpc/Check";
			RpcFacade.rpcCall(method, mBillID);
			return null;
		}

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

		}
	};
	private void InitButtonSave() {
		Button btnSave = ActivityUtil.FindButton(this, R.id.Return_Button_Save);
		if (!mEnableSave) {
			btnSave.setVisibility(View.GONE);
		}
		btnSave.setOnClickListener(saveTask);
	}

	ViewOnClickTask saveTask = new ViewOnClickTask(this, "保存中...") {
		public Object call() throws Exception {
			mDmo.setString("Remark", textViewRemark.getText().toString());
			if (mBillID > 0) {
				String method = "/Sale/Returns/Rpcs/MobileReturnRpc/Update";
				RpcFacade.rpcCall(method, mDmo);
			} else {
				String method = "/Sale/Returns/Rpcs/MobileReturnRpc/Insert";
				mBillID = RpcFacade.rpcCall(method, mDmo);
			}
			return null;
		}

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

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.return_edit);
		Intent intent = getIntent();
		mBillID = intent.getLongExtra("ID", 0);
		initBillTask.execute();
	}
	@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 ReceiveSelectSaleOutStore(Intent intent)
	{
		firstVisiblePosition = listView.getBottom();
		Object[] result = (Object[]) intent.getSerializableExtra("Result");
		ManyList details = mDmo.getManyList("GoodsDetails");
		for (Object item : result) {
			@SuppressWarnings("unchecked")
			HashMap<String, Object> map = (HashMap<String, Object>) item;
			try {
				RpcObject detail = RpcObject.create("/Sale/Returns/BO/ReturnsRecord_GoodsDetails");
				detail.setLong("Goods_ID", (Long) map.get("Goods_ID"));
				detail.setString("Goods_Name", (String) map.get("Goods_Name"));
				detail.setString("Goods_Code", (String) map.get("Goods_Code"));
				detail.setString("Goods_Spell", (String) map.get("Goods_Spell"));
				//detail.setMoney("UnitNum", (BigDecimal) map.get("UnitNum"));
				detail.setMoney("Price", (BigDecimal) map.get("Price"));
				long saleid=(Long)map.get("SaleOutStore_ID");
				Date saledate=(Date)map.get("LoadTime");				
				String saleiddate=saleid+"/"+DateTimeUtil.FormatDate(saledate);
				System.out.println(saleiddate);
				
				detail.setString("SaleOutStore_ID", saleiddate);
//				Short temp=(Short)map.get("ReturnsManner");
//				detail.setNamedValue("ReturnsManner", temp);				
				
				details.add(detail);
			} catch (JsonRpcException e) {
				e.printStackTrace();
			}
		}
		applyToUI();
	}
	
	
	@SuppressWarnings("unchecked")
	private void ReceiveEditDetail(Intent intent) {
		int position = intent.getIntExtra("Position", -1);
		
		RpcObject detail = mDmo.getManyList("GoodsDetails").get(position);
		//HashMap<String, Object> map = (HashMap<String, Object>) intent.getSerializableExtra("GoodsDetails");
		
		detail.setMoney("UnitNum",StringUtil.ParseMoney(intent.getStringExtra("UnitNum")));		
		applyToUI();
	}

	private void ReceiveSelectGoodsResult(Intent intent) {
		firstVisiblePosition = listView.getBottom();
		Object[] result = (Object[]) intent.getSerializableExtra("Result");
		ManyList details = mDmo.getManyList("GoodsDetails");
		for (Object item : result) {
			@SuppressWarnings("unchecked")
			HashMap<String, Object> map = (HashMap<String, Object>) item;
			try {
				RpcObject detail = RpcObject.create("/Sale/Returns/BO/ReturnsRecord_GoodsDetails");
				detail.setLong("Goods_ID", (Long) map.get("ID"));
				detail.setString("Goods_Name", (String) map.get("Name"));
				detail.setString("Goods_Code", (String) map.get("Code"));
				detail.setString("Goods_Spell", (String) map.get("Spell"));
				detail.setMoney("UnitNum", (BigDecimal) map.get("UnitNum"));
				detail.setMoney("Price", (BigDecimal) map.get("Price"));
				
				Short temp=(Short)map.get("ReturnsManner");
				detail.setNamedValue("ReturnsManner", temp);				
				
				details.add(detail);
			} catch (JsonRpcException e) {
				e.printStackTrace();
			}
		}
		applyToUI();
	}
	@SuppressWarnings("unchecked")
	private void ReceiveSelectBuyerResult(Intent intent) {
		HashMap<String, Object> map = (HashMap<String, Object>) intent
				.getSerializableExtra("Result");
		mDmo.setString("Buyer_Name", (String) map.get("Name"));
		mDmo.setLong("Buyer_ID", (Long) map.get("ID"));
		applyToUI();
	}

	private void ReceiveSelectRemarkResult(Intent intent) {
		String Remark = (String) intent.getSerializableExtra("Result");
		mDmo.setString("Remark", Remark);
		applyToUI();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, Option_FindDetail, 0, "查找明细");
		menu.add(0, Option_ClearDetail, 1, "清空明细");
		return super.onCreateOptionsMenu(menu);
	}

	String detailSearchKey;
	CallableTask searchDetailTask = new CallableTask(this, "") {

		private int searchResult;

		public Object call() throws Exception {
			searchResult = -1;
			ManyList details = mDmo.getManyList("GoodsDetails");
			for (int i = 0; i < details.size(); i++) {
				RpcObject item = details.get(i);
				if (MatchDetail(item, detailSearchKey)) {
					searchResult = i;
					break;
				}
			}

			Log.d("OrderEdit", String.format("退货登记单明细搜索结果:%s", searchResult));

			// TODO Auto-generated method stub
			return null;
		}

		private boolean MatchDetail(RpcObject item, String detailSearchKey) {
			String spell = item.getString("Goods_Spell");
			if (spell.contains(detailSearchKey)) {
				return true;
			}
			String code = item.getString("Goods_Code");
			if (code.contains(detailSearchKey)) {
				return true;
			}
			String goodsName = item.getString("Goods_Name");
			if (goodsName.contains(detailSearchKey)) {
				return true;
			}
			return false;
		}

		@Override
		protected void successUI() {
			if (searchResult >= 0) {
				selectedPosition = searchResult;
				firstVisiblePosition = searchResult;
				applyToUI();
			} else {
				DialogUtil
						.AutoHiddenAlert(ReturnEditActivity.this, "没有查找到匹配的明细");
			}
		}
	};
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Option_FindDetail:
			DialogUtil.Prompt(ReturnEditActivity.this, "存货明细查找", "支持名称编码拼音首字母",
					"", InputType.TYPE_CLASS_TEXT, new OnPromptListener() {
						public void OnPrompt(String prompt) {
							detailSearchKey = prompt;
							searchDetailTask.execute();
						}

						@Override
						public void OnPrompt2(HashMap<String, Object> prompt) {
							// TODO Auto-generated method stub
							
						}
					});
			break;
		case Option_ClearDetail:
			DialogUtil.Confirm(ReturnEditActivity.this, "确定要清空明细吗?", "是", "否",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							selectedPosition = -1;
							mDmo.getManyList("GoodsDetails").clear();
							applyToUI();
						}
					});
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@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);
	}

}
