# coding=utf-8
from api.models.hot import Hot, City, Region, HotRegion, HotCity
from rpc.decorators import (
    bind, bind_context
)
from django.db.models import Q
from gm_types.gaia import SLIDE_USER_TYPE, SLIDE_PAYMENT_TYPE, REQUEST_SOURCE
from django.db import transaction
from datetime import datetime
from rpc.tool.dict_mixin import to_dict
from api.models import City, Province
from api.tool.user_tool import get_user_and_payment_info, get_user_from_context


@bind('api/search/hot/get_hot_search')
def get_hot_search(srch_key, srch_val, begin_time_min, begin_time_max,
                   offline_time_min, offline_time_max, is_online,
                   region_id, city_id, q='', page=1, size=30,):

    page = int(page)
    size = int(size)

    q = Q()
    if srch_key and srch_val:
        if srch_key == 'id':
            q &= Q(id=srch_val)
        else:
            q &= Q(name=srch_val)
    if begin_time_min:
        q &= Q(begin_time__gte=begin_time_min)
    if begin_time_max:
        q &= Q(begin_time__lte=begin_time_max)
    if offline_time_min:
        q &= Q(offline_time__gte=offline_time_min)
    if offline_time_max:
        q &= Q(offline_time__lte=offline_time_max)
    if is_online:
        q &= Q(is_online=is_online)
    if region_id:
        q &= Q(region__in=region_id)
    if city_id:
        q &= Q(city__in=city_id)

    res = Hot.objects.select_related().filter(q)

    total_count = res.count()
    start_pos = (page - 1) * size
    start_pos = start_pos if start_pos >= 0 else 0

    hot_list = [{
        'id': i.id,
        'name': i.name,
        'begin_time': i.begin_time.strftime('%Y-%m-%d %H:%M:%S') if i.begin_time else '',
        'offline_time': i.offline_time.strftime('%Y-%m-%d %H:%M:%S') if i.offline_time else '',
        'sort_num': i.sort_num,
        'is_online': i.is_online
    } for i in res[start_pos: start_pos + size]
    ]

    return {'total': total_count, 'hot_list': hot_list, 'page': page, 'size': size}


@bind('api/search/hot/insert_hot_list')
@transaction.atomic
def insert_hot_list(id, name, pic, sort_num, channel, region_list=None, city_list=None,
                    user_type=None, pay_type=None, is_online=None, topic=None, new_topic=None,
                    begin_time=None, offline_time=None):

    if begin_time:
        begin_time = datetime.strptime(begin_time, '%Y-%m-%d %H:%M:%S')
    if offline_time:
        offline_time = datetime.strptime(offline_time, '%Y-%m-%d %H:%M:%S')
    if is_online == 'false':
        is_online = False
    if is_online == 'true':
        is_online = True

    hot = Hot.objects.filter(id=id).first()
    if hot:
        hot.name = name
        hot.pic = pic
        hot.sort_num = sort_num
        hot.channel = channel
        hot.user_type = user_type
        hot.pay_type = pay_type
        hot.is_online = is_online
        hot.topic = topic
        hot.new_topic = new_topic
        hot.begin_time = begin_time
        hot.offline_time = offline_time
        hot.save()

        old_region = set(hot.region.all())
        new_region = set(Region.objects.filter(id__in=region_list))
        HotRegion.objects.filter(hot=hot, region__in=(old_region-new_region)).delete()
        if new_region - old_region:
            HotRegion.objects.bulk_create([HotRegion(hot=hot, region=region) for region in (new_region-old_region)])
        old_city = set(hot.city.all())
        new_city = set(City.objects.filter(id__in=city_list))
        HotCity.objects.filter(hot=hot, city__in=(old_city-new_city)).delete()

        if new_city - old_city:
            HotCity.objects.bulk_create([HotCity(hot=hot, city=city) for city in (new_city - old_city)])
    else:
        hot = Hot.objects.create(name=name, pic=pic, sort_num=sort_num, channel=channel, user_type=user_type,
                                 pay_type=pay_type, is_online=is_online, topic=topic, new_topic=new_topic,
                                 begin_time=begin_time, offline_time=offline_time)

        region_obj_list = Region.objects.filter(id__in=region_list).all()
        if region_obj_list:
            HotRegion.objects.bulk_create([HotRegion(hot=hot, region=region) for region in region_obj_list])
        city_obj_list = City.objects.filter(id__in=city_list).all()
        if city_obj_list:
            HotCity.objects.bulk_create([HotCity(hot=hot, city=city) for city in city_obj_list])


@bind_context('api/search/app_hot/get_hot_search')
def app_get_got_search(ctx, current_city_id, platform=None, device_id=None):

    now = datetime.now()
    user = get_user_from_context(ctx)
    user_info = get_user_and_payment_info(user, platform, device_id)
    ### 获取新老用户信息
    user_type_choices = [SLIDE_USER_TYPE.ALL_USER]
    user_type_choices.append(SLIDE_USER_TYPE.NEW_USER if user_info.get('is_new_user') else SLIDE_USER_TYPE.OLD_USER)
    ## 获取是否支付信息
    payment_choices = [SLIDE_PAYMENT_TYPE.ALL_PAYMENT]
    payment_choices.append(SLIDE_PAYMENT_TYPE.HAVE_PAYMENT if user_info.get('have_payment') else SLIDE_PAYMENT_TYPE.NO_PAYMENT)

    q = Q(is_online=True, begin_time__lte=now, offline_time__gt=now)
    if current_city_id:
        province = City.objects.filter(id=current_city_id).values_list('province')
        current_region_id = Province.objects.filter(id=province).values_list('region')
        q &= (Q(city=current_city_id, user_type__in=user_type_choices, pay_type__in=payment_choices) |
              Q(region=current_region_id, user_type__in=user_type_choices, pay_type__in=payment_choices) |
              Q(city=None, region=None,  user_type__in=user_type_choices, pay_type__in=payment_choices))
    else:
        q &= Q(city=None, region=None, user_type__in=user_type_choices, pay_type__in=payment_choices)

    res = Hot.objects.filter(q).order_by('sort_num').values_list('name', 'pic', 'topic', 'new_topic', 'sort_num')
    res = res.distinct()
    hot_list = []
    for i in res[:14]:
        if i[2]:
            hot_list.append({
                "name": i[0],
                "pic": i[1],
                "gm_url": i[2],
                'sort_num': i[4]
            })
        elif not i[2] and i[3]:
            hot_list.append({
                "name": i[0],
                "pic": i[1],
                "gm_url": i[3],
                'sort_num': i[4]
            })
        elif not i[2] and not i[3]:
            hot_list.append({
                "name": i[0],
                "pic": i[1],
                "gm_url": None,
                'sort_num': i[4]
            })

    return hot_list


@bind('api/search/hot/new_or_old_user')
def new_or_old_user():
    user_list = []
    for id, name in SLIDE_USER_TYPE:
        user_list.append({
            'id': id,
            'name': name
        })
    return user_list


@bind('api/search/hot/whether_to_pay')
def whether_to_pay():
    whether_list = []
    for id, type in SLIDE_PAYMENT_TYPE:
        whether_list.append({
            'id': id,
            'type': type
        })
    return whether_list


@bind('api/search/hot/show_channels')
def show_channels():
    channels_list = []
    for id, channels in REQUEST_SOURCE:
        channels_list.append({
            'id': id,
            'channels': channels
        })
    return channels_list


@bind('api/search/hot/details')
def get_hot_details(id):

    res = Hot.objects.filter(id=id).first()
    if not res:
        return {}
    data = to_dict(res)
    return data

