package com.lianxin.pubqq.setup;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lianxin.pubqq.R;
import com.lianxin.pubqq.chat.EMChatActivity;
import com.lianxin.panqq.common.BaseActivity;
import com.lianxin.panqq.common.DefineChat;
//import com.lianxin.pubqq.chat.ChatActivity;
import com.lianxin.panqq.common.DefineUser;
import com.lianxin.panqq.utils.ImagesUtils;
import com.lianxin.panqq.utils.TimeUtil;
import com.lianxin.panqq.widget.list.XListView;
import com.lianxin.panqq.widget.list.XListView.IXListViewListener;
import com.lianxin.panqq.main.EMGroupManager;
//import com.lianxin.panqq.chat.entity.EMMessage;
//import com.lianxin.panqq.chat.utils.MyLogger;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.list.bean.Member;
import com.lianxin.panqq.client.MemberClient;
import com.lianxin.panqq.client.callback.updataCallBack;
import com.lianxin.panqq.client.entity.SearMemberList;
import com.lianxin.panqq.common.bean.InformMessage;
import com.lianxin.panqq.common.bean.InformMessage.OaType;
import com.lianxin.panqq.setup.bean.ReplyMessage;

/**
 * 回复消息列表
 *
 */
public class ReplyListActivity extends BaseActivity implements IXListViewListener {
    
	private XListView mListView;
	private ReplyListAdapter mAdapter;
	private List<Member> userList;//搜索用户列表
	private List<ReplyMessage> replyList;//回复消息列表	
	private InformMessage informInfo; //通知消息列表	
	private EditText ed_search;	
	private int groupId = 10058;	
	private int groupType = DefineUser.TYPE_CROWD;		
	public static final int FRIST_GET_DATE = 111;
	public static final int REFRESH_GET_DATE = 112;
	public static final int LOADMORE_GET_DATE = 113;

	private static int page = 0;

//	private static MyLogger Log = MyLogger.yLog();
	
