# -*- coding: utf-8 -*-

from __future__ import unicode_literals, absolute_import, print_function
import random
import time
import json
import datetime

from django.db import models
from django.utils import timezone

from gm_upload import ImgUrlField, IMG_TYPE
from gm_types.gaia import IDOL_GENDER
from api.models.user import User
from api.models import PLATFORM_CHOICES
from rpc.cache import variety_cache


class VarietyActivity(models.Model):
    class Meta:
        verbose_name = u'综艺投票活动'
        db_table = 'api_variety_activity'
        app_label = 'api'

    name = models.CharField(max_length=100, verbose_name='名称')
    title = models.CharField(max_length=100, verbose_name='标题')

    start_time = models.DateTimeField(null=False, verbose_name='开始时间')
    end_time = models.DateTimeField(null=False, verbose_name='结束时间')

    header_banner = ImgUrlField('顶部banner图片', max_length=255, img_type=IMG_TYPE.NOWATERMARK)
    waist_banner = ImgUrlField('腰部banner图片', max_length=255, img_type=IMG_TYPE.NOWATERMARK)

    waist_url = models.CharField(max_length=200, verbose_name='腰部banner的URL配置')
    rule = models.TextField(max_length=2048, verbose_name='活动规则', null=False)

    is_online = models.BooleanField(default=True, verbose_name='是否上线')

    others_banner_config = models.TextField('腰部banner配置数据')


    @property
    def assemble_banner_data(self):
        """口红需求增加"""
        banner_list = [
            {
                'waist_banner': self.waist_banner,
                'waist_url': self.waist_url,
            },
        ]
        if self.others_banner_config:
            wait_to_assemble = json.loads(self.others_banner_config)

            second_banner = wait_to_assemble['second_banner']
            third_banner = wait_to_assemble['third_banner']
            if second_banner:
                banner_list.extend([
                    {
                        'waist_banner': wait_to_assemble['second_banner'],
                        'waist_url': wait_to_assemble['second_url'],
                    }
                ])
            if third_banner:
                banner_list.extend([
                    {
                        'waist_banner': wait_to_assemble['third_banner'],
                        'waist_url': wait_to_assemble['third_url'],
                    },
                ])
        return banner_list

    def data(self):
        return {
            "activity_id": self.id,
            "name": self.name,
            "title": self.title,
            "rule": self.rule,
            "start_time": self.start_time.strftime('%Y-%m-%d  %H:%M:%S'),
            "end_time": self.end_time.strftime('%Y-%m-%d  %H:%M:%S'),
            "all_waist_banner_list": self.assemble_banner_data,
            "header_banner": self.header_banner,
            "waist_banner": self.waist_banner,
            "waist_url": self.waist_url
        }


class VarietyIdol(models.Model):
    class Meta:
        verbose_name = u'idol列表'
        db_table = 'api_variety_idol'
        app_label = 'api'

    activity = models.ForeignKey(VarietyActivity, null=False, verbose_name=u'某期活动')

    user = models.ForeignKey(User, null=False, verbose_name='马甲号')

    nick_name = models.CharField(max_length=50, verbose_name='昵称')
    icon_url = ImgUrlField('idol头像', max_length=255, img_type=IMG_TYPE.NOWATERMARK)

    hera_vote_num = models.IntegerField(default=0, verbose_name=u'后台添加票数')
    real_vote = models.IntegerField(default=0, verbose_name=u'真实票数')

    last_modify_time = models.DateTimeField(auto_now=True, verbose_name=u'最近一次修改时间')

    is_online = models.BooleanField(default=True)
    # 口红王子最后一期，增加女Idol
    gender = models.CharField(u'idol性别', choices=IDOL_GENDER, default=IDOL_GENDER.MALE, max_length=2)
    order = models.IntegerField(u'排序', default=0)
    gif_url = ImgUrlField(u'idol动态头像', max_length=255, null=True, img_type=IMG_TYPE.NOWATERMARK)

    def data(self):
        return {
            "id": self.id,
            "activity_id": self.activity_id,
            "user_id": self.user_id,
            "nick_name": self.nick_name,
            "icon_url": self.icon_url,
            "vote_num": self.hera_vote_num + self.real_vote,
            "order": self.order,
            "gif_url": self.gif_url if self.gender == IDOL_GENDER.FEMALE else ''
        }


