# coding=utf-8

import tablib
from datetime import datetime
from django.core.management.base import BaseCommand
from django.db import transaction

from point.models import Points
from api.models import Order, Person
from .utils import get_mail
from gm_types.gaia import POINTS_TYPE, POINTS_OPERATION

change_time = datetime.now().strftime('%Y%m%d%H%M%S')


def format_id(order_id):
    return u' {}'.format(order_id)


class Command(BaseCommand):
    def handle(self, *args, **options):
        not_do = tablib.Dataset()
        not_do.headers = [
            u'订单ID', u'应扣美分', u'用户ID', u'补偿美分',u'用户美分'
        ]
        do_order = tablib.Dataset()
        do_order.headers = [
            u'订单ID', u'应扣美分', u'用户ID',
        ]

        # 问题数据从2017-11 末上线
        for i in Points.objects.filter(operation='remove', reason='5', number=30, add_time__gt='2017-11-01'):
            try:
                with transaction.atomic():
                    order_point = int(Order.objects.get(id=i.link_order_id).points_deduction * 100)
                    person = Person.objects.select_for_update().get(user_id=i.user_id)
                    if person.points + 30 - order_point >= 0:
                        person.points = person.points + 30 - order_point
                        person.save(update_fields=['points'])
                        Points.objects.select_for_update().filter(id=i.id).update(number=order_point)
                        do_order.append((
                            format_id(i.link_order_id),
                            order_point,
                            i.user_id,
                        ))
                    else:
                        Points.objects.select_for_update().filter(id=i.id).update(number=order_point)
                        fix_point = -(person.points + 30 - order_point)
                        Points.objects.create(user_id=i.user_id, operation=POINTS_OPERATION.ADD,
                                              reason=POINTS_TYPE.SYSTEM_ADD, number=fix_point)
                        person.points = 0
                        person.save(update_fields=['points'])
                        x = (
                            format_id(i.link_order_id),
                            order_point,
                            i.user_id,
                            fix_point,
                            person.points,
                        )
                        not_do.append(x)
                    print i.id
            except Exception as e:
                print e.message
                continue

        open('{}未扣除订单.xlsx'.format(change_time), 'wb').write(not_do.xlsx)
        open('{}已处理订单.xlsx'.format(change_time), 'wb').write(do_order.xlsx)
        send_email = u'chenfeifei@igengmei.com'
        get_mail(u'{}_未扣除订单.xlsx'.format(change_time), u'未扣除订单', send_email, not_do.xlsx).send()
        get_mail(u'{}_已处理订单.xlsx'.format(change_time), u'已处理订单', send_email, do_order.xlsx).send()
        print 'DONE!'
