# coding=utf-8
# create by oldman at 2018/9/3
from api import Service
from api.models import Special, ServiceItem, ServiceRegisterItem


def service_is_activity(service_id, special_id):
    """
    判断美购是否可以添加到专题中
    :param service_id:
    :param end_time:
    :return:
    """
    try:
        services = Service.objects.filter(id=service_id)
        if not services.exists():
            return {
                'code': 0,
                'message': u'{}美购不存在！'.format(service_id)
            }
        service = services.first()
        if not service.is_online:
            return {
                'code': 0,
                'message': u'{}美购已经下线！'.format(service.id)
            }

        special = Special.objects.get(id=special_id)
        if service.end_time and service.end_time < special.end_time:
            return {
                'code': 0,
                'message': u'{}美购有效期不足！'.format(service.id)
            }
    except Exception:
        return {
            'code': 0,
            'message': u'{}美购不存在！'.format(service_id)
        }
    return dict(code=1)


def sku_is_activity(sku_id, special_id):
    try:
        skus = ServiceItem.objects.filter(parent_id=0, id=sku_id)
        if not skus.exists():
            return dict(code=0, message=u'{}sku不存在！'.format(sku_id))
        sku = skus.first()
        serviceregisteritem = ServiceRegisterItem.objects.filter(serviceitem=sku)
        if serviceregisteritem.exists():
            if not serviceregisteritem.first().is_online:
                return {
                    'code': 0,
                    'message': u'{}sku不再售卖！'.format(sku_id)
                }
        service = sku.service
        if not service.is_online:
            return {
                'code': 0,
                'message': u'{}sku所在美购已经下线！'.format(sku_id)
            }

        special = Special.objects.get(id=special_id)
        if service.end_time and service.end_time < special.end_time:
            return {
                'code': 0,
                'message': u'{}sku所在美购有效期不足！'.format(sku_id)
            }
    except Exception:
        return dict(code=0, message=u'{}sku不存在！'.format(sku_id))
    return dict(code=1)