    @Override
   	public void onCreate(Bundle savedInstanceState) {
      	 
   		super.onCreate(savedInstanceState);
   		setContentView(R.layout.setup_replylist);
		mListView = (XListView)findViewById(R.id.user_xListView);
		mListView.setPullLoadEnable(true);

		groupType = getIntent().getIntExtra("TypeType", DefineUser.TYPE_CROWD);
		groupId = getIntent().getIntExtra("TypeID", 10001);	
		int position = getIntent().getIntExtra("Position", 1);	
		informInfo = GloableParams.InformList.get(position);		
		initData();	
		initView();		
		//mAdapter =  new ReplyListAdapter(this, userList);
		mAdapter =  new ReplyListAdapter(this, replyList);		
		mListView.setAdapter(mAdapter);
		mListView.setXListViewListener(this);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position,
					long id) {
				ReplyMessage child = mAdapter.getItem(position-1);				
				Intent intent = new Intent(ReplyListActivity.this, EMChatActivity.class);
				intent.putExtra("Chat_ID", child.getUserid());
				intent.putExtra("Chat_Type", DefineChat.ChatType_USER);		
				intent.putExtra("Chat_Name", child.getName());
				startActivity(intent);			}
			
		});
		resetData();	//刷新远程数据
		//过滤搜索listview中的内容
		ed_search = (EditText) findViewById(R.id.tv_search);		
		ed_search.addTextChangedListener(new TextWatcher() {
			
			@Override//当editText发生变化的时候
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				mAdapter.getFilter().filter(arg0);
			}
			//这两个方法在这里没有什么用
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}
		});		
    }
 
	protected void initView() {
	
		ImageView img_image = (ImageView)findViewById(R.id.iv_avatar);
		TextView txt_title = (TextView)findViewById(R.id.tv_title);
		TextView txt_type = (TextView)findViewById(R.id.tv_oatype);		
		TextView txt_name = (TextView)findViewById(R.id.tv_name);
		TextView txt_time = (TextView)findViewById(R.id.tv_time);
		TextView txt_content = (TextView)findViewById(R.id.tv_content);	
		TextView txt_state = (TextView)findViewById(R.id.tv_state);	
		
		txt_title.setText(informInfo.getTitle());
		txt_name.setText(informInfo.getFrom());		
		txt_content.setText(informInfo.getReason());
		txt_time.setText(TimeUtil.getMsgTime(informInfo.getTime()));		
		txt_type.setText(informInfo.getType());	
			
        int image = informInfo.getHeadImg();
        if(image>80) image = image%80;
        img_image.setImageResource(ImagesUtils.images[image]); 			

	}    
    
    //第一次加载数据
    private void initData() {
		if(userList != null && userList.size() > 0)
			return;    	
    	mListView.setPullLoadEnable(false);
 		mListView.setPullRefreshEnable(false);
 		 
      //  if(TextUtils.isEmpty(GloableParams.m_szServerIp))         	
 		    LoadLocalItems(FRIST_GET_DATE); 
       // else
 		//    getRemoteItems(FRIST_GET_DATE);
 	//	   initDemoData();		    
		replyList = new ArrayList<ReplyMessage>();
		for (int i = 0; i < userList.size(); i++) {
			ReplyMessage newReply = new ReplyMessage();
			newReply.setUserid(userList.get(i).userId);
			newReply.setName(userList.get(i).getName());
			newReply.setHeadImg(userList.get(i).imageid);
			long time = System.currentTimeMillis() - 10000 - 1000 * i;
			newReply.setTime(time);
			replyList.add(newReply);
		}    
	}
    //刷新远程数据
    private void resetData() {
   	    mListView.setPullLoadEnable(false);
		mListView.setPullRefreshEnable(false);
		 
        if(TextUtils.isEmpty(GloableParams.m_szServerIp))         	
		    LoadLocalItems(REFRESH_GET_DATE); 
        else
		    getRemoteItems(REFRESH_GET_DATE);
	} 

	@Override
	public void onRefresh() { 
		mListView.setPullLoadEnable(false);
		 mListView.setPullRefreshEnable(false);
	    //geneItems(REFRESH_GET_DATE); 
        if(TextUtils.isEmpty(GloableParams.m_szServerIp)) 		 
 		    LoadLocalItems(REFRESH_GET_DATE); 
        else
 		    getRemoteItems(REFRESH_GET_DATE);	    
	}
 
	@SuppressLint("SimpleDateFormat")
	private void onLoadStatus(int allCount,int newCount) {
		// TODO Auto-generated method stub
		mListView.stopRefresh();
		mListView.stopLoadMore();
		if(newCount>=0){
		    SimpleDateFormat  formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");     
		    Date  curDate  =  new Date(System.currentTimeMillis());//获取当前时间     
		    String   str   =   formatter.format(curDate);     
		    mListView.setRefreshTime(str);
		    mListView.setFooterCount(allCount, newCount);	
		}
		mListView.setPullLoadEnable(true);
		mListView.setPullRefreshEnable(true);
	}	
	
	@Override
	public void onLoadMore() { 
		mListView.setPullLoadEnable(false);
		mListView.setPullRefreshEnable(false);
	//	geneItems(LOADMORE_GET_DATE); 
 	//	LoadLocalItems(LOADMORE_GET_DATE);		
 	//	getRemoteItems(LOADMORE_GET_DATE);	
        if(TextUtils.isEmpty(GloableParams.m_szServerIp)) 		 
 		    LoadLocalItems(LOADMORE_GET_DATE); 
        else
 		    getRemoteItems(LOADMORE_GET_DATE); 		
	}

	private void getRemoteItems(final int ACTION) {
		int nCount = userList.size();	
		//MemberClient.updataMember(ACTION,10061, new updataCallBack(){
		MemberClient.updataMember(groupType,groupId,nCount, new updataCallBack(){

			@Override
			public void onSuccess(int statusCode, byte[] recvBuf) {
				SearMemberList searlist = new SearMemberList(recvBuf);	
				final List<Member> newuserList = searlist.getMemberList();
				runOnUiThread(new Runnable() {
					public void run() {
						int newCount = 0;
						if(newuserList == null )
							newCount = 0;
						else
							newCount = newuserList.size();	
						if(ACTION==REFRESH_GET_DATE||ACTION==FRIST_GET_DATE){
							userList = newuserList;					
						}
						else
						{		
							if(newuserList != null )
							for(int i=0;i<newuserList.size();i++){ 
								
								userList.add(newuserList.get(i));			
							}
						}
						//Toast.makeText(MemberListActivity.this, "message"+statusCode, 0).show();				
						int allCount = userList.size();		
						if(ACTION==FRIST_GET_DATE){//第一次加载
							onLoadStatus(allCount,newCount);
							page = 1;						
						}else if(ACTION==REFRESH_GET_DATE){//刷新数据
							mAdapter = new ReplyListAdapter(ReplyListActivity.this, replyList);
							mListView.setAdapter(mAdapter);
							onLoadStatus(allCount,newCount);
							page = 1;
						}else if(ACTION==LOADMORE_GET_DATE){//加载更多
							mAdapter.notifyDataSetChanged();
							onLoadStatus(allCount,newCount);
							page++; 
						}								
					}
				});					
				
			}

			@Override
			public void onFailure(int statusCode,  String message) {
				final String str = message;				
				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(ReplyListActivity.this, str, 0).show();						
						onLoadStatus(0,-1);								
					}
				});					
				return;
			}

			
		});
	 
	}	
	
	private void LoadLocalItems(final int ACTION) {

		int newCount = 0;
		List<Member> newuserList = null;	
		if(ACTION==REFRESH_GET_DATE||ACTION==FRIST_GET_DATE){
//			newuserList = UserFileLoadUtil.readUser(getBaseContext(), "area.json");	
			newuserList = EMGroupManager.getInstance().getGroupMembers(groupId,groupType);
		//	newuserList = EMGroupManager.getInstance().loadGroupMember(1666,DefineUser.TYPE_MYCLASS);			
		//	userList.clear();
			userList = newuserList;
			if(newuserList == null )
				newCount = 0;
			else
				newCount = newuserList.size();			
		}
		else
		{
			newuserList = EMGroupManager.getInstance().getGroupMembers(groupId,groupType);
			if(newuserList == null )
				newCount = 0;
			else
				newCount = newuserList.size();			
			if(newuserList != null )
			for(int i=0;i<newuserList.size();i++){ 
				
				userList.add(newuserList.get(i));			
			}
		}
		int allCount = userList.size();		
			if(ACTION==FRIST_GET_DATE){//第一次加载
				onLoadStatus(allCount,newCount);
				page = 1;			
			}else if(ACTION==REFRESH_GET_DATE){//刷新数据
				mAdapter = new ReplyListAdapter(ReplyListActivity.this, replyList);
				mListView.setAdapter(mAdapter);
				onLoadStatus(allCount,newCount);
				page = 1;
			}else if(ACTION==LOADMORE_GET_DATE){//加载更多
				mAdapter.notifyDataSetChanged();
				onLoadStatus(allCount,newCount);
				page++; 
			}		

	}	
	
    private void initDemoData() {

    	replyList = new ArrayList<ReplyMessage>();

		ReplyMessage msg1 = new ReplyMessage(); 	
		msg1.userId = 10186;
		msg1.nickname = "财务处长汪";
		msg1.reply = "准予财务支付";		
		msg1.replytime = System.currentTimeMillis()-3000;
		msg1.imageid = 15;							
		replyList.add(msg1);
		ReplyMessage msg2 = new ReplyMessage(); 	
		msg2.userId = 10178;
		msg2.nickname = "财务校长刘";
		msg2.reply = "准予报销";		
		msg2.replytime = System.currentTimeMillis()-6000;
		msg2.imageid = 21;							
		replyList.add(msg2);
		ReplyMessage msg3 = new ReplyMessage(); 	
		msg3.userId = 10153;
		msg3.nickname = "主管校长吴";
		msg3.reply = "本次出差系学校公派，准予报销";		
		msg3.replytime = System.currentTimeMillis()-11000;
		msg3.imageid = 17;							
		replyList.add(msg3);
		ReplyMessage msg4 = new ReplyMessage(); 	
		msg4.userId = 310;
		msg4.nickname = "数理学院";
		msg4.reply = "情况属实";		
		msg4.replytime = System.currentTimeMillis()-17000;
		msg4.imageid = 15;		
		replyList.add(msg4);		
		
	}
 
}
 