# 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, User, UserExtra
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
from pay.tasks.groupbuy_msg_tool import groupbuy_msg_list


@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
                if price_info.selling_rule:
                    activity_id = price_info.selling_rule.activity_id
                else:
                    activity_id = 0
            if price_info.is_default_price is True:
                default_price = price_info.gengmei_price
        if len(price_objects) == 2:
            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,
    }


@bind_context('api/groupbuy/msgs')
def gets_groupbuy_msg_list_by_special_id(ctx, special_id, offset=0, count=100):
    """ 获取指定活动下 拼团轮播消息 """
    msgs, all_user_ids = groupbuy_msg_list(activity_id=special_id, offset=offset, count=count)
    
    users = User.objects.filter(id__in=all_user_ids)
    user_extras = UserExtra.objects.filter(user_id__in=all_user_ids)
    users_dict = {obj.id: obj for obj in users}
    user_extras_dict = {obj.user_id : obj for obj in user_extras}

    def replace_lastname(name):
        return name[0] + '***' + name[-1]

    def res_msg_body(obj):
        default_portrait = 'http://pic.igengmei.com/user/icon@2x.png'
        creator_portrait = user_extras_dict.get(obj.get('creator_user_id')).portrait
        creator_name = users_dict.get(obj.get('creator_user_id')).last_name
        user_name = users_dict.get(obj.get('user_id')).last_name
        user_portrait = user_extras_dict.get(obj.get('user_id')).portrait
        return [
            {
                'user_name': replace_lastname(creator_name),
                'user_portrait': creator_portrait + '-w' if creator_portrait else default_portrait + '-w',
                'message': obj.get('message'),
            },
            {
                'user_name': replace_lastname(user_name),
                'user_portrait': user_portrait + '-w' if user_portrait else default_portrait + '-w',
                'message': obj.get('message'),
            }
        ]

    res = []
    [res.extend(res_msg_body(obj)) for obj in msgs]

    return res
