# coding: utf-8

from django.db import models
from communal.cache.push import personalize_push_cache


class PersonalizeActionTag(models.Model):
    """
    用户行为标签，根据时间排序，取最新的10条行为对应的标签
    http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=36560964
    """
    class Meta:
        verbose_name = '用户行为标签'
        db_table = 'api_personalize_action_tag'
        unique_together = ('date_index', 'device_id')

    date_index = models.DateField(verbose_name='统计日期', auto_now_add=True)
    device_id = models.CharField(verbose_name='设备id', max_length=64)
    tag_info = models.CharField(verbose_name='标签相关信息', max_length=512)
    '''
    tag_info 数据格式：
    id,id:time#id,id:time
    '''

#
# def parse_personalize_action_task(date_index=None):
#     CACHE_KEY_PERSONALIZE_ACTION_TAG_INFO = 'demeter:push:action_tag_push:action_tag_info'
#
#     def format_action_tag_info(tag_info):
#         result = []
#         for _item in tag_info.split('#'):
#             tags, action_time = _item.split(':')
#             if tags:
#                 result.append(dict(
#                     tags=tags,
#                     action_date=action_time
#                 ))
#         return result
#
#     personalize_action_dict = {}
#     import datetime
#     if not date_index:
#         date_index = str(datetime.date.today())
#
#     first_item = PersonalizeActionTag.objects.filter(date_index=date_index).first()
#     last_item = PersonalizeActionTag.objects.filter(date_index=date_index).last()
#
#     search_offset = 100
#     split_ids = [(i, i+search_offset) for i in range(first_item.id, last_item.id, search_offset)]
#     for (start_id, end_id) in split_ids:
#         res = PersonalizeActionTag.objects.filter(id__range=(start_id, end_id)).values(
#             "tag_info", "device_id"
#         )
#         for obj in res:
#             action_tag_info = format_action_tag_info(obj['tag_info'])
#             if action_tag_info:
#                 personalize_action_dict[obj['device_id']] = action_tag_info
#
#     for device_id, tag_info in personalize_action_dict.items():
#         personalize_push_cache.hmset(CACHE_KEY_PERSONALIZE_ACTION_TAG_INFO, device_id, tag_info)
