# -*- coding: utf-8 -*-

import json
from django.db import models
from gm_types.gaia import TAG_TYPE
from gm_types.gaia import SLIDE_USER_TYPE, SLIDE_PAYMENT_TYPE
from gm_upload import IMG_TYPE, ImgUrlField
from rpc.cache import index_func_cache

from api.models import Tag
from polymer.models import Polymer
from rpc.tool.dict_mixin import to_dict
from api.basemodel import RequestSourceModel


class SideSkidCategory(models.Model):
    class Meta:
        verbose_name = u'首页横滑分类'
        db_table = 'api_gmhome_sideskidcategory'
        app_label = 'api'

    name = models.CharField(u'分类名称', max_length=30, unique=True)
    tags = models.ManyToManyField(Tag)
    polymer = models.ForeignKey(Polymer, null=True)
    ordering = models.IntegerField(u'排序', default=0, null=True, blank=True)
    is_online = models.BooleanField(u'是否上线', default=False)
    created_time = models.DateTimeField(u'创建时间', auto_now_add=True)
    updated_time = models.DateTimeField(u'更新时间', auto_now=True)
    slide_icon = ImgUrlField(img_type=IMG_TYPE.SLIDE, max_length=1024, null=False, blank=False,
                                verbose_name=u'分类引导icon')

    def to_dict(self):
        data = to_dict(
            self, fields=['name', 'is_online', 'ordering', 'id', 'polymer', 'slide_icon', 'created_time'])
        data['tag_type'] = TAG_TYPE.FREE
        return data


class IndexFunction(models.Model):
    RKEY_VISIBLE = 'index_func_visible'
    class Meta:
        verbose_name = u'首页功能区'
        db_table = 'api_index_function'
        app_label = 'api'

    title = models.CharField(u'标题', max_length=30, default='')
    user_type = models.CharField(u'用户类型', max_length=2, choices=SLIDE_USER_TYPE.choices,
                                 default=SLIDE_USER_TYPE.ALL_USER)
    is_payment = models.CharField(u'有无支付', max_length=2, choices=SLIDE_PAYMENT_TYPE.choices,
                                  default=SLIDE_PAYMENT_TYPE.ALL_PAYMENT)
    start_time = models.DateTimeField(u'开始时间')
    end_time = models.DateTimeField(u'结束时间', null=True)
    is_online = models.BooleanField(u'是否上线', default=False)
    card_data = models.TextField(u'入口卡片信息')

    @classmethod
    def get_visible(cls):
        try:
            visible = index_func_cache.get(cls.RKEY_VISIBLE)
            if not visible:
                return True
            else:
                visible = json.loads(visible)
            if 'function' in visible:
                return visible['function']
            else:
                return True
        except:
            return True

    @classmethod
    def set_visible(cls, visible=True):
        visible_data = index_func_cache.get(cls.RKEY_VISIBLE)
        try:
            visible_data = json.loads(visible_data)
        except:
            visible_data = {}
        visible_data['function'] = visible
        index_func_cache.set(cls.RKEY_VISIBLE, json.dumps(visible_data))

    @classmethod
    def get_func(cls):
        pass