class Invite(models.Model):
    class Meta:
        verbose_name = u'邀请记录表'
        db_table = 'api_variety_idol_invite'
        app_label = 'api'

    inviter = models.ForeignKey(User, verbose_name=u'邀请人', related_name='variety_vote_inviter')
    invitee = models.ForeignKey(User, verbose_name=u'被邀请人', related_name='variety_vote_invitee')
    activity = models.ForeignKey(VarietyActivity, verbose_name=u'活动')

    # 填写邀请码时间的相关信息
    create_time = models.DateTimeField(default=timezone.now)
    mobile = models.CharField(max_length=20, default='', verbose_name=u'电话号码')
    device_id = models.CharField(max_length=100, verbose_name=u'设备ID')
    device_model = models.CharField(verbose_name=u'具体型号', null=True, max_length=40)
    device_platform = models.CharField(choices=PLATFORM_CHOICES, default=PLATFORM_CHOICES.ANDROID, max_length=20,
                                       verbose_name=u'设备类型')
    device_mul_user = models.BooleanField(default=False, verbose_name='填写邀请码设备是否多个用户登录')

    is_online = models.BooleanField(default=True)


class InvoteStatistics(models.Model):
    class Meta:
        verbose_name = u'邀请统计表'
        db_table = 'api_variety_idol_vote_statistics'
        app_label = 'api'

    inviter = models.ForeignKey(User, verbose_name=u'邀请人')
    activity = models.ForeignKey(VarietyActivity, verbose_name=u'活动')

    create_time = models.DateField(default=datetime.date.today, verbose_name=u'日期')
    hera_invite_cnt = models.IntegerField(default=0, verbose_name=u'hera后台添加的邀请数')
    real_invite_cnt = models.IntegerField(default=0, verbose_name=u'真实的邀请数')


class UserInviteCode(models.Model):
    class Meta:
        verbose_name = u'用户邀请码'
        db_table = 'api_variety_invite_code'
        app_label = 'api'

    key = "invite_code"

    user = models.OneToOneField(User, verbose_name='用户', related_name='invite_code')
    code = models.CharField(max_length=10, verbose_name='用户邀请码')

    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间')

    @classmethod
    def gen_code(cls, user_id):
        # 邀请码 = 时间戳（毫秒级）后6为 + 随机2位

        cnt = 20
        while cnt:
            pre = str(int(round(time.time() * 1000)))[-6:]
            end = '%02d' % int(random.random() * 100)
            code = '%08d' % (int(pre) * 100 + int(end))
            try:
                UserInviteCode.objects.get(code=code)
                cnt -= 1
            except UserInviteCode.DoesNotExist:
                variety_cache.hset(cls.key, user_id, code)
                return code

    @classmethod
    def get_code(cls, user):

        code = variety_cache.hget(cls.key, user.id)
        if not code:
            try:
                u = UserInviteCode.objects.get(user=user)
                code = u.code
            except UserInviteCode.DoesNotExist:
                code = cls.gen_code(user.id)
                u = UserInviteCode()
                u.user = user
                u.code = code
                u.save()
            variety_cache.hset(cls.key, user.id, code)

        return code


