# coding=utf-8
import random
from django.core.management import BaseCommand
from django.db import transaction
from multiprocessing.pool import Pool
from gm_types.gaia import ACTIVITY_TYPE_ENUM
from api.models import SpecialItem
from api.models import SKUPriceRule
from api.models import ServiceItemPrice
from .utils import get_mail


def add_total_num(price_id, specialitem):
    with transaction.atomic():
        price = ServiceItemPrice.objects.select_for_update().get(id=price_id)
        if specialitem.doctorseckillapply_id:
            total_num = specialitem.doctorseckillapply.stock
        else:
            total_num = price.sale_limit
        total_num_fake = round(total_num * random.randint(110, 150) * 0.01)
        ServiceItemPrice.objects.filter(id=price_id).update(total_num=total_num,
                                                            total_num_fake=total_num_fake)


class Command(BaseCommand):
    """
    处理秒杀美购总数量
    python manage.py insert_20170515_serviceitemprice_total_num
    """

    def handle(self, *args, **options):
        error_message = ''
        specialitems = SpecialItem.objects.filter(serviceitem__isnull=False)
        bgn = 0
        step = 1000
        cnt = specialitems.count()
        p = Pool(processes=4)
        while bgn <= cnt:
            for specialitem in specialitems[bgn: bgn+step].iterator():
                try:
                    rule = SKUPriceRule.objects.get(activity_id=specialitem.special_id,
                                                    activity_type=ACTIVITY_TYPE_ENUM.SECKILL if specialitem.special.is_seckill else ACTIVITY_TYPE_ENUM.SPECIAL,
                                                    )
                    price_id = ServiceItemPrice.objects.filter(service_item_id=specialitem.serviceitem_id,
                                                               selling_rule_id=rule.id).first().id
                    res = p.apply_async(add_total_num, args=(price_id, specialitem))
                    res.get()
                    print price_id
                except Exception as e:
                    message = '{}:{}'.format(specialitem.id, e.message)
                    print message
                    error_message += message + '\n'
                    continue
            bgn += step
        p.close()
        p.join()
        get_mail('serviceitemprice_total_num_error.txt', '处理秒杀美购总数量错误信息',
                 ['chenfeifei@gmei.com'], error_message).send()
        print 'DONE!'
