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

from api.models import Service, Order, User, ORDER_OPERATION_ROLE, ORDER_OPERATION_TYPE, SERVICE_MODE
from datetime import datetime
from django.db.models import Q
import random
from api.manager.order_manager import  _create_order

service_ids = [977]

class Command(BaseCommand):

    def handle(self, *args, **options):
        services = Service.objects.filter(id__in=service_ids)
        q = Q(created_time__gt=datetime(2015,9,1),created_time__lt=datetime(2015,9,30))

        bot = User.objects.get(pk=22)
        for service in services:
            city = service.doctor.hospital.city
            q &= Q(user__userextra__city=city)
            orders = Order.objects.filter(q).values('user').distinct()
            for i in xrange(random.randint(100,200)):
                user = random.choice(orders)
                uid = user['user']
                user = User.objects.get(pk=uid)
                if service.is_multiattribute:
                    item = service.items.first()
                    order = _create_order(service,item.key,0,'',user, service_mode=SERVICE_MODE.SECKILL)
                else:
                    order = _create_order(service,None,0,'',user, service_mode=SERVICE_MODE.SECKILL)
                order.operate(bot.person,ORDER_OPERATION_TYPE.PAY,ORDER_OPERATION_ROLE.SYSTEM)
                order.operate(bot.person, ORDER_OPERATION_TYPE.VALIDATE, ORDER_OPERATION_ROLE.SYSTEM)
                print "{} {} generated".format(order.name,user.username, order.status)