#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
__title__ = '删除用户美分信息，201706之前的记录'
__author__ = 'xierong@gmei.com'
__mtime__ = '18/1/3'
'''
import multiprocessing
from django.core.management import BaseCommand
from django.db import connection, transaction

from api.models.user import User
from point import Points

from gm_types.gaia import POINTS_OPERATION, POINTS_TYPE




def DelUserPoint(per_user, deadline_date):
    try:
        old_point_all = Points.objects.filter(add_time__lte=deadline_date, user=per_user).values('operation', 'number')
        connection.close()  # fix problem: mysql closed connect unilateral

        add_old = 0
        remove_old = 0
        for item in old_point_all:
            if item['operation'] == POINTS_OPERATION.ADD:
                add_old += int(item['number'])
            elif item['operation'] == POINTS_OPERATION.REMOVE:
                remove_old += int(item['number'])


        point_left = add_old - remove_old
        original = per_user.person.points

        if point_left > 0 and original > 0:
            if point_left > original:
                per_user.person.points = 0
                point_left = original
            else:
                per_user.person.points = original - point_left

            print 'point_change:{0}\t{1}\t{2}'.format(per_user.id, original, per_user.person.points)

            per_user.save()

            with transaction.atomic():
                p = Points(
                    user=per_user,
                    operation=POINTS_OPERATION.REMOVE,
                    reason=POINTS_TYPE.CLEAR_ANNUALLY,
                    number=point_left,
                    link_user=per_user
                )
                p.save()


    except Exception, e:
        print e


class Command(BaseCommand):

    def handle(self, *args, **options):

        deadline_date = '2017-06-01'

        pool = multiprocessing.Pool(processes=4)
        for per_user in User.objects.all().iterator():
            pool.apply_async(DelUserPoint, (per_user, deadline_date))

        pool.close()
        pool.join()


