package com.backfire.doudizhu.luck;

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.Bitmap;
import android.graphics.drawable.AnimationDrawable;
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.Gravity;
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.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

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.DeviceUtil;
import com.backfire.doudizhu.common.DownLoadImage;
import com.backfire.doudizhu.common.DownLoadImageListener;
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.popupwindow.AlertPopupWindow;
import com.backfire.popupwindow.EnterConnectPopupWindow;
import com.backfire.utils.Log;

public class LuckActivity extends ActivityThirdPlatform{
	Drawable bg;
	
	RelativeLayout luck_msg;
	private ImageView luck_light;
	private Button luck_zhen;
	private TextView pan_desc;
	
	RelativeLayout parser_msg;
	private List<ExchangeCard> myParsers = null;
	private GridView parser_list;
	private TextView parser_text;
	private PaeserViewAdapter parserListAdapter = null;
	
	RelativeLayout record_msg;
	private List<ExchangeRecord> myRecords = null;
	private ListView record_list;
	private TextView record_text;
	private RecordViewAdapter recordListAdapter = null;
	
	private TextView flow_desc;
	RelativeLayout luck_parser_exchange;
	
	AnimationDrawable lightAnimation;
	ZhuanPanView pan;
	Thread panThread;
	
	private int needLottery = 0;
	boolean isPeasering = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.luck_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.onclick_luck)).getPaint().setFakeBoldText(true);
		((Button)findViewById(R.id.onClick_parser)).getPaint().setFakeBoldText(true);
		((Button)findViewById(R.id.onClick_record)).getPaint().setFakeBoldText(true);
		userMsgChange();
		
		luck_msg = (RelativeLayout)findViewById(R.id.luck_msg);		//获取大转盘底背景
		luck_light = (ImageView)findViewById(R.id.luck_light);	//设置灯光动画
		luck_zhen = (Button)findViewById(R.id.luck_zhen);	//转针
		pan_desc = (TextView)findViewById(R.id.pan_desc);	//大转盘描述
		pan = (ZhuanPanView)findViewById(R.id.luck_pan);	//转盘
		
		((ImageView)findViewById(R.id.luck_bg)).setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.choujiang_bg1, 0, 0)));
		
		parser_msg = (RelativeLayout)findViewById(R.id.parser_msg);		
		myParsers = new ArrayList<ExchangeCard>();
		parser_text = (TextView)findViewById(R.id.parser_text);	
		
		record_msg = (RelativeLayout)findViewById(R.id.record_msg);		
		myRecords = new ArrayList<ExchangeRecord>();
		record_text = (TextView)findViewById(R.id.record_text);	
		
		luck_parser_exchange = (RelativeLayout)findViewById(R.id.luck_parser_exchange);	
		flow_desc = (TextView)findViewById(R.id.flow_desc);	
		
		luck_msg.setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.help_list_bg_left, 0, 0)));
		parser_msg.setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.help_list_bg_middle, 0, 0)));
		record_msg.setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.help_list_bg_right, 0, 0)));
		
		String desc = "兑奖流程：兑换奖品---填写资料---兑换成功---工作人员与您确认资料---发放奖品<br/><t/>"
				+"兑换话费奖，会在7个工作日内发放。<br/><t/>"
				+"兑换实物奖，会在15个工作日内进行配送。<br/><t/>"
				+"如有其他疑问，请咨询客服QQ：2788243535，QQ群：257470601。";
		flow_desc.setText(Html.fromHtml(desc));
		
		panThread = new Thread(pan);
		panThread.start();
		luck_zhen.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				beginRotate();
			}
		});
		(new Handler()).postDelayed(new Runnable(){

			@Override
			public void run() {
				requestLuckTurnTabel();
			}
			
		}, 100);
	}

	@Override
	protected void onDestroy() {
		pan.clear();
		super.onDestroy();
	}
	public void beginRotate(){
		long lottery = UserMessageCenter.getInstance().getUserInfo().getLottery();
		if(lottery>=needLottery){
			requestLuckyDraw();
			if(pan!=null)pan.startRotate();
		}else{
			showAlert("您的彩券不足，不能抽奖哦。<br/>彩券获得方式有:<br/>1.大奖赛获胜越多，彩券越多！<br/>2.每日连续登录，最少可领取5张彩券！<br/>3.完成全部每日任务，最少获得100张彩券！");
		}
	}
	public void stopRotate(int degree,final String desc){
		pan.stopRotate(degree,new ZhuanPanStopListener(){

			@Override
			public void onFinish() {
				isPeasering = false;
				if(desc!=null && desc.length()>0){
					showInfo(desc);
					userMsgChange();
				}
			}
			
		});
	}
	public void initLableView(){
		luck_msg.setVisibility(View.GONE);
		parser_msg.setVisibility(View.GONE);
		record_msg.setVisibility(View.GONE);
		luck_parser_exchange.setVisibility(View.GONE);
	}
	public void requestLuckTurnTabel(){
		initLableView();
		luck_msg.setVisibility(View.VISIBLE);
		if(needLottery>0){
			
		}else{
			TreeMap<String, Object> param = new TreeMap<String, Object>();
			param.put("uid", UserMessageCenter.getInstance().getUserInfo().getUid());
			param.put("session", UserMessageCenter.getInstance().getUserInfo().getSession());
		
			String json = new MyJson(param).toString();
			PHPRequestPool.getInstance().AddRequest(new LuckMsgRequestCallback(),
					PHPMethodName.CLI_LUCK_TURN_TABLE, json);
			startLoading("正在加载数据，请稍等...");
		}
	}
	public void requestParserList(){
		initLableView();
		parser_msg.setVisibility(View.VISIBLE);
		luck_parser_exchange.setVisibility(View.VISIBLE);
		if(myParsers.size()<=0){
			parser_text.setVisibility(View.GONE);
			
			TreeMap<String, Object> param = new TreeMap<String, Object>();
			param.put("uid", UserMessageCenter.getInstance().getUserInfo().getUid());
			param.put("session", UserMessageCenter.getInstance().getUserInfo().getSession());
		
			String json = new MyJson(param).toString();
			PHPRequestPool.getInstance().AddRequest(new ParserListRequestCallback(),
					PHPMethodName.CLI_PARSER_LIST_REQ, json);
			startLoading("正在加载数据，请稍等...");
		}else{
			((GridView)findViewById(R.id.parser_list)).setVisibility(View.VISIBLE);
			parser_text.setVisibility(View.GONE);
		}
	}
	public void requestRecodeList(){
		initLableView();
		record_msg.setVisibility(View.VISIBLE);
		if(myRecords.size()<=0){
			record_text.setVisibility(View.GONE);
			
			TreeMap<String, Object> param = new TreeMap<String, Object>();
			param.put("uid", UserMessageCenter.getInstance().getUserInfo().getUid());
			param.put("session", UserMessageCenter.getInstance().getUserInfo().getSession());
		
			String json = new MyJson(param).toString();
			PHPRequestPool.getInstance().AddRequest(new RecordListRequestCallback(),
					PHPMethodName.CLI_EXCHANGE_RECORD_INTEGRAL, json);
			startLoading("正在加载数据，请稍等...");
		}else{
			((ListView)findViewById(R.id.record_list)).setVisibility(View.VISIBLE);
			record_text.setVisibility(View.GONE);
		}
	}
	public void requestLuckyDraw(){
		if(!isPeasering){
			isPeasering = true;
			TreeMap<String, Object> param = new TreeMap<String, Object>();
			param.put("uid", UserMessageCenter.getInstance().getUserInfo().getUid());
			param.put("session", UserMessageCenter.getInstance().getUserInfo().getSession());
		
			String json = new MyJson(param).toString();
			PHPRequestPool.getInstance().AddRequest(new LuckDrawRequestCallback(),
					PHPMethodName.CLI_LUCK_DRAW, json);
		}
	}
	public void requestParser(int cardID,String name_connect,String phone_connect,String qq_connect,String cardName,long need){
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", UserMessageCenter.getInstance().getUserInfo().getUid());
		param.put("session", UserMessageCenter.getInstance().getUserInfo().getSession());
		param.put("cardID", cardID);
		param.put("connectName", name_connect);
		param.put("connectphone", phone_connect);
		param.put("connectqq", qq_connect);
	
		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new ParserRequestCallback(cardName,need),
				PHPMethodName.CLI_PARSER_REQ, json);
		startLoading("开始兑换，请稍等...");
	}
	private void initLuckPan(String desc,int needLoy,Bitmap bitmap){
		userMsgChange();
		pan_desc.setText(Html.fromHtml(desc));
		needLottery = needLoy;
		pan.setContext(this, bitmap, luck_zhen);
	}
	
	private void userMsgChange(){
		((TextView)findViewById(R.id.user_money)).setText(UserMessageCenter.getLobbyMoney(UserMessageCenter.getInstance().getUserInfo().getMoney()));
		((TextView)findViewById(R.id.user_lottery)).setText(UserMessageCenter.getLobbyMoney(UserMessageCenter.getInstance().getUserInfo().getLottery()));
		((TextView)findViewById(R.id.user_exchange)).setText(UserMessageCenter.getLobbyMoney(UserMessageCenter.getInstance().getUserInfo().getExchangeCard()));
		((TextView)findViewById(R.id.luck_parser_exchange_text)).setText(UserMessageCenter.getLobbyMoney(UserMessageCenter.getInstance().getUserInfo().getExchangeCard()));

	}
	/*
	 * 返回按钮对应的处理方法
	 */
	public void onClick_back(){
		ActivityContainer.getInstance().switchTo(this, ActivityType.LOBBY_ACTIVITY);
	}
	/*
	 * 返回按钮对应的处理方法
	 */
	public void onClick_back(View view){
		onClick_back();
	}
	public void onclick_luck(View view){
		requestLuckTurnTabel();
	}
	public void onClick_parser(View view){
		requestParserList();
	}
	public void onClick_record(View view){
		requestRecodeList();
	}
	@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);
	}
	
	public void showMessage(String msg){
		stopLoading();
		DdzApplication.getApplication().showToast(msg);
	}
	private void showAlert(String msg){
		AlertPopupWindow alert = new AlertPopupWindow(this,msg,true);
		alert.setListens(null);
		alert.ShowWindowInCenter();
	}
	@Override
	public void rechargeSuccess(String msg) {
		showInfo(msg);
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if(hasFocus) { 
			luck_light = (ImageView) this.findViewById(R.id.luck_light);
			luck_light.setBackgroundResource(R.anim.luck_bg_ani);
			if(luck_light!=null){
				if(lightAnimation==null)lightAnimation = (AnimationDrawable) luck_light.getBackground();
				if(!lightAnimation.isRunning()){
					lightAnimation.start();
				}
			}
		
		}
		super.onWindowFocusChanged(hasFocus);
	}
	private class LuckMsgRequestCallback implements PHPCallbackInterface {

		public void onFinish(PHPResult result) {	
			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);
					int retCode = JSONUtil.getInt(res, "retCode", 2);
					String msg =JSONUtil.getString(res, "retMsg", "");
					
					if(ret==1){//成功获取大转盘信息
						final String desc  = JSONUtil.getString(res, "desc", "");	// 大转盘信息描述
						final int needLoy  = JSONUtil.getInt(res, "needLottery", 0);	// 点击抽奖所需奖券
						String imageUrl  = JSONUtil.getString(res, "imageUrl", "");	//  大转盘图像地址
						long lottery = JSONUtil.getLong(res, "Lottery", -1);	// 用户持有奖券
						if(lottery>=0){
							UserMessageCenter.getInstance().getUserInfo().setLottery(lottery);
						}
						String imageName  = JSONUtil.getString(res, "imageName", "luck_pan_20131113");		// 大转盘信息描述
						if(imageName.equalsIgnoreCase("luck_pan_20131113")){
							initLuckPan(desc,needLoy,DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.luck_pan_20131113, 0, 0));
							stopLoading();
						}else{
							Bitmap pan = DownLoadImage.loadBitmap(LuckActivity.this, imageName);	//成功获取转盘文件
							if(pan!=null){
								initLuckPan(desc,needLoy,pan);
								stopLoading();
							}else{
								DownLoadImage.saveBitmap(LuckActivity.this, imageName, imageUrl, new DownLoadImageListener() {
									
									@Override
									public void onFinish(Bitmap bitmap) {
										initLuckPan(desc,needLoy,bitmap);
										stopLoading();
									}
									
									@Override
									public void onFailed() {
										// TODO Auto-generated method stub
										stopLoading();
									}
								});
							}
						}
					}else{
						showMessage(msg+"("+retCode+")");
					}
				}else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				
			}
		}
	}
	private class LuckDrawRequestCallback implements PHPCallbackInterface {

		public void onFinish(PHPResult result) {
			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);
					int retCode = JSONUtil.getInt(res, "retCode", 2);
					String msg =JSONUtil.getString(res, "retMsg", "");
					
					if(ret==1){//成功获取大转盘信息
						final String desc  = JSONUtil.getString(res, "desc", "");	// 大转盘信息描述
						final int rotateDegree  = JSONUtil.getInt(res, "rotateDegree", 0);	// 点击抽奖所需奖券
						UserInfo self = UserMessageCenter.getInstance().getUserInfo();
						self.setMoney(self.getMoney()+JSONUtil.getLong(res, "money", 0));
						self.setLottery((self.getLottery()+JSONUtil.getLong(res, "lottery", 0))-needLottery);
						self.setExchangeCard((self.getExchangeCard()+JSONUtil.getLong(res, "exchange", 0)));
						
						showDrawToast("扣取"+needLottery+"彩券");
						stopRotate(rotateDegree,desc);
					}else{
						showMessage(msg+"("+retCode+")");
					}
				}else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				
			}
		}
	}
	private class ParserRequestCallback implements PHPCallbackInterface {
		private String cardName;
		private long need;
		public ParserRequestCallback(String cardName,long need){
			this.cardName = cardName;
			this.need = need;
		}
		public void onFinish(PHPResult result) {
			stopLoading();
			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);
					int retCode = JSONUtil.getInt(res, "retCode", 2);
					String msg =JSONUtil.getString(res, "retMsg", "");
					
					if(ret==1){//成功获取大转盘信息
						String desc  = "恭喜您，兑换"+cardName+"成功！";	// 大转盘信息描述
						UserInfo self = UserMessageCenter.getInstance().getUserInfo();
						self.setExchangeCard(self.getExchangeCard() - need);
						showInfo(desc);
						userMsgChange();
					}else{
						showMessage(msg+"("+retCode+")");
					}
				}else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				
			}
		}
	}
	private class ParserListRequestCallback implements PHPCallbackInterface
	{
		/* (non-Javadoc)
		 * @see com.backfire.php.PHPCallbackInterface#onFinish(com.backfire.php.PHPResult)
		 */
		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 cardsArray = JSONUtil.getJSONArray(res, "cards");
							if(cardsArray!=null && cardsArray.length()>0){
								try {
									myParsers.clear();
									for(int i=0,n=cardsArray.length();i<n;i++){
										JSONObject e = cardsArray.getJSONObject(i);
										ExchangeCard info = new ExchangeCard();
										info.setDesc(JSONUtil.getString(e, "desc", ""));
										info.setName(JSONUtil.getString(e, "name", ""));
										info.setId(JSONUtil.getInt(e, "id", 0));
										info.setNeed(JSONUtil.getLong(e, "need", 0));
										info.setImageName(JSONUtil.getString(e, "imageName", ""));
										info.setImageURL(JSONUtil.getString(e, "imageURL", ""));
										myParsers.add(info);
									}
								} catch (JSONException e) {
									e.printStackTrace();
									String msg = getString(R.string.network_error);
									showMessage(msg);
								}
							}
							
							if(myParsers.size()>0){
								((GridView)findViewById(R.id.parser_list)).setVisibility(View.VISIBLE);
								parser_text.setVisibility(View.GONE);
								if (parser_list == null) {
									parserListAdapter = new PaeserViewAdapter(LuckActivity.this);
									parser_list = (GridView)findViewById(R.id.parser_list);
									parser_list.setVerticalScrollBarEnabled(true);
									parser_list.setAdapter(parserListAdapter);
									parser_list.setSelected(true);
									parser_list.setSelection(0);
								}else
								{
									parserListAdapter.notifyDataSetChanged();
								}
							}else{
								((GridView)findViewById(R.id.parser_list)).setVisibility(View.GONE);
								parser_text.setVisibility(View.VISIBLE);
								parser_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 PaeserViewAdapter extends BaseAdapter
	{
		
		private LayoutInflater mLayoutInflater;
		public PaeserViewAdapter(Context context)
		{
			this.mLayoutInflater = LayoutInflater.from(context);
		}
		public int getCount() {
			int count = 0;
			if (myParsers != null) {
				count =  myParsers.size();
			}
			return count;
		}
		public Object getItem(int position) {
			return null;
		}
		public long getItemId(int position) {
			return 0;
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			ParserViewHolder holder = null;
			if( convertView == null)
			{
				holder = new ParserViewHolder();
				convertView = this.mLayoutInflater.inflate(R.layout.luck_card_item, null);
				
				holder.parser_exahange = (TextView)convertView.findViewById(R.id.parser_exahange);
				holder.parser_alipay = (Button)convertView.findViewById(R.id.parser_alipay);
				holder.parser_image = (ImageView)convertView.findViewById(R.id.parser_image);
				holder.parser_award = (ImageView)convertView.findViewById(R.id.parser_award);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ParserViewHolder)convertView.getTag();
			}
			ExchangeCard card = myParsers.get(position);
			if (card != null) {
				//holder.icon.setImageBitmap();
				holder.parser_exahange.setText(card.getNeed()+"");
				final int id = card.getId();
				final long need = card.getNeed();
				final String name = card.getName();
				final String imageUrl = card.getImageURL();
				if(UserMessageCenter.getInstance().getUserInfo().getExchangeCard()>=need){
					holder.parser_award.setVisibility(View.VISIBLE);
				}else{
					holder.parser_award.setVisibility(View.GONE);
				}
				holder.parser_alipay.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if(UserMessageCenter.getInstance().getUserInfo().getExchangeCard()>=need){
							try {
								EnterConnectPopupWindow enter = new EnterConnectPopupWindow(LuckActivity.this,id,name,need);
								enter.setListens(LuckActivity.this);
								enter.ShowWindowInCenter();
							} catch (Exception e) {
								Log.e(this, e);
							}
						}else{
							showMessage("无敌卡不足，不能兑奖!");
						}
					}
				});
				holder.parser_image.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if(UserMessageCenter.getInstance().getUserInfo().getExchangeCard()>=need){
							try {
								EnterConnectPopupWindow enter = new EnterConnectPopupWindow(LuckActivity.this,id,name,need);
								enter.setListens(LuckActivity.this);
								enter.ShowWindowInCenter();
							} catch (Exception e) {
								Log.e(this, e);
							}
						}else{
							showMessage("无敌卡不足，不能兑奖!");
						}
					}
				});
				String imageName  = card.getImageName();	// 大转盘信息描述
				if(imageName.equalsIgnoreCase("luck_parse_gird_10card_20111118")){
					holder.parser_image.setBackgroundResource(R.drawable.luck_parse_gird_10card_20111118);
				}else if(imageName.equalsIgnoreCase("luck_parse_gird_50card_20111118")){
					holder.parser_image.setBackgroundResource(R.drawable.luck_parse_gird_50card_20111118);
				}else if(imageName.equalsIgnoreCase("luck_parse_gird_100card_20111118")){
					holder.parser_image.setBackgroundResource(R.drawable.luck_parse_gird_100card_20111118);
				}else if(imageName.equalsIgnoreCase("luck_parse_gird_disk_20111118")){
					holder.parser_image.setBackgroundResource(R.drawable.luck_parse_gird_disk_20111118);
				}else if(imageName.equalsIgnoreCase("luck_parse_gird_iphone_20111118")){
					holder.parser_image.setBackgroundResource(R.drawable.luck_parse_gird_iphone_20111118);
				}else if(imageName.equalsIgnoreCase("luck_parse_gird_pad_20111118")){
					holder.parser_image.setBackgroundResource(R.drawable.luck_parse_gird_pad_20111118);
				}else if(imageName.equalsIgnoreCase("luck_parse_gird_power_20111118")){
					holder.parser_image.setBackgroundResource(R.drawable.luck_parse_gird_power_20111118);
				}else if(imageName.equalsIgnoreCase("luck_parse_gird_router_20111118")){
					holder.parser_image.setBackgroundResource(R.drawable.luck_parse_gird_router_20111118);
				}else{
					Bitmap bitmap = DownLoadImage.loadBitmap(LuckActivity.this, imageName);	//成功获取转盘文件
					if(bitmap!=null){
						holder.parser_image.setBackgroundDrawable(new BitmapDrawable(bitmap));
					}else{
						final ImageView image = holder.parser_image;
						DownLoadImage.saveBitmap(LuckActivity.this, imageName, imageUrl, new DownLoadImageListener() {
							
							@Override
							public void onFinish(Bitmap bitmap) {
								image.setBackgroundDrawable(new BitmapDrawable(bitmap));
							}
							
							@Override
							public void onFailed() {
								// TODO Auto-generated method stub
								stopLoading();
							}
						});
					}
				}
			}
			return convertView;
		}
	}
	public final class ParserViewHolder {
		public ImageView parser_image; 		    // 任务名称
		public TextView parser_exahange; 		    // 任务名称
		public Button parser_alipay; 			//领取按钮
		public ImageView parser_award;
	}
	
	private class RecordListRequestCallback implements PHPCallbackInterface
	{
		/* (non-Javadoc)
		 * @see com.backfire.php.PHPCallbackInterface#onFinish(com.backfire.php.PHPResult)
		 */
		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 recordsArray = JSONUtil.getJSONArray(res, "records");
							if(recordsArray!=null && recordsArray.length()>0){
								try {
									myRecords.clear();
									for(int i=0,n=recordsArray.length();i<n;i++){
										JSONObject e = recordsArray.getJSONObject(i);
										ExchangeRecord info = new ExchangeRecord();
										String time = JSONUtil.getString(e, "time", "");
										if(time!=null && time.trim().length()>10){
											time = time.substring(0,10);
										}
										info.setTime(time);
										info.setName(JSONUtil.getString(e, "name", ""));
										info.setId(JSONUtil.getInt(e, "id", 0));
										info.setStatus(JSONUtil.getInt(e, "status", 0));
										myRecords.add(info);
									}
								} catch (JSONException e) {
									e.printStackTrace();
									String msg = getString(R.string.network_error);
									showMessage(msg);
								}
							}
							
							if(myRecords.size()>0){
								((ListView)findViewById(R.id.record_list)).setVisibility(View.VISIBLE);
								record_text.setVisibility(View.GONE);
								if (record_list == null) {
									recordListAdapter = new RecordViewAdapter(LuckActivity.this);
									record_list = (ListView)findViewById(R.id.record_list);
									record_list.setVerticalScrollBarEnabled(true);
									record_list.setAdapter(recordListAdapter);
									record_list.setSelected(true);
									record_list.setSelection(0);
								}else
								{
									recordListAdapter.notifyDataSetChanged();
								}
							}else{
								((ListView)findViewById(R.id.record_list)).setVisibility(View.GONE);
								record_text.setVisibility(View.VISIBLE);
								record_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 RecordViewAdapter extends BaseAdapter
	{
		
		private LayoutInflater mLayoutInflater;
		public RecordViewAdapter(Context context)
		{
			this.mLayoutInflater = LayoutInflater.from(context);
		}
		public int getCount() {
			int count = 0;
			if (myRecords != null) {
				count =  myRecords.size();
			}
			return count;
		}
		public Object getItem(int position) {
			return null;
		}
		public long getItemId(int position) {
			return 0;
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			RecordViewHolder holder = null;
			if( convertView == null)
			{
				holder = new RecordViewHolder();
				convertView = this.mLayoutInflater.inflate(R.layout.luck_record_item, null);
				
				holder.record_name = (TextView)convertView.findViewById(R.id.record_name);
				holder.record_time = (TextView)convertView.findViewById(R.id.record_time);
				holder.record_status = (TextView)convertView.findViewById(R.id.record_status);
				convertView.setTag(holder);
			}
			else
			{
				holder = (RecordViewHolder)convertView.getTag();
			}
			ExchangeRecord record = myRecords.get(position);
			if (record != null) {
				//holder.icon.setImageBitmap();
				holder.record_name.setText(record.getName());
				holder.record_time.setText(record.getTime());
				int status = record.getStatus();
				if(status==2){
					holder.record_status.setText("已发奖");
				}else{
					holder.record_status.setText("正在处理");
				}
				
				
			}
			return convertView;
		}
	}
	public final class RecordViewHolder {
		public TextView record_name; 		    // 兑换奖品名称
		public TextView record_time;       		//兑换时间
		public TextView record_status; 			//当前状态״̬
	}
	
	public void showDrawToast(String string) {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.banner, null);
		TextView text = (TextView) view.findViewById(R.id.banner_title);
		text.setText(Html.fromHtml(string));
		Toast toast = new Toast(this);
		toast.setView(view);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP, DeviceUtil.AdaptScreenWidth(this, 110), DeviceUtil.AdaptScreenHeight(this, 100));
		toast.show();

	}

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

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

	@Override
	protected void orderFailed(long needMoney) {
		
	}

}



