package BWP.MobileSale.Order;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

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.SelectAccountingUnitActivity;
import BWP.MobileSale.SelectBuyerActivity;
import BWP.MobileSale.SelectGoodsActivity;
import BWP.MobileSale.SelectRemarkActivity;
import BWP.MobileSale.SelectStoreActivity;
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.ViewOnClickTask;
import BWP.widget.SelectSimpleAdapter;
import android.R.bool;
import android.R.string;
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.opengl.Visibility;
import android.os.Bundle;
import android.text.InputType;
import android.text.format.Time;
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.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class OrderEditActivity extends LoginedActivity {

	public static RpcObject EditingDetail;

	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_SelectAccountingUnit = 6;
	static final int RequestCode_SelectStore = 7;
	
	
	private static final int Option_FindDetail = 0;

	private static final int Option_ClearDetail = 1;

	private TextView textView_BuyerName;
	private TextView textView_Balance;
	private TextView textView_AccountingUnit;
	private TextView textView_StoreName;
	private long mBillID;
	private RpcObject mDmo;
	private List<RpcObject> mDetails;	
	private int selectedPosition = -1;

	private boolean mEnableSave = true;
	boolean mEnableCheck = false;
	boolean mEnableUnCheck = false;	
	boolean mEnableDelete = false;
	boolean mShowUnCheck = false;	
	private TextView button_Date;
	private TextView textViewRemark;
	private ListView listView;

	private TextView textViewDetailCount;
	String detailSearchKey;
	private int firstVisiblePosition;
	private Button btnReturn;
	private boolean isOrNotShowBalance;
	private boolean isOrNotShowSecond;
	private boolean isOrNotShowAccountingUnitAndStore;
	private boolean isEditSecond,isEditMain,showRemark;	
	boolean enableSaleXiWangEnable = false;	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_edit);
		Intent intent = getIntent();
		mBillID = intent.getLongExtra("ID", 0);
		btnReturn = (Button)this.findViewById(R.id.Order_Button_Return);
		CheckVisibale();
		if(!isOrNotShowBalance){
			this.findViewById(R.id.balanceLayout).setVisibility(View.GONE);
			}
		btnReturn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		initBillTask.execute();
	}
	
	private void CheckVisibale() {
		try {
			String method = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckIsOrNotShowBalance";
			isOrNotShowBalance = RpcFacade.rpcCall(method);
			String method2 = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckIsOrNotShowSecond";
			isOrNotShowSecond = RpcFacade.rpcCall(method2);
			String method3 = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckIsOrNotShowAccountingUnitAndStore";
			isOrNotShowAccountingUnitAndStore = RpcFacade.rpcCall(method3);
			String method4 = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckIsEditSecond";
			isEditSecond = RpcFacade.rpcCall(method4);
			String method5 = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckIsEditMain";
			isEditMain = RpcFacade.rpcCall(method5);
		} catch (Exception e) {

		}
		try {
			String method = "/Sale/Sale/Rpcs/MobileOrderRpc/ShowRemark";
			showRemark = RpcFacade.rpcCall(method);
		} catch (Exception e) {

		}	
		try {
    		String method="/Sale/Sale/Rpcs/MobileSaleClientRpc/SaleXiWangEnable";
        	enableSaleXiWangEnable = RpcFacade.rpcCall(method);
		} catch (Exception e) { 
		}
	}

	
	
	@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_SelectStore:
			ReceiveSelectStoreResult(intent);
			break;
		case RequestCode_SelectAccountingUnit:
			ReceiveSelectAccountingUnitResult(intent);
			break;
		}

	}
	
	@SuppressWarnings("unchecked")
	private void ReceiveSelectAccountingUnitResult(Intent intent) {	
			HashMap<String, Object> map = (HashMap<String, Object>) intent
					.getSerializableExtra("Result");
			mDmo.setString("AccountingUnit_Name", (String) map.get("Name"));
			mDmo.setLong("AccountingUnit_ID", (Long) map.get("ID"));
			applyToUI();
	}

	private void ReceiveSelectStoreResult(Intent intent) {
		HashMap<String, Object> map = (HashMap<String, Object>) intent
				.getSerializableExtra("Result");
		mDmo.setString("Store_Name", (String) map.get("Name"));
		mDmo.setLong("Store_ID", (Long) map.get("ID"));
		applyToUI();
	}

	CallableTask initBillTask = new CallableTask(this, "读取单据中...") {
		public Object call() throws Exception {
			if (mBillID > 0) {
				String method = "/Sale/Sale/Rpcs/MobileOrderRpc/Load";
				mDmo = RpcFacade.rpcCall(method, mBillID);
				method = "/Sale/Sale/Rpcs/MobileOrderRpc/EnableCheck";
				mEnableCheck = RpcFacade.rpcCall(method, mBillID);
				method = "/Sale/Sale/Rpcs/MobileOrderRpc/EnableUnCheck";
				mEnableUnCheck = RpcFacade.rpcCall(method, mBillID);
			} else {
				mDmo = RpcObject.create("/Sale/Sale/BO/MobileOrder");
				mDmo.setDate("Date", new Date());
			}
			return null;
		}

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

	};
	private void initControls() {
		
		InitButtonSave();

		InitButtonCheck();
		InitButtonUnCheck();
		InitButtonDelete();
		InitLoadTQSave();
		InitLoadTQSave2();
		InitListView();

		InitRemark();

		InitBuyer();

		InitDate();
		
		InitStore();
		
		InitAccountingUnit();
	}
	private void InitDate() {
		button_Date = ActivityUtil.Find(this, R.id.Order_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("Date", 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.Order_TextView_BuyerName);
		if(isOrNotShowBalance){
			textView_Balance = ActivityUtil.Find(this, R.id.Order_TextView_Balance);
		}
		Button searchBuyerButton = ActivityUtil.FindButton(this,
				R.id.Order_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 InitAccountingUnit() {
		LinearLayout layout = (LinearLayout)findViewById(R.id.accountingUnitUI);
		if(!isOrNotShowAccountingUnitAndStore){
			return;
		}
		layout.setVisibility(View.VISIBLE);
		textView_AccountingUnit = ActivityUtil.Find(this, R.id.Order_TextView_AccountingUnit);
		Button searchButton = ActivityUtil.FindButton(this,
				R.id.Order_Button_SelectAccountingUnit);
		if (!mEnableSave) {
			searchButton.setVisibility(View.GONE);
			return;
		}

		searchButton.setOnClickListener(new OnClickListener() {

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

		});
	}
	
	private void InitStore() {
		LinearLayout layout = (LinearLayout)findViewById(R.id.storeUI);
		if(!isOrNotShowAccountingUnitAndStore){
			
			return;
		}
		layout.setVisibility(View.VISIBLE);
		textView_StoreName = ActivityUtil.Find(this, R.id.Order_TextView_Store);
		
		Button searchButton = ActivityUtil.FindButton(this,
				R.id.Order_Button_SelectStore);
		if (!mEnableSave) {
			searchButton.setVisibility(View.GONE);
			return;
		}

		searchButton.setOnClickListener(new OnClickListener() {

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

		});
	}
	
	
	//摘要
	private void InitRemark() {
		if (mEnableSave) {
			textViewRemark = ActivityUtil.Find(this, R.id.Order_EditText_Remark);
			ActivityUtil.Find(this, R.id.Order_TextView_Remark).setVisibility(
					View.GONE);

			Button searchRemarkButton = ActivityUtil.FindButton(this,
					R.id.Order_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.Order_TextView_Remark);
			ActivityUtil.Find(this, R.id.Order_EditText_Remark).setVisibility(
					View.GONE);
			ActivityUtil.FindButton(this, R.id.Order_Button_SelectRemark).setVisibility(
					View.GONE);
		}
	}
	//ListView
	private void InitListView() {
		textViewDetailCount = ActivityUtil
				.Find(this, R.id.Order_TextView_DetailCount);
		listView = ActivityUtil.Find(this, R.id.Order_ListView);
		Button selectGoods = ActivityUtil.Find(this, R.id.Order_Button_SelectGoods);
		selectGoods.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if(mDmo.getLong("Buyer_ID") == null){
					Toast.makeText(getApplicationContext(), "请先选择购货客户！", 1).show();
					return;
				}
				if(mDmo.getDate("Date") == null){
					Toast.makeText(getApplicationContext(), "请先选择到货时间！", 1).show();
					return;
				}
				
				Intent intent = new Intent();
				intent.putExtra("Buyer_ID", mDmo.getLong("Buyer_ID"));
				intent.putExtra("AccountingUnit_ID", mDmo.getLong("AccountingUnit_ID"));
				Date date = mDmo.getDate("Date");
				button_Date = (TextView)findViewById(R.id.Order_Button_Date);
				intent.putExtra("Date", button_Date.getText());
				intent.putExtra("IsOrNotShowSecond", isOrNotShowSecond);
				intent.putExtra("IsEditSecond", isEditSecond);
				intent.putExtra("IsEditMain", isEditMain);
				intent.putExtra("ShowRemark", showRemark);				
				intent.setClass(arg0.getContext(), SelectGoodsActivity.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("Details").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("run to this");
				if(button_Date.getText()==null || button_Date.getText() == ""){
					Toast.makeText(getApplicationContext(), "请先选择到货时间！", 1).show();
				}
				selectedPosition = position;
				RpcObject result = mDmo.getManyList("Details").get(position);
				EditingDetail = result;
				Intent intent = new Intent();
				intent.setClass(arg1.getContext(),
						OrderDetailEditActivity.class);
				intent.putExtra("Position", position);
				intent.putExtra("IsOrNotShowSecond", isOrNotShowSecond);
				intent.putExtra("Buyer_ID", mDmo.getLong("Buyer_ID"));
				intent.putExtra("Date", button_Date.getText());
				intent.putExtra("AccountingUnit_ID", mDmo.getLong("AccountingUnit_ID"));
				intent.putExtra("IsEditSecond", isEditSecond);
				intent.putExtra("IsEditMain", isEditMain);
				intent.putExtra("ShowRemark", showRemark);				
				HashMap<String, Object> map = new HashMap<String, Object>();
				Iterator<Entry<String, Object>> iterator = result.entrySet()
						.iterator();
				while (iterator.hasNext()) {
					Entry<String, Object> entry = iterator.next();
					String cccString = entry.getKey();
					if(cccString.equals("Goods_ConvertMode")){
						continue;
					}
					map.put(entry.getKey(), entry.getValue());
				}
				intent.putExtra("Detail", map);
				startActivityForResult(intent, RequestCode_EditDetail);
			}

		});
		 
	}
	
	//删除
	private void InitButtonDelete() {
		deleteTask.setPrompt("确定要删除吗?");
		Button buttonDelete = ActivityUtil.Find(this, R.id.Order_Button_Delete);
		if (!mEnableDelete) {
			buttonDelete.setVisibility(View.GONE);
		}
		buttonDelete.setOnClickListener(deleteTask);
	}
	ViewOnClickTask deleteTask = new ViewOnClickTask(this, "删除中...") {

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

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

		}
	};
	
	//审核
	private void InitButtonCheck() {
		Button buttonSave = ActivityUtil.Find(this, R.id.Order_Button_Check);
		if (!mEnableCheck) {
			buttonSave.setVisibility(View.GONE);
		}
		buttonSave.setOnClickListener(checkTask);

	}
	ViewOnClickTask checkTask = new ViewOnClickTask(this, "审核中...") {

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

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

		}
	};
	
	private void InitButtonUnCheck() {
		Button buttonSave = ActivityUtil.Find(this, R.id.Order_Button_UnCheck);
		if (!mEnableUnCheck||!mShowUnCheck) {
			buttonSave.setVisibility(View.GONE);
		}
		buttonSave.setOnClickListener(unCheckTask);

	}
	
	ViewOnClickTask unCheckTask = new ViewOnClickTask(this, "撤销中...") {

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

		@Override
		protected void successUI() {
			DialogUtil.AutoHiddenAlert(OrderEditActivity.this, "撤销成功");
			finish();
			Intent intent = new Intent();
			intent.putExtra("ID", mBillID);
			intent.setClass(OrderEditActivity.this, OrderEditActivity.class);
			startActivityForResult(intent, OrderEditActivity.RequestCode_Open);

		}
	};
	//保存
	private void InitButtonSave() {
		Button buttonSave = ActivityUtil.Find(this, R.id.Order_Button_Save);
		if (!mEnableSave) {
			buttonSave.setVisibility(View.GONE);
		}
		buttonSave.setOnClickListener(saveTask);
	}
	
	ViewOnClickTask saveTask = new ViewOnClickTask(this, "保存中...") {
		public Object call() throws Exception {
			mDmo.setString("Remark", textViewRemark.getText().toString());
			if (mBillID > 0) {
				String method = "/Sale/Sale/Rpcs/MobileOrderRpc/Update";
				RpcFacade.rpcCall(method, mDmo);
			} else {
				String method = "/Sale/Sale/Rpcs/MobileOrderRpc/Insert";
				mBillID = RpcFacade.rpcCall(method, mDmo);
			}
			return null;
		}

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

	};
	
	int type = 0;
	private void InitLoadTQSave() {
		Button buttonLoad = ActivityUtil.Find(this, R.id.Order_Button_LoadTQ);
		if (!enableSaleXiWangEnable ) {
			buttonLoad.setVisibility(View.GONE);
		}
		buttonLoad. setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if(mDmo.getLong("Buyer_ID") == null){
					Toast.makeText(getApplicationContext(), "请先选择购货客户！", 1).show();
					return;
				}
				if(mDmo.getDate("Date") == null){
					Toast.makeText(getApplicationContext(), "请先选择到货时间！", 1).show();
					return;
				} 
				type = 0;
				loadTQTask.execute();
			}

		});
	}

	private void InitLoadTQSave2() {
		Button buttonLoad = ActivityUtil.Find(this, R.id.Order_Button_LoadTQ2);
		if (!enableSaleXiWangEnable  ) {
			buttonLoad.setVisibility(View.GONE);
		}
		buttonLoad.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (mDmo.getLong("Buyer_ID") == null) {
					Toast.makeText(getApplicationContext(), "请先选择购货客户！", 1)
							.show();
					return;
				}
				if (mDmo.getDate("Date") == null) {
					Toast.makeText(getApplicationContext(), "请先选择到货时间！", 1)
							.show();
					return;
				}
				type = 1;
				loadTQTask.execute();
			}

		});
	}

 	ViewOnClickTask loadTQTask = new ViewOnClickTask(this, "加载中...") {
		public Object call() throws Exception { 
				String method = "/Sale/SaleXiWang/Rpcs/OrderRpc/GetLastOrderInfo";
				ManyList details = mDmo.getManyList("Details");
				mDetails = RpcFacade.rpcCall (method, mDmo.getLong("Buyer_ID"),mDmo.getDate("Date"),type ,details);
	 
			return null;
		}

		@Override
		protected void successUI() {
			ManyList details = mDmo.getManyList("Details");
			details.clear();
			for (RpcObject item : mDetails) {
				details.add(item);
			}
			applyToUI();
		}

	};
	
	private void applyToUI() {
		if (mDmo == null) {
			DialogUtil.Alert(OrderEditActivity.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("Date")));
		textViewRemark.setText(mDmo.getString("Remark"));
		if(isOrNotShowBalance){
			SetBalance();
		}
		if(isOrNotShowAccountingUnitAndStore){
			textView_AccountingUnit.setText(mDmo.getString("AccountingUnit_Name"));
			textView_StoreName.setText(mDmo.getString("Store_Name"));
		}
		ManyList details = mDmo.getManyList("Details");

		BigDecimal allMoney = 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("Number");
			if (number == null) {
				number = new BigDecimal(0);
			}
			allMoney = allMoney.add(price.multiply(number)); 
		}

		textViewDetailCount.setText(String.format("%s￥%.2f", details.size(),
				allMoney));
 
		SelectSimpleAdapter adapter = new SelectSimpleAdapter(
				OrderEditActivity.this, details,
				R.layout.order_edit_detail_list_item, new String[] {
						"Goods_Name", "Number","SecondNumber", "Price","BatchNo_Name","LastYearInfo" ,"LastWeekInfo"}, new int[] {
						R.id.Goods_Name, R.id.Number,R.id.SecondNumber, R.id.Price,R.id.BatchNo ,R.id.TQNumber  ,R.id.TQNumber2});
		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);
		 
				
	}
	

	@SuppressWarnings("unchecked")
	private void ReceiveEditDetail(Intent intent) {
		int position = intent.getIntExtra("Position", -1);
		RpcObject detail = mDmo.getManyList("Details").get(position);
		HashMap<String, Object> map = (HashMap<String, Object>) intent
				.getSerializableExtra("Detail");
		detail.setMoney("Number", (BigDecimal) map.get("Number"));
		detail.setMoney("SecondNumber", (BigDecimal) map.get("SecondNumber"));
		detail.setMoney("Price", (BigDecimal) map.get("Price"));
		detail.setMoney("PolicyPrice", (BigDecimal) map.get("PolicyPrice"));
		detail.setString("Remark", (String) map.get("Remark"));		
		if(map.get("BatchNo_ID")!=null){
			detail.setLong("BatchNo_ID", (Long) map.get("BatchNo_ID"));
			detail.setString("BatchNo_Name", (String) map.get("BatchNo_Name"));
		}
		applyToUI();
		
	}

	private void ReceiveSelectGoodsResult(Intent intent) {
		firstVisiblePosition = listView.getBottom();
		Object[] result = (Object[]) intent.getSerializableExtra("Result");
		ManyList details = mDmo.getManyList("Details");
		for (Object item : result) {
			@SuppressWarnings("unchecked")
			HashMap<String, Object> map = (HashMap<String, Object>) item;
			try {
				RpcObject detail = RpcObject
						.create("/Sale/Sale/BO/MobileOrder_Detail");
				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("Number", (BigDecimal) map.get("Number"));
				detail.setMoney("SecondNumber", (BigDecimal) map.get("SecondNumber"));
				detail.setMoney("Price", (BigDecimal) map.get("Price"));
				detail.setMoney("Goods_SecondaryUnit1RelativeRatio", (BigDecimal) map.get("Goods_SecondaryUnit1RelativeRatio"));
				detail.setMoney("Goods_SecondaryUnit1Ratio", (BigDecimal) map.get("Goods_SecondaryUnit1Ratio"));
				detail.setMoney("LeftRatio", (BigDecimal) map.get("LeftRatio"));
				detail.setMoney("RightRatio", (BigDecimal) map.get("RightRatio"));
				detail.setLong("BatchNo_ID", (Long) map.get("BatchNo_ID"));
				detail.setString("BatchNo_Name", (String) map.get("BatchNo_Name"));		
				detail.setString("Remark", (String) map.get("remark"));
				if(details.size() > 0){
				if(detail.getLong("BatchNo_ID") == null){
					RpcObject orderDetail = details.get(details.size()-1);
					detail.setLong("BatchNo_ID", orderDetail.getLong("BatchNo_ID"));
					detail.setString("BatchNo_Name", orderDetail.getString("BatchNo_Name"));
				}
				}
				detail.setMoney("PolicyPrice", (BigDecimal)map.get("PolicyPrice"));
				
				details.add(detail);
			} catch (JsonRpcException e) {
				e.printStackTrace();
			}
		}
		applyToUI();
	}

	private void GetLeftAndRightRatio(Long buyer_ID, Long goods_ID,RpcObject detail) {
		String method = "/Sale/Sale/Rpcs/MobileOrderRpc/GetLeftAndRightRatio";
		RpcObject orderDetail = RpcFacade.rpcCall(method, buyer_ID,goods_ID);
		if(orderDetail!=null){
			detail.setMoney("Goods_SecondaryUnit1Ratio", orderDetail.getMoney("Goods_SecondaryUnit1Ratio"));
			detail.setMoney("Goods_SecondaryUnit1RelativeRatio", orderDetail.getMoney("Goods_SecondaryUnit1RelativeRatio"));
			detail.setMoney("LeftRatio", orderDetail.getMoney("LeftRatio"));
			detail.setMoney("LeftRatio", orderDetail.getMoney("LeftRatio"));
		}
	}

	@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 SetBalance(){
		String method = "/Sale/Sale/Rpcs/MobileOrderRpc/GetBlance";
		BigDecimal balance = RpcFacade.rpcCall(method, mDmo.getLong("Buyer_ID"));
		if(balance!=null){
			textView_Balance.setText(balance.toString());
		}else{
			textView_Balance.setText("");
		}
	}

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

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Option_FindDetail:
			DialogUtil.Prompt(OrderEditActivity.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(OrderEditActivity.this, "确定要清空明细吗?", "是", "否",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							selectedPosition = -1;
							mDmo.getManyList("Details").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);
	}
	
	CallableTask searchDetailTask = new CallableTask(this, "") {

		private int searchResult;

		public Object call() throws Exception {
			searchResult = -1;
			ManyList details = mDmo.getManyList("Details");
			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(OrderEditActivity.this, "没有查找到匹配的明细");
			}
		}
	};

}
