# coding=utf8
from __future__ import unicode_literals, absolute_import, print_function
import json
from itertools import chain
from django.db import models
from django.contrib.auth.models import User
from rpc.cache import gadget_cache
from .types import TAG_TYPE
from .tag import Tag
from gm_upload import ImgUrlField, IMG_TYPE


class BodyPart(models.Model):
    """
    第一级分类:
    """

    class Meta:
        verbose_name = u'10. 身体部位（美圈）'
        verbose_name_plural = u'10. 身体部位（美圈）'
        db_table = 'api_bodypart'
        app_label = 'api'

    id = models.IntegerField(primary_key=True, help_text=u"身体部位的Id")
    name = models.CharField(max_length=30, unique=True, help_text=u"身体部位", db_index=True)
    image_url = ImgUrlField(img_type=IMG_TYPE.BODYPART, max_length=300, help_text=u"身体部位对应的图片", null=True, blank=True,
                            default='')
    index_img_url = ImgUrlField(img_type=IMG_TYPE.BODYPART, max_length=300, verbose_name=u"首页带文字图片", default=None,
                                null=True, blank=True)
    rank = models.IntegerField(default=0, verbose_name=u"排序", help_text=u"越小越排在前面")
    is_deleted = models.BooleanField(default=False, help_text=u"是否标记删除")
    is_invalid = models.BooleanField(default=False, help_text=u"是否为有效的分类")
    is_hide_to_doctor = models.BooleanField(default=False, verbose_name=u'是否对医生隐藏')
    is_recommend = models.BooleanField(verbose_name=u'是否推荐', help_text=u'在美圈频道首页是否展示为推荐美圈',
                                       default=False)
    # 增加用户关注，用作美圈
    users = models.ManyToManyField(User, blank=True, related_name=u'zones')
    icon = ImgUrlField(img_type=IMG_TYPE.BODYPART, verbose_name=u'图标', max_length=100, default=u'', blank=True)
    icon_web = ImgUrlField(img_type=IMG_TYPE.BODYPART, verbose_name=u'WEB版图标', max_length=100, default=u'', blank=True)
    tag = models.ForeignKey(Tag, null=True, blank=True)

    def item_data(self):
        return {
            'name': self.tag.name,
            'tag_type': u'body_part',
            'tag_id': self.tag.id,
            'id': self.id,
            'icon': self.icon,
            'icon_web': self.icon_web,
        }

    def get_tag(self):
        return Tag.objects.get(name=self.name, tag_type=TAG_TYPE.BODY_PART)

    def wiki_group_data(self, tag_id=None):
        group_data = {'group_name': self.name, 'icon': self.icon, 'wiki': []}
        if tag_id:
            tags = self.sub_items.filter(id=tag_id, is_deleted=False)
        else:
            tags = self.sub_items.filter(is_deleted=False)
        wiki_items = (tag.wiki_items.filter(is_online=True) for tag in tags)
        group_data['wiki'] = [wiki.wiki_data() for wiki in chain.from_iterable(wiki_items)]

        return group_data

    def __unicode__(self):
        return self.name
