#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   RobertDing
#   E-mail  :   robertdingx@gmail.com
#   Date    :   17/05/26 15:10:42
#   Desc    :   购物车相关
#

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

from gm_types.gaia import SERVICE_ITEM_PRICE_TYPE
from api.models import Shopcart, ServiceRegister


class ShopcartDB(DataBuilder):
    def getval_is_can_be_sold(self, item):
        price_info = item.service_item.get_current_price_info() or {}
        service_can_sold = item.service.is_can_be_sold()
        service_item_has_stock = item.service_item.sku_stock > 0
        return bool(service_can_sold and service_item_has_stock and price_info)

    def getval_service_item_names(self, item):
        return item.service_item.items_name

    def getval_buy_limit(self, item):
        return item.service_item.get_buy_limit()

    def getval_is_seckill(self, item):
        price_info = item.service_item.get_current_price_info() or {}
        return bool(price_info.get('price_type') == SERVICE_ITEM_PRICE_TYPE.SECKILL)

    def getval_number(self, item):
        buy_limit = item.service_item.get_buy_limit()
        number = item.number if 0 < item.number <= buy_limit else buy_limit
        return number

    def getval_register_id(self, item):
        register = ServiceRegister.objects.get(id=item.service.servicereg.first().id)
        return register.id



@DB
class ShopcartDQ(DataSQLQuery):
    model = Shopcart
    data_model = ShopcartDB
