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

from django.db.models import Q
from gm_types.gaia import TAG_TYPE, DOCTOR_TYPE, ACTIVITY_TYPE_ENUM, SERVICE_SELL_TYPE

from api.models import (
    Service, CouponInfo, ServiceItem
)

from api.tool.user_tool import get_user_from_context
from api.tool.log_tool import logging_exception

from rpc.decorators import bind, cache_page, bind_context
from rpc.tool.error_code import gen, CODES
from .service_utils import get_service_header_pic_info, get_show_special_info, calcate_sku_discount_price, fill_discount_price


@bind_context('api/service/service_detail')
def get_base_service_detail(ctx, service_id, coupon_info_id=None):
    '''
    since: 7.16  2019/9/20
    '''
    user = get_user_from_context(ctx)
    try:
        service = Service.objects.get(id=service_id)
    except:
        return gen(CODES.SERVICE_NOT_EXSIT)

    non_flagship_spu = support_groupbuy = service.service_type != SERVICE_SELL_TYPE.FLAGSHIP_STORE_SERVICE
    data = service.get_base_service_detail(user, support_groupbuy=support_groupbuy, support_seckill=non_flagship_spu, default_select=False)

    if not non_flagship_spu:
        # 旗舰店美购不展示秒杀样式, 不展示大促样式
        data['is_seckill'] = False
        data['promotion_image'] = ''

    special_info = get_show_special_info(service)
    data.update(special_info)
    data['header_pic'] = get_service_header_pic_info(service)[:6]
    return data


@bind_context('api/service/sku_info')
def get_service_sku_info(ctx, service_id, coupon_info_id=None, support_flag_ship=True):
    '''
    获取美购详情页sku列表数据
    :param ctx:
    :param service_id:
    :param coupon_info_id:
    :return:
    '''
    user = get_user_from_context(ctx)
    try:
        service = Service.objects.get(id=service_id)
    except:
        return gen(CODES.SERVICE_NOT_EXSIT)

    coupon_info = None
    try:
        if coupon_info_id:
            coupon_info = CouponInfo.objects.get(id=coupon_info_id)
            if coupon_info.user != user:
                coupon_info = None
    except:
        pass

    if support_flag_ship:
        sku_info = service.get_city_sku_detail_info(coupon_info)
    else:
        sku_info = service.get_sku_detail_info(coupon_info)

    if not sku_info:
        return gen(CODES.SKU_NOT_FOUND)

    flagship_spu = service.service_type == SERVICE_SELL_TYPE.FLAGSHIP_STORE_SERVICE
    if flagship_spu:
        if support_flag_ship:
            # 旗舰店美购不展示秒杀样式, 不展示大促样式
            for city_sku in sku_info:
                for nsk in city_sku.get('normal_sku_list') or []:
                    nsk['is_seckill'] = False
                    nsk['promotion_image'] = ''
        else:
            ### 旧版本兼容新数据
            sku_info['groupbuy_sku_list'] = []
            normal_sku_list = sku_info['normal_sku_list']
            sku_ids = [sku['service_item_id'] for sku in normal_sku_list]
            sku_objs = ServiceItem.objects.filter(parent_id=0, id__in=sku_ids)
            id2obj_sku_map = {s.id: s for s in sku_objs}
            for s in normal_sku_list:
                sobj = id2obj_sku_map.get(s['service_item_id'])
                if sobj:
                    s['name'] = ((sobj.city_name and sobj.city_name + '@') or '') + sobj.sku_name

    if support_flag_ship:
        for city_sku in sku_info:
            calcate_sku_discount_price(city_sku, user=user)
    else:
        calcate_sku_discount_price(sku_info, user=user)

    return {
        'sku_info': sku_info
    }


@bind_context('api/service/sku_detail')
def get_service_sku_detail(ctx, service_id, service_item_id, coupon_info_id=None):
    '''
    获取单个sku展示
    :param ctx:
    :param service_id:
    :param service_item_id:
    :return:
    '''
    result = {}
    if not all([service_id, service_item_id]):
        return result

    user = get_user_from_context(ctx)
    coupon_info = None
    try:
        if coupon_info_id:
            coupon_info = CouponInfo.objects.get(id=coupon_info_id)
            if coupon_info.user != user:
                coupon_info = None
    except:
        pass

    try:
        si_obj = ServiceItem.objects.get(id=int(service_item_id))
        if si_obj.service_id != int(service_id):
            return result

        sids = [service_item_id]
        normal_price = Service.get_current_price_info_by_service_item_ids(sids)[service_item_id]
        if not normal_price:
            return result

        groupbuy_price = Service.get_current_groupbuy_price_info_by_service_item_ids(sids)[service_item_id]
        multibuy_price = Service.get_current_multibuy_price_info_by_service_item_ids(sids).get(service_item_id)
        normal_price = ServiceItem._format_normal_sku_price_info(normal_price, si_obj)
        groupbuy_price = ServiceItem._format_groupbuy_sku_price_info(groupbuy_price, si_obj)
        multibuy_price = ServiceItem._format_multibuy_sku_price_info(multibuy_price, si_obj)

        price_keys = ['normal_price', 'groupbuy_price', 'multibuy_price']
        compare_prices = {
            'groupbuy_price': groupbuy_price,
            'multibuy_price': multibuy_price,
            'normal_price': normal_price,
        }
        exist_prices = {}
        exist_price_keys = []
        for k in price_keys:
            v = compare_prices.get(k)
            if v:
                exist_prices[k] = v
                exist_price_keys.append(k)

        selected_price = 'normal_price'
        if exist_prices:
            def compare_func(key):
                price_info = exist_prices[key]
                if price_info.get('is_groupbuy'):
                    return price_info['groupbuy_price']
                elif price_info.get('is_multibuy'):
                    return price_info['single_price']
                else:
                    return price_info['gengmei_price']
            selected_price = min(exist_price_keys, key=compare_func)

        fill_discount_price(normal_price, user=user)
        Service.fill_sku_info_with_coupon_info([normal_price], coupon_info)
        result['normal_price'] = normal_price
        if selected_price != 'normal_price':
            normal_price['is_seckill'] = False
            normal_price['promotion_image'] = ''

            if selected_price == 'groupbuy_price':
                fill_discount_price(groupbuy_price, is_groupbuy=True, user=user)
                result['groupbuy'] = groupbuy_price
            elif selected_price == 'multibuy_price':
                fill_discount_price(multibuy_price, user=user)
                save_money = max(0, multibuy_price['multibuy_count'] * normal_price['gengmei_price'] -
                    multibuy_price['gengmei_price'])
                multibuy_price['save_money'] = save_money
                result['multibuy'] = multibuy_price

        return result
    except:
        logging_exception()
        return result
