# coding=utf8
from __future__ import unicode_literals, absolute_import, print_function

from django.db import models
from django.db.models import Q
from django.utils.html import strip_tags

from .types import TAG_TYPE
from .types import ACHE_LEVEL, ANESTHESIA_TYPE
from .bodypartsubitem import BodyPartSubItem
from .tag import Tag
from api.models import SURGICAL_GRADE_CHOICES
from api.models import TREATMENT_MEANS_CHOICES
from api.models import WIKI_HOSPITAL_TREATMENT_CHOICES
from api.models import WIKI_COMPLEXITY_TYPE
from api.models import WIKI_RISK_FACTOR_TYPE
from api.models import OPTIMIZE_WIKI_TYPE
from api.models import SLIDE_TYPE
from api.models import WIKI_LEVEL
from relation.models import UserTagRelation

from gm_upload import IMG_TYPE, ImgUrlField


class SearchWikiManager(models.Manager):
    def query(self, q):
        return self.get_queryset().filter(Q(item_name__contains=q) | Q(synonym__contains=q) | Q(slogan__contains=q))


class ItemWiki(models.Model):
    class Meta:
        verbose_name = u'整形项目（wiki）'
        verbose_name_plural = u'整形项目（wiki）'
        db_table = 'api_itemwiki'
        app_label = 'api'

    # # 手术等级
    # SURGICAL_GRADE_CHIOCES = (
    #     ('1', u'一级手术'),
    #     ('2', u'二级手术'),
    #     ('3', u'三级手术'),
    #     ('4', u'四级手术'),
    # )

    # # 治疗方式
    # TREATMENT_MEANS_CHOICES = (
    #     ('1', u'手术'),
    #     ('2', u'激光'),
    #     ('3', u'注射'),
    #     ('4', u'其他'),
    # )

    # TREATMENT_MEANS_CHOICES_MAP = {
    #     '1' : u'手术',
    #     '2' : u'激光',
    #     '3' : u'注射',
    #     '4' : u'其他',
    # }
    # # TODO: 按照gm-types增加

    # HOSPITAL_TREATMENT_CHOICES = (
    #     ('0', u'否'),
    #     ('1', u'是'),
    # )

    objects = models.Manager()
    search = SearchWikiManager()

    item_name = models.CharField(u'项目名称', max_length=30)
    surgical_grade = models.CharField(
        u'手术等级', max_length=1, choices=SURGICAL_GRADE_CHOICES,
        default=SURGICAL_GRADE_CHOICES.ONE
    )
    synonym = models.CharField(u'同义词', max_length=200, blank=True, default='')
    treatment_means = models.CharField(
        u'治疗方式', max_length=1, choices=TREATMENT_MEANS_CHOICES,
        default=TREATMENT_MEANS_CHOICES.OPERATE
    )
    effect_continue = models.CharField(u'维持时间', max_length=100, blank=True, null=True)
    price_range = models.CharField(u'价格区间', max_length=200, blank=True, default='')

    hospital_treatment = models.CharField(
        u'是否住院', max_length=1, choices=WIKI_HOSPITAL_TREATMENT_CHOICES,
        default=WIKI_HOSPITAL_TREATMENT_CHOICES.NO
    )
    recovery_time = models.CharField(u'恢复时间', blank=True, max_length=200)
    level_safety = models.CharField(u'风险系数', blank=True, max_length=20)
    side_effect = models.TextField(u'风险提醒', blank=True)
    slogan = models.TextField(u'项目描述', blank=True)
    fit_people = models.TextField(u'适应人群', blank=True, default='')
    advantage = models.TextField(u'优点', blank=True)
    disadvantage = models.TextField(u'缺点', blank=True)
    treatment_method = models.TextField(u'治疗过程', blank=True)
    image = ImgUrlField(u'图片URL', img_type=IMG_TYPE.HOSPITAL, max_length=255, blank=True)
    avoid_people = models.TextField(u'禁忌人群', blank=True)
    notes = models.TextField(u'注意事项', blank=True)
    learn_more = models.TextField(u'了解更多', blank=True)
    faq = models.TextField(u'常见问题', blank=True)
    level_attention = models.CharField(u'关注度', max_length=20, blank=True)
    level_complex = models.CharField(u'复杂度', max_length=20, blank=True)
    bodypart_subitem = models.ForeignKey(
        BodyPartSubItem, related_name="wiki_items",
        default=None, null=True, blank=True, verbose_name=u"项目类别"
    )
    item_sub_item = models.CharField(u'一级分类-二级分类-项目名称', max_length=50, blank=True)
    treatment_effect = models.TextField(u'治疗效果', blank=True)
    treatment_length = models.CharField(u'治疗时长', max_length=100, blank=True)
    anesthesia_method = models.CharField(u'麻醉方法', max_length=100, blank=True)
    line_days = models.CharField(u'拆线天数', max_length=100, blank=True, null=True)
    treat_num = models.CharField(u'治疗次数', max_length=100, blank=True)
    recovery_process = models.CharField(u'恢复过程', max_length=100, blank=True, null=True)
    is_online = models.BooleanField(u'是否上线', default=False, help_text=u"是否上线")
    tag = models.OneToOneField(Tag, blank=True, null=True)
    created_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True, null=True, blank=True)
    complexity_type = models.IntegerField(
        verbose_name=u'复杂度', choices=WIKI_COMPLEXITY_TYPE, null=False,
        default=WIKI_COMPLEXITY_TYPE.DEFAULT
    )
    treatment_time_min = models.IntegerField(verbose_name=u'治疗时长最小值', null=False, default=0)
    treatment_time_max = models.IntegerField(verbose_name=u'治疗时长最大值', null=False, default=0)
    line_days_min = models.IntegerField(verbose_name=u'拆线天数最小值', null=False, default=0)
    line_days_max = models.IntegerField(verbose_name=u'拆线天数最大值', null=False, default=0)
    risk_factor_type = models.IntegerField(
        verbose_name=u'风险系数', null=False, choices=WIKI_RISK_FACTOR_TYPE,
        default=WIKI_RISK_FACTOR_TYPE.DEFAULT
    )
    hospital_days_min = models.IntegerField(verbose_name=u'住院天数最小值', null=False, default=0)
    hospital_days_max = models.IntegerField(verbose_name=u'住院天数最大值', null=False, default=0)
    recovery_time_max = models.IntegerField(verbose_name=u'恢复天数最大值', null=False, default=0)
    recovery_time_min = models.IntegerField(verbose_name=u'恢复天数最小值', null=False, default=0)
    price_min = models.IntegerField(verbose_name=u'价格最小值', null=False, default=0)
    price_max = models.IntegerField(verbose_name=u'价格最 大值', null=False, default=0)
    effect_duration_md = models.TextField(verbose_name=u'效果维持时间', blank=True, null=False, default='')
    risk_warning_md = models.TextField(u'风险提示', blank=True, null=False, default='')
    description_md = models.TextField(verbose_name=u'内容介绍和适合人群', blank=True, null=False,
                                      default='')  # ATTENTION: 用于判断是否取是新添加的wiki内容
    advantage_md = models.TextField(verbose_name=u'优点', blank=True, null=False, default='')
    shortcoming_md = models.TextField(verbose_name=u'缺点', blank=True, null=False, default='')
    avoid_people_md = models.TextField(u'禁忌人群', blank=True, null=False, default='')
    recovery_md = models.TextField(u'恢复情况', blank=True, null=False, default='')
    notes_md = models.TextField(u'注意事项', blank=True, null=False, default='')

    ache_level = models.CharField(verbose_name=u'疼痛感', max_length=5, choices=ACHE_LEVEL, default=ACHE_LEVEL.ZERO)
    anesthesia_type = models.CharField(
        verbose_name=u'麻醉方法', max_length=5,
        choices=ANESTHESIA_TYPE, default=ANESTHESIA_TYPE.NONE
    )
    show_diary = models.BooleanField(verbose_name=u'显示推荐美购', default=True)
    show_service = models.BooleanField(verbose_name=u'显示推荐美购', default=True)
    show_zone = models.BooleanField(verbose_name=u'显示推荐圈子', default=True)
    recover_time_md = models.IntegerField(verbose_name=u'恢复时间', null=False, default=0)
    effect_time_md = models.IntegerField(verbose_name=u'见效时间', null=False, default=0)
    image_head = ImgUrlField(u'图片URL', img_type=IMG_TYPE.HOSPITAL, max_length=255, blank=True)

    def __unicode__(self):
        return self.item_name

    def wiki_data(self):
        data = {
            'id': self.id,
            'wiki_name': self.item_name,  # wiki_name
            'icon_url': self.tag.icon_url if hasattr(self, 'tag') else '',
            'slogan': self.slogan,

            'name': self.tag.name,  # tag_name
            'tag_id': self.tag.id,
            'desc': self.tag.description,
            'title': self.tag.name,  # 冗余字段 不要再使用name
            'is_new_tag': 0,   ## 标明是老标签
        }
        return data

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

    @classmethod
    def get_wiki_by_tagid(cls, tag_id):
        try:
            wiki = cls.objects.get(tag_id=tag_id)
            return wiki
        except:
            return None

    def get_wiki_detail(self):
        data = {
            'id': self.id,
            'name': self.item_name,
            'introduce': self.slogan if self.slogan else u'',
            'price_range': self.price_range if self.price_range else u'',
            'level_safety': self.risk_factor_type if self.risk_factor_type else 0,
            'effect_continue': self.effect_continue if self.effect_continue else u'',
            'advantage': self.advantage if self.advantage else u'',
            'disadvantage': self.disadvantage if self.disadvantage else u'',
            'fit_people': self.fit_people if self.fit_people else u'',
            'treat_means': self.get_treatment_means_display() if self.treatment_means else u'',
            'treat_length': self.treatment_length if self.treatment_length else u'',
            'treat_num': self.treat_num if self.treat_num else u'',
            'hospital_treat': self.get_hospital_treatment_display() if self.hospital_treatment else u'',
            'treat_method': self.treatment_method if self.treatment_method else u'',
            'anesthesia_method': self.anesthesia_method if self.anesthesia_method else u'',
            'line_days': self.line_days if self.line_days else u'',
            'recovery_time': self.recovery_time if self.recovery_time else u'',
            'notes': self.notes if self.notes else u'',
            'side_effect': self.side_effect if self.side_effect else u'',
            'avoid_people': self.avoid_people if self.avoid_people else u'',
        }
        return data

    def _get_wiki_image_util(self, img):
        from api.tool.image_utils import get_w_path, get_thumb_path, get_full_path
        image_data = {
            'image': get_w_path(img),
            'image_thumb': get_thumb_path(img),
            'image_half': get_full_path(img, '-half'),
            'image_wide': get_full_path(img, '-wide'),
            'image_w': get_w_path(img),
        }
        return image_data

    def get_wiki_image_data(self):
        return self._get_wiki_image_util(self.image)

    def get_wiki_image_head_data(self):
        return self._get_wiki_image_util(self.image_head)

    def get_project_wiki_detail(self):
        data = {
            'id': self.id,
            'name': self.tag.name,
            'introduce': self.description_md,

            'price_range': '%d-%d' % (
                self.price_min if self.price_min else 0,
                self.price_max if self.price_max else 0,
            ) if self.price_min or self.price_max else u'',

            'level_safety': self.risk_factor_type,
            'effect_continue': self.effect_duration_md,
            'advantage': self.advantage_md,
            'disadvantage': self.shortcoming_md,
            'treat_means': self.get_treatment_means_display() if self.treatment_means else u'',

            'treat_length': '%d-%d' % (
                self.treatment_time_min if self.treatment_time_min else 0,
                self.treatment_time_max if self.treatment_time_max else 0,
            ) if self.treatment_time_min or self.treatment_time_max else u'',

            'hospital_treat': self.get_hospital_treatment_display() if self.hospital_treatment else u'',
            'anesthesia_method': self.anesthesia_method if self.anesthesia_method else u'',

            'line_days': u'%d-%d' % (
                self.line_days_min if self.line_days_min else 0,
                self.line_days_max if self.line_days_max else 0,
            ) if self.line_days_max or self.line_days_min else u'',

            'notes': self.notes_md,
            'side_effect': self.risk_warning_md,
            'avoid_people': self.avoid_people_md,
            'zone': self.get_tag_info(),
            'gengmei_discount': self.get_gengmei_discount(),
        }
        return data

    def get_tag_info(self):
        query = UserTagRelation.objects.filter(related_tag=self.tag).order_by('-id')

        return {
            'tag_id': self.tag.id,
            'tag_name': self.tag.name,
            'discuss': {
                'num': query.count(),  # 圈子关注数
                'users': [o.user.userextra.get_portrait() for o in query[0:8]]  # 关注该圈子的部分用户头像
            }
        }

    def get_gengmei_discount(self):
        res = {'has_service': True, 'discount': ''}
        try:
            service = self.tag.services.filter(is_online=True).order_by('gengmei_price')[0]
            lower_price = service.gengmei_price
        except:
            res['has_service'] = False
            return res

        if self.price_max:
            gengmei_discount = int((float(lower_price) / self.price_max) * 10)
            if gengmei_discount >= 10:
                res['discount'] = ''
            elif gengmei_discount == 0:
                res['discount'] = 1
            else:
                res['discount'] = gengmei_discount
        return res

    def get_optimize_files(self):
        data = {
            'treatment_means': self.treatment_means,
            'ache_level': self.ache_level,
            'effect_duration_md': self.effect_duration_md,
            'treatment_time_min': self.treatment_time_min,
            'treatment_time_max': self.treatment_time_max,
            'price_min': self.price_min,
            'price_max': self.price_max,
            'anesthesia_type': self.anesthesia_type,
            'hospital_treatment': self.hospital_treatment,
            'hospital_days_min': self.hospital_days_min,
            'hospital_days_max': self.hospital_days_max,
            'line_days_min': self.line_days_min,
            'line_days_max': self.line_days_max,
            'recover_time_md': self.recover_time_md,
            'effect_time_md': self.effect_time_md,
        }
        return data

    def get_slogan(self):
        try:
            opwiki = self.optimizewiki.filter(
                type=OPTIMIZE_WIKI_TYPE.ABSTRACT,
                is_delete=False,
                is_visible=True
            ).last()

            if not opwiki:
                raise OptimizeWiki.DoesNotExist
        except OptimizeWiki.DoesNotExist:
            return self.slogan

        return strip_tags(opwiki.content)


