# coding=utf-8
from django.core.management import BaseCommand
from django.db import connection

from api.models import Order, CouponInfo
from pay.models import ServiceSnapshot
from api.tool.service_tool import get_serviceitem_by_option_id

import json


class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        import math

        d = ServiceSnapshot.objects.filter(coupon_info_id__isnull=False, coupon_gengmei_percent__isnull=True) \
            .values_list('id', 'coupon_value')

        for item in d:
            id = item[0]
            coupon_deduction = item[1]

            if coupon_deduction is None or coupon_deduction < 0:
                print "coupon_deduction is None or coupon_deduction < 0 ServiceSnapshot_Id: " + str(id)

            gengmei_percent = 100
            assert 0 <= gengmei_percent <= 100
            coupon_gengmei_value = int(math.floor(coupon_deduction * gengmei_percent / 100.00))
            coupon_doctor_value = coupon_deduction - coupon_gengmei_value

            if coupon_gengmei_value < 0 or coupon_doctor_value < 0:
                print "coupon_gengmei_value <0 or coupon_doctor_value <0 ServiceSnapshot_Id: " + str(id)

            # 系统记录中仅仅有一条order_id为6544680941的记录，他的coupon_deduction为-1，这里迁移的时候就去掉了assert
            # assert coupon_gengmei_value >= 0
            # assert coupon_doctor_value >= 0

            update_dict = {'coupon_gengmei_percent': gengmei_percent,
                           'coupon_gengmei_value': coupon_gengmei_value,
                           'coupon_doctor_value': coupon_doctor_value}

            if update_dict:
                count = ServiceSnapshot.objects.filter(id=id).update(**update_dict)
                if count > 0:
                    print "update ServiceSnapshot id: " + str(id)

        print "success!"
