# -*- coding: UTF-8 -*-

from django.db.models import Q
from django.conf import settings

from gm_types.gaia import SIGN_SWITCH_STATUS
from rpc.decorators import bind_context

from rpc.exceptions import RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
from talos.models.topic import ActivityWinlist, Activity
from talos.models.topic import Problem
from rpc.tool.error_code import CODES, gen
from hera.queries.talos.activity import ActivityDQ
from hera.queries.talos.topic import TopicDQ
from hera.utils import model_edit
from api.models.sign_activity import SignConfig


activity_pre = 'hera/activity'


@bind_context(activity_pre + '/query')
def activity_query(ctx, options):
    dqobj = ActivityDQ()
    return dqobj.process(**options)


@bind_context(activity_pre + '/get')
def activity_detail(ctx, activity_id, options=None):
    try:
        activity = Activity.objects.get(id=activity_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }

    activity_data = to_dict(activity, **options)
    return activity_data


@bind_context(activity_pre + '/choices')
def activity_choices(ctx, q='', page=1, num=30, initial=None):
    page = int(page)
    num = int(num)

    if initial is not None:
        if isinstance(initial, (list, tuple)):
            qry = Q(id__in=initial)
        else:
            qry = Q(id=initial)
    else:
        qry = Q(id__contains=q) | Q(title__contains=q)
    query = Activity.objects.using(settings.MIMAS_SLAVE_DB_NAME).filter(qry)
    total_count = query.count()
    start_pos = (page - 1) * num
    start_pos = start_pos if start_pos >= 0 else 0
    results = [
        {
            'id': obj.id,
            'text': u'{}:{}'.format(obj.id, obj.title),
        } for obj in query[start_pos: start_pos + num]
    ]
    return {'total_count': total_count, 'results': results, 'page': page, 'num': num}


@bind_context(activity_pre + '/edit')
def activity_edit(ctx, activity_id, activity_info=None):
    if activity_info is None:
        return None

    activity_info['doctor_id'] = activity_info.pop('doctor')
    activity = model_edit(Activity, activity_id, activity_info)
    return activity.id


@bind_context(activity_pre + '/listupdate')
def activity_listupdate(ctx, items):
    info = []
    for obj in items:
        activity = Activity.objects.get(pk=obj['key'])
        activity.is_online = obj['is_online']
        activity.save()
        info.append(obj['key'])
    return info


@bind_context(activity_pre + '/topic/query')
def activity_topic_query(ctx, options):
    dqobj = TopicDQ()
    return dqobj.process(**options)


@bind_context(activity_pre + '/topic/win')
def topic_win(ctx, activity_id, topic_id):
    try:
        topic = Problem.objects.get(id=topic_id)
        user = topic.user
        person_id = user.person_id
    except Problem.DoesNotExist:
        return gen(CODES.TOPIC_NOT_FOUND)

    try:
        activity = Activity.objects.get(id=activity_id)
    except Activity.DoesNotExist:
        return gen(CODES.ACTIVITY_NOT_EXIST)

    win_limit = activity.win_limit
    win_people_num = activity.winners.all().count()

    if win_people_num >= win_limit:
        return gen(CODES.ACTIVITY_REACH_WIN_LIMIT)

    ActivityWinlist.objects.create(activity=activity, person_id=person_id, topic=topic_id)
    return to_dict(activity)


@bind_context(activity_pre + '/win_num')
def get_win_people_num(ctx, activity_id):
    """
    获取活动中奖人数
    """
    try:
        activity = Activity.objects.get(id=activity_id)
    except Activity.DoesNotExist:
        return gen(CODES.ACTIVITY_NOT_EXIST)

    win_limit = activity.win_limit
    win_num = activity.winners.all().count()
    return {
        'win_limit': win_limit,
        'win_num': win_num
    }


@bind_context(activity_pre + '/status')
def get_win_people_num(ctx, status, switch):
    """
    7730新签到活动
    """
    config = SignConfig.objects.first()
    if config:
        if switch == SIGN_SWITCH_STATUS.ENTER_SWITCH:
            config.enter_switch = True if str(status) == 'true' else False
            config.save()
        elif switch == SIGN_SWITCH_STATUS.FLOAT_WINDOW_SWITCH:
            config.float_window_switch = True if str(status) == 'true' else False
            config.save()
        elif switch == SIGN_SWITCH_STATUS.SWITCH_STATUS:
            return {
                'enter_switch': config.enter_switch,
                'float_window_switch': config.float_window_switch
            }
        else:
            return {'result': 0}
    else:
        if switch == SIGN_SWITCH_STATUS.ENTER_SWITCH:
            SignConfig.objects.create(enter_switch=True if str(status) == 'true' else False)
        elif switch == SIGN_SWITCH_STATUS.FLOAT_WINDOW_SWITCH:
            SignConfig.objects.create(float_window_switch=True if str(status) == 'true' else False)
        elif switch == SIGN_SWITCH_STATUS.SWITCH_STATUS:
            return {
                'enter_switch': False,
                'float_window_switch': False
            }
        else:
            return {'result': 0}

    return {'result': 1}


@bind_context(activity_pre + '/sign_icon')
def get_sign_icon(ctx, space_icon, routine_icon):
    """新签到活动--icon设置"""
    config = SignConfig.objects.first()
    if routine_icon:
        config.routine_icon = routine_icon
    if space_icon:
        config.space_icon = space_icon
    config.save()
    return {
        'routine_icon': config.routine_icon,
        'space_icon': config.space_icon,
    }
