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

from django.db.models import Q, F
from api.models.order import Order
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from api.models.freecustom import FreeCustom
from gm_types.gaia import TAG_TYPE
from datetime import timedelta
from gm_dataquery.db import DB


class FreecustomDB(DataBuilder):
    def getval_user_id(self, obj):
        return obj.user.user.id

    def getval_user_name(self, obj):
        return obj.user.user.last_name

    def getval_create_time(self, obj):
        return str(obj.create_time).split('.')[0]

    def getval_feedback_time(self, obj):
        if obj.feedback_time:
            return str(obj.feedback_time).split('.')[0]

    def getval_tags(self, obj):
        data = u''
        for tag in obj.tags.all():
            tag_data = u'{}:{}/{}'.format(
                tag.id, tag.name, TAG_TYPE.getDesc(tag.tag_type))
            data = data + tag_data
        return data


@DB
class FreecustomDQ(DataSQLQuery):
    model = FreeCustom
    data_model = FreecustomDB

    def filter_create_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_feedback_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_user_name(self, srch_key, srch_val, regex=False):
        q = Q(user__user__last_name__contains=srch_val)
        return q

    def filter_has_order(self, srch_key, srch_val, regex=False):
        if srch_val == u'1':
            self.distinct = True
            q = Q(user__user__order__status__in=[u'1', u'2'])\
                & Q(user__user__order__pay_time__gt=F('create_time'))\
                & Q(user__user__order__pay_time__lt=F('create_time') + timedelta(days=30))
            return q

    def filter_has_phone(self, srch_key, srch_val, regex=False):
        q = Q(phone='')
        return q if srch_val == u'0' else ~q
