# -*- coding:utf-8 -*-
'''
date: 2019-04-03
目标: 地推渠道推广, 做的临时活动
涉及此次的新增表, 统一定义在该models中, 基本上就是一次性使用

注:  基本上都是一次性使用, 里面的邀请码记录等可酌情扩展
'''

import datetime

from django.db import models
from django.contrib.auth.models import User

from gm_types.gaia import TEMP_ACTIVITY_TYPE, EXCHANGE_TYPE
from rpc.tool.random_tool import random_str

activity_time_long = {
    ### 活动类型:                      时长: hours
    TEMP_ACTIVITY_TYPE.GROUND_PUSH1904: 48
}

def get_aty_long(aty):
    '''
    获取活动时长
    '''
    return activity_time_long.get(aty) or 168

class BaseModel(models.Model):

    class Meta:
        abstract = True

    is_online = models.BooleanField(verbose_name=u"是否有效", default=True)
    create_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True, db_index=True)
    is_deleted = models.BooleanField(verbose_name='是否删除', default=False)


class UserShareCode(BaseModel):
    '''
    用户分享码表
    '''
    user = models.ForeignKey(User)
    start_time = models.DateTimeField(verbose_name='开始时间')
    end_time = models.DateTimeField(verbose_name='结束时间')
    share_code = models.CharField(max_length=20, verbose_name='邀请码', null=False, default='')
    code_type = models.IntegerField(verbose_name='分享码类型', choices=TEMP_ACTIVITY_TYPE, default=TEMP_ACTIVITY_TYPE.GROUND_PUSH1904)

    @classmethod
    def get_obj_by_share_code_type(cls, share_code, code_type):
        '''
        根据邀请码及类型获取对应记录
        '''
        us = None
        try:
            us = cls.objects.get(share_code=share_code, code_type=code_type)
        except:
            pass

        return us


    @classmethod
    def get_sharecode_by_user_aty(cls, user_id, aty):
        '''
        根据用户及活动类型, 生成分享码
        '''
        record = None
        try:
            record = cls.objects.get(user_id=user_id, code_type=aty)
        except:
            pass

        now = datetime.datetime.now()
        if not record:
            share_code = cls.gen_share_code(user_id, aty)
            new_obj = cls()
            new_obj.user_id = user_id
            new_obj.code_type = aty
            new_obj.start_time = now
            new_obj.end_time = now + datetime.timedelta(hours=get_aty_long(aty))
            new_obj.share_code = share_code
            new_obj.save()
            record = new_obj
        result = {}
        if record:
            result['share_code'] = record.share_code if record.end_time > now else None
            result['end_time'] = record.end_time
        return result


    @classmethod
    def gen_share_code(cls, user_id, aty):
        '''
        生成分享码
        '''
        while True:
            random_code = random_str(16)
            if not cls.objects.filter(share_code=random_code).exists():
                break
        return random_code


class UserExchange(BaseModel):
    '''
    用户兑换记录 ## 用户邀请达标, 可以申请兑换

    注: 根据活动类型, 限制是否同一用户是否可兑换多次, 不建议user-activity_type做联合主键
    '''
    user = models.ForeignKey(User)
    activity_type = models.IntegerField(verbose_name='活动类型', choices=TEMP_ACTIVITY_TYPE, default=TEMP_ACTIVITY_TYPE.GROUND_PUSH1904)
    exchange_status = models.IntegerField(verbose_name='兑换状态', choices=EXCHANGE_TYPE, default=EXCHANGE_TYPE.APPLY)


    @classmethod
    def get_record_by_uid_aty(cls, user_id, aty_type):
        try:
            return cls.objects.get(user_id=user_id, activity_type=aty_type)
        except:
            return None

    @classmethod
    def create_record(cls, user_id, status, aty_type):
        new_obj = cls()
        new_obj.user_id = user_id
        new_obj.exchange_status = status
        new_obj.activity_type = aty_type
        new_obj.save()


