# coding: utf-8

import json

from django.db import models
from django.db.models import DateTimeField, CharField, IntegerField, BooleanField
from django.db.models import ForeignKey, ManyToManyField, TextField

from gm_types.gaia import ADVER_MANAGEMENT_TYPE, ADVER_MANAGEMENT_POSITION_TYPE
from gm_types.hera import BUSINESS_TYPE

from api.models import Service, City, Tag
from api.models import Doctor

class ExtendTips(models.Model):
    class Meta:
        verbose_name = u'推广tips'
        db_table = 'api_extendtips'
        app_label = 'api'

    tip_name = models.CharField(max_length=4, verbose_name=u'推广tips名称')


class AdvertiseManagement(models.Model):
    class Meta:
        verbose_name = u'广告位管理'
        db_table = 'api_advertisemanagement'
        app_label = 'api'

    service = ForeignKey(Service, verbose_name=u'美购', null=True)
    show_city = ManyToManyField(City, verbose_name=u'展示城市', db_table='api_advertisemanagement_show_city')
    show_position = CharField(u'展示位置', max_length=20, null=True)
    # show_days = models.IntegerField(verbose_name=u'展示天数', blank=True, null=True)
    start_time = DateTimeField(u'开始日期')
    end_time = DateTimeField(u'结束日期')
    extend_tip = ForeignKey(ExtendTips, verbose_name=u'推广tips')
    is_online = BooleanField(default=True)
    doctor = ForeignKey(Doctor)
    search_words = TextField(u'搜索词', null=True)
    adver_type = CharField(max_length=8, choices=ADVER_MANAGEMENT_TYPE, default=ADVER_MANAGEMENT_TYPE.SERVICE)
    ordering = IntegerField(u'展示顺序', default=99999)
    tags = models.ManyToManyField(Tag, db_table="api_tag_relation_ad")
    business_type = CharField(max_length=32, choices=BUSINESS_TYPE, default=BUSINESS_TYPE.ADVERTISE)

    @property
    def get_search_words(self):
        return json.loads(self.search_words) if self.search_words else []

    @property
    def get_show_position(self):
        return self.show_position.split(',')

    def tag_relations(self):
        return self.tags.all()

    def show_city_tags(self):
        return [x.tag.id for x in self.show_city.filter(is_online=True)]

class TagRelationAd(models.Model):
    class Meta:
        verbose_name = u'广告位关联tag'
        app_label = 'api'
        db_table = 'api_tag_relation_ad'

    advertisemanagement = models.ForeignKey(AdvertiseManagement, default=None, null=True, blank=True, related_name='advertisemanagement_relations')
    tag = models.ForeignKey(Tag, default=None, null=True, blank=True, related_name='tag_relations')

