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

import json
from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from rpc.tool.protocol import gm_protocol
from api.models import Slide, SmallImage, ShowCity
from api.models import IndexFunction
from gm_types.gaia import SLIDE_TYPE, SLIDE_SERVICE_TYPE
from gm_dataquery.db import DB


class SlideDB(DataBuilder):
    def getval_slide_type(self, obj):
        return SLIDE_TYPE.getDesc(obj.slide_type)

    def getval_service_type(self, obj):
        return SLIDE_SERVICE_TYPE.getDesc(obj.service_type)


@DB
class SlideDQ(DataSQLQuery):
        model = Slide
        data_model = SlideDB

        def filter_effect_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_cities(self, srch_key, srch_val, regex=False):
            if srch_key is not None:
                show_cities = ShowCity.objects.filter(city_id=srch_val)
                slidies = [item.slide_id for item in show_cities]
                return Q(id__in=slidies)


class SmallImageDB(DataBuilder):
    def getval_jump_type(self, obj):
        if obj.service:
            return u'美购'
        if obj.special:
            return u'专题'
        if obj.diary_id:
            return u'日记本'
        if obj.tag:
            return u'指定的圈子'
        if obj.url:
            return u'网页'
        if obj.topic_id:
            return u'帖子'
        if obj.activity_id:
            return u'免费活动'
        if obj.new_url == gm_protocol.my_points:
            return u'我的积分'
        if obj.new_url == u'gengmei://common_webview?url=http://backend.igengmei.com/hybrid/invitation/my_invitation':
            return u'邀请好友'


@DB
class SmallImageDQ(DataSQLQuery):
        model = SmallImage
        data_model = SmallImageDB


class IndexFunctionDB(DataBuilder):
    def getval_card_data(self, obj, need_escape=False):
        return json.loads(obj.card_data)


@DB
class IndexFunctionDQ(DataSQLQuery):
    model = IndexFunction
    data_model = IndexFunctionDB

