#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2018/9/5
from __future__ import absolute_import
import json
from django.db import transaction
from django.db.models import Q
from gm_dataquery.db import DB
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery


from lipstick.models import LipstickPrize, LipstickRecord


@DB
class LipstickPrizeDQ(DataSQLQuery):
    model = LipstickPrize
    data_model = DataBuilder

    def create(self, **kwargs):
        rank = kwargs.get('rank')
        activity_id = kwargs.get('activity_id')
        with transaction.atomic():
            LipstickPrize.objects.filter(activity_id=activity_id, rank=rank, is_online=True).update(is_online=False)
            obj = self.model.objects.create(**kwargs)
        return {'id': obj.id}

    def filter_activity__name(self, key, value, regex=False):
        return Q(activity__id=int(value))


class LipstickRecordDB(DataBuilder):

    def getval_contact(self, obj):
        if obj.express_info:
            express_info = json.loads(obj.express_info)
            return '%s, %s' %(express_info.get('receiver', '-'), express_info.get('phone', '-'))
        return ''

    def getval_address(self, obj):
        if obj.express_info:
            express_info = json.loads(obj.express_info)
            return '%s, %s' %(express_info.get('region', '-'), express_info.get('address', '-'))
        return ''

@DB
class LipstickRecordDQ(DataSQLQuery):
    model = LipstickRecord
    data_model = LipstickRecordDB

    def filter_activity__name(self, key, value, regex=False):
        return Q(activity__id=int(value))