class OptimizeWiki(models.Model):
    class Meta:
        verbose_name = u'优化整形项目（wiki）'
        verbose_name_plural = u'优化整形项目（wiki）'
        db_table = 'api_optimizewiki'
        app_label = 'api'

    wiki = models.ForeignKey(ItemWiki, verbose_name='关联百科', related_name=u'optimizewiki')
    title = models.CharField(verbose_name='标题', max_length=50, default='')
    type = models.CharField(
        verbose_name='类型', max_length=1,
        choices=OPTIMIZE_WIKI_TYPE, default=OPTIMIZE_WIKI_TYPE.ABSTRACT
    )
    ordering = models.IntegerField(verbose_name='排序', default=9999999)
    is_visible = models.BooleanField(verbose_name='是否显示', default=True)
    is_delete = models.BooleanField(verbose_name='是否删除', default=False)
    content = models.TextField(verbose_name=u'内容', null=True, blank=True, default='')

    def data(self):
        return {
            'title': self.title,
            'type': self.type,
            'content': self.content,
        }


class ConnectWiki(models.Model):
    class Meta:
        verbose_name = u'关联百科'
        verbose_name_plural = u'关联百科'
        db_table = 'api_connectwiki'
        app_label = 'api'

    wiki = models.ForeignKey(ItemWiki, related_name='parentwiki')
    connectwiki = models.ForeignKey(ItemWiki, verbose_name=u'关联百科', related_name='childwiki')

    @classmethod
    def get_related_wikis(cls, wiki):
        related_wikis = cls.objects.filter(wiki=wiki)
        if related_wikis:
            wikis = [
                {
                    'wiki_id': _wiki.connectwiki.id,
                    'wiki_name': _wiki.connectwiki.item_name,
                }
                for _wiki in related_wikis
            ]
        else:
            wikis = []

        return wikis


