package BWP.MobileSale.Order;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

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

import BWP.MobileSale.LoginedActivity;
import BWP.MobileSale.R;
import BWP.MobileSale.Util.ActivityUtil;
import BWP.MobileSale.Util.CallableTask;
import BWP.MobileSale.Util.DateTimeUtil;
import BWP.MobileSale.Util.DialogUtil;
import BWP.MobileSale.Util.DialogUtil.SetDate;
import BWP.MobileSale.Util.StringUtil;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Spinner;
import android.widget.TextView;

public class OrderListActivity extends LoginedActivity {

	int pageCount = 0;
	boolean flag = false;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		switch(requestCode){
		case OrderEditActivity.RequestCode_Open:
			StartQuery(false);
			break;
		}
	}

	private int GetPageCount(){
		String method = "/Sale/Sale/Rpcs/MobileOrderRpc/GetMobileOrderPageNum";
		try{
			RpcObject argument = SetArgument();
			return RpcFacade.rpcCall(method,argument);
		}catch(Exception e){
					
		}
		return 0;
	}

	ViewBinder viewBinder = new ViewBinder() {
		public boolean setViewValue(View view, Object data,
				String textRepresentation) {
			if (view.getId() == R.id.TextView_Date) {
				((TextView)view).setText(DateTimeUtil.FormatDate((Date) data));
				return true;
			}
			else{
				return false;
			}
		}
	};
	
	String[] columnNames = new String[]{"ID","Money","Buyer_Name","Date","BillState"};
	
	int[] columnIDs = new int[]{R.id.TextView1,R.id.TextView2,R.id.TextView3,R.id.TextView_Date,R.id.TextView_BillState};
	
	class SumInfo{
		public int RowCount;
		public BigDecimal Money;
		@Override
		public String toString() {
			return String.format("共%s条记录,%s元",RowCount,Money);
		}
		
	}
	
	SumInfo mSumInfo = new SumInfo();
	int pageIndex = 1;
	CallableTask searchTask = new CallableTask(this, "查询中...") {

		public Object call() throws Exception {
			String method = "/Sale/Sale/Rpcs/MobileOrderRpc/Search";
			
			if(flag == false){
				pageCount = GetPageCount();
			}
			
			Resources resource = getResources();
			
/*
			String searchkey = (String) filter.getSelectedItem();
			argument.setString("SearchKey", searchkey);
	*/	
			RpcObject argument = SetArgument();
			DFDataTable table = RpcFacade.rpcCall(method, argument);
			List<RpcObject> rows = table.getRows();
			mSumInfo.Money = new BigDecimal(0);
			for(RpcObject row:rows){
				mSumInfo.Money = mSumInfo.Money.add(row.getMoney("Money"));
			}
			adapter = new SimpleAdapter(OrderListActivity.this, rows,
					R.layout.order_list_item, columnNames,columnIDs);
			adapter.setViewBinder(viewBinder);
			return null;
			
		}

		

		@Override
		protected void successUI() {
			listView.setAdapter(adapter);
		}


	};
	
	private RpcObject SetArgument() throws ParseException {
		RpcObject argument = RpcObject.create("/Sale/Sale/Rpcs/RpcSearch");
		argument.setString("SearchKey2", (String)billStateFilter.getSelectedItem());
		argument.setString("OrderBy", (String)orderByFilter.getSelectedItem());
		String dateText = buttonDate.getText().toString();
		String dateText2 = buttonEndDate.getText().toString();
		if(!StringUtil.IsNullOrEmpty(dateText)){
			Date parseDate = (Date) DateTimeUtil.ParseDate(dateText);
			argument.setDate("Date1", parseDate);
		}
		if(!StringUtil.IsNullOrEmpty(dateText2)){
			Date parseEndDate = (Date) DateTimeUtil.ParseDate(dateText2);
			argument.setDate("Date2", parseEndDate);
		}
		argument.setInt("PageIndex", pageIndex);
		return argument;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, Menu.FIRST, 0, "刷新");
		menu.add(0,2,1,"统计");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST:
			StartQuery(false);
			break;
		case 2:
			DialogUtil.Alert(this, mSumInfo.toString());
			break;
		}
		return super.onOptionsItemSelected(item);
	}

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

		setContentView(R.layout.order_list);

		initButtonReturn();

		initListView();

		initFilter();
		
		initButtonDate();
		initButtonNextPage();
		initButtonUpPage();
		StartQuery(false);

	}

	private void initFilter() {
		orderByFilter = (Spinner) findViewById(R.id.Spinner_OrderBy);
		billStateFilter = (Spinner) findViewById(R.id.Spinner_BillStateFilter);
		
		OnItemSelectedListener listener = new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				pageIndex = 1;
				StartQuery(false);
				
			}

			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		};
		
		orderByFilter.setOnItemSelectedListener(listener);
		billStateFilter.setOnItemSelectedListener(listener);
		
	}

	private void initButtonReturn() {
		ActivityUtil.FindButton(this, R.id.Button_Return)

		.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});
	}
	
	private void initButtonNextPage() {
		ActivityUtil.FindButton(this, R.id.Button_NextPage)
		.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				pageIndex++;
				if(pageIndex >= pageCount){
					return;
				}
				StartQuery(true);
			}
		});
	}
	
	private void initButtonUpPage() {
		ActivityUtil.FindButton(this, R.id.Button_UpPage)
		.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				
				pageIndex--;
				if(pageIndex <= 0){
					return;
				}
				StartQuery(true);
			}
		});
	}
	private void initListView() {
		listView = ActivityUtil.Find(this, R.id.ListView);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				HashMap<String, Object> map = (HashMap<String, Object>) arg0
						.getItemAtPosition(arg2);
				Intent intent = new Intent();
				intent.putExtra("ID", (Long) map.get("ID"));
				intent.setClass(arg1.getContext(), OrderEditActivity.class);
				startActivityForResult(intent,
						OrderEditActivity.RequestCode_Open);
			}

		});
	}

	private void initButtonDate() {
		buttonDate = ActivityUtil.FindButton(this, R.id.Button_Date);
		DialogUtil.AddSelectDateDialog(buttonDate, new SetDate() {			

			@Override
			public void setDate(java.util.Date date) {
				pageIndex = 1;
				StartQuery(false);
			}

		});
		buttonEndDate = ActivityUtil.FindButton(this, R.id.Button_EndDate);
		DialogUtil.AddSelectDateDialog(buttonEndDate, new SetDate() {			

			@Override
			public void setDate(java.util.Date date) {
				pageIndex = 1;
				StartQuery(false);
			}

		});
	}

	private void StartQuery(boolean flag2) {
		flag = flag2;
		searchTask.execute();
	}

	ListView listView;
	private SimpleAdapter adapter;
	private Button buttonDate;
	private Button buttonEndDate;

	private Spinner filter;
	private Spinner billStateFilter;
	private Spinner orderByFilter;
}
