# coding=utf-8
# create by oldman at 2018/1/10
from datetime import datetime, timedelta
from gm_types.error import ERROR
from django.conf import settings
from hippo.models import Merchant, gen
from hippo.models import UserBrowsing, UserBrowsingDetail, MerchantDailyConv, MerchantPvStat, MerchantUvStat
from hippo.tool.user_tool import get_doctor_from_context
from rpc.decorators import bind_context, bind
from api.tasks.userbrowsing import add_user_browsing
from rpc.cache import browsing_message_cache
from api.tool.datetime_tool import get_timestamp


@bind('doctor/userbrowsing/add')
def user_browsing_add(data_info):
    """
    添加一条用户浏览记录
    :param ctx:
    :param data_info:{'id'：美购或者医生或者机构的id,
    'page_type': USER_BROWSING_TYPE,
    'user_id': 用户ID，
    'browsing_time'：浏览时间('2018-01-01 00:00:00')
    }
    :return:
    """
    add_user_browsing.delay(data_info)


@bind_context('doctor/userbrowsing/list')
def user_browsing_list(ctx, start_time=None, end_time=None, start=0, limit=10):
    """

    :param ctx:
    :param start_time:
    :param end_time:
    :param start:
    :param limit:
    :return:
    """
    doctor = get_doctor_from_context(ctx)
    merchants = Merchant.objects.filter(doctor_id=doctor.id)
    if not merchants.exists():
        raise gen(ERROR.OPERATION_NOT_SUPPORTED)
    merchant = merchants.first()
    base_userbrowsing = MerchantUvStat.objects.filter(merchant_id=merchant.id)
    if start_time:
        base_userbrowsing = base_userbrowsing.filter(last_browsing_time__gte=start_time)
    if end_time:
        base_userbrowsing = base_userbrowsing.filter(last_browsing_time__lte=end_time)

    base_userbrowsing = base_userbrowsing.order_by('-last_browsing_time')
    count = base_userbrowsing.count()
    userbrowsings = base_userbrowsing[start:start + limit]

    return {
        'total': count,
        'res_list': [item.get_data() for item in userbrowsings]
    }


@bind_context('doctor/userbrowsing/detail')
def user_browsing_detail(ctx, userbrowsing_id, start=0, limit=10):
    userbrowsing = MerchantUvStat.objects.get(id=userbrowsing_id)
    start_time = datetime.now() + timedelta(days=-7)
    user_browsing_detail_base = MerchantPvStat.objects.filter(merchant_id=userbrowsing.merchant_id,
                                                              user_id=userbrowsing.user_id,
                                                              browsing_time__gte=start_time
                                                              ).order_by('-browsing_time')

    count = user_browsing_detail_base.count()
    user_browsing_details = user_browsing_detail_base[start: start + limit]
    return {
        'total': count,
        'res_list': [item.get_data() for item in user_browsing_details],
        'user_key': userbrowsing.get_data().get('user_key')
    }


@bind_context('doctor/userbrowsing/send_message')
def user_browsing_detail(ctx, user_id, merchant_id):
    today = datetime.now()
    is_send = MerchantDailyConv.objects.filter(merchant_id=merchant_id, user_id=user_id, date=today).exists()
    if is_send:
        return {'result': 1}
    else:
        torrow = today + timedelta(days=1)
        expire_time = datetime(torrow.year, torrow.month, torrow.day, 0, 0, 0, 0)
        name = str(merchant_id)
        key = 'merchant_message_count'
        count = browsing_message_cache.hget(name, key)
        if count and int(count) >= settings.MERCHANT_DAILY_MESSAGE:
            return {'result': 0}
        else:
            MerchantDailyConv.objects.create(merchant_id=merchant_id, user_id=user_id)
            browsing_message_cache.hincrby(name, key)
            browsing_message_cache.expireat(name, expire_time)
        return {'result': 1}
