package com.backfire.doudizhu.ranklist;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import net.yeeyo.doudizhu.feiyu.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.backfire.doudizhu.ActivityContainer;
import com.backfire.doudizhu.ActivityContainer.ActivityType;
import com.backfire.doudizhu.ActivityThirdPlatform;
import com.backfire.doudizhu.common.ClickFilter;
import com.backfire.doudizhu.common.DdzApplication;
import com.backfire.doudizhu.common.JSONUtil;
import com.backfire.doudizhu.common.MyJson;
import com.backfire.doudizhu.userinfo.UserInfo;
import com.backfire.doudizhu.userinfo.UserMessageCenter;
import com.backfire.php.PHPCallbackInterface;
import com.backfire.php.PHPMethodName;
import com.backfire.php.PHPRequestPool;
import com.backfire.php.PHPResult;
import com.backfire.php.PHPResult.ErrorCode;
import com.backfire.room.data.ConfigCenter;
import com.backfire.room.data.ResCenter;
import com.backfire.utils.Log;

public class HighScoreActivity extends ActivityThirdPlatform {

	private List<HighScore> moneyscores = null;
	private ListView scoreListView;
	private MoneyViewAdapter scoresListAdapter = null;

	private List<HighScore> buyscores = null;
	private ListView buyListView;
	private BuyViewAdapter buyListAdapter = null;

	private RelativeLayout money_layout;
	private RelativeLayout buy_layout;

	private RelativeLayout money_level_layout;
	private RelativeLayout buy_level_layout;

	private TextView money_level_text;
	private TextView buy_level_text;