class ThirdRecord(BaseModel):
    '''
    记录第三方信息, 目前只有微信
    '''
    platform_id = models.CharField(verbose_name='第三方平台id', max_length=60, null=False)
    nickname = models.CharField(verbose_name='昵称', max_length=255, null=False)
    imgurl = models.CharField(verbose_name='头像', max_length=255, null=False)
    activity_type = models.IntegerField(verbose_name='活动类型', choices=TEMP_ACTIVITY_TYPE, default=TEMP_ACTIVITY_TYPE.GROUND_PUSH1904)
    city = models.CharField(verbose_name='城市', max_length=255, null=True)


    @classmethod
    def get_record_by_pid_aty(cls, platform_id, aty_type):
        '''
        根据活动类型及第三方id获取信息
        '''
        try:
            return cls.objects.get(platform_id=platform_id, activity_type=aty_type)
        except:
            pass
        return None


    @classmethod
    def create_info_record(cls, platform_id, nickname, imgurl, city, aty_type):
        record = cls.get_record_by_pid_aty(platform_id, aty_type)
        if record:
            record.nickname = nickname
            record.imgurl = imgurl
            record.save()
        else:
            new_obj = cls()
            new_obj.platform_id = platform_id
            new_obj.nickname = nickname
            new_obj.imgurl = imgurl
            new_obj.activity_type = aty_type
            new_obj.city = city
            new_obj.save()


class UserShowInfo(BaseModel):
    '''
    记录本次活动中用户进入的微信(第三方)信息, 和用户系统的第三方平台无关

    activity_type: 可能每次活动用户展示的名称不同
    platform_id, 用于记录该次活动, 显示的第三方信息, 只针对该次活动做绑定
    '''
    user = models.ForeignKey(User)
    activity_type = models.IntegerField(verbose_name='活动类型', choices=TEMP_ACTIVITY_TYPE, default=TEMP_ACTIVITY_TYPE.GROUND_PUSH1904)
    thirdrecord = models.ForeignKey(ThirdRecord)


    @classmethod
    def get_showinfo_by_uid_aty(cls, user_id, aty_type):
        try:
            return cls.objects.get(activity_type=aty_type, user_id=user_id)
        except:
            return None


    @classmethod
    def create_showinfo(cls, user_id, aty_type, platform_id):

        user_showinfo = cls.get_showinfo_by_uid_aty(user_id, aty_type)
        if user_showinfo:
            return

        record = ThirdRecord.get_record_by_pid_aty(platform_id, aty_type)
        new_obj = cls()
        new_obj.user_id = user_id
        new_obj.activity_type = aty_type
        new_obj.thirdrecord = record
        new_obj.save()


    @classmethod
    def get_platformid_by_userid(cls, user_id, aty_type):
        record = None
        try:
            record = cls.objects.get(user_id=user_id, activity_type=aty_type)
        except:
            pass
        if record:
            return record.thirdrecord.platform_id
        return None


class UserInvite(BaseModel):
    '''
    邀请者与被邀请者关系表
    '''
    inviter = models.ForeignKey(User, related_name='invitees')
    invitee = models.ForeignKey(User, related_name='inviters')
    invite_status = models.IntegerField(verbose_name='邀请状态, 如注册|登录|付费或不关心等', default=0, null=False)
    activity_type = models.IntegerField(verbose_name='活动类型', choices=TEMP_ACTIVITY_TYPE, default=TEMP_ACTIVITY_TYPE.GROUND_PUSH1904, db_column='acvitity_type')
    share_code = models.CharField(verbose_name='邀请码', max_length=60, null=True)

    @classmethod
    def create_relation(cls, inviter_id, invitee_id, invite_status, aty_type, share_code):
        '''
        创建邀请关系
        '''
        new_obj = UserInvite()
        new_obj.inviter_id = inviter_id
        new_obj.invitee_id = invitee_id
        new_obj.invite_status = invite_status
        new_obj.activity_type = aty_type
        new_obj.share_code = share_code
        new_obj.save()

    @classmethod
    def get_record_by_invitee_aty(cls, invitee_id, aty_type):
        '''
        根据被邀请者id及活动类型获取记录
        '''
        try:
            return cls.objects.filter(invitee=invitee_id, activity_type=aty_type).first()
        except:
            return None

    @classmethod
    def get_inviteeinfo_by_inviter_aty_status(cls, inviter_id, aty_type, inv_status):
        invitee_ids = list(cls.objects.filter(inviter=inviter_id, activity_type=aty_type, invite_status=inv_status).order_by('update_time').values_list('invitee_id', flat=True))
        show_info = []
        if invitee_ids:
            show_query = UserShowInfo.objects.filter(activity_type=aty_type, user_id__in=invitee_ids)
            for sq in show_query:
                show_info.append({
                    'user_id': sq.user_id,
                    'nickname': sq.thirdrecord.nickname,
                    'imgurl': sq.thirdrecord.imgurl,
                    # 'openid': sq.thirdrecord.platform_id
                })

            show_info.sort(key=lambda x:invitee_ids.index(x['user_id']))
        return show_info
