# coding: utf-8

from django.db.models import Q
from gm_types.error import ERROR

from api.manager.groupbuy_manager import get_groupbuy_team_info_by_hash_ids
from api.models import ServiceItem, ServiceItemPrice,GroupBuyTeamOrder
from api.tool.image_utils import get_full_path
from rpc.decorators import bind,bind_context
from rpc.tool.error_code import gen
from rpc.tool.log_tool import info_logger
from gm_types.gaia import GROUPBUY_STATUS,ACTIVITY_TYPE_ENUM
from api.tool.user_tool import get_user_from_context


@bind_context('api/groupbuy/share/detail')
def get_groupbuy_share_info_by_hash_id(ctx,hash_id, need_service=True):
    """通过hash_id获取拼团小组信息"""
    

    service_data = {}
    groupbuy_info = get_groupbuy_team_info_by_hash_ids(hash_ids=[hash_id], need_user_info=True)

    if not groupbuy_info or len(groupbuy_info) != 1:
        gen(ERROR.GROUPBUY_NOT_EXISTS)
    groupbuy_info = groupbuy_info[hash_id]

    user =get_user_from_context(ctx)

    user_id=0
    if user:
        user_id=user.id

    info_logger.info("团购订单详情页用户")
    info_logger.info(user)

    try:
        info_logger.info("团购分享文案")
        info_logger.info(groupbuy_info)

        create_user_id=groupbuy_info.get("creator_user_id")
        groupbuy_team_id=groupbuy_info.get("id")

        #是否是第一视角
        groupbuyteam_order=GroupBuyTeamOrder.objects.get(groupbuy_team_id=groupbuy_team_id,user_id=create_user_id)


        groupbuy_info.update({"view_angle":"","order_id":groupbuyteam_order.order_id})

        info_logger.info(groupbuy_info)
    except Exception as e:
        info_logger.info(e)

    activity_id = None
    if need_service:
        service_item = ServiceItem.objects.only('id', 'service').prefetch_related('service').\
                        get(id=groupbuy_info['service_item_id'])

        info_logger.info("美购-------")
        #service_flag

        price_objects = ServiceItemPrice.objects.only('is_default_price', 'gengmei_price', 'selling_rule').filter(
            Q(is_enable=True, is_default_price=True, service_item_id=groupbuy_info['service_item_id']) |
            Q(id=groupbuy_info['price_id'])
        ).prefetch_related('selling_rule')

        assert len(price_objects) == 2
        default_price = groupbuy_price = None
        for price_info in price_objects:
            if price_info.id == groupbuy_info['price_id']:
                groupbuy_price = price_info.gengmei_price
                activity_id = price_info.selling_rule.activity_id
            elif price_info.is_default_price is True:
                default_price = price_info.gengmei_price

        assert default_price is not None and groupbuy_price is not None
        assert activity_id is not None

        try:
            selected_item_name = ''.join(service_item.items_name)
        except:
            selected_item_name = ''

        service_item_id=groupbuy_info['service_item_id']
        #获取单买价格
        price_list=ServiceItemPrice.objects.filter(service_item_id=service_item_id,is_enable=True).exclude(selling_rule__activity_type__in=[ACTIVITY_TYPE_ENUM.GROUPBUY,ACTIVITY_TYPE_ENUM.MOREBUY])
        danmai_price=min(price_list,key=lambda x:x.gengmei_price)

        #{groupbuy_leave}个名额！，立省{save_money}
        service_data = {
            "service_id": service_item.service_id,
            "selected_item_name": selected_item_name,
            "name": service_item.service.short_description,
            "image_header": get_full_path(service_item.service.image_header, '-half'),
            "groupbuy_price": groupbuy_price,
            "danmai_price":danmai_price.gengmei_price,
            "default_price": default_price,
            "tag_name":service_item.service.show_tags,
            "short_description": service_item.service.short_description,
        }

        info_logger.info("分享service_data----")
        info_logger.info(service_data)
    return {
        "groupbuy_info": groupbuy_info,
        "service_data": service_data,
        "user_id":user_id,
        "activity_id": activity_id,
    }
