# coding=utf-8
import datetime

from django.core.management import BaseCommand
from api.models import (
    Order,
)
from gm_types.gaia import ORDER_STATUS
from api.models.hera import SpecialPool
from rpc.cache import diary_cache
from rpc.context import get_rpc_remote_invoker
from gm_types.poseidon import RecallType


SELL_AMOUNT_STATUS = [ORDER_STATUS.PAID, ORDER_STATUS.USED, ORDER_STATUS.SETTLED]
SPECIAL_POOL_SELL_AMOUNT_KEY = 'diary_topic_detail_special_pool_{}'
rpc_client = get_rpc_remote_invoker()


def get_poseidon_visual_page_params(visual_page_id):
    return rpc_client['poseidon/visual/get_doris_param_by_page_id'](page_id=visual_page_id).unwrap()


def get_service_from_doris(params):
    res = rpc_client['doris/search/spu_sku'](
        device_id='',
        offset=0,
        size=50,
        user_city_tag_id=params.get('user_city_tag_id', -1),
        recall_type=params.get('recall_type'),
        unit_id=params.get('unit_id', None),
        promotion_ids=params.get('promotion_ids', []),
        tag_ids=params.get('tag_ids', []),
        sort_params=params.get('sort_params', {}),
        sort_type=params.get('sort_type'),
        filters=params.get('filters', {})
    ).unwrap()
    return res


def get_visual_page_service_ids(visual_page_id):
    """
        return service_item_ids, service_ids
    """
    if not visual_page_id:
        return []
    params = get_poseidon_visual_page_params(visual_page_id)
    res = get_service_from_doris(params)
    # TODO get service_ids or service_item_ids from res
    recall_type = params.get('recall_type', RecallType.SKU)
    if recall_type == RecallType.SKU:
        return res, []
    elif recall_type == RecallType.SPU:
        return [], res.get('service_ids', [])
    return [], []


def get_sell_amount(visual_page_service_ids=None, visual_page_service_item_ids=None):
    count = 0
    if visual_page_service_item_ids:
        for service_item_id in visual_page_service_item_ids:
            count = count + Order.objects.filter(status__in=SELL_AMOUNT_STATUS, service_item_id=service_item_id).count()
        return count
    elif visual_page_service_ids:
        for service_id in visual_page_service_ids:
            count = count + Order.objects.filter(status__in=SELL_AMOUNT_STATUS, service_id=service_id).count()
        return count
    else:
        return count


def set_visual_page_sell_amount(visual_page_id, sell_amount):
    if not visual_page_id:
        return
    key = SPECIAL_POOL_SELL_AMOUNT_KEY.format(visual_page_id)
    diary_cache.set(key, sell_amount)


class Command(BaseCommand):

    def handle(self, *args, **options):
        print('start update special pool commodity count record {}'.format(datetime))
        all_pools = SpecialPool.objects.filter(is_online=True)
        visual_page_ids = [item.visual_page_id for item in all_pools]
        for visual_page_id in visual_page_ids:
            print('set special pool commodity count record visual_page_id is {} at {}'.format(visual_page_id, datetime))
            visual_page_service_item_ids, visual_page_service_ids = get_visual_page_service_ids(visual_page_id)
            if visual_page_service_ids:
                visual_page_service_sell_amount = get_sell_amount(visual_page_service_ids=visual_page_service_ids)
            elif visual_page_service_item_ids:
                visual_page_service_sell_amount = get_sell_amount(
                    visual_page_service_item_ids=visual_page_service_item_ids)
            else:
                visual_page_service_sell_amount = 0
            set_visual_page_sell_amount(visual_page_id, visual_page_service_sell_amount)
        print('end update special pool commodity count record {}'.format(datetime))
