# -*- coding: UTF-8 -*-

from datetime import datetime

from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.error import ERROR
from api.models import KaBalance
from rpc.exceptions import GaiaRPCFaultException


@DB
class KaDQ(DataSQLQuery):
    model = KaBalance

    def create(self, **kwargs):
        start_time = datetime.strptime(str(kwargs['start_time']), '%Y-%m-%d %H:%M:%S')
        last_obj = KaBalance.objects.filter(merchant_id=kwargs['merchant_id'], is_online=1).order_by('-update_time').first()
        if last_obj and start_time < last_obj.start_time:
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'选择日期不能小于当前已存在记录的创建时间,请重新选择', data=None)
        if last_obj:
            last_obj.end_time = kwargs['start_time']
            last_obj.save()
        return DataSQLQuery.create(self,**kwargs)