	Drawable bg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.high_score_activity);

		bg = new BitmapDrawable(DdzApplication
				.getApplication()
				.getBmpPool()
				.getBitmap(R.drawable.shop_bg,
						DdzApplication.getApplication().screenWidth,
						DdzApplication.getApplication().screenHeight));
		((ImageView) this.findViewById(R.id.activity_bg))
				.setBackgroundDrawable(bg);

		((Button) findViewById(R.id.money_btn)).getPaint()
				.setFakeBoldText(true);
		((Button) findViewById(R.id.buy_btn)).getPaint().setFakeBoldText(true);

		money_layout = (RelativeLayout) findViewById(R.id.money_layout);
		buy_layout = (RelativeLayout) findViewById(R.id.buy_layout);

		money_level_layout = (RelativeLayout) findViewById(R.id.money_level_layout);
		buy_level_layout = (RelativeLayout) findViewById(R.id.buy_level_layout);

		money_level_text = (TextView) findViewById(R.id.money_level_text);
		buy_level_text = (TextView) findViewById(R.id.buy_level_text);
		userMsgChange();

		((ImageView) findViewById(R.id.activity_title_bg))
				.setBackgroundDrawable(new BitmapDrawable(DdzApplication
						.getApplication().getBmpPool()
						.getBitmap(R.drawable.title_bg, 0, 0)));
		money_layout.setBackgroundDrawable(new BitmapDrawable(DdzApplication
				.getApplication().getBmpPool()
				.getBitmap(R.drawable.help_list_bg_left, 0, 0)));
		buy_layout.setBackgroundDrawable(new BitmapDrawable(DdzApplication
				.getApplication().getBmpPool()
				.getBitmap(R.drawable.help_list_bg_middle, 0, 0)));

		moneyscores = new ArrayList<HighScore>();
		buyscores = new ArrayList<HighScore>();
		(new Handler()).postDelayed(new Runnable() {

			@Override
			public void run() {
				requestMoneyList();
			}

		}, 100);
	}

	private void userMsgChange() {
		((ImageView) findViewById(R.id.lobby_user_icon))
				.setBackgroundResource(UserMessageCenter
						.getUserIcon(UserMessageCenter.getInstance()
								.getUserInfo().getIcon()));
		((TextView) findViewById(R.id.lobby_user_nick))
				.setText(UserMessageCenter.getInstance().getUserInfo()
						.getNick());
		((TextView) findViewById(R.id.lobby_user_money))
				.setText(UserMessageCenter.getItemMoney(UserMessageCenter
						.getInstance().getUserInfo().getMoney()));
		((TextView) findViewById(R.id.my_money_1)).setText(Html
				.fromHtml("总资产：<font color=\"#dbe15b\">"
						+ UserMessageCenter.getLobbyMoney(UserMessageCenter
								.getInstance().getUserInfo().getMoney())
						+ "</font>"));
	}

	public void onClick_money(View view) {
		initView();
		money_layout.setVisibility(View.VISIBLE);
		if (moneyscores.size() == 0) {
			requestMoneyList();
		} else {
			money_level_layout.setVisibility(View.VISIBLE);
		}
		playBtnPressMusic();
	}

	public void onClick_buy(View view) {
		initView();
		buy_layout.setVisibility(View.VISIBLE);
		if (buyscores.size() == 0) {
			requestBuyList();
		} else {
			buy_level_layout.setVisibility(View.VISIBLE);
		}
		playBtnPressMusic();
	}

	public void onClick_direct_buy(View view) {
		quickBuy(1);// 直接购买
		// Toast.makeText(this, "功能暂未开放", Toast.LENGTH_SHORT).show();
		playBtnPressMusic();
	}

	private void initView() {
		money_layout.setVisibility(View.GONE);
		buy_layout.setVisibility(View.GONE);
		money_level_text.setVisibility(View.GONE);
		buy_level_text.setVisibility(View.GONE);
	}

	/*
	 * 返回按钮对应的处理方法
	 */
	public void onClick_back() {
		ActivityContainer.getInstance().switchTo(this,
				ActivityType.LOBBY_ACTIVITY);
	}

	/*
	 * 返回按钮对应的处理方法
	 */
	public void onClick_back(View view) {
		onClick_back();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (ClickFilter.TestMultiClick())
			return false;
		if (!this.isFinishing() && event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			onClick_back();
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void requestBuyList() {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(
				new ProcessBuyListRequestCallback(),
				PHPMethodName.CLI_BUY_LIST_REQ, json);
		startLoading("正在加载数据...");
	}

	private class ProcessBuyListRequestCallback implements PHPCallbackInterface {
		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.backfire.php.PHPCallbackInterface#onFinish(com.backfire.php.PHPResult
		 * )
		 */
		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				if (result != null && result.code == ErrorCode.SUCCESS) {
					JSONObject res = JSONUtil.parse(result.recvData);
					if (res != null) {
						Log.v(this, result.recvData);
						int ret = JSONUtil.getInt(res, "ret", 2);
						if (ret == 1) {
							JSONArray scoresArray = JSONUtil.getJSONArray(res,
									"rechargeRanks");
							if (scoresArray != null && scoresArray.length() > 0) {
								try {
									buyscores.clear();
									for (int i = 0, n = scoresArray.length(); i < n; i++) {
										JSONObject p = scoresArray
												.getJSONObject(i);
										HighScore score = new HighScore();
										score.setPosition(JSONUtil.getInt(p,
												"position", 0));
										score.setUnick(JSONUtil.getString(p,
												"unick", ""));
										score.setMoney(JSONUtil.getLong(p,
												"money", 0));
										score.setIcon(JSONUtil.getString(p,
												"icon", ""));
										score.setUid(JSONUtil.getLong(p, "uid",
												0));
										if (score.getPosition() == 1) {
											score.setScoreicon(R.drawable.rank_first);
										} else if (score.getPosition() == 2) {
											score.setScoreicon(R.drawable.rank_second);
										} else if (score.getPosition() == 3) {
											score.setScoreicon(R.drawable.rank_third);
										}
										buyscores.add(score);
									}
								} catch (JSONException e) {
									e.printStackTrace();
									String msg = getString(R.string.network_error);
									showMessage(msg);
								}
							}
							if (buyscores.size() > 0) {
								buy_level_layout.setVisibility(View.VISIBLE);
								buy_level_text.setVisibility(View.GONE);
								if (buyListView == null) {
									buyListAdapter = new BuyViewAdapter(
											HighScoreActivity.this);
									buyListView = (ListView) findViewById(R.id.buyListView);
									buyListView
											.setVerticalScrollBarEnabled(true);
									buyListView.setAdapter(buyListAdapter);
									buyListView.setSelected(true);
									buyListView.setSelection(0);
								} else {
									scoresListAdapter.notifyDataSetChanged();
								}
								HighScore score = buyscores.get(0);
								if (score.getPosition() > 0)
									((TextView) findViewById(R.id.my_icon_score_2))
											.setText(score.getPosition() + "");
								else
									((TextView) findViewById(R.id.my_icon_score_2))
											.setText("未入榜");
								((ImageView) findViewById(R.id.my_icon_2))
										.setBackgroundResource(ResCenter
												.getUserIcon(UserMessageCenter
														.getInstance()
														.getUserInfo()
														.getIcon()));
								((TextView) findViewById(R.id.my_nick_2))
										.setText(score.getUnick());
								((TextView) findViewById(R.id.my_money_2))
										.setText(Html.fromHtml("昨日充值：<font color=\"#dbe15b\">"
												+ ConfigCenter
														.getLobbyMoney(score
																.getMoney())
												+ "</font>"));
							} else {
								buy_level_layout.setVisibility(View.GONE);
								buy_level_text.setVisibility(View.VISIBLE);
								buy_level_text.setText("暂不存在该排行");
							}

						} else {
							// 登陆失败
							int retCode = JSONUtil.getInt(res, "retCode", 2);
							String msg = JSONUtil.getString(res, "retMsg", "");
							showMessage(msg + "(" + retCode + ")");
						}
					} else {
						String msg = getString(R.string.network_error);
						showMessage(msg);
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
			}
		}
	}

	private class MoneyViewAdapter extends BaseAdapter {

		private LayoutInflater mLayoutInflater;

		public MoneyViewAdapter(Context context) {
			this.mLayoutInflater = LayoutInflater.from(context);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getCount()
		 */
		@Override
		public int getCount() {
			int count = 0;
			if (moneyscores != null) {
				count = moneyscores.size() - 1;
			}
			return count;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getItem(int)
		 */

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getItemId(int)
		 */
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getView(int, android.view.View,
		 * android.view.ViewGroup)
		 */
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			try {
				ViewHolder holder = null;
				if (convertView == null) {
					holder = new ViewHolder();
					convertView = this.mLayoutInflater.inflate(
							R.layout.hight_scrore_item, null);

					holder.icon = (ImageView) convertView
							.findViewById(R.id.icon);
					holder.position = (TextView) convertView
							.findViewById(R.id.position);
					holder.nick = (TextView) convertView
							.findViewById(R.id.nick);
					holder.money = (TextView) convertView
							.findViewById(R.id.money);
					holder.iconscore = (ImageView) convertView
							.findViewById(R.id.scoreicon);
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				HighScore score = moneyscores.get(position + 1);
				if (score != null) {
					if (score.getScoreicon() > 0) {
						holder.iconscore.setVisibility(View.VISIBLE);
						holder.position.setVisibility(View.GONE);
						holder.iconscore.setImageResource(score.getScoreicon());
					} else {
						holder.iconscore.setVisibility(View.GONE);
						holder.position.setVisibility(View.VISIBLE);
						holder.position.setText(score.getPosition() + "");
					}
					holder.nick.setText(score.getUnick());
					holder.money.setText(Html
							.fromHtml("总资产：<font color=\"#dbe15b\">"
									+ ConfigCenter.getLobbyMoney(score
											.getMoney()) + "</font>"));
					holder.icon.setBackgroundResource(ResCenter
							.getUserIcon(score.getIcon()));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}
	}

	private void requestMoneyList() {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(
				new ProcessMoneyRequestCallback(),
				PHPMethodName.CLI_MONET_LIST_REQ, json);
		startLoading("正在加载数据...");
	}

	private class ProcessMoneyRequestCallback implements PHPCallbackInterface {
		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.backfire.php.PHPCallbackInterface#onFinish(com.backfire.php.PHPResult
		 * )
		 */
		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				if (result != null && result.code == ErrorCode.SUCCESS) {
					JSONObject res = JSONUtil.parse(result.recvData);
					if (res != null) {
						Log.v(this, result.recvData);
						int ret = JSONUtil.getInt(res, "ret", 2);
						if (ret == 1) {
							JSONArray scoresArray = JSONUtil.getJSONArray(res,
									"wealthRanks");
							if (scoresArray != null && scoresArray.length() > 0) {
								try {
									moneyscores.clear();
									for (int i = 0, n = scoresArray.length(); i < n; i++) {
										JSONObject p = scoresArray
												.getJSONObject(i);
										HighScore score = new HighScore();
										score.setPosition(JSONUtil.getInt(p,
												"position", 0));
										score.setUnick(JSONUtil.getString(p,
												"unick", ""));
										score.setMoney(JSONUtil.getLong(p,
												"money", 0));
										score.setIcon(JSONUtil.getString(p,
												"icon", "1"));
										score.setUid(JSONUtil.getLong(p, "uid",
												0));
										if (score.getPosition() == 1) {
											score.setScoreicon(R.drawable.rank_first);
										} else if (score.getPosition() == 2) {
											score.setScoreicon(R.drawable.rank_second);
										} else if (score.getPosition() == 3) {
											score.setScoreicon(R.drawable.rank_third);
										}
										moneyscores.add(score);
									}
								} catch (JSONException e) {
									e.printStackTrace();
									String msg = getString(R.string.network_error);
									showMessage(msg);
								}
							}
							if (moneyscores.size() > 0) {
								money_level_layout.setVisibility(View.VISIBLE);
								money_level_text.setVisibility(View.GONE);
								Log.i(this, "moneyscores:" + moneyscores.size());
								if (scoreListView == null) {
									scoresListAdapter = new MoneyViewAdapter(
											HighScoreActivity.this);
									scoreListView = (ListView) findViewById(R.id.scoreListView);
									scoreListView
											.setVerticalScrollBarEnabled(true);
									scoreListView.setAdapter(scoresListAdapter);
									scoreListView.setSelected(true);
									scoreListView.setSelection(0);
								} else {
									scoresListAdapter.notifyDataSetChanged();
								}
								HighScore score = moneyscores.get(0);
								if (score.getPosition() > 0)
									((TextView) findViewById(R.id.my_icon_score_1))
											.setText(score.getPosition() + "");
								else
									((TextView) findViewById(R.id.my_icon_score_1))
											.setText("未入榜");
								((ImageView) findViewById(R.id.my_icon_1))
										.setBackgroundResource(ResCenter
												.getUserIcon(UserMessageCenter
														.getInstance()
														.getUserInfo()
														.getIcon()));
								((TextView) findViewById(R.id.my_nick_1))
										.setText(score.getUnick());
								((TextView) findViewById(R.id.my_money_1))
										.setText(Html.fromHtml("总资产：<font color=\"#dbe15b\">"
												+ ConfigCenter
														.getLobbyMoney(UserMessageCenter
																.getInstance()
																.getUserInfo()
																.getMoney())
												+ "</font>"));
							} else {
								money_level_layout.setVisibility(View.GONE);
								money_level_text.setVisibility(View.VISIBLE);
								money_level_text.setText("暂不存在该排行");
							}

						} else {
							// 登陆失败
							int retCode = JSONUtil.getInt(res, "retCode", 2);
							String msg = JSONUtil.getString(res, "retMsg", "");
							showMessage(msg + "(" + retCode + ")");
						}
					} else {
						String msg = getString(R.string.network_error);
						showMessage(msg);
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
			}
		}
	}

	private class BuyViewAdapter extends BaseAdapter {

		private LayoutInflater mLayoutInflater;

		public BuyViewAdapter(Context context) {
			this.mLayoutInflater = LayoutInflater.from(context);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getCount()
		 */
		@Override
		public int getCount() {
			int count = 0;
			if (buyscores != null) {
				count = buyscores.size() - 1;
			}
			return count;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getItem(int)
		 */

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getItemId(int)
		 */
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getView(int, android.view.View,
		 * android.view.ViewGroup)
		 */
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			try {
				ViewHolder holder = null;
				if (convertView == null) {
					holder = new ViewHolder();
					convertView = this.mLayoutInflater.inflate(
							R.layout.hight_scrore_item, null);

					holder.icon = (ImageView) convertView
							.findViewById(R.id.icon);
					holder.position = (TextView) convertView
							.findViewById(R.id.position);
					holder.nick = (TextView) convertView
							.findViewById(R.id.nick);
					holder.money = (TextView) convertView
							.findViewById(R.id.money);
					holder.iconscore = (ImageView) convertView
							.findViewById(R.id.scoreicon);
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				HighScore score = buyscores.get(position + 1);
				if (score != null) {
					if (score.getScoreicon() > 0) {
						holder.iconscore.setVisibility(View.VISIBLE);
						holder.position.setVisibility(View.GONE);
						holder.iconscore.setImageResource(score.getScoreicon());
					} else {
						holder.iconscore.setVisibility(View.GONE);
						holder.position.setVisibility(View.VISIBLE);
						holder.position.setText(score.getPosition() + "");
					}
					holder.nick.setText(score.getUnick());
					holder.money.setText(Html
							.fromHtml("昨日充值：<font color=\"#dbe15b\">"
									+ ConfigCenter.getLobbyMoney(score
											.getMoney()) + "</font>"));
					holder.icon.setBackgroundResource(ResCenter
							.getUserIcon(score.getIcon()));
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return convertView;
		}
	}

	public final class ViewHolder {
		ImageView iconscore; // 商品图标
		TextView position; // 商品价格
		TextView nick; // 商品价格
		TextView money; // 商品描述
		ImageView icon;; // 购买按钮
	}

	@Override
	public void showMessage(String msg) {
		DdzApplication.getApplication().showToast(msg);
	}

	@Override
	public void rechargeSuccess(String msg) {
		// TODO Auto-generated method stub
		userMsgChange();
		showInfo(msg);
	}

	public void quickBuy(int type) {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());
		param.put("type", type);

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new RechargeGoodsCallback(0),
				PHPMethodName.CLI_DIRECT_BUY_REQ, json);
		startLoading("正在加载数据...");
	}

	@Override
	protected void orderFailed(final long needMoney) {
		stopLoading();
		String msg = "充值不成功，请重试！";
		showMessage(msg);
		UserMessageCenter.getInstance().isGoodBuying = false;
	}

	@Override
	public void updateUserMsgSuccess() {
		userMsgChange();
	}

	@Override
	public String getTipBuy(long needMoney) {
		// TODO Auto-generated method stub
		return null;
	}

}
