# coding=utf-8
import datetime
from django.contrib.auth.models import User
from openpyxl import load_workbook
from django.core.management import BaseCommand
from social.models import UserFollow


class Command(BaseCommand):

    def handle(self, *args, **options):
        data = []
        wb = load_workbook(filename=u'/tmp/add_fans.xlsx')
        sheetnames = wb.get_sheet_names()
        ws = wb.get_sheet_by_name(sheetnames[0])
        # 读取excel
        for rx in range(2, ws.get_highest_row() + 1):
            item = {}
            item['id'] = ws.cell(row=rx, column=1).value
            item['fans'] = ws.cell(row=rx, column=3).value
            data.append(item)
        # 添加粉丝
        for item in data:
            today = datetime.date.today()
            last_login = datetime.datetime(today.year - 1, today.month, today.day, 23, 59, 59)
            users_fans = UserFollow.objects.filter(follow_id=item['id']).values_list('user_id', flat=True)
            users = User.objects.filter(last_login__lte=last_login).exclude(id__in=list(users_fans))[0:int(item['fans'])]
            count = 1000
            flag = True
            start_num = 0
            while flag:
                fans_list = []
                for user in users[start_num: start_num+count]:
                    fans_list.append(UserFollow(follow_id=item['id'], user=user, is_virtual_fan=True))
                if fans_list:
                    print 'UserID={} start={}'.format(item['id'], start_num)
                    UserFollow.objects.bulk_create(fans_list)
                    start_num += count
                else:
                    flag = False
        print 'Done'



