package com.backfire.popupwindow;

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.os.Handler;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.backfire.doudizhu.ActivityBase;
import com.backfire.doudizhu.ActivityThirdPlatform;
import com.backfire.doudizhu.common.DdzApplication;
import com.backfire.doudizhu.common.JSONUtil;
import com.backfire.doudizhu.common.LoadingProgressDialog;
import com.backfire.doudizhu.common.MyJson;
import com.backfire.doudizhu.task.Task;
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 TaskPopupWindow extends BasePopupWindow{
	private View view;
	private int width;
	private int height;
	
	private ImageView setting_close;
	
	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;
	/**
	 * @param activity
	 */
	public TaskPopupWindow(ActivityBase activity) {
		super(activity);
		this.initSetting();
	}
	private void initSetting(){
		try {
			LayoutInflater mLayoutInflater = (LayoutInflater) mActivity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			int layoutRourse = R.layout.task_pop;
			
			view = mLayoutInflater.inflate(layoutRourse, null);
			
			view.setFocusableInTouchMode(true);
			 
			setting_close = (ImageView)view.findViewById(R.id.info_close);
			task_text = (TextView)view.findViewById(R.id.task_text);
			tasks_total_tip_msg = (TextView)view.findViewById(R.id.tasks_total_tip_msg);
			tasks_total_tip_image = (ImageView)view.findViewById(R.id.tasks_total_tip_image);
			myTasks = new ArrayList<Task>();
			//init();
			
			(new Handler()).postDelayed(new Runnable(){

				@Override
				public void run() {
					requestTodayTasksList();
				}
				
			}, 100);
			
			this.setFocusable(true);
			this.setConsumeKeyEvent(true);
			ImageView popupview = (ImageView) view.findViewById(R.id.info_bg);
			width = popupview.getLayoutParams().width;
			height = popupview.getLayoutParams().height;
			this.createPopupWindow(view, width, height);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	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);
		LoadingProgressDialog.show(mActivity,"正在加载数据中...");
	}
	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);
		LoadingProgressDialog.show(mActivity,"正在加载数据中...");
	}
	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_pop_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(mActivity.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(mActivity.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);
							
							mActivity.playBtnPressMusic();
						}
					});
				}else if(task.getCanAliPay()==3){
					holder.task_alipay.setText(mActivity.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) {
			LoadingProgressDialog.dissmissDlg();
			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 = mActivity.getString(R.string.network_error);
									showMessage(msg);
								}
							}
							
							if(myTasks.size()>0){
								((ListView)view.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(mActivity);
									task_list = (ListView)view.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)view.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 = mActivity.getString(R.string.network_error);
						showMessage(msg);
					}
				} else {
					String msg = mActivity.getString(R.string.network_error);
					showMessage(msg);
				}
			}else{
				String msg = mActivity.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) {
			LoadingProgressDialog.dissmissDlg();
			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", "");
							try {
								((ActivityThirdPlatform)mActivity).rechargeSuccess(tipMsg);
							} catch (Exception e) {
								Log.e(this, e);
								e.printStackTrace();
							}
							//RoomInfo.getInstance().setTaskCount(0);
							requestTodayTasksList();
						}
					}else {
						String msg = mActivity.getString(R.string.network_error);
						showMessage(msg);
					}
				} else {
					String msg = mActivity.getString(R.string.network_error);
					showMessage(msg);
				}
			}else{
				String msg = mActivity.getString(R.string.network_error);
				showMessage(msg);
			}
		}
	}
	
	private void showMessage(String msg){
		DdzApplication.getApplication().showToast(msg);
	}
	/**
	 * 为各组件设置监听器
	 */
	public void setListens() {
		setting_close.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				CloseWindow();
				
				mActivity.playBtnPressMusic();
			}
			
		});
		view.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				CloseWindow();
				return false;
			}
		});
		view.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				float x = event.getX();
				float y = event.getY();

				if (x < 0 || x > width || y < 0 || y > height) {
					CloseWindow();
				}
				return true;
			}
		});
	}
	
	@Override
	protected boolean popupWindowWillShow() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected void popupWindowDidShow() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void popupWindowWillDissmiss() {
		// TODO Auto-generated method stub
		
	}
	public final class TaskViewHolder {
		public TextView task_name; 		    // 任务名称
		public SeekBar seekbar_task; 		//任务进度
		public TextView task_process;       //进度描述
		public Button task_alipay; 			//领取按钮
	}
}


