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

import json
from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.dict_mixin import to_dict

from api.models.advertise_management import AdvertiseManagement, ExtendTips
from datetime import datetime
from gm_types.gaia import ADVER_MANAGEMENT_TYPE, ADVER_MANAGEMENT_POSITION_TYPE
from gm_types.error import ERROR
from gm_dataquery.db import DB

from rpc.exceptions import GaiaRPCFaultException


class AdvertiseManagementDB(DataBuilder):
    def getval_service__name(self, obj, default=''):
        return obj.service.name if obj.service else ''

    def getval_show_city__name(self, obj, default=''):
        return [x.name for x in obj.show_city.all()]

    def getval_show_positions(self, obj, default=''):
        position = obj.show_position.split(',')
        name = []
        for pos in position:
            name.append(ADVER_MANAGEMENT_POSITION_TYPE.getDesc(pos))
        return ','.join(name)

    def getval_provinces(self, obj):
        return list(set([x.province.name for x in obj.show_city.all()]))

    def getval_search_words(self, obj):
        search_words = json.loads(obj.search_words) if obj.search_words else []
        return ';'.join(search_words)

    def getval_tags__name(self, obj):
        return [x.name for x in obj.tags.all()]


@DB
class AdvertiseManagementDQ(DataSQLQuery):
        model = AdvertiseManagement
        data_model = AdvertiseManagementDB

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

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

        def filter_is_at_time(self, srch_key, srch_val, regex=False):
            result = self.filter_end_time(
                'end_time',
                [datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S"), ''],
                regex)
            return ~result if srch_val == '1' else result

        def filter_search_words(self, srch_key, srch_val, regex=False):
            if srch_val:
                srch = srch_val.split(';')
                while '' in srch:
                    srch.remove('')
                search_words = json.dumps(srch)
                return Q(search_words=search_words)
            return Q()

        def filter_show_position(self, srch_key, srch_val, regex=False):
            if srch_val:
                return Q(show_position__contains=srch_val)
            return Q()

        def create(self, **kwargs):
            now = datetime.now()
            q = Q(
                is_online=True,
                end_time__gt=now,
                service_id=kwargs['service_id'],
                show_position=kwargs['show_position'],
                adver_type=ADVER_MANAGEMENT_TYPE.SERVICE
            )
            if AdvertiseManagement.objects.filter(q).exists():
                raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message='已有在线的未到期美购广告位', data=None)
            tags = kwargs.pop('tags')
            show_city = kwargs.pop('show_city')
            if kwargs.get('search_words'):
                search_words = kwargs['search_words'].split(';')
                kwargs['search_words'] = json.dumps(search_words)
            item = AdvertiseManagement.objects.create(**kwargs)
            item.tags = tags
            item.show_city = show_city
            return to_dict(item)


@DB
class ExtendTipsDQ(DataSQLQuery):
    model = ExtendTips
