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

from django.conf import settings
from django.db import models
from django.utils import timezone
from django.db.models import Q
from gm_types.user_hierarchy import EventType, FEEDBACK
from gm_types.gaia import USER_RIGHTS_LEVEL, INDEX_CARD_TYPE


class UserEventLog(models.Model):

    class Meta:
        verbose_name = u'用户相关事件记录'
        verbose_name_plural = u'用户相关事件记录'
        db_table = 'api_user_event_log'
        app_label = 'user_hierarchy'
        index_together = ['user_id', 'event_type']

    user_id = models.IntegerField()
    trigger_time = models.DateTimeField(verbose_name=u'触发时间', null=True, blank=True)
    created_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    event_type = models.CharField(verbose_name=u'事件类型', max_length=2, choices=EventType)
    related_item_id = models.CharField(verbose_name=u'相关内容ID', max_length=40, blank=True, null=True)
    value = models.IntegerField(verbose_name='分值')

    @classmethod
    def get_user_value(cls, user_id):
        logs = cls.objects.filter(user_id=user_id).values('value')
        user_value = 0
        for log in logs:
            user_value += log['value']
        return user_value

    @classmethod
    def get_user_today_value(cls, user_id):
        logs = cls.objects.filter(trigger_time__date=datetime.date.today(), user_id=user_id).values('value')
        user_value = 0
        for log in logs:
            user_value += log['value']
        return user_value


class UserGrowthValue(models.Model):

    class Meta:
        verbose_name = u'用户成长值'
        verbose_name_plural = u'用户成长值'
        db_table = 'api_user_growth_value'
        app_label = 'user_hierarchy'

    user_id = models.IntegerField(db_index=True, unique=True)
    value = models.IntegerField()
    level = models.CharField(
        max_length=1,
        choices=USER_RIGHTS_LEVEL,
        default=USER_RIGHTS_LEVEL.V1,
        verbose_name='用户权益等级'
    )

    @property
    def next_level_value(self):
        next_level = str(int(self.level) + 1)
        if int(next_level) > int(USER_RIGHTS_LEVEL.V7):
            return 0

        return settings.LEVEL_START_VALUE[next_level] - self.value

    @property
    def next_level(self):
        next_level = str(int(self.level) + 1)
        if int(next_level) >= int(USER_RIGHTS_LEVEL.V7):
            return USER_RIGHTS_LEVEL.V7
        else:
            return next_level


class GrowthTask(models.Model):

    class Meta:
        verbose_name = u'用户成长任务'
        verbose_name_plural = u'用户成长任务'
        db_table = 'api_growth_task'
        app_label = 'user_hierarchy'

    title = models.CharField(max_length=100, verbose_name='标题')
    content = models.CharField(max_length=300, verbose_name='内容')
    result = models.CharField(max_length=300, verbose_name='任务分数')
    events = models.CharField(max_length=100, verbose_name='包含事件')
    is_daily = models.BooleanField(verbose_name='是否为每日任务', default=True)

    @classmethod
    def get_user_today_status(cls, user_id):
        today = datetime.date.today()
        tasks = cls.objects.all()
        _data = []

        for task in tasks:
            events = json.loads(task.events).get('events')
            query = Q(user_id=user_id, event_type__in=events)
            if task.is_daily:
                query &= Q(trigger_time__date=today)
            _status = UserEventLog.objects.filter(query).exists()
            _data.append({
                'title': task.title,
                'content': task.content,
                'result': task.result,
                'status': _status,
            })

        return _data


class UserFeedback(models.Model):

    class Meta:
        verbose_name = "隐藏反馈"
        verbose_name_plural = "隐藏反馈"
        db_table = 'api_user_feedback'
        app_label = 'user_hierarchy'

    element_type = models.CharField(verbose_name="类型：日记、帖子、回答", max_length=5, choices=INDEX_CARD_TYPE)
    element_id = models.CharField(verbose_name="隐藏元素ID", max_length=100, db_index=True)
    feedback_type = models.IntegerField(verbose_name="用户反馈原因", max_length=2, choices=FEEDBACK)

    user_id = models.IntegerField(verbose_name="用户ID", db_index=True)
    device_id = models.CharField(verbose_name="设备ID", max_length=50, db_index=True)

    create_time = models.DateTimeField("创建时间", auto_now_add=True)
