package BWP.MobileSale;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
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.Config.LoginUserConfig;
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 android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.SimpleAdapter.ViewBinder;
import java.util.HashMap;

public class SelectGoodsActivity extends LoginedActivity {
	
	LinkedHashMap<Long, HashMap<String, Object>> selected = new LinkedHashMap<Long, HashMap<String, Object>>();
	
	private EditText searchKey;
	private ListView listView;
	private SimpleAdapter adapter;
	private Boolean mStarred;
	
	CallableTask searchTask = new CallableTask(this, "查询中...") {

		public Object call() throws Exception {
			String method = "/Sale/Sale/Rpcs/MobileOrderGoodsRpc/Search";
			RpcObject argument = RpcObject.create("/Sale/Sale/Rpcs/RpcSearch");
			argument.setString("SearchKey", searchKey.getText().toString());
			argument.setBoolean("Starred", mStarred);
			DFDataTable table = RpcFacade.rpcCall(method, argument);
			List<RpcObject> rows = table.getRows();
			adapter = new SimpleAdapter(SelectGoodsActivity.this, rows,
					R.layout.goods_multiselect_item, new String[] { "Name",
							"Code", "ID", "Starred"}, new int[] {
							R.id.TextView_Name, R.id.TextView_Code,
							R.id.CheckBox, R.id.CheckBox_Star });
			adapter.setViewBinder(binder);
			return null;
		}

		@Override
		protected void successUI() {
			listView.setAdapter(adapter);
		}
	};
	
	ViewBinder binder = new ViewBinder() {

		public boolean setViewValue(View view, Object data,
				String textRepresentation) {
			if (view.getId() == R.id.CheckBox) {
				CheckBox box = (CheckBox) view;
				box.setChecked(selected.containsKey(data));
				return true;
			} 
			else {
				return false;
			}
		}

	};
	
	String addMethod = "/Sale/Sale/Rpcs/MobileOrder_User_GoodsRpc/Add";
	String removeMethod = "/Sale/Sale/Rpcs/MobileOrder_User_GoodsRpc/Remove";
	
	public void RemoveGoods(long mGoodsID){
		RpcFacade.rpcCall(removeMethod, mGoodsID);
		
	}

	public void AddGoods(long mGoodsID){
		RpcFacade.rpcCall(addMethod, mGoodsID);
		
	}
	long buyer_ID,accountingUnit_ID;
	Date date;
	static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        
		setContentView(R.layout.selectgoods);
		Intent intent = getIntent();
		if(intent.getSerializableExtra("Buyer_ID") != null){
			buyer_ID = Long.parseLong(intent.getSerializableExtra("Buyer_ID").toString());
		}
		if(intent.getSerializableExtra("AccountingUnit_ID") == null){
			accountingUnit_ID = 0;
		}else{
			accountingUnit_ID = Long.parseLong(intent.getSerializableExtra("AccountingUnit_ID").toString());
		}
		