class WikidetailAdver(models.Model):
    class Meta:
        verbose_name = u'wiki详情页广告位'
        db_table = u'api_wikidetailadver'
        app_label = u'api'

    image_header = ImgUrlField(img_type=IMG_TYPE.ADVERTISE, max_length=300, verbose_name=u'wiki详情广告图片', default=u'')
    # 只跳转 0，1，2，9，10，11，15，17
    jump_type = models.CharField(max_length=10, choices=SLIDE_TYPE, default=SLIDE_TYPE.ACTIVITY, verbose_name=u'跳转到')
    jump_target = models.CharField(max_length=300, verbose_name=u'ID/URL/TYPE')
    wiki = models.ForeignKey(ItemWiki, related_name=u'wikidetailadver')
    is_online = models.BooleanField(verbose_name=u'是否上线', default=False)

    def data(self):
        return {
            'jump_type': self.jump_type,
            'target': self.jump_target,
            'image': self.image_header,
        }


class WikiStruct(models.Model):
    class Meta:
        verbose_name = u'百科层级关系'
        db_table = u'api_wikistruct'
        app_label = u'api'

    wiki = models.ForeignKey(ItemWiki, related_name=u'wikistruct')
    parent = models.ForeignKey('self', verbose_name=u'父级id', blank=True, null=True, related_name='child_wiki')
    struct_level = models.CharField(verbose_name=u'所在层级', max_length=5, choices=WIKI_LEVEL, default=WIKI_LEVEL.THREE)
    sort = models.IntegerField(verbose_name=u'排序', default=99999)


class TagWiki(models.Model):
    class Meta:
        verbose_name = "标签wiki"
        db_table = u'api_tagwiki'
        app_label = u'api'

    tag = models.ForeignKey(Tag, related_name=u'tagwiki')
    itemwiki = models.ForeignKey(ItemWiki, blank=True, null=True)


