package BWP.MobileSale.BranchOrder;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
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.BackRunTask;
import BWP.MobileSale.LoginedActivity;
import BWP.MobileSale.R;
import BWP.MobileSale.Ui.DownRefreshListView;
import BWP.MobileSale.Ui.DownRefreshListView.OnRefreshListener;
import BWP.MobileSale.Util.ActivityUtil;
import BWP.MobileSale.Util.CallableTask;
import BWP.MobileSale.Util.DateTimeUtil;
import BWP.MobileSale.Util.DialogUtil;
import BWP.MobileSale.Util.StringUtil;
import BWP.MobileSale.Util.DialogUtil.SetDate;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
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.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;

public class BranchOrderMainActivity extends LoginedActivity implements
		OnScrollListener {

	
	int perPageSize=20;
	int pageIndex=0;
	
	int MenuRefresh = 1;
	DownRefreshListView listView;
	
	String[] names = new String[] { "ID", "TodayLoadMoney", "BillDate",
			"Buyer_Name", "DiffReadyMoney" };
	int[] tos = new int[] { R.id.TextView_ID, R.id.TextView_TodayLoadMoney,
			R.id.TextView_BillDate, R.id.TextView_Buyer,
			R.id.TextView_DiffReadyMoney };

	ViewBinder viewBinder = new ViewBinder() {
		public boolean setViewValue(View view, Object data,
				String textRepresentation) {
			if (view.getId() == R.id.TextView_BillDate) {
				((TextView) view).setText(DateTimeUtil.FormatDate((Date) data));
				return true;
			} else {
				return false;
			}
		};
	};



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.branchorder_main);
		initFilter();
		initButtonDate();
		Button btnReturn=(Button)findViewById(R.id.Button_branchordermain_Return);
		btnReturn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		loadMoreButton = new Button(this);
		loadMoreButton.setText("查看更多...");
		loadMoreButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				loadMoreButton.setText("正在加载中..."); // 设置按钮文字
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						try {
							loadMoreData();
							
						} catch (JsonRpcException e) {
							e.printStackTrace();
						}
						pageadapter.notifyDataSetChanged();
						loadMoreButton.setText("查看更多..."); // 恢复按钮文字

					}
				}, 1000);
			}
		});
		InitActivity();
		//后期去掉的
		//listView.addFooterView(loadMoreButton);
		listView.setOnScrollListener(this);

		StartSearch();
	}

	private void StartSearch() {
		//searchTask.execute();
		searchTask1.execute();
	}

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

			public void setDate(Date date) {
				StartSearch();
			}

		});
	}
	private void InitActivity() {
		InitListView();
	}

	private void InitListView() {
		listView = (DownRefreshListView) findViewById(R.id.downrefreshlist);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				BranchOrderListView map = (BranchOrderListView) arg0.getItemAtPosition(arg2);
				
				
				Intent intent = new Intent();
				intent.putExtra("ID", map.getID());
				intent.setClass(arg1.getContext(), BranchOrderEditActivity.class);
				startActivity(intent);
			}
		});
		
		listView.setonRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				new AsyncTask<Void, Void, Void>() {
					protected Void doInBackground(Void... params) {
						try {
							
							Thread.sleep(500);
							
							String method = "/Sale/BranchOrder/Rpcs/MobileBranchOrderRpc/SearchRefresh";
							RpcObject argument = RpcObject.create("/Sale/Sale/Rpcs/RpcSearch");
							Resources resource = getResources();
							long maxid= pageadapter.Items.get(0).getID();
							argument.setLong("LastMaxId", maxid);
							
							String searchkey = (String) filter.getSelectedItem();
							argument.setString("SearchKey", searchkey);
						
							argument.setString("SearchKey2", (String)billStateFilter.getSelectedItem());
							
							String dateText = buttonDate.getText().toString();
							if(!StringUtil.IsNullOrEmpty(dateText)){
								Date parseDate = DateTimeUtil.ParseDate(dateText);
								argument.setDate("Date1", parseDate);
							}
							
							
							//pageIndex=0;
							
							DFDataTable table = RpcFacade.rpcCall(method, argument);
							List<RpcObject> rows = table.getRows();

						
							for (Iterator iterator = rows.iterator(); iterator.hasNext();) {

								RpcObject rpcObject = (RpcObject) iterator.next();

								BranchOrderListView item = new BranchOrderListView();
								item.setID(rpcObject.getLong("ID"));
								item.setBuyerName(rpcObject.getString("Buyer_Name"));
								item.setBillDate(rpcObject.getDate("BillDate"));
								System.out.println("---"+item.getID());
								item.setDiffReadyMoney(rpcObject.getMoney("DiffReadyMoney"));
								item.setTodayLoadMoney(rpcObject.getMoney("TodayLoadMoney"));							
					
								pageadapter.AddRefreshItem(item);
								
							}							
							
							
							
						} catch (Exception e) {
							e.printStackTrace();
						}
						
						
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						pageadapter.notifyDataSetChanged();
						listView.onRefreshComplete();
					}

				}.execute();
			}
		});
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == MenuRefresh) {
			pageIndex=0;
			StartSearch();
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MenuRefresh, 0, "刷新");
		return super.onCreateOptionsMenu(menu);

	}

	private void initFilter() {
		filter = ActivityUtil.Find(this, R.id.Spinner_Filter);
		billStateFilter = (Spinner) findViewById(R.id.Spinner_BillStateFilter);
		
		OnItemSelectedListener listener = new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				StartSearch();
				
			}

			public void onNothingSelected(AdapterView<?> parent) {
								
			}
		};
		
		filter.setOnItemSelectedListener(listener);
		billStateFilter.setOnItemSelectedListener(listener);
		
	}
	
	private Button refreshMoreButton;
	private Handler handler = new Handler();
	private Button loadMoreButton;
	private int visibleLastIndex = 0; // 最后的可视项索引
	private int visibleItemCount; // 当前窗口可见项总数
	private BranchOrderListViewAdapter pageadapter;
	private Spinner filter;
	private Spinner billStateFilter;
	private Button buttonDate;
	CallableTask searchTask1 = new CallableTask(this, "查询中...") {

		@Override
		public Object call() throws Exception {

			String method = "/Sale/BranchOrder/Rpcs/MobileBranchOrderRpc/Search";
			RpcObject argument = RpcObject.create("/Sale/Sale/Rpcs/RpcSearch");
			Resources resource = getResources();
			argument.setInt("PageSize", perPageSize);
			argument.setInt("PageIndex", pageIndex);
			
			//System.out.println("PageSize--"+perPageSize);
			//System.out.println("PageIndex--"+pageIndex);
			
			String searchkey = (String) filter.getSelectedItem();
			argument.setString("SearchKey", searchkey);
			//System.out.println("SearchKey--"+searchkey);
		
			argument.setString("SearchKey2", (String)billStateFilter.getSelectedItem());
			//System.out.println("SearchKey2--"+(String)billStateFilter.getSelectedItem());
			
			String dateText = buttonDate.getText().toString();
			if(!StringUtil.IsNullOrEmpty(dateText)){
				Date parseDate = DateTimeUtil.ParseDate(dateText);
				argument.setDate("Date1", parseDate);
				//System.out.println("Date1--"+DateTimeUtil.FormatDate(parseDate));
			}
			
			
			
			pageIndex=pageIndex+1;
			
			DFDataTable table = RpcFacade.rpcCall(method, argument);
			List<RpcObject> rows = table.getRows();

			List<BranchOrderListView> items = new ArrayList<BranchOrderListView>();

			for (Iterator iterator = rows.iterator(); iterator.hasNext();) {

				RpcObject rpcObject = (RpcObject) iterator.next();

				BranchOrderListView item = new BranchOrderListView();
				item.setID(rpcObject.getLong("ID"));
				item.setBuyerName(rpcObject.getString("Buyer_Name"));
				//item.setBillDate(rpcObject.getDate("BillDate"));
				//item.setBillDate(DateTimeUtil.AddDays(rpcObject.getDate("BillDate"),1) );						
				
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(rpcObject.getDate("BillDate"));
				calendar.add(Calendar.DATE, 0); 				
			
				Date date = DateTimeUtil.ParseDate(DateTimeUtil.FormatDate(calendar));
				item.setBillDate(date);
				//System.out.println(DateTimeUtil.FormatDate(date));
				
				item.setDiffReadyMoney(rpcObject.getMoney("DiffReadyMoney"));
				item.setTodayLoadMoney(rpcObject.getMoney("TodayLoadMoney"));

				items.add(item);

			}
			pageadapter = new BranchOrderListViewAdapter(items,
					BranchOrderMainActivity.this);
		
			
			return null;

		}

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

		}
	};

	
	private void loadMoreData() throws JsonRpcException {
	

		String method = "/Sale/BranchOrder/Rpcs/MobileBranchOrderRpc/Search";
		RpcObject argument = RpcObject.create("/Sale/Sale/Rpcs/RpcSearch");
		Resources resource = getResources();
		argument.setInt("PageSize", perPageSize);
		argument.setInt("PageIndex", pageIndex);
		
		String searchkey = (String) filter.getSelectedItem();
		argument.setString("SearchKey", searchkey);
	
		argument.setString("SearchKey2", (String)billStateFilter.getSelectedItem());
		
		String dateText = buttonDate.getText().toString();
		if(!StringUtil.IsNullOrEmpty(dateText)){
			
			try {
				Date parseDate = DateTimeUtil.ParseDate(dateText);
				argument.setDate("Date1", parseDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
		}
		
		
		pageIndex=pageIndex+1;
		
		DFDataTable table = RpcFacade.rpcCall(method, argument);
		List<RpcObject> rows = table.getRows();

		
//后期去掉的
//		if(rows.isEmpty()||rows.size()<perPageSize)
//		{
//			listView.removeFooterView(loadMoreButton);
//		}
		for (Iterator iterator = rows.iterator(); iterator.hasNext();) {

			RpcObject rpcObject = (RpcObject) iterator.next();

			BranchOrderListView item = new BranchOrderListView();
			item.setID(rpcObject.getLong("ID"));
			item.setBuyerName(rpcObject.getString("Buyer_Name"));
			
			//item.setBillDate(DateTimeUtil.AddDays(rpcObject.getDate("BillDate"),1) );
			Date dd=rpcObject.getDate("BillDate");
			Calendar calendar = Calendar.getInstance();
			calendar.set(dd.getYear(),dd.getMonth(), dd.getDay());
			Date date = DateTimeUtil.RemoveTime(calendar.getTime());
			item.setBillDate(date);
			System.out.println(date);
			item.setDiffReadyMoney(rpcObject.getMoney("DiffReadyMoney"));
			item.setTodayLoadMoney(rpcObject.getMoney("TodayLoadMoney"));

			
			pageadapter.addItem(item);
		}
		
		
System.out.println("后台加载中结束");
		
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

		this.visibleItemCount = visibleItemCount;
		visibleLastIndex = firstVisibleItem + visibleItemCount - 1;

		// if(totalItemCount == datasize+1){
		// listView.removeFooterView(loadMoreView);
		// Toast.makeText(this, "数据全部加载完!", Toast.LENGTH_LONG).show();
		// }

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		int itemsLastIndex = pageadapter.getCount() - 1; // 数据集最后一项的索引
		int lastIndex = itemsLastIndex + 1;
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& visibleLastIndex == lastIndex) {
			// 如果是自动加载,可以在这里放置异步加载数据的代码
		}
	
	}
	
	@Override
	protected void onResume() {
		pageIndex=0;
		StartSearch();
		super.onResume();
	}
}
