# coding=utf-8
'''
    定时检测专题 美券失效
    更新关联美购信息
    脚本执行周期 每30分钟一次
'''
from datetime import datetime
from django.core.management import BaseCommand

from api.models import Special, SpecialItem, Coupon, CouponSpecialRestrict
from api.tasks.service_task import refresh_service_cache_with_special_ids, refresh_service_cache_with_coupon


class Command(BaseCommand):

    def get_time(self):
        now = datetime.now()
        return datetime(now.year, now.month, now.day)

    def invalid_coupon(self):
        time = self.get_time()
        qs = Coupon.objects.filter(end_time=time)
        if not qs.count():
            return []
        return qs.filter(end_time__lte=datetime.now()).values_list('id', flat=True)

    def invalid_special(self):
        time = self.get_time()
        qs = Special.objects.filter(is_online=True, end_time=time)
        if not qs.count():
            return []
        return qs.filter(end_time__lte=datetime.now()).values_list('id', flat=True)

    def handle(self, *args, **kwargs):
        print 'service_cache_info_refresh start time:', datetime.now()
        coupon_ids = self.invalid_coupon()
        if coupon_ids:
            refresh_service_cache_with_coupon(coupon_ids)
        special_ids = self.invalid_special()
        if special_ids:
            refresh_service_cache_with_special_ids(special_ids)
        print 'service_cache_info_refresh end time:', datetime.now()
