package BWP.MobileSale.Return;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;

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

import BWP.MobileSale.CommandService;
import BWP.MobileSale.LoginedActivity;
import BWP.MobileSale.R;
import BWP.MobileSale.SelectGoodsActivity;
import BWP.MobileSale.UserGoodsStarCommand;
import BWP.MobileSale.Util.ActivityUtil;
import BWP.MobileSale.Util.CallableTask;
import BWP.MobileSale.Util.DialogUtil;
import BWP.MobileSale.Util.OnPromptGoodsListener;
import BWP.MobileSale.Util.StringUtil;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
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.SimpleAdapter.ViewBinder;

public class ReturnSelectGoodsActivity extends LoginedActivity {
	private EditText searchKey;
	private ListView listView;
	private SimpleAdapter adapter;
	private Boolean mStarred;
	
	private String MannerReturn="退货拉回";
	private String MannerAbort="丢弃或销毁";

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

	};

	CallableTask searchTask = new CallableTask(this, "查询中...") {

		public Object call() throws Exception {
			String method = "/Sale/Returns/Rpcs/MobileReturnGoodsRpc/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(ReturnSelectGoodsActivity.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);
		}
	};

	LinkedHashMap<Long, RpcObject> selected = new LinkedHashMap<Long, RpcObject>();

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

		setContentView(R.layout.return_selectgoods);

		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() {

			/* (non-Javadoc)
			 * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
			 */
			/* (non-Javadoc)
			 * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
			 */
			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 {
					selected.put(id, data);
					BigDecimal number = data.getMoney("UnitNum");
					//BigDecimal price = data.getMoney("Price");
					//Short manner = data.getShort("ReturnsManner");
		
					
					String numStr="";
					//String priceStr="";
					//String mannerStr="";
					if(number!=null)
					{
						numStr=number.toString();
					}
//					if(priceStr!=null)
//					{
//						priceStr=priceStr.toString();
//					}
					
//					if(manner!=null)
//					{
//						if(manner == 0)
//						{
//							mannerStr=MannerReturn;
//						}
//						if(manner == 1)
//						{
//							mannerStr=MannerAbort;
//						}
//						
//					}
//					DialogUtil.Prompt(SelectGoodsActivity.this, "请输入",
//							data.getString("Number"), StringUtil.ToString(number),InputType.TYPE_NUMBER_FLAG_DECIMAL, new OnPromptListener() {
//								public void OnPrompt(String prompt) {
//									data.setMoney("Number",StringUtil.ParseMoney(prompt));
//								}
//							});
					try {
						DialogUtil.PromptGoods(ReturnSelectGoodsActivity.this, "请输入", numStr,  "", new OnPromptGoodsListener() {
							
							@Override
							public void OnPrompt(String num, String hadleType) {
								
								data.setMoney("UnitNum", StringUtil.ParseMoney(num));
								//data.setMoney("Price", StringUtil.ParseMoney(price));							
								
								
//								if(hadleType.equals(MannerReturn))
//								{
//									Short a=0;
//									data.setShort("ReturnsManner", a);
////									data.setNamedValue("ReturnsManner", a);								
//									
//								}
//								else if(hadleType.equals(MannerAbort))
//								{
//									Short a=1;
//									data.setShort("ReturnsManner", a);
//									//data.setNamedValue("ReturnsManner", a);							
//									
//								}
//								else
//								{
//									System.out.println("没有匹配的");
//								}															
								
							}
						});
					} catch (Exception e) {						
						e.printStackTrace();
						System.out.println("错误："+e.getMessage());
					}

					
				}
			}

		});

		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.i("SaleReturn", "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("SaleReturn", StringUtil.ToString(starred));

				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(ReturnSelectGoodsActivity.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) {
				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();
	}

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