# -*- coding:utf-8 -*-
'''
用于获取美购的分享数据
'''

from gm_types.gaia import DISTRIBUTE_TYPES
from rpc.decorators import bind, bind_context
from api.util import goods_util
from api.tool.user_tool import get_user_from_context
from rpc.tool.log_tool import info_logger, price_logger

@bind_context('api/spu/share_data')
def get_spu_share_data(ctx, spu_id, support_groupbuy=True):
    '''
    获取spu的分享数据
    '''
    try:
        spu_obj = goods_util.get_spu_obj_by_id(spu_id)
    except Exception as e:
        raise e
    user = get_user_from_context(ctx)
    base_share_data = spu_obj.get_base_share_data()
    price_info = spu_obj.get_top_price_show(support_groupbuy)
    lowest_price = (str(price_info['gengmei_price']).split('-')[0]).strip()
    base_share_data['show_price'] = lowest_price
    base_share_data['spu_id'] = spu_obj.id
    info_logger.info('api/spu/share_data user:{} spu_name:{}'.format(user, base_share_data['spu_name']))
    if user:
        base_share_data['distribute_info'] = {
            'distribute_id': str(user.id),
            'distribute_type': DISTRIBUTE_TYPES.USER
        }
    return base_share_data


@bind_context('api/sku/share_data')
def get_sku_share_data(ctx, sku_id, support_groupbuy=True):
    '''
    获取sku的分享数据
    '''
    try:
        sku_obj = goods_util.get_sku_obj_by_id(sku_id)
    except Exception as e:
        raise e

    try:
        spu_obj = goods_util.get_spu_obj_by_id(sku_obj.service_id)
    except Exception as e:
        raise e
    user = get_user_from_context(ctx)
    sku_price = sku_obj.get_show_price(support_groupbuy) or {}
    share_data = spu_obj.get_base_share_data()
    share_data['sku_name'] = sku_obj.items_name[0] if sku_obj.items_name else ""
    share_data['show_price'] = sku_price.get('gengmei_price') or 0
    share_data['sku_id'] = sku_obj.id
    share_data['spu_id'] = spu_obj.id
    info_logger.info('api/spu/share_data user:{} sku_name:{}'.format(user, share_data['sku_name']))
    if user:
        share_data['distribute_info'] = {
            'distribute_id': str(user.id),
            'distribute_type': DISTRIBUTE_TYPES.USER
        }
    return share_data

