#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import multiprocessing

from django.core.management import BaseCommand
from gm_types.gaia import ORDER_STATUS

from talos.models.diary import Diary
from talos.services.order import OrderService


def _get_time(diary):

    order = OrderService.get_order_from_order_id(diary.order_id)
    if order and order.status == ORDER_STATUS.USED:
        times = datetime.datetime.strptime(order.last_modified, "%Y-%m-%d %H:%M:%S")
        return times

    return diary.created_time


def _async_func(diary):
    diary.operation_time = _get_time(diary)
    diary.save()


class Command(BaseCommand):
    """
        针对清洗 设置手术时间为NULL 日记本

        清洗规则: 美购日记本,治疗时间返订单验证时间; 非美购日记本,治疗时间返回创建日记本的时间
    """

    def handle(self, *args, **kwargs):
        print "start work"

        pool = multiprocessing.Pool(processes=4)
        diaries = Diary.objects.filter(is_online=True, operation_time=None).iterator()

        for diary in diaries:
            pool.apply_async(_async_func, (diary,))
        pool.close()
        pool.join()

        print 'end work'
