# coding=utf-8
'''
与交易相关
'''
from __future__ import unicode_literals, absolute_import

from datetime import datetime, timedelta
from django.db.models import Count

from gm_rpcd.all import bind
from talos.rpc import bind_context

from talos.models.diary import Diary, DiaryExtra


@bind('diary/order')
def talos_diary_order(order_id):
    try:
        diary = Diary.objects.get(
            order_id=order_id
        )
    except Diary.DoesNotExist:
        return False
    else:
        return diary.topics.exists()


@bind('diary/order_ids')
def talos_recent_order_ids(days=30):
    try:
        days = int(days)
    except (ValueError, TypeError):
        days = 30

    # queryset = Diary.objects.filter(created_time__gt=datetime.now() - timedelta(days=days),
    #     extra_info__diary__isnull=True
    # ).values_list('order_id', flat=True).distinct()
    #
    # return list(filter(lambda x: x is not None, queryset))

    diaries = Diary.objects.filter(created_time__gt=datetime.now() - timedelta(days=days)).values("id", "order_id").iterator()
    pre_diary_dic = {diary["id"]: diary for diary in diaries}
    pre_diary_ids = pre_diary_dic.keys()
    extra_ids = list(DiaryExtra.objects.filter(diary_id__in=pre_diary_ids).values_list("diary_id", flat=True))

    diary_ids = set(pre_diary_ids) - set(extra_ids)
    order_ids = set(pre_diary_dic[did]["order_id"] for did in diary_ids)

    return list(filter(lambda x: x is not None, order_ids))
