package com.backfire.doudizhu.shop;

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.View.OnClickListener;
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 cn.wimipay.sdk.WimiPaySdk;

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.lobby.AddStatistics;
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.utils.Log;

public class ShopActivity extends ActivityThirdPlatform {

	private List<Product> myProducts_1 = null;
	private List<Product> myProducts_2 = null;

	private ListView[] productListView;
	private MyProductViewAdapter[] productListAdapter = null;
	private RelativeLayout[] product_layout = null;

	private TextView[] product_list_text = null;
	Drawable bg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shop_activity);
		
		
//		WimiPaySdk.init(this);//微米支付初始化
		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.onClick_type_1)).getPaint()
				.setFakeBoldText(true);
		((Button) findViewById(R.id.onClick_type_2)).getPaint()
				.setFakeBoldText(true);
		userMsgChange();

		product_layout = new RelativeLayout[2];
		product_layout[0] = (RelativeLayout) findViewById(R.id.product_layout_1);
		product_layout[1] = (RelativeLayout) findViewById(R.id.product_layout_2);

		productListView = new ListView[2];
		productListView[0] = (ListView) findViewById(R.id.product_list_1);
		productListView[1] = (ListView) findViewById(R.id.product_list_2);

		product_list_text = new TextView[2];
		product_list_text[0] = (TextView) findViewById(R.id.product_list_1_text);
		product_list_text[1] = (TextView) findViewById(R.id.product_list_2_text);

		((ImageView) findViewById(R.id.activity_title_bg))
				.setBackgroundDrawable(new BitmapDrawable(DdzApplication
						.getApplication().getBmpPool()
						.getBitmap(R.drawable.title_bg, 0, 0)));
		product_layout[0].setBackgroundDrawable(new BitmapDrawable(
				DdzApplication.getApplication().getBmpPool()
						.getBitmap(R.drawable.help_list_bg_left, 0, 0)));
		product_layout[1].setBackgroundDrawable(new BitmapDrawable(
				DdzApplication.getApplication().getBmpPool()
						.getBitmap(R.drawable.help_list_bg_middle, 0, 0)));

		myProducts_1 = new ArrayList<Product>();
		myProducts_2 = new ArrayList<Product>();

		productListAdapter = new MyProductViewAdapter[2];
		(new Handler()).postDelayed(new Runnable() {

			@Override
			public void run() {
				requestGoodsList(1);
			}

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

	/*
	 * 返回按钮对应的处理方法
	 */
	public void onClick_back() {
		
//		WimiPaySdk.onDestroy();
		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();
		if (bg != null)
			bg.setCallback(null);
		if (myProducts_1 != null) {
			myProducts_1.clear();
			myProducts_1 = null;
		}
		if (myProducts_2 != null) {
			myProducts_2.clear();
			myProducts_2 = null;
		}
		if (productListView != null) {
			for (int i = 0, n = productListView.length; i < n; i++) {
				productListView[i] = null;
			}
			productListView = null;
		}
		if (product_layout != null) {
			for (int i = 0, n = product_layout.length; i < n; i++) {
				product_layout[i] = null;
			}
			product_layout = null;
		}
	}

	private void requestGoodsList(int type) {
		for (int i = 0, n = product_list_text.length; i < n; i++) {
			product_list_text[i].setVisibility(View.GONE);
		}

		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 ProcessGoodsListRequestCallback(type),
				PHPMethodName.CLI_PRODUCTLIST_REQ, json);
		startLoading("正在加载数据中...");
	}

	private class MyProductViewAdapter extends BaseAdapter {

		private LayoutInflater mLayoutInflater;
		private int type;

		public MyProductViewAdapter(Context context, int type) {
			this.mLayoutInflater = LayoutInflater.from(context);
			this.type = type;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getCount()
		 */
		@Override
		public int getCount() {
			int count = 0;
			if (getMyProduct(type) != null) {
				count = getMyProduct(type).size();
			}
			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.shop_list_item, null);

					holder.icon = (ImageView) convertView
							.findViewById(R.id.product_img);
					holder.product_hot = (ImageView) convertView
							.findViewById(R.id.product_hot);
					holder.productName = (TextView) convertView
							.findViewById(R.id.product_name);
					holder.productPrice = (TextView) convertView
							.findViewById(R.id.product_price);
					holder.productDesc = (TextView) convertView
							.findViewById(R.id.product_desc);
					holder.productBuy = (Button) convertView
							.findViewById(R.id.product_buy);
					holder.product_extra = (TextView) convertView
							.findViewById(R.id.product_extra);
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				Product myProduct = getMyProduct(type).get(position);
				if (myProduct != null) {
					// holder.icon.setImageBitmap();
					holder.productPrice.setText(String.valueOf(+myProduct
							.getPrice()) + ".00");
					holder.productDesc.setText(Html.fromHtml(myProduct
							.getDesc()));
					holder.productName.setText(Html.fromHtml(myProduct
							.getProductName()));
					holder.product_extra.setText(Html.fromHtml(myProduct
							.getGiftinfo()));
					holder.icon.setImageResource(getBitmapFromId(myProduct
							.getImageUrl()));
					int hotImage = myProduct.getHotImage();
					if (hotImage == 1) {
						holder.product_hot
								.setBackgroundDrawable(new BitmapDrawable(
										DdzApplication
												.getApplication()
												.getBmpPool()
												.getBitmap(
														R.drawable.shop_hot_1,
														0, 0)));
						holder.product_hot.setVisibility(View.VISIBLE);
					} else {
						holder.product_hot.setVisibility(View.GONE);
					}
					final int pid = myProduct.getProductID();
					final int price = myProduct.getPrice();
					final String payCode = myProduct
							.getSomeStr1();
					String temp = myProduct.getDesc();
					if (myProduct.getGiftinfo().trim().length() > 0) {
						temp = myProduct.getDesc() + ","
								+ Html.fromHtml(myProduct.getGiftinfo());
					}
					final String desc = temp;
					holder.productBuy.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							// 购买按钮被点击
							getServerOrder(payCode, UserMessageCenter
									.getInstance().getUserInfo().getUid(), pid,
									price, desc, 0);
							// Toast.makeText(ShopActivity.this, "功能暂未开放",
							// Toast.LENGTH_SHORT).show();
							playBtnPressMusic();
						}
					});
					holder.productId = position;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return convertView;
		}
	}

	private class ProcessGoodsListRequestCallback implements
			PHPCallbackInterface {
		private int type = 0;

		public ProcessGoodsListRequestCallback(int type) {
			this.type = type;
		}

		@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 productsArray = JSONUtil.getJSONArray(
									res, "products");
							if (productsArray != null
									&& productsArray.length() > 0) {
								try {
									getMyProduct(type).clear();
									for (int i = 0, n = productsArray.length(); i < n; i++) {
										JSONObject p = productsArray
												.getJSONObject(i);
										Product myProduct = new Product();
										myProduct.setProductID(JSONUtil.getInt(
												p, "productID", 0));
										myProduct
												.setProductName(JSONUtil
														.getString(p,
																"productName",
																""));
										myProduct.setPrice(JSONUtil.getInt(p,
												"price", 0));
										myProduct.setDesc(JSONUtil.getString(p,
												"desc", ""));
										myProduct.setImageUrl(JSONUtil
												.getString(p, "imageUrl", ""));
										myProduct.setSomeStr1(JSONUtil
												.getString(p, "paycode", ""));
										myProduct.setHotImage(JSONUtil.getInt(
												p, "hotImage", 0));
										myProduct.setGiftinfo(JSONUtil
												.getString(p, "giftinfo", ""));
										getMyProduct(type).add(myProduct);
									}
								} catch (JSONException e) {
									e.printStackTrace();
									String msg = getString(R.string.network_error);
									showMessage(msg);
								}
							}
							if (getMyProduct(type).size() > 0) {
								productListAdapter[getTypeValue(type)] = new MyProductViewAdapter(
										ShopActivity.this, type);
								productListView[getTypeValue(type)]
										.setVerticalScrollBarEnabled(true);
								productListView[getTypeValue(type)]
										.setAdapter(productListAdapter[getTypeValue(type)]);
								productListView[getTypeValue(type)]
										.setSelected(true);
								productListView[getTypeValue(type)]
										.setSelection(0);
								setVisibleView(type);
							} else {
								setInVisibleView(type);
							}

						} else {
							// 登录失败
							int retCode = JSONUtil.getInt(res, "retCode", 2);
							String msg = JSONUtil.getString(res, "retMsg", "");
							showMessage(msg + "(" + retCode + ")");
							AddStatistics.addCanNotPayStatistics(
									ShopActivity.this, "获取商品失败：" + msg + "("
											+ retCode + ")");
						}
					} else {
						String msg = getString(R.string.network_error);
						showMessage(msg);
						AddStatistics.addCanNotPayStatistics(ShopActivity.this,
								"获取商品失败：数据包解析异常");
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
					AddStatistics.addCanNotPayStatistics(ShopActivity.this,
							"获取商品失败：数据包解析异常");
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				AddStatistics.addCanNotPayStatistics(ShopActivity.this,
						"获取商品失败：网络异常异常");
			}
		}
	}

	private int getTypeValue(int type) {
		switch (type) {
		case 1:
			return 0;
		case 3:
			return 1;
		default:
			return 0;
		}
	}

	private void setVisibleView(int type) {
		for (int i = 0, n = product_layout.length; i < n; i++) {
			if (i == getTypeValue(type)) {
				product_layout[i].setVisibility(View.VISIBLE);
				productListView[i].setVisibility(View.VISIBLE);
				product_list_text[i].setVisibility(View.GONE);
			} else {
				productListView[i].setVisibility(View.GONE);
				product_layout[i].setVisibility(View.GONE);
				product_list_text[i].setVisibility(View.GONE);
			}
		}
	}

	private void setInVisibleView(int type) {
		for (int i = 0, n = product_layout.length; i < n; i++) {
			if (i == getTypeValue(type)) {
				product_layout[i].setVisibility(View.VISIBLE);
				productListView[i].setVisibility(View.GONE);
				product_list_text[i].setVisibility(View.VISIBLE);
				product_list_text[i].setText("暂无该类商品");
			} else {
				product_layout[i].setVisibility(View.GONE);
				productListView[i].setVisibility(View.GONE);
				product_list_text[i].setVisibility(View.GONE);
			}
		}
	}

	public void onClick_type_1(View view) {
		requestGoodsList(1);
		playBtnPressMusic();
	}

	public void onClick_type_2(View view) {
		requestGoodsList(3);
		playBtnPressMusic();
	}

	private List<Product> getMyProduct(int type) {
		switch (type) {
		case 1:
			return myProducts_1;
		case 3:
			return myProducts_2;
		default:
			return myProducts_1;
		}
	}

	public final class ViewHolder {
		ImageView icon; // 商品图标
		TextView productName; // 商品价格
		TextView productPrice; // 商品价格
		TextView productDesc; // 商品描述
		TextView product_extra; // 商品描述
		Button productBuy; // 购买按钮
		ImageView product_hot; // 购买按钮
		int productId; // 商品ID
	}

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

	private int getBitmapFromId(String sid) {
		int bitmap = 0;
		int id = 0;
		try {
			id = Integer.parseInt(sid);
		} catch (Exception e) {

		}
		switch (id) {
		case 1:
			bitmap = R.drawable.box_1;
			break;
		case 2:
			bitmap = R.drawable.box_2;
			break;
		case 3:
			bitmap = R.drawable.box_3;
			break;
		case 4:
			bitmap = R.drawable.box_4;
			break;
		case 5:
			bitmap = R.drawable.box_5;
			break;
		case 6:
			bitmap = R.drawable.box_6;
			break;
		case 7:
			bitmap = R.drawable.box_7;
			break;
		case 8:
			bitmap = R.drawable.box_8;
			break;
		case 9:
			bitmap = R.drawable.box_9;
			break;
		default:
			bitmap = R.drawable.box_1;
			break;
		}
		return bitmap;
	}

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

	public void rechargeSuccess(String msg) {
		userMsgChange();
		showInfo(msg);
	}

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

	}

	@Override
	public String getTipBuy(long needMoney) {
		return null;
	}
}