class UserVote(models.Model):
    class Meta:
        verbose_name = u'用户票数记录表'
        db_table = 'api_variety_user_votenum'
        app_label = 'api'

    login_vote_key = "login_vote-{activity_id}-{user_id}"
    invite_vote_key = "invite_vote-{activity_id}-{user_id}"

    user = models.ForeignKey(User, verbose_name=u'用户')
    activity = models.ForeignKey(VarietyActivity, verbose_name=u'活动')

    create_time = models.DateField(default=datetime.date.today)
    update_time = models.DateTimeField(auto_now_add=True)

    login_vote = models.IntegerField(default=0, verbose_name='用户登录票')
    invite_vote = models.IntegerField(default=0, verbose_name='用户邀请票')

    def data(self):
        return {
            "login_vote": self.login_vote,
            "invite_vote": self.invite_vote,
        }

    @classmethod
    def data_from_redis(cls, activity_id, user_id):
        """redis中获取用户剩余投票数。"""

        return {
            "login_vote": variety_cache.get(cls.login_vote_key.format(user_id=user_id, activity_id=activity_id)) or 0,
            "invite_vote": variety_cache.get(cls.invite_vote_key.format(user_id=user_id, activity_id=activity_id)) or 0,
        }

    def set_to_redis(self, login_vote, invite_vote):
        variety_cache.set(
            self.login_vote_key.format(user_id=self.user_id, activity_id=self.activity_id),
            login_vote
        )
        variety_cache.set(
            self.invite_vote_key.format(user_id=self.user_id, activity_id=self.activity_id),
            invite_vote
        )

    def set_to_db(self):
        """用户的redis数据设置到"""

    @classmethod
    def vote(cls, activity_id, user_id, vote_num):
        login_key = cls.login_vote_key.format(activity_id=activity_id, user_id=user_id)
        invite_key = cls.invite_vote_key.format(activity_id=activity_id, user_id=user_id)
        login_vote = variety_cache.get(login_key) or 0
        invite_vote = variety_cache.get(invite_key) or 0

        rest_login_vote = login_vote - vote_num if login_vote > vote_num else 0
        rest_invite_vote = invite_vote - (0 if login_vote > vote_num else vote_num - login_vote)

        variety_cache.set(invite_key, rest_login_vote)
        variety_cache.set(invite_key, rest_invite_vote)

        vote_info = {
            "login_vote": rest_login_vote,
            "invite_vote": rest_invite_vote,
        }

        return vote_info


class UserVoteLog(models.Model):
    class Meta:
        verbose_name = u'用户票数增长记录表'
        db_table = 'api_variety_votenum_record'
        app_label = 'api'

    user = models.ForeignKey(User, verbose_name=u'用户')
    activity = models.ForeignKey(VarietyActivity, verbose_name=u'活动')

    change_type = models.IntegerField(verbose_name='变化原因')  # 登录、邀请，之后用gm_types枚举

    vote_num = models.IntegerField(verbose_name='投票数', default=10)
    create_time = models.DateField(default=datetime.date.today)


class VarietyVoteLog(models.Model):
    class Meta:
        verbose_name = u'投票记录表'
        db_table = 'api_variety_vote_Log'
        app_label = 'api'

    voter = models.ForeignKey(User, verbose_name=u'投票人')
    activity = models.ForeignKey(VarietyActivity, verbose_name=u'活动')
    idol = models.ForeignKey(VarietyIdol, verbose_name='被投票的idol')

    is_real = models.IntegerField(verbose_name='是否是真是用户产生的票数', default=True)

    vote_num = models.IntegerField(verbose_name='投票数')
    create_time = models.DateTimeField(default=timezone.now)


class VarietyTotalInvite(models.Model):
    class Meta:
        verbose_name = u'用户邀请记录统计表'
        db_table = 'api_variety_total_invite'
        app_label = 'api'
        unique_together = ("inviter", "activity")

    inviter = models.ForeignKey(User, verbose_name=u'邀请人')
    activity = models.ForeignKey(VarietyActivity, verbose_name=u'活动')

    hera_total_invite = models.IntegerField(default=0, verbose_name=u'hera本期添加总数')

    real_total_invite = models.IntegerField(default=0, verbose_name=u'本期真实邀请总数')

    total_invite_num = models.IntegerField(default=0, verbose_name=u'本期邀请总数')
