package com.backfire.doudizhu.task;

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

public class TaskActivity extends ActivityThirdPlatform{
	private List<Task> myTasks = null;
	private ListView task_list;
	private TextView task_text;
	private TextView tasks_total_tip_msg;
	private ImageView tasks_total_tip_image;
	private MyTaskViewAdapter taskListAdapter = null;
	Drawable bg;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_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_task)).getPaint().setFakeBoldText(true);
		task_text = (TextView)findViewById(R.id.task_text);
		tasks_total_tip_msg = (TextView)findViewById(R.id.tasks_total_tip_msg);
		tasks_total_tip_image = (ImageView)findViewById(R.id.tasks_total_tip_image);
		userMsgChange();
		
		((ImageView)findViewById(R.id.activity_title_bg)).setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.title_bg, 0, 0)));
		((RelativeLayout)findViewById(R.id.task_msg)).setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.help_list_bg_left, 0, 0)));
		
		myTasks = new ArrayList<Task>();
		(new Handler()).postDelayed(new Runnable(){

			@Override
			public void run() {
				requestTodayTasksList();
			}
			
		}, 100);
		//init();
	}
	
	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()));
	}
	private void requestTodayTasksList(){
		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",0);
		
		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new TaskListRequestCallback(), PHPMethodName.CLI_TASK_LIST_REQ, json);
		startLoading("正在加载数据中...");
	}
	
	private void alipayTasksRequest(int type,int taskID){
		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);
		param.put("taskID",taskID);
		
		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new TaskAlipayRequestCallback(), PHPMethodName.CLI_ALIPAY_TASK_REQ, json);
		startLoading("正在加载数据中...");
	}
	/*
	 * 返回按钮对应的处理方法
	 */
	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);
	}
	
	private class MyTaskViewAdapter extends BaseAdapter
	{
		
		private LayoutInflater mLayoutInflater;
		public MyTaskViewAdapter(Context context)
		{
			this.mLayoutInflater = LayoutInflater.from(context);
		}
		public int getCount() {
			int count = 0;
			if (myTasks != null) {
				count =  myTasks.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) {
			TaskViewHolder holder = null;
			if( convertView == null)
			{
				holder = new TaskViewHolder();
				convertView = this.mLayoutInflater.inflate(R.layout.task_list_item, null);
				
				holder.task_name = (TextView)convertView.findViewById(R.id.task_name);
				holder.seekbar_task = (SeekBar)convertView.findViewById(R.id.seekbar_task);
				holder.task_process = (TextView)convertView.findViewById(R.id.task_process);
				holder.task_alipay = (Button)convertView.findViewById(R.id.task_alipay);
				convertView.setTag(holder);
			}
			else
			{
				holder = (TaskViewHolder)convertView.getTag();
			}
			Task task = myTasks.get(position);
			if (task != null) {
				//holder.icon.setImageBitmap();
				holder.task_name.setText(Html.fromHtml(task.getTaskName()));
				if(task.getTotalRate()<=0){
					holder.seekbar_task.setProgress(0);
					holder.task_process.setText("进度：0/1");
				}else if(task.getCompelteRate()>task.getTotalRate()){
					holder.seekbar_task.setProgress(100);
					holder.task_process.setText("进度："+task.getTotalRate()+"/"+task.getTotalRate());
				}else{
					holder.seekbar_task.setProgress(task.getCompelteRate()*100/task.getTotalRate());
					holder.task_process.setText("进度："+task.getCompelteRate()+"/"+task.getTotalRate());
				}
				holder.seekbar_task.setEnabled(false);
				holder.task_alipay.getPaint().setFakeBoldText(true);
				if(task.getCanAliPay()==1){
					holder.task_alipay.setText(TaskActivity.this.getString(R.string.task_running));
					holder.task_alipay.setBackgroundResource(R.drawable.task_running_btn);
					holder.task_alipay.setEnabled(true);
					holder.task_alipay.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							//进行中任务，点击不做任何处理
						}
					});
				}else if(task.getCanAliPay()==2){
					holder.task_alipay.setText(TaskActivity.this.getString(R.string.task_alipaying));
					holder.task_alipay.setBackgroundResource(R.drawable.common_btn);
					holder.task_alipay.setEnabled(true);
					final int taskID = task.getTaskID();
					holder.task_alipay.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							//领取任务奖励
							alipayTasksRequest(0,taskID);
							playBtnPressMusic();
						}
					});
				}else if(task.getCanAliPay()==3){
					holder.task_alipay.setText(TaskActivity.this.getString(R.string.task_alipayed));
					holder.task_alipay.setBackgroundResource(R.drawable.common_btn);
					holder.task_alipay.setEnabled(false);
				}
			}
			return convertView;
		}
	}
	private class TaskListRequestCallback 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){
							String tipMsg = JSONUtil.getString(res, "tipMsg", "");
							JSONArray tasksArray = JSONUtil.getJSONArray(res, "tasks");
							if(tasksArray!=null && tasksArray.length()>0){
								try {
									myTasks.clear();
									for(int i=0,n=tasksArray.length();i<n;i++){
										JSONObject e = tasksArray.getJSONObject(i);
										Task info = new Task();
										info.setTaskID(JSONUtil.getInt(e, "taskID", 0));
										info.setTaskName(JSONUtil.getString(e, "taskName", ""));
										info.setTaskDesc(JSONUtil.getString(e, "taskDesc", ""));
										info.setCompelteRate(JSONUtil.getInt(e, "compelteRate", 0));
										info.setTotalRate(JSONUtil.getInt(e, "totalRate", 0));
										info.setCanAliPay(JSONUtil.getInt(e, "canAliPay", 0));
										myTasks.add(info);
									}
								} catch (JSONException e) {
									e.printStackTrace();
									String msg = getString(R.string.network_error);
									showMessage(msg);
								}
							}
							
							if(myTasks.size()>0){
								((ListView)findViewById(R.id.task_list)).setVisibility(View.VISIBLE);
								tasks_total_tip_msg.setVisibility(View.VISIBLE);
								tasks_total_tip_image.setVisibility(View.VISIBLE);
								task_text.setVisibility(View.GONE);
								if (task_list == null) {
									taskListAdapter = new MyTaskViewAdapter(TaskActivity.this);
									task_list = (ListView)findViewById(R.id.task_list);
									task_list.setVerticalScrollBarEnabled(true);
									task_list.setAdapter(taskListAdapter);
									task_list.setSelected(true);
									task_list.setSelection(0);
								}else
								{
									taskListAdapter.notifyDataSetChanged();
								}
								tasks_total_tip_msg.setText(Html.fromHtml(tipMsg));
							}else{
								((ListView)findViewById(R.id.task_list)).setVisibility(View.GONE);
								task_text.setVisibility(View.VISIBLE);
								tasks_total_tip_msg.setVisibility(View.GONE);
								tasks_total_tip_image.setVisibility(View.GONE);
								task_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 TaskAlipayRequestCallback 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){
							JSONObject total = JSONUtil.getJSONObject(res, "totalmoney");
							if(total!=null){
								UserInfo self = UserMessageCenter.getInstance().getUserInfo();
								self.setMoney(JSONUtil.getLong(total, "money", 0));
								self.setVip(JSONUtil.getInt(total, "vip", 0));
								self.setVipTime(JSONUtil.getInt(total, "vipTime", 0));
								self.setExchangeCard(JSONUtil.getLong(total, "exchange", 0));
								self.setLottery(JSONUtil.getLong(total, "lottery", 0));
							}
							String tipMsg = JSONUtil.getString(res, "tipMsg", "");
							DdzApplication.getApplication().showMoneyToast(tipMsg);
							userMsgChange();
							requestTodayTasksList();
						}
					}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);
			}
		}
	}
	
	public void showMessage(String msg){
		DdzApplication.getApplication().showToast(msg);
	}
	public final class TaskViewHolder {
		public TextView task_name; 		    // 任务名称
		public SeekBar seekbar_task; 		//任务进度
		public TextView task_process;       //进度描述
		public Button task_alipay; 			//领取按钮
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		 if(bg!=null)bg.setCallback(null);
			if(myTasks!=null){
				myTasks.clear();
				myTasks = null;
			}
			task_list = null;
			taskListAdapter = null;
	}
	
	@Override
	public void rechargeSuccess(String msg) {
		userMsgChange();
		showInfo(msg);
	}

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

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

	@Override
	protected void orderFailed(long needMoney) {
		// TODO Auto-generated method stub
		
	}
}


