package com.zhiweidata.bjfzxWebapp.listener;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

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

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.zhiwei.weibobusiness.business.SearchBusiness;
import com.zhiwei.weibobusiness.business.UsersBusiness;
import com.zhiwei.weibobusiness.weibo4j.model.Status;
import com.zhiwei.weibobusiness.weibo4j.model.StatusWapper;
import com.zhiwei.weibobusiness.weibo4j.model.User;
import com.zhiwei.weibobusiness.weibo4j.model.WeiboException;
import com.zhiweidata.bjfzxWebapp.entity.Keyword;
import com.zhiweidata.bjfzxWebapp.entity.WeiboBusiness;
import com.zhiweidata.bjfzxWebapp.util.MidAurl;
import com.zhiweidata.bjfzxWebapp.util.TimeUtil;

/**
 * @ClassName: WeiboEvetSearchByBusiness 
 * @Description: TODO(通过商业接口获取微博事件数据) 
 * @author xuyimeng 
 * @date 2018年2月6日 上午11:13:43
 */
public class WeiboEvetSearchByBusiness
{
	private static Logger log = LoggerFactory.getLogger(WeiboEvetSearchByBusiness.class);
    private UsersBusiness businessUsers;
    private SearchBusiness searchBusiness;
    

    public WeiboEvetSearchByBusiness(String token)
    {
        super();
        searchBusiness = new SearchBusiness(token);
        businessUsers = new UsersBusiness(token);
    }

    /**
     * 
     * @TODO(TODO 从商业接口获取微博数据)
     * @author 陈炜涛
     * @param startTime
     * @param endTime
     * @param words
     * @param keyword
     * @return
     * @time 2016年10月31日下午3:03:07
     * @return List<WeiboEvent>
     */
    public List<WeiboBusiness> weiboKeywordSearchByBusiness(String startTime,
            String endTime, String words, Keyword keyword)
    {
        List<WeiboBusiness> weibos = new ArrayList<WeiboBusiness>();

        int volume;
        int count = 50;
        int pageMax=0;
        String sort = "time";

        int start = (int) (TimeUtil.parseTime(startTime).getTime() / 1000l);
        int end = (int) (TimeUtil.parseTime(endTime).getTime() / 1000l);
        try
        {
            volume = (int) searchBusiness.getSearchWeiboVolume(words, start,
                    end);// 获取数据总页数
            pageMax = (volume / count) <= 20 ? (volume / count) : 20;
            
            for (int page = 1; page < pageMax + 1; page++)
            {
                try
                { 	
                    StatusWapper sw = searchBusiness.getSearchWeibo(words,
                            page, count, start, end, sort,1,3,3);               
                    List<Status> statuses = sw.getStatuses();
                    for (Status status : statuses)
                    {
                    	WeiboBusiness weibo = statusToWeiboEvent(status, keyword);
                    	if (weibo != null)
                    	{
                    		weibos.add(weibo);
                    	}
                    }
                }
                catch (WeiboException e)
                {
                    log.error("【微博商业接口】第{}页获取数据出错,原因:【{}】", page,
                            e.getMessage());
                }

            }
        }
        catch (Exception e)
        {
            log.error("【微博商业接口】获取总页数出错,原因:【{}】", e.getMessage());
        }

        return weibos;
    }

    /**
     * @Title: getUserInfoByIDS
     * @Description: TODO(使用商业接口来批量获取用户信息)50000次/小时/IP；
     * @param @param idsList 设定文件
     * @return void 返回类型
     */
    public List<User> getBatchUsersByIDS(List<String> idsList)
    {
        List<User> userList = new ArrayList<User>();

        int count = 0; // 需要获取的用户总数

        for (String uids : idsList)
        {
            userList.addAll(getUsersByIds(uids));
            count += uids.split(",").length;
        }
        System.out.println("用户总数：" + count + "\t 获取回来的用户条数：" + userList.size());
        return userList;
    }

    /**
     * @Title: Users2DBList
     * @Description: TODO(把Users转换为)
     * @param @param userList
     * @param @return 设定文件
     * @return List<DBObject> 返回类型
     */
    public List<DBObject> Users2DBList(List<User> userList)
    {
        List<DBObject> beans = new ArrayList<DBObject>();
        for (User user : userList)
        {
            beans.add(userToDBObject(user));
        }
        return beans;
    }

    /**
     * @Title: userToDBObject
     * @Description: TODO(工具类，把一个微博的User类转换为DBObject)
     * @param @param user
     * @return DBObject 返回类型
     */
    public DBObject userToDBObject(User user)
    {
        Class<?> clazz = user.getClass();
        Field[] fields = clazz.getDeclaredFields();
        BasicDBObject userObj = new BasicDBObject();
        for (Field field : fields)
        {
            String fieldName = field.getName();
            if (!fieldName.equals("serialVersionUID")
                    && !fieldName.equals("status"))
            {
                PropertyDescriptor pd = null;
                try
                {
                    pd = new PropertyDescriptor(fieldName, clazz);
                }
                catch (IntrospectionException e)
                {
                    e.printStackTrace();
                }
                if (pd != null)
                {
                    try
                    {
                        Method method = pd.getReadMethod();
                        // 把DBObject _id设置为用户Id的值
                        if (fieldName.equals("id"))
                        {
                            userObj.put("_id",
                                    Long.valueOf((String) method.invoke(user)));
                        }
                        else
                        {
                            userObj.put(fieldName, method.invoke(user));
                        }
                    }
                    catch (IllegalAccessException e)
                    {
                        e.printStackTrace();
                    }
                    catch (IllegalArgumentException e)
                    {
                        e.printStackTrace();
                    }
                    catch (InvocationTargetException e)
                    {
                        e.printStackTrace();
                    }
                }

            }
        }
        return userObj;
    }

