# -*- 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,info_logger

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
from api.manager.service_info_manager import service_feed_infos_by_special


@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

    sku_ids = []
    if support_flag_ship:
        sku_info = service.get_city_sku_detail_info(coupon_info)
        for item in sku_info:
            sku_ids.extend([sku['service_item_id'] for sku in item['normal_sku_list']])
    else:
        sku_info = service.get_sku_detail_info(coupon_info)
        sku_ids = [sku['service_item_id'] for sku in sku_info['normal_sku_list']]

    if not sku_info:
        return gen(CODES.SKU_NOT_FOUND)

    sku_objs = ServiceItem.objects.filter(parent_id=0, id__in=sku_ids)
    sku_obj_dict = {item.id: item for item in sku_objs}

    if isinstance(sku_info, list):
        for sku in sku_info:
            for item in sku.get('normal_sku_list'):
                obj = sku_obj_dict.get(item.get('service_item_id'))
                item['sku_description'] = obj.sku_description if obj else ""
            for item in sku.get('groupbuy_sku_list'):
                obj = sku_obj_dict.get(item.get('service_item_id'))
                item['sku_description'] = obj.sku_description if obj else ""
    elif isinstance(sku_info, dict):
        for item in sku_info.get('normal_sku_list'):
            obj = sku_obj_dict.get(item.get('service_item_id'))
            item['sku_description'] = obj.sku_description if obj else ""
        for item in sku_info.get('groupbuy_sku_list'):
            obj = sku_obj_dict.get(item.get('service_item_id'))
            item['sku_description'] = obj.sku_description if obj else ""

    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']

            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)

    service_info = {
        'is_stage': service.can_stage
    }

    return {
        'sku_info': sku_info,
        'service_info': service_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


@bind('api/service/by_special')
def gets_service_infos_by_special(ctx, special_ids):
    return service_feed_infos_by_special(special_ids)


@bind_context('api/service/sku_coupon_info')
def get_service_sku_coupon_info(ctx, service_id, service_item_id,coupon_info_id=None, support_flag_ship=True):
    """
    获取美购详情页sku列表计算券信息
    :param ctx:
    :param service_id:
    :param service_item_id:
    :param coupon_info_id:
    :param support_flag_ship:
    :return:
    """
    try:
        user = get_user_from_context(ctx)
        print(service_id,service_item_id)
        try:
            service = Service.objects.get(id=service_id)
        except Exception as ex:
            info_logger.info(ex)
            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)
        info_logger.info('test: sku_info: %s' % sku_info)

        if not sku_info:
            return gen(CODES.SKU_NOT_FOUND)

        # if support_flag_ship:
        #     info_logger.info('test: per one support_flag_ship')
        #     item_sku_info = {}
        #     for city_sku in sku_info:  # todo 考虑是 旗舰店商品 这层才是有意义
        #         info_logger.info('test2: city_sku %s' % city_sku)
        #         normal_sku_list = city_sku.get('normal_sku_list', [])
        #         groupbuy_sku_list = city_sku.get('groupbuy_sku_list', [])
        #         for normal_sku_info in normal_sku_list:
        #             if normal_sku_info['service_item_id'] == service_item_id:
        #                 item_sku_info = normal_sku_info
        #                 break
        #         info_logger.info('test2: item_sku_info %s' % item_sku_info)
        #         if item_sku_info:
        #             break
        #         else:
        #             for groupbuy_sku_info in groupbuy_sku_list:
        #                 if groupbuy_sku_info['service_item_id'] == service_item_id:
        #                     item_sku_info = groupbuy_sku_info
        #                     break
        #             if item_sku_info:
        #                 break

        #     if not item_sku_info:
        #         return {}

        #     fill_discount_price(item_sku_info, user=user)
        #     fill_discount_price(item_sku_info.get('multibuy'), user=user)
        #     info_logger.info('test: get_service_sku_coupon_info after %s' % item_sku_info)

        # else:
        info_logger.info('test: per noe not support_flag_ship')
        item_sku_info = {}
        normal_sku_list = sku_info.get('normal_sku_list', [])
        groupbuy_sku_list = sku_info.get('groupbuy_sku_list', [])

        for normal_sku_info in normal_sku_list:
            if normal_sku_info['service_item_id'] == service_item_id:
                item_sku_info = normal_sku_info
                break

        if not item_sku_info:
            for groupbuy_sku_info in groupbuy_sku_list:
                if groupbuy_sku_info['service_item_id'] == service_item_id:
                    item_sku_info = groupbuy_sku_info
                    break

        if not item_sku_info:
            return {}
        
        fill_discount_res = fill_discount_price(item_sku_info, user=user)
        info_logger.info('test: not support_flag_ship after %s' % item_sku_info)
        info_logger.info('test: item_sku_info %s' % fill_discount_res)

        response_data = {
            "pre_payment_price": item_sku_info["pre_payment_price"],
            "discount_price": fill_discount_res['discount_price'],
            "pre_coupon_deduction": fill_discount_res['pre_coupon_deduction'],
            "last_coupon_deduction": fill_discount_res['last_coupon_deduction'],
            "can_discount": fill_discount_res['can_discount'],
            "service_item_id":item_sku_info['service_item_id'],
            "service_id":item_sku_info['service_id'],
        }

        return response_data
    except Exception as ex:
        info_logger.info('ex %s' % ex)
        return {}
