#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
from django.db.models import Q

from api.tool.datetime_tool import get_timestamp_epoch
from rpc.tool.error_code import gen, CODES
from agile.services import TagV3Service
from variety_show.models.young_models import (
    YoungBaseInfo,
    YoungTag,
    Idol,
    IdolTag,
    VoteRecord,
)
from variety_show.services.service_base import ServiceBase


class YoungActivityService(ServiceBase):

    @staticmethod
    def format_young_activity_base_info(young_fame_obj):
        """
        转化活动基本信息
        :param young_fame_obj:
        :return:
        """
        return {
            "young_fame_id": young_fame_obj.id,
            "start_timestamp": get_timestamp_epoch(young_fame_obj.start_time),
            "end_timestamp": get_timestamp_epoch(young_fame_obj.end_time),
            "rules": young_fame_obj.rule,
        }

    @classmethod
    def get_young_activity_rel_tag_ids(cls, young_fame_id):
        """
        获取活动关联的标签ID
        :param young_fame_id:
        :return:
        """
        return list(set(cls.get_querysets_data(
            model_=YoungTag,
            query=Q(young_id=young_fame_id)
        ).values_list("tag_id", flat=True)))

    @classmethod
    def safe_get(cls, young_fame_id):

        try:
            young_fame_obj = YoungBaseInfo.objects.get(pk=young_fame_id)
        except YoungBaseInfo.DoesNotExist:
            gen(CODES.ACTIVITY_NOT_EXIST)

        if not young_fame_obj.is_online:
            gen(CODES.ACTIVITY_OFFLINE)

        return young_fame_obj

    @classmethod
    def get_valid_young_activity_info(cls):
        """
        获取有效的活动信息
        :return:
        """
        result = {}

        young_fame_obj = cls.get_querysets_data(
            model_=YoungBaseInfo,
            query=cls.base_query,
            order_by=["-id"]
        ).first()

        if not young_fame_obj:
            return result

        return cls.format_young_activity_base_info(young_fame_obj)


class YoungIdolsService(ServiceBase):
    """
    少年之名 学员
    """

    @classmethod
    def safe_get(cls, idol_id):

        try:
            idol_obj = Idol.objects.get(pk=idol_id)
        except Idol.DoesNotExist:
            gen(CODES.ACTIVITY_IDOL_NOT_FOUND)

        if not idol_obj.is_online:
            gen(CODES.ACTIVITY_IDOL_NOT_FOUND)

        return idol_obj

    @staticmethod
    def format_young_idol_info(idol_obj, with_tags=False):
        """
        格式化学员信息
        :param idol_obj:
        :param with_tags:
        :return:
        """
        info = {
            "idol_id": idol_obj.id,
            "idol_name": idol_obj.name,
            "idol_portrait": idol_obj.image,  # 头像
            "is_out": idol_obj.is_out,
            "real_votes": idol_obj.real_votes,  # 真实票数
            "fake_votes": idol_obj.fake_votes,  # 虚拟票数
            "hera_votes": idol_obj.hera_votes,  # 后台增票
            "tags": []
        }
        if with_tags:
            tag_ids = list(IdolTag.objects.filter(idol_id=idol_obj.id).values_list("tag_id", flat=True))
            tagv3_infos = TagV3Service.get_tags_v3_by_ids(tag_ids)
            info["tags"] = list(tagv3_infos.values())

        return info


    @classmethod
    def get_young_idols(cls, start_num=0, count=10):
        """
        获取全部学员列表
        :return:
        """
        idols = cls.get_querysets_data(
            model_=Idol,
            query=cls.base_query
        )

        return list(map(cls.format_young_idol_info, idols))

    @classmethod
    def get_young_idol_by_id(cls, idol_id, with_tags=False):

        young_idols = cls.get_young_idol_by_ids([idol_id], with_tags)
        young_idol = young_idols.get(idol_id)

        return young_idol

    @classmethod
    def get_young_idol_by_ids(cls, idol_ids, with_tags=False):
        """
        通过ID获取学员信息
        :param idol_ids:
        :return:
        """
        idols = cls.get_querysets_data(
            model_=Idol,
            query=cls.base_query & Q(pk__in=idol_ids)
        )
        return {
            idol.id: cls.format_young_idol_info(idol, with_tags=with_tags) for idol in idols
        }

    @classmethod
    def get_young_idol_info_by_group_id(cls, group_id):
        """
        通过小组ID获取学员信息
        :param group_id:
        :return:
        """
        idol_obj = cls.get_querysets_data(
            model_=Idol,
            query=cls.base_query & Q(group_id=group_id),
            order_by=["id"]
        ).first()

        if not idol_obj:
            return {}

        return cls.format_young_idol_info(idol_obj)

    @classmethod
    def get_vote_records(cls, user_id):
        """
        获取投票记录
        :return:
        """
        records = cls.get_querysets_data(
            model_=VoteRecord,
            query=Q(user_id=user_id),
            order_by=['-id'],
            fields=['idol_id', 'create_time']
        )

        return records