    /**
     * @Title: getBatchUserByIds
     * @Description: TODO(通过商业接口获取用户数据)
     * @param @param uids
     * @param @return 设定文件
     * @return List<User> 返回类型
     */
    public List<User> getUsersByIds(String uids)
    {
        List<User> userList = new ArrayList<User>();
        try
        {
            userList = businessUsers.showUser(uids);
        }
        catch (WeiboException e)
        {
            e.printStackTrace();
        }
        return userList;
    }

    /**
     * @Title: getBatchUserByIds
     * @Description: TODO(通过商业接口获取用户数据)
     * @param @param uids
     * @param @return 设定文件
     * @return List<User> 返回类型
     */
    public List<User> getUsersByArryIds(List<String> uidlists)
    {
        List<User> userList = new ArrayList<User>();

        int num = 0;
        String ids = "";
        List<String> idslist = new ArrayList<String>();
        for (String id : uidlists)
        {
            if ("".equals(ids))
            {
                ids = ids + id;
            }
            else
            {
                ids = ids + "," + id;
            }
            num++;
            if (num / 49 >= 1)
            {
                idslist.add(ids);
                ids = "";
            }
        }
        if (!"".equals(ids))
        {
            idslist.add(ids);
        }
        

        for (String idss : idslist)
        {
            try
            {
                userList.addAll(businessUsers.showUser(idss));
            }
            catch (WeiboException e)
            {
                e.printStackTrace();
            }
        }

        return userList;
    }

    /**
     * 
     * @TODO(TODO 将微博返回的字段按需求重新封装)
     * @author 陈炜涛
     * @param status
     * @param keyword
     * @return
     * @time 2016年10月31日下午3:04:46
     * @return WeiboEvent
     */
    public WeiboBusiness statusToWeiboEvent(Status status, Keyword keyword)
    {
        WeiboBusiness weibo = new WeiboBusiness();

        weibo.setGroupName(keyword.getGroupName());
        weibo.setId(keyword.getKeyword() + "_" + status.getId());
        weibo.setKeyword(keyword.getKeyword());
        weibo.setMid(status.getId() + "");
        weibo.setCreatedAt(status.getCreatedAt());
        String source = "";
        if (status.getSource() != null)
        {
            source = status.getSource().getName();
        }
        weibo.setSource(source);
        weibo.setReposts_count(status.getRepostsCount());
        weibo.setComments_count(status.getCommentsCount());
        int hdl_count = status.getRepostsCount() + status.getCommentsCount();
        weibo.setHdl_count(hdl_count);
        weibo.setText(status.getText());

        if (status.getUser() != null)
        {
            weibo.setUid(status.getUser().getId());
            weibo.setUsername(status.getUser().getScreenName());
            weibo.setFensi(status.getUser().getFollowersCount());
            weibo.setWeibo(status.getUser().getStatusesCount());
            weibo.setImg_url(status.getUser().getProfileImageUrl());
            weibo.setGuanzhu(status.getUser().getFriendsCount());
            weibo.setSex(status.getUser().getGender());
            weibo.setLocation(status.getUser().getLocation());
            weibo.setVtype(status.getUser().getVerifiedType());
            weibo.setDescription(status.getUser().getDescription());
            weibo.setReason(status.getUser().getVerifiedReason());
            weibo.setUrl("http://weibo.com/" + status.getUser().getId() + "/"
                    + MidAurl.mid2url(status.getId() + ""));
        }
        Status rootStatus = status.getRetweetedStatus();
        int isforword = 0;
        if (rootStatus != null)
        {
            isforword = 1;
            String root_username = "";
            String root_uid = "";
            if (rootStatus.getUser() != null)
            {
                root_username = rootStatus.getUser().getScreenName();
                root_uid = rootStatus.getUser().getId();
            }
            weibo.setRoot_mid(rootStatus.getMid());
            weibo.setRoot_createdAt(rootStatus.getCreatedAt());
            weibo.setRoot_username(root_username);
            weibo.setRoot_text(rootStatus.getText());
            weibo.setRoot_reposts_count(rootStatus.getRepostsCount());
            weibo.setRoot_comments_count(rootStatus.getCommentsCount());
            weibo.setRoot_uid(root_uid);
        }
        weibo.setIsForword(isforword);
        weibo.setSaveTime(new Date().getTime());
        
        String key = keyword.getKeyword();
		if (key.contains("+"))
		{
			key = key.replaceAll("\\+", " ");
		}
		if (key.contains("-"))
		{
			key = key.replaceAll("\\-", " ");
		}
		
		String[] keys = key.split("\\s+");
		
		String str = ".*";
		for (String keyStr : keys)
		{
			str += keyStr + ".*";
		}
		
//		if (keyword.equals("币新")) {
//			str += keyword + ".*";
//		}
		
		Pattern patt = Pattern.compile(str);
		
		if (!patt.matcher(status.getText()).find())
		{
			return null;
		}
		return weibo;
    }
}
