# coding=utf-8

import json
import datetime

from django.db import transaction
from django.db.models import F
from gm_types.gaia import COUPON_TYPES

from api.models import CouponInfo
from api.models import SpecialSeckillService, ServiceItem
from api.tool.log_tool import logging_exception


def increase_inventory(order):
    '''
    增加库存
    根据属性区分,秒杀商品还是普通商品分别采取不同策略
    '''
    try:
        if order.service_item_id is not None:
            # 库存转移到SKU之后，新下的单都有service_item_id，旧的单也会之后将service_item_id进行赋值
            with transaction.atomic():
                try:
                    service_item_obj = ServiceItem.objects.get(id=order.service_item_id)
                    if order.service_item_price_id is not None:
                        service_item_obj.increase_price_sale_limit(order.service_item_price_id)

                    service_item_obj.increase_stock()
                except:
                    logging_exception()
    except:
        logging_exception()


def decrease_inventory(order):
    try:
        if order.service_item_id is not None:
            # 库存转移到SKU之后，新下的单都有service_item_id，旧的单也会之后将service_item_id进行赋值
            with transaction.atomic():
                try:
                    service_item_obj = ServiceItem.objects.get(id=order.service_item_id)
                    if order.service_item_price_id is not None:
                        service_item_obj.decrease_price_sale_limit(order.service_item_price_id)

                    service_item_obj.decrease_stock()
                except:
                    logging_exception()
    except:
        logging_exception()


def _convert_to_float(raw_number):
    if not raw_number:
        return 0
    return float(raw_number)


def refund_value_info(refund_order):
    estimated_fee = refund_order.estimated_fee
    real_fee = refund_order.real_fee
    return {
        'estimated_fee': estimated_fee,
        'real_fee': real_fee,
        'coupon_value': None,  # 不再使用
    }