		String dateStr = intent.getSerializableExtra("Date").toString();
		try {
			 date = dateFormat.parse(dateStr);	
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		final boolean isOrNotShowSecond = intent.getBooleanExtra("IsOrNotShowSecond",false);
		final boolean isEditSecond = intent.getBooleanExtra("IsEditSecond",true);
		final boolean isEditMain = intent.getBooleanExtra("IsEditMain",true);
		final boolean showRemark = intent.getBooleanExtra("ShowRemark",false);		
		searchKey = ActivityUtil.Find(this, R.id.EditText_Search);
		Button searchButton = ActivityUtil.Find(this, R.id.Button_Search);
		listView = ActivityUtil.Find(this, R.id.ListView);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		listView.setOnItemClickListener(new OnItemClickListener() {
			String method = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckEditPriceRole";
			final boolean hasEditPriceRole = RpcFacade.rpcCall(method);
			String method3 = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckIsOrNotShowPolicyPrice";
			final boolean isOrNotShowPolicyPrice = RpcFacade.rpcCall(method3);
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				final RpcObject data = (RpcObject) arg0.getItemAtPosition(arg2);
				Long id = data.getLong("ID");
				if (selected.containsKey(id)) {
					selected.remove(id);
				} else {
					final HashMap<String,Object> lastData = new HashMap<String,Object>();
					lastData.put("ID",data.get("ID"));
					lastData.put("Name",data.get("Name"));
					lastData.put("Code",data.get("Code"));
					lastData.put("Spell",data.get("Spell"));
					lastData.put("Number",null);
					lastData.put("SecondNumber",null);
					lastData.put("Price",null);
					lastData.put("BatchNo_ID", null);
					lastData.put("BatchNo_Name", null);
					lastData.put("Remark", null);					
					selected.put(id, lastData);
					long goods_ID = Long.parseLong(data.get("ID").toString());
					String method = "/Sale/Sale/Rpcs/MobileOrderRpc/GetLeftAndRightRatio";
					final RpcObject orderDetail = RpcFacade.rpcCall(method, buyer_ID,goods_ID);
					final BigDecimal goods_SecondaryUnit1RelativeRatio =  orderDetail.getMoney("Goods_SecondaryUnit1RelativeRatio");
					final BigDecimal goods_SecondaryUnit1Ratio =  orderDetail.getMoney("Goods_SecondaryUnit1Ratio");
					final BigDecimal leftRatio = orderDetail.getMoney("LeftRatio");
					final BigDecimal rightRatio = orderDetail.getMoney("RightRatio");
					lastData.put("Goods_SecondaryUnit1RelativeRatio", goods_SecondaryUnit1RelativeRatio);
					lastData.put("Goods_SecondaryUnit1Ratio", goods_SecondaryUnit1Ratio);
					lastData.put("LeftRatio", leftRatio);
					lastData.put("RightRatio", rightRatio);
					String method2 = "/Sale/Sale/Rpcs/MobileOrderRpc/GetPolicyPrice";
					final BigDecimal policyPrice;
					if(accountingUnit_ID > 0){
						policyPrice = RpcFacade.rpcCall(method2, goods_ID,buyer_ID,date,accountingUnit_ID);	
					}else{
						policyPrice = RpcFacade.rpcCall(method2, goods_ID,buyer_ID,date,null);
					}
					lastData.put("PolicyPrice", policyPrice);
					try {
							PromptWithTwoInput(SelectGoodsActivity.this, "请输入数量和价格",
									lastData.get("Name").toString(), lastData,isOrNotShowSecond,isOrNotShowPolicyPrice, hasEditPriceRole,isEditMain,isEditSecond,showRemark,new OnPromptListener() {
										public void OnPrompt2(HashMap<String, Object> prompt) {
											Object goodsNum = prompt.get("goodsNum");
											Object goodsPrice = prompt.get("goodsPrice");
											Object goodsSecondNum = prompt.get("goodsSecondNum");
											Object goodsBatchNo_ID = prompt.get("goodsBatchNo_ID");
											Object goodsBatchNo_Name = prompt.get("goodsBatchNo_Name");
											Object remark = prompt.get("remark");											
											if(goodsPrice!=null&&hasEditPriceRole==true){
												lastData.put("Price",(BigDecimal)goodsPrice);
											}
											if(goodsNum!=null){
												lastData.put("Number",(BigDecimal)goodsNum);
											}
											
											if(goodsSecondNum!=null){
												lastData.put("SecondNumber",(BigDecimal)goodsSecondNum);
											}
											if(goodsBatchNo_ID!=null){
												lastData.put("BatchNo_ID",(Long)goodsBatchNo_ID);
											}
											if(goodsBatchNo_Name!=null){
												lastData.put("BatchNo_Name",goodsBatchNo_Name.toString());
											}											
											if(remark!=null){
												lastData.put("Remark",remark.toString());
											}
										}

										@Override
										public void OnPrompt(String prompt) {
											// TODO Auto-generated method stub
											
										}

									
									});

						
					} catch (JsonRpcException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
				}
			}

		});
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.i("SaleOrder", "setOnItemLongClickListener");

				RpcObject data = (RpcObject) parent.getItemAtPosition(position);
				Long goodsID = data.getLong("ID");
				Boolean starred = data.getBoolean("Starred");
				starred = !starred;
				data.put("Starred", starred);
				CheckBox box = (CheckBox) view.findViewById(R.id.CheckBox_Star);
				box.setChecked(starred);
				Log.i("SaleOrder", StringUtil.ToString(starred));
				if(starred){
					AddGoods(goodsID);
				}else{
					RemoveGoods(goodsID);
				}
				/*
				UserGoodsStarCommand command = new UserGoodsStarCommand(
						goodsID, starred);
				CommandService.AddCommand(command);
				Intent intent = new Intent();
				intent.setClass(view.getContext(), CommandService.class);
				startService(intent);
				*/
				return true;
			}
		});

		Button okButton = ActivityUtil.Find(this, R.id.Button_OK);
		okButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.putExtra("Result", selected.values().toArray());
				ActivityUtil.Finish(SelectGoodsActivity.this, intent);
			}

		});

		Button cancelButton = ActivityUtil.Find(this, R.id.Button_Cancel);
		cancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				finish();
			}

		});

		searchButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				mStarred = null;
				BeginSearch();
			}

		});

		searchButton.setOnLongClickListener(new OnLongClickListener() {

			public boolean onLongClick(View v) {
				new AlertDialog.Builder(v.getContext())
						.setTitle("搜索范围")
						.setItems(R.array.search_starred_options,
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {
										switch (which) {
										case 0:
											mStarred = null;
											break;
										case 1:
											mStarred = true;
											break;
										case 2:
											mStarred = false;
											break;
										} 
										BeginSearch();
									}
								}).show();
				return true;
			}
		});

		mStarred = true;
		BeginSearch();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		if(requestCode == RequestCode_SelectBatchNo){
			HashMap<String, Object> map = (HashMap<String, Object>) data
					.getSerializableExtra("Result");
			Object id = (Object) map.get("ID");
			batchNo_ID.setText(id.toString());
			batchNo.setText((String)map.get("Name"));

		}
	}
	
	
	
	static final int RequestCode_SelectBatchNo = 1;
	static TextView batchNo;
	static TextView batchNo_ID;
	static TextView goodsPolicyPrice;
	static EditText goodsNum;
	static EditText goodsSecondNum;	
	static EditText remark;
	static EditText goodsPrice;

	public static void PromptWithTwoInput(final Context context,
			final String title, String message,
			HashMap<String, Object> lastData, final boolean isOrNotShowSecond,
			boolean isOrNotShowPolicyPrice, boolean hasEditPriceRole,
			boolean isEditMain, boolean isEditSecond, boolean showRemark,
			final OnPromptListener onprompt) {

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(context.LAYOUT_INFLATER_SERVICE);
		final View view;

		view = inflater.inflate(R.layout.edittext, null);
		String method = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckIsOrNotShowBatchNo";
		final boolean hasShowBatchNoRole = RpcFacade.rpcCall(method);
		if (hasShowBatchNoRole) {
			Button selectBatchNo = (Button) view
					.findViewById(R.id.SelectBatchNo);

			selectBatchNo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setClass(v.getContext(), SelectBatchNoActivity.class);
					Activity activity = (Activity) context;
					activity.startActivityForResult(intent,
							RequestCode_SelectBatchNo);
				}
			});
			batchNo = (TextView) view.findViewById(R.id.BatchNo);
			batchNo_ID = (TextView) view.findViewById(R.id.BatchNo_ID);
		} else {
			TableRow row = (TableRow) view.findViewById(R.id.tableRow4);
			row.setVisibility(view.GONE);
		}

		goodsPolicyPrice = (TextView) view.findViewById(R.id.goodsPolicyPrice);
		if (!hasEditPriceRole) {
			TableRow row = (TableRow) view.findViewById(R.id.tableRow2);
			row.setVisibility(view.GONE);
		}
		if (isOrNotShowPolicyPrice) {
			BigDecimal PolicyPrice = (BigDecimal) lastData.get("PolicyPrice");
			if (PolicyPrice.compareTo(new BigDecimal(0)) == 1) {
				goodsPolicyPrice.setText(PolicyPrice.toString());
			}
		} else {
			TableRow row = (TableRow) view.findViewById(R.id.tableRow3);
			row.setVisibility(view.GONE);
		}
		remark = (EditText) view.findViewById(R.id.EditText_Remark);
		if (!showRemark) {
			TableRow row = (TableRow) view.findViewById(R.id.tableRow5);
			row.setVisibility(view.GONE);
		}
		goodsNum = (EditText) view.findViewById(R.id.goodsNum);
		goodsNum.setEnabled(isEditMain);

		goodsNum.setText(StringUtil.ToString(lastData.get("Number")));
		goodsSecondNum = (EditText) view.findViewById(R.id.goodsSecondNum);
		goodsSecondNum.setEnabled(isEditSecond);

		if (title != "请输入数量") {
			EditText goodsPrice = (EditText) view.findViewById(R.id.goodsPrice);
			goodsPrice.setText(StringUtil.ToString(lastData.get("Price")));
		}
		if (isOrNotShowSecond) {
			goodsSecondNum.setText(StringUtil.ToString(lastData
					.get("SecondNumber")));
			final Object leftRatio = lastData.get("LeftRatio");
			final Object rightRatio = lastData.get("RightRatio");
			final Object goods_SecondaryUnit1RelativeRatio = lastData
					.get("Goods_SecondaryUnit1RelativeRatio");
			final Object goods_SecondaryUnit1Ratio = lastData
					.get("Goods_SecondaryUnit1Ratio");
			if (leftRatio != null && rightRatio != null
					&& goods_SecondaryUnit1RelativeRatio != null
					&& goods_SecondaryUnit1Ratio != null) {
				final BigDecimal rightRatio2 = (BigDecimal) rightRatio;
				final BigDecimal leftRatio2 = (BigDecimal) leftRatio;
				final BigDecimal goods_SecondaryUnit1RelativeRatio2 = (BigDecimal) goods_SecondaryUnit1RelativeRatio;
				final BigDecimal goods_SecondaryUnit1Ratio2 = (BigDecimal) goods_SecondaryUnit1Ratio;
				goodsNum.addTextChangedListener(new TextWatcher() {

					@Override
					public void onTextChanged(CharSequence s, int start,
							int before, int count) {
						if (goodsNum.hasFocus()) {
							BigDecimal number = StringUtil.ParseMoney(s
									.toString());

							if (number != null
									&& goods_SecondaryUnit1Ratio2 != null
									&& goods_SecondaryUnit1RelativeRatio2 != null) {
								BigDecimal mainUnitNum = ((number).divide(
										leftRatio2, 6,
										BigDecimal.ROUND_HALF_EVEN))
										.multiply(rightRatio2);
								BigDecimal secondNumber = (mainUnitNum
										.multiply(goods_SecondaryUnit1RelativeRatio2))
										.divide(goods_SecondaryUnit1Ratio2, 6,
												BigDecimal.ROUND_HALF_EVEN);
								goodsSecondNum.setText(secondNumber.toString());

							}
						}

					}

					@Override
					public void beforeTextChanged(CharSequence s, int start,
							int count, int after) {
						// TODO Auto-generated method stub

					}

					@Override
					public void afterTextChanged(Editable s) {

					}
				});

				goodsSecondNum.addTextChangedListener(new TextWatcher() {

					@Override
					public void onTextChanged(CharSequence s, int start,
							int before, int count) {
						if (goodsSecondNum.hasFocus()) {
							BigDecimal secondNumber = StringUtil.ParseMoney(s
									.toString());
							if (secondNumber != null
									&& goods_SecondaryUnit1Ratio2 != null
									&& goods_SecondaryUnit1RelativeRatio != null) {
								BigDecimal mainUnitNum = ((secondNumber)
										.multiply(goods_SecondaryUnit1Ratio2))
										.divide(goods_SecondaryUnit1RelativeRatio2);
								BigDecimal number = (mainUnitNum
										.divide(rightRatio2))
										.multiply(leftRatio2);
								goodsNum.setText(number.toString());
							}
						}
					}

					@Override
					public void beforeTextChanged(CharSequence s, int start,
							int count, int after) {
						// TODO Auto-generated method stub

					}

					@Override
					public void afterTextChanged(Editable s) {

					}
				});
			}
		} else {
			goodsSecondNum.setVisibility(view.GONE);
			TextView textView_Second = (TextView) view
					.findViewById(R.id.TextView_SecondNum);
			textView_Second.setVisibility(view.GONE);
		}
		Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title)
				.setMessage(message)
				.setView(view)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface arg0, int arg1) {
						// EditText goodsNum =
						// (EditText)view.findViewById(R.id.goodsNum);
						// EditText goodsSecondNum =
						// (EditText)view.findViewById(R.id.goodsSecondNum);
						HashMap<String, Object> returnlist = new HashMap<String, Object>();
						if (title != "请输入数量") {
							goodsPrice = (EditText) view
									.findViewById(R.id.goodsPrice);
							returnlist.put("goodsNum", StringUtil
									.ParseMoney(goodsNum.getText().toString()));
							returnlist.put("goodsPrice",
									StringUtil.ParseMoney(goodsPrice.getText()
											.toString()));
							if (isOrNotShowSecond) {
								returnlist.put("goodsSecondNum", StringUtil
										.ParseMoney(goodsSecondNum.getText()
												.toString()));
							}
						} else {
							returnlist.put("goodsNum", StringUtil
									.ParseMoney(goodsNum.getText().toString()));
							if (isOrNotShowSecond) {
								returnlist.put("goodsSecondNum", StringUtil
										.ParseMoney(goodsSecondNum.getText()
												.toString()));
							}
						}
						if (hasShowBatchNoRole) {
							if (batchNo.getText() != null
									&& batchNo.getText() != ""
									&& batchNo_ID.getText() != null
									&& batchNo_ID.getText() != "") {
								String eee = batchNo.getText().toString();
								String ddd = batchNo_ID.getText().toString();
								returnlist.put("goodsBatchNo_Name", batchNo
										.getText().toString());
								returnlist.put("goodsBatchNo_ID", Long
										.parseLong(batchNo_ID.getText()
												.toString()));
							}
						}
						returnlist.put("remark",  remark.getText().toString() );
						onprompt.OnPrompt2(returnlist);
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

					}
				}).show();

	}

	void BeginSearch() {
		searchTask.execute();
	}
}
