# coding=utf-8
from __future__ import unicode_literals

import random
import datetime
from gm_rpcd.all import bind
from talos.rpc import bind_context
from talos.services import get_user_from_context

from talos.decorators import cache_page
from talos.cache.base import high_quality_user_cache
from social.models import SocialInfo

from talos.services.user import UserService
from talos.models.diary import Diary
from talos.models.topic import TopicReply, Problem
from talos.models import ReplyCollect
from utils.rpc import get_current_user
from gm_rpcd.all import bind


@bind_context('diary/high_quality_users')
def get_high_quality_users(ctx):
    # 获取八个优质用户
    current_user = get_user_from_context()

    if not high_quality_user_cache.get('high_quality_user'):
        return []

    _all_user_ids = [int(i) for i in high_quality_user_cache.get('high_quality_user').split(',')]
    if len(_all_user_ids) < 20:
        user_ids = _all_user_ids
    else:
        user_ids = random.sample(_all_user_ids, 20)

    result = []
    followings = {}
    if current_user and current_user.id:
        social_info = SocialInfo(uid=current_user.id)
        followings = social_info.is_following_users(user_ids)

    user_id_list = []
    for user_id in user_ids:
        # 排除关注用户
        if followings.get(user_id):
            continue
        if len(user_id_list) >= 8:
            break
        else:
            user_id_list.append(user_id)

    user_infos = UserService.get_users_by_user_ids(user_ids=user_id_list)

    for user_id in user_id_list:
        user_info = user_infos[user_id]
        r_social = SocialInfo(uid=user_id)
        result.append({
            'user_id': user_info.id,
            'nick_name': user_info.nickname,
            'portrait': user_info.portrait,
            'membership_level': user_info.membership_level,
            'fans_count': r_social.fans_count if r_social else 0,
        })

    return result


@bind('diary/get_users_by_diary_ids')
@cache_page(60 * 60)
def get_users_by_diary_ids(diary_ids):

    result = {}
    if not diary_ids:
        return result

    user_id_list = Diary.objects.filter(id__in=diary_ids).values("user_id", "id")
    diary_user_ids = {item["user_id"]: item["id"] for item in user_id_list}
    if not diary_user_ids:
        return result

    user_infos = UserService.get_users_by_user_ids(user_ids=list(diary_user_ids.keys()))

    for user_id, diary_id in diary_user_ids.items():
        user_info = user_infos[user_id]
        result[str(diary_id)] ={
            'user_id': user_info.id,
            'nick_name': user_info.nickname,
            'portrait': user_info.portrait,
            'membership_level': user_info.membership_level,
        }

    return result


@bind('topic/task/add_fake_fans')
def get_topic_diary_info_to_add_fake_fans(start_time, end_time, q_type):
    '''
    gaia 定时任务调取，根据不同条件
    :param start_time:  时间区间-起始时间
    :param end_time: 时间区间-结束时间
    :param q_type: 查询类型:diary,topicreply
    :return:
    '''
    re_data = []
    if not start_time or not end_time or not q_type:
        return re_data

    if q_type == 'diary':
        diarys = Diary.objects.filter(audit_time__range=[start_time, end_time]).values('user_id', 'content_level')
        re_data = list(diarys)
    elif q_type == 'topicreply':
        topic_reply = TopicReply.objects.filter(reply_date__range=[start_time, end_time]).values('diary', 'problem').distinct()
        final_set = set()
        for replys in topic_reply:
            if replys['problem']:
                user_id = Problem.objects.get(id=replys['problem']).user_id
                final_set.add(user_id)
            elif replys['diary']:
                user_id = Diary.objects.get(id=replys['diary']).user_id
                final_set.add(user_id)
        re_data = list(final_set)

    return re_data