# coding=utf-8
from celery import shared_task

from gm_types.gaia import VOTE_CHANGE_TYPE

from api.models import UserExtra
from api.tool.variety_vote import get_current_activity_by_time, unlock_user_invite_code
from api.models.variety_vote import UserVoteLog, VarietyVoteLog, \
    Invite, InvoteStatistics
from statistic.models import Device


@shared_task
def record_variety_vote(idol_id, user_id, vote_num, activity_id, is_real=True):
    """记录用户投票。"""
    log = VarietyVoteLog()
    log.activity_id = activity_id
    log.voter_id = user_id
    log.idol_id = idol_id
    log.vote_num = vote_num
    log.is_real = is_real
    log.save()


@shared_task
def record_user_vote_num(user_id, vote_num, activity_id=None, change_type=VOTE_CHANGE_TYPE.LOGIN):
    """记录用户票数变化。登录、邀请、投票"""

    log = UserVoteLog()
    log.user_id = user_id

    if not activity_id:
        activity, _ = get_current_activity_by_time()
        log.activity = activity
    else:
        log.activity_id = activity_id
    log.change_type = change_type
    log.vote_num = vote_num
    log.save()


@shared_task()
def record_invite(inviter_id, invitee_id, activity_id, device_id, platform):
    """记录用户邀请记录"""
    invite = Invite()
    invite.inviter_id = inviter_id
    invite.invitee_id = invitee_id
    invite.activity_id = activity_id
    invite.device_platform = platform
    invite.device_id = device_id

    try:
        invitee = UserExtra.objects.get(user_id=invitee_id)
        invite.mobile = invitee.phone if invitee.phone else ''
    except:  # 没有用户手机号
        invite.mobile = ''

    # 目前并不能确定下来Device表会不会存在多条device_id，platform相同的记录，使用最近一条数据
    invite.device_model = Device.objects.filter(device_id=device_id, platform=platform)\
                                        .values_list("model", flat=True)\
                                        .order_by("-id")\
                                        .first()
    device_mul_user = False
    try:
        if Device.objects.get(device_id=device_id).user.count() > 1:
            device_mul_user = True
    except Device.MultipleObjectsReturned:
        device_mul_user = True
    except:
        device_mul_user = False

    invite.device_mul_user = device_mul_user
    invite.save()

    unlock_user_invite_code(invitee_id)


@shared_task()
def record_invite_statistics(inviter_id, activity_id, date, invite_cnt=1):
    """记录用户邀请记录"""
    invite_statistics, _ = InvoteStatistics.objects.get_or_create(
        inviter_id=inviter_id, activity_id=activity_id, create_time=date
    )

    invite_statistics.real_invite_cnt += invite_cnt
    invite_statistics.save()

