package com.zhiwei.weixin;


import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhiwei.weixin.http.HttpRequest;
import com.zhiwei.weixin.pojo.User;
import com.zhiweidata.bjfzxWebapp.util.WechatCodeUtil;

/** 
 * @Package com.zhiwei.weixin.util
 * @ClassName: UserManager
 * @Description: TODO(用户管理接口)
 * @author 志伟
 * @date 2015-3-10 下午6:20:08
 */
public class Users {

    // 调用接口获取access_token  
    private static String token ;  
	//记录日志
	private static Logger log = LoggerFactory.getLogger(Users.class);
	
	//根据微信id查询微信用户信息
	private static String show_userInfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	//获取标签下粉丝列表
	private static String showOpenids_bygroup_url = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=ACCESS_TOKEN";
	//查看微信公号的所有用户（前10000名）
	private static String show_openid_url =	"https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN";
	
	private static String show_openidNext_url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";
	
	public Users()
	{
		token = WechatCodeUtil.getToken();
	}
	
	
	/**
	 * 
	 * @Title: showUserByWxId 
	 * @Description: TODO(查看用户信息) 
	 * @param @param openid
	 * @param @return 设定文件 
	 * @return User 返回类型
	 */
	public User showUserByWxId(String openid)
	{
		User user = new User();
		String requestUrl = show_userInfo_url.replace("ACCESS_TOKEN", token).replace("OPENID", openid);
		JSONObject jsonObject = HttpRequest.httpRequest(requestUrl, "GET", null);
		
		// 如果请求成功
		if (null != jsonObject) 
		{
			String nickname = null;
			if(null != jsonObject.get("nickname"))
			{
				nickname = jsonObject.getString("nickname");
			}
			user.setGroupid(null);
			user.setOpenid(openid);
			user.setNickname(nickname);
			user.setHeadimgurl(jsonObject.getString("headimgurl"));
			user.setSex(jsonObject.getString("sex"));
			user.setCountry(jsonObject.getString("country"));
			user.setProvince(jsonObject.getString("province"));
			user.setCity(jsonObject.getString("city"));
			user.setSubscribe_time(jsonObject.getString("subscribe_time"));
		}
		return user;
	}
	
	
	/**
	 * 
	 * @Title: getUserList 
	 * @Description: TODO(拉取公告所有粉丝用户openid) 
	 * @param @return 设定文件 
	 * @return HashMap 返回类型
	 */
	@SuppressWarnings({ "unchecked"})
	public List<String> getUserList()
	{
		boolean f = true;
		String next_openid = "";
		List<String> list = new ArrayList<String>();
		int i = 0;
		while(f)
		{
			String requestUrl = show_openid_url.replace("ACCESS_TOKEN", token);
			String requestUrlNext = show_openidNext_url.replace("ACCESS_TOKEN", token).replace("NEXT_OPENID", next_openid);
			JSONObject jsonObject = HttpRequest.httpRequest(requestUrl, "GET", null);
			if(null != jsonObject)
			{
				try {
					int page = (int)Math.ceil((jsonObject.getInt("total")/10000.00));
					if(i==page)
					{
						break;
					}else
					{
						jsonObject = HttpRequest.httpRequest(requestUrlNext, "GET", null);
					}
					List<String> openIdList = (List<String>)jsonObject.getJSONObject("data").get("openid");
					list.addAll(openIdList);
					next_openid = jsonObject.getString("next_openid");
					i++;
				} catch (Exception e) {
					e.printStackTrace();
					log.error("拉取微信公众号粉丝用户信息时出现错误："+jsonObject,e.getMessage());
					return list;
				}
			}
		}
		return list;
	}
	
	
	/**
	 * 
	 * @Title: getUserListByGroupId 
	 * @Description: TODO(获取此分组下粉丝用户openid) 
	 * @param @return 设定文件 
	 * @return HashMap 返回类型
	 */
	public List<String> getUserListByGroupId(int groupId)
	{
		boolean f = true;
		String next_openid = "";
		List<String> list = new ArrayList<String>();
		while(f)
		{
			String requestUrl = showOpenids_bygroup_url.replace("ACCESS_TOKEN", token);
			JSONObject postData = new JSONObject();
			postData.put("tagid", groupId);
			postData.put("next_openid", next_openid);
			JSONObject jsonObject = HttpRequest.httpRequest(requestUrl, "GET", postData.toString());
			if(null != jsonObject)
			{
				try {
					String count = jsonObject.getString("count");
					if(count.equals("0"))
					{
						break;
					}
					List<String> openIdList = (List<String>)jsonObject.getJSONObject("data").get("openid");
					list.addAll(openIdList);
					next_openid = jsonObject.getString("next_openid");
				} catch (Exception e) {
					e.printStackTrace();
					log.error("拉取微信公众号粉丝用户信息时出现错误："+jsonObject,e.getMessage());
					return list;
				}
			}
		}
		return list;
	}
}
