# coding=utf-8
import math
from django.core.management import BaseCommand
from .utils import get_mail
from api.models import DoctorSeckillApply
from gm_types.gaia import DOCTOR_SECKILL_APPLY_STATUS


class Command(BaseCommand):
    """
    处理活动报名自营抽成
    python manage.py insert_20170601_doctorseckillapply_self_support_discount
    """

    def handle(self, *args, **options):
        error_message = ''
        doctorseckillapplys = DoctorSeckillApply.objects.filter(status=DOCTOR_SECKILL_APPLY_STATUS.PASS)
        for apply in doctorseckillapplys.iterator():
            try:
                price_info = apply.service_item.get_default_price_info()
                self_support_discount_rate = price_info['self_support_discount'] * 1.00 / price_info['gengmei_price']
                apply.self_support_discount = math.ceil(apply.seckill_price * self_support_discount_rate)
                apply.save()
                print apply.id
            except Exception as e:
                message = '{}:{}'.format(apply.id, e.message)
                print message
                error_message += message + '\n'
                continue
        get_mail('doctorseckillapply_self_support_discount_error.txt', '处理活动报名自营抽成错误信息',
                 ['chenfeifei@gmei.com'], error_message).send()
        print 'DONE!'
