# coding=utf-8
import logging, traceback, time
from api.models import UserBlackList, Doctor
from talos.models.live import LiveWhiteList
from talos.models.diary import DiaryCheck
from .transfer import MIN_TIME
from .es import tzlc
from api.tool.user_tool import filter_user_nick_name
from gm_types.gaia import DIARY_CONTENT_LEVEL
from social.models import UserFollow
from answer.models.answer import QuestionFavor, Question


def get_2grams(s):
    if len(s) < 2:
        return [s]
    else:
        return [a + b for a, b in zip(s[0:-1], s[1:])]


def get_user(instance):
    try:
        # alias
        u = instance
        nickname = filter_user_nick_name(u)
        res = {
            'id': u.id,
            'last_name': nickname,
            'last_name_not_analyzed': nickname,
            'is_active': u.is_active,
            'membership_level': u.userextra.membership_level,
            'last_login': tzlc(u.userextra.last_login) or MIN_TIME,
        }

        if any([
            LiveWhiteList.objects.filter(user_id=u.id).exists(),
            DiaryCheck.objects.filter(
                diary__user_id=u.id,
                content_level=DIARY_CONTENT_LEVEL.EXCELLENT
            ).exists(),
        ]):
            res['last_name_2grams'] = get_2grams(nickname)
        else:
            res['last_name_2grams'] = None

        user_in_black_list = UserBlackList.objects.filter(bind_user=u).exists()
        user_is_doctor = Doctor.objects.filter(user=u).exists()

        if user_in_black_list or user_is_doctor:
            res['is_active'] = False

        res['follow_question'] = []
        # 先拿到用户
        all_follow_ids = by_user_id_get_follow_ids(u.id)

        # 我关注的问题ID
        all_questin_ids = list(
            QuestionFavor.objects.filter(user_id=u.id, is_online=True).values("question_id", "user_id", "update_time"))
        logging.info("get all_questin_ids:%s，res:%s" % (all_questin_ids, res))
        for item in all_questin_ids:
            res['follow_question'].append(
                {"question_id": item.get("question_id", None),
                 "create_time": int(time.mktime(tzlc(item.get("update_time", None)).timetuple())),
                 "follow_type": 1})

        if len(all_follow_ids) > 500:
            all_follow_ids = all_follow_ids[:500]

        questin_ids = Question.objects.using("mimas_hera_read_db").filter(user__in=all_follow_ids,
                                                                          is_online=True).values("id", "update_time",
                                                                                                 "user")
        for item in questin_ids:
            res['follow_question'].append(
                {"question_id": item.get("id", None),
                 "create_time": int(time.mktime(tzlc(item.get("update_time", None)).timetuple())),
                 "follow_type": 2})
        logging.info("get res:%s" % res)

        return res
    except:
        logging.error("catch exception,err_msg:%s" % traceback.format_exc())
        return None


def by_user_id_get_follow_ids(user_id):
    try:
        all_follow_ids = [int(user_id)]
        data = UserFollow.objects.filter(user_id=user_id, bond=True).values_list("follow_id", flat=True)
        all_follow_ids.extend(data)
        return all_follow_ids
    except:
        logging.error("catch exception,err_msg:%s" % traceback.format_exc())
        return []
