# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function

import datetime
from django.conf import settings

from api.tool.consult_tool import ConsultConfig
from api.tool.user_tool import get_user_from_context
from api.tool.user_tool import get_user_extra_by_user_id
from sms.utils.smsfactory import send_sms
from api.models.consult import (
    ConsultWiki,
    ConsultScience,
    ConsultTheme,
)
from api.models.freecustom import (
    FreeCustom,
    FreecustomImage,
    FreecustomTag,
)
from api.models import (
    Tag,
    User,
)
from api.models import TREATMENT_MEANS_CHOICES

from rpc.decorators import bind_context
from rpc.tool.error_code import CODES, gen
from rpc.cache import add_limit_num, get_limit_num

from social.models import SocialInfo
from rpc.tool.log_tool import logging_exception
from message.views.message import internal_message_send
from gm_types.push import PUSH_STAT_CATEGORY


@bind_context('api/consult/config', login_required=False)
def get_consult_config(ctx):
    """
    获取咨询配置
    """
    config = ConsultConfig.get()
    return config


@bind_context('api/consult/wiki', login_required=False)
def get_consult_wiki(ctx):
    """
    获取咨询首页百科
    """
    consults = ConsultWiki.objects.filter(is_online=True).order_by('ordering')
    result = []
    for consult in consults:
        result.append({
            'wiki_id': consult.wiki_id,
            'icon': consult.icon,
            'wiki_name': consult.wiki.wiki_data()['wiki_name'],
            'slogan': consult.wiki.wiki_data()['slogan'],
            'tag_id': consult.wiki.wiki_data()['tag_id'],
            'title': consult.wiki.wiki_data()['title'],
        })
    return result


@bind_context('api/consult/free_custom_made', login_required=True)
def free_custom_made(ctx, phone, tag_list, plan_type, operation_type,
                    recover_time, descprition, images, select_phone=None):
    """
    免费定制
    """
    user = get_user_from_context(ctx)

    redis_key = '{module}:{id}:{str}'.format(module='free_custom_made', id=user.id,
        str =datetime.date.today().strftime('%y.%m.%d'))

    times = get_limit_num(redis_key)
    if times and times >= settings.MAX_CUSTOM_DAY_TIME:
        return {'error': CODES.MAX_CUSTOM_MADE_TIME_ERROR, 'message':CODES.getDesc(CODES.MAX_CUSTOM_MADE_TIME_ERROR)}
    else:
        add_limit_num(redis_key, 24*60*60, settings.MAX_CUSTOM_DAY_TIME)

    freecustom = FreeCustom()
    if not phone:
        phone = user.person.phone

    if plan_type:
        freecustom.plan_type = plan_type
    if operation_type:
        freecustom.operation_type = operation_type
    if recover_time:
        freecustom.recover_time = recover_time
    if descprition:
        freecustom.comments = descprition
    if phone:
        freecustom.phone = phone
    if user:
        freecustom.user = user.person
    if select_phone:
        freecustom.is_phone_connect = select_phone

    freecustom.save()

    tags = Tag.objects.filter(id__in=tag_list)

    for tag in tags:
        free_tag = FreecustomTag()
        free_tag.freecustom = freecustom
        free_tag.tag = tag
        free_tag.save()

    for image in images:
        free_image = FreecustomImage()
        free_image.freecustom = freecustom
        free_image.image_url = image
        free_image.save()

    return gen(CODES.SUCCESS)


@bind_context('api/consult/science_knowledge', login_required=False)
def get_science_knowledge(ctx, start_num=0, count=10):
    """
    获取科普知识
    """
    end_num = start_num + count - 1
    sciences = ConsultScience.objects.filter(is_online=True)[start_num:end_num]
    result = []
    for science in sciences:
        wikis = []
        for science_wiki in science.related_wikis.all():
            wikis.append({
                'wiki_id': science_wiki.wiki.wiki_data()['id'],
                'wiki_name': science_wiki.wiki.tag.name,
            })

        result.append({
            'desc': science.desc,
            'image': science.image,
            'title': science.wiki.tag.name,
            'wiki_id': science.wiki.wiki_data()['id'],
            'wiki_name': science.wiki.tag.name,
            'wikis': wikis,
        })
    return result

@bind_context('api/consult/theme', login_required=False)
def get_science_knowledge(ctx):
    """
    获取精选主题
    """
    themes = ConsultTheme.objects.filter(is_online=True)
    result = []
    for theme in themes:
        result.append({
            'desc': theme.desc,
            'image': theme.image,
            'title': theme.title,
            'id': theme.id,
        })
    return result

@bind_context('api/consult/theme_detail', login_required=False)
def get_theme_detail(ctx, theme_id=0):
    """
    获取精选主题详情页
    """
    result = {}
    try:
        theme = ConsultTheme.objects.get(id=theme_id)
    except:
        return result

    theme_wikis = theme.related_wikis.all()

    result['detail']= []
    result['title'] = theme.title

    for theme_wiki in theme_wikis:

        result['detail'].append({
            'wiki_id': theme_wiki.wiki.wiki_data()['id'],
            'wiki_name': theme_wiki.wiki.tag.name,
            'icon': theme_wiki.image,
            'introduction': theme_wiki.wiki.advantage_md,
            'treatment_means': TREATMENT_MEANS_CHOICES.getDesc(theme_wiki.wiki.treatment_means) and \
                TREATMENT_MEANS_CHOICES.getDesc(theme_wiki.wiki.treatment_means) or '',
            'treatment_time_min': theme_wiki.wiki.treatment_time_min,
            'treatment_time_max': theme_wiki.wiki.treatment_time_max,
            'slogan': theme_wiki.slogan,
        })

    return result

@bind_context("api/consult/add_follow_phone", login_required=True)
def user_add_follow(ctx, phone):
    try:
        follow_user = User.objects.get(id=settings.BOSS)
        user = get_user_from_context(ctx)
        social_info = SocialInfo(uid=user.id)
        social_info.follow(uid=follow_user.id)

        msg_res = internal_message_send(
            sender_user_id=settings.BOSS,
            target_user_id=user.id,
            content={
                'text': u'您好，您在更美APP上提交了免费医美定制，48小时内将与您通过私信进一步沟通，祝您越来越美丽！',
            },
            push_stat_labels={
                'push_stat_category': PUSH_STAT_CATEGORY.CONSULT,
            },
        )
        if msg_res['error'] != CODES.SUCCESS:
            gen(msg_res['error'])

        msg = u'您好，您在更美APP上提交了免费医美定制，48小时内将与您通过私信进一步沟通，祝您越来越美丽！【更美APP】'
        send_sms(phone, 5, [])
    except User.DoesNotExist:
        logging_exception()
        return gen(CODES.USER_NOT_FOUND)


@bind_context("api/consult/add_follow", login_required=True)
def user_add_follow(ctx):
    try:
        follow_user = User.objects.get(id=settings.BOSS)
        user = get_user_from_context(ctx)
        social_info = SocialInfo(uid=user.id)
        social_info.follow(uid=follow_user.id)

        msg_res = internal_message_send(
            sender_user_id=settings.BOSS,
            target_user_id=user.id,
            content={
                'text': u'您好，您在更美APP上提交了免费医美定制，48小时内将与您通过私信进一步沟通，祝您越来越美丽！',
            },
            push_stat_labels={
                'push_stat_category': PUSH_STAT_CATEGORY.CONSULT,
            },
        )
        if msg_res['error'] != CODES.SUCCESS:
            gen(msg_res['error'])

    except User.DoesNotExist:
        logging_exception()
        return gen(CODES.USER_NOT_FOUND)
