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

import datetime
import json

from celery import shared_task
from django.conf import settings

from django_bulk_update.helper import bulk_update

from rpc.cache import shop_cart_cache

from gm_types.push import PUSH_INFO_TYPE

from api.models import Shopcart
from api.models import Person
from api.tool import notification_tool
from api.tool import support_tool

from api.manager import service_info_manager

from api.tasks.push_task import allocate_push_task_multi

slave_db = settings.SLAVE_DB_NAME

shopcart_push_sended_key_format = '{}_push_sended:{}'
shopcart_push_price_cache_key_format = '{}_sku_gm_price:{}'


@shared_task
def send_check_shopcart_tasks():
    now = datetime.datetime.now()
    today_str = now.strftime('%Y%m%d')

    all_person_id = Shopcart.objects.using(settings.SLAVE_DB_NAME).values_list('person_id', flat=True).distinct()

    batch_size = 10

    todo_pids = []
    for pid in all_person_id:
        k = shopcart_push_sended_key_format.format(today_str, pid)
        r = shop_cart_cache.get(k)
        if r is None:
            todo_pids.append(pid)
            if len(todo_pids) >= batch_size:
                check_user_shopcart.delay(todo_pids)
                todo_pids = []

    if todo_pids:
        check_user_shopcart.delay(todo_pids)


@shared_task
def check_user_shopcart(person_ids):
    now = datetime.datetime.now()
    today_str = now.strftime('%Y%m%d')

    scs = list(Shopcart.objects.filter(person_id__in=person_ids, gengmei_price_at_last_push__gt=0))

    price_is_down_person_ids = set()

    update_list = []
    for sc in scs:
        service_item_id = sc.service_item_id
        cache_key = shopcart_push_price_cache_key_format.format(today_str, service_item_id)

        cache_gengmei_price = shop_cart_cache.get(cache_key)
        if cache_gengmei_price is not None:
            gengmei_price = int(cache_gengmei_price)
        else:
            price_info = service_info_manager.get_current_price_info_by_sku_ids(
                [service_item_id]).get(service_item_id, None)
            gengmei_price = price_info['gengmei_price'] if price_info else -1
            shop_cart_cache.setex(cache_key, 4 * 3600, gengmei_price)

        if 0 < gengmei_price < sc.gengmei_price_at_last_push:
            price_is_down_person_ids.add(sc.person_id)
            sc.gengmei_price_at_last_push = gengmei_price
            update_list.append(sc)

    bulk_update(update_list, update_fields=['gengmei_price_at_last_push'], batch_size=100)

    if price_is_down_person_ids:
        user_ids = list(Person.objects.filter(id__in=price_is_down_person_ids).values_list('user_id', flat=True))
        send_shopcart_price_change_push(user_ids)

        for pid in price_is_down_person_ids:
            send_key = shopcart_push_sended_key_format.format(today_str, pid)
            shop_cart_cache.setex(send_key, 24 * 3600, 'true')


@shared_task
def send_shopcart_price_change_push(user_ids):
    print ("send_shopcart_price_change_push:{}".format(user_ids))
    kwargs = {
        'user_id': user_ids,
        'extra': {
            "type": PUSH_INFO_TYPE.GM_PROTOCOL,
            "pushUrl": 'gengmei://shop_cart_list',
        },
        'alert': "您加入购物车内的商品已经降价了，赶快去购买吧~",
        'labels': {'event_type': 'push', 'event': 'product_price_reducing'},
    }

    allocate_push_task_multi(**kwargs)
