#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   RobertDing
#   E-mail  :   robertdingx@gmail.com
#   Date    :   17/12/02 14:51:39
#   Desc    :   data query
#

from django.db.models import Q

from gm_dataquery.db import DB
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery


from point.models.mall import PointGoods, PointActivity
from point.models.mall import PointActivityGoods, PointUserGoods


class GoodsDB(DataBuilder):
    def getval_user_count(self, item):
        return PointUserGoods.objects.filter(activity_goods__good=item).count()


@DB
class GoodsDQ(DataSQLQuery):
    data_model = GoodsDB
    model = PointGoods


@DB
class ActivityDQ(DataSQLQuery):
    model = PointActivity


@DB
class ActivityGoodsDQ(DataSQLQuery):
    model = PointActivityGoods

    def create(self, **kwargs):
        kwargs['current_stock'] = kwargs['stock']
        return super(ActivityGoodsDQ.sqlquery, self).create(**kwargs)

    def update(self, updates, **kwargs):
        is_online = updates['is_online']
        PointActivityGoods.objects.filter(**kwargs).update(is_online=is_online)


class UserGoodsDB(DataBuilder):
    def getval_special(self, obj):
        if not obj.special:
            return "美分商城"
        else:
            return obj.special.id


@DB
class UserGoodsDQ(DataSQLQuery):
    model = PointUserGoods
    data_model = UserGoodsDB

    def filter_has_express_no(self, key, value, regex):
        q = Q(express_no='')
        if int(value):
            q = ~q
        return q
