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

from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB

from api.models import Campaign, CampaignImageLink
from gm_types.gaia import SLIDE_TYPE
from datetime import datetime



class CampaignDB(DataBuilder):
    def getval_online_time(self, obj):
        if obj.online_time:
            return obj.online_time.strftime('%Y-%m-%d')
        return ''

    def getval_offline_time(self, obj):
        if obj.offline_time:
            return obj.offline_time.strftime('%Y-%m-%d')
        return ''

    def getval_status(self, obj):
        now_t = datetime.now()
        if now_t < obj.online_time:
            return u'即将开始'
        elif now_t > obj.offline_time:
            return u'已结束'
        else:
            return u'进行中'


@DB
class CampaignDQ(DataSQLQuery):
        model = Campaign
        data_model = CampaignDB

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

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


class CampaignImageLinkDB(DataBuilder):
    def getval_link_type(self, obj):
        return SLIDE_TYPE.getDesc(obj.link_type)

    def getval_related_name(self, obj):
        if obj.link_type == SLIDE_TYPE.TOPIC:
            return obj.topic.ask if obj.topic else ''
        elif obj.link_type == SLIDE_TYPE.URL:
            return obj.url
        elif obj.link_type == SLIDE_TYPE.SERVICE:
            return obj.service.name if obj.service else ''
        elif obj.link_type == SLIDE_TYPE.DIARY:
            return obj.diary.title if obj.diary else ''
        elif obj.link_type == SLIDE_TYPE.ZONE_SINGLE:
            return obj.zone_single.name if obj.zone_single else ''
        elif obj.link_type == SLIDE_TYPE.TAG:
            return obj.tag.name if obj.tag else ''
        elif obj.link_type == SLIDE_TYPE.SPECIAL:
            return obj.special.title if obj.special else ''
        else:
            return SLIDE_TYPE.getDesc(obj.link_type)


@DB
class CampaignImageLinkDQ(DataSQLQuery):
        model = CampaignImageLink
        data_model = CampaignImageLinkDB
        pass
