#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
__title__ = '同步用户已绑定的手机号到实名制表中'
__author__ = 'xierong@gmei.com'
__mtime__ = '17/9/18'
des: 
手机号注册 -> Person
更新手机号 -> UserExtra
绑定手机号 -> Person,UserExtra
'''
import multiprocessing
from django.core.management import BaseCommand
from django.db import connection
from api.models.user import UserAuthentication
from api.models.person import Person


def AsyncUserPhone(start_index, end_index):
    start_pk = start_index
    final_pk = end_index
    end_pk = start_index + 1000
    print start_pk, final_pk

    print 'start work'
    while end_pk <= final_pk:
        try:
            phone_info = Person.objects.filter(phone__isnull=False).values('user_id', 'phone')[start_pk:end_pk]
            connection.close()  # fix problem: mysql closed connect unilateral

            insert_lst = []
            for item in phone_info:
                if UserAuthentication.objects.get(user_id=item['user_id']).exist():
                    continue

                insert_lst.append(UserAuthentication(phone=item['phone'], user_id=item['user_id']))

            if insert_lst:
                print 'start insert'
                UserAuthentication.objects.bulk_create(insert_lst)

            start_pk = end_pk
            end_pk += 1000

            connection.close()
        except Exception, e:
            print e
    else:
        try:
            phone_info = Person.objects.filter(phone__isnull=False).values('user_id', 'phone')[start_pk:final_pk]
            connection.close()

            insert_lst = []
            for item in phone_info:
                if UserAuthentication.objects.get(user_id=item['user_id']).exist():
                    continue
                insert_lst.append(UserAuthentication(phone=item['phone'], user_id=item['user_id']))

            print 'update final:', len(insert_lst)
            if insert_lst:
                UserAuthentication.objects.bulk_create(insert_lst)

            connection.close()
        except Exception, e:
            print e


class Command(BaseCommand):

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

        total_pk = Person.objects.count()
        connection.close()

        print 'total person count:', total_pk

        process_num = 4
        final_pk = total_pk + 1
        index_num = int(final_pk) / process_num

        pool = multiprocessing.Pool(processes=process_num)

        for i in xrange(process_num):
            start_pk = i * index_num
            end_pk = start_pk + index_num

            pool.apply_async(AsyncUserPhone, (start_pk, end_pk))

        pool.close()
        pool.join()