# coding:utf-8
from __future__ import unicode_literals

import os
import tablib
import random
from datetime import datetime
from django.core.management import BaseCommand
from django.db import transaction
from api.models import UserExtra
from gm_types.gaia import LOGIN_AUTH_TYPE
from gm_types.gaia import PLATFORM_CHANNEL
from api.tool.person import create_person_by_phone


# 使用方式 python manage.py create_fake_user 10000000000 100
class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('start_phone')
        parser.add_argument('num')

    def handle(self, *args, **options):
        print('start')
        start = options.get('start_phone')
        num = options.get('num')
        self.create_users(start, num)

    def create_users(self, start, num):
        start = int(start)
        num = int(num)
        platform = PLATFORM_CHANNEL.UNKNOWN # 0
        email = ''
        login_auth_type = LOGIN_AUTH_TYPE.phone # '1'
        area_id = 1
        success_list = []
        i = 0
        export_result = tablib.Dataset()
        export_result.headers = [
            u'用户id', u'手机号',
            u'密码',
        ]
        create_time = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
        # 每一次执行都要生成一份csv文件
        export_path = 'create_fake_user_{}'.format(create_time)
        open(u'{}.csv'.format(export_path), 'wb').write(export_result.csv)
        while len(success_list) < num:
            export_result.headers = None
            password = self.build_password()
            phone = start + i
            p = str(phone)
            print(p)
            try:
                with transaction.atomic():
                    user = UserExtra.create_user(p, email, password, login_auth_type)
                    p = create_person_by_phone(p, user, platform, password, area_id)
                    if p:
                        p.is_puppet = True
                        p.save(update_fields=['is_puppet'])
            except Exception as e:
                print('<{}> failed with {}'.format(phone, e))
            else:
                export_row = [
                    user.id,
                    str(phone),
                    password,
                ]
                export_result.append(export_row)
                open(u'{}.csv'.format(export_path), 'a+').write(export_result.csv)
                export_result.pop()
                success_list.append(p)
            i += 1

        print(u'文件已保存至{}'.format(export_path))

        file_dir = os.path.abspath('.') + '/'
        file_name = file_dir + 'phones.log'
        with open(file_name, 'w') as f:
            for p in success_list:
                f.write(u'{}\n'.format(p).encode('utf-8'))
            f.close()
        print(u'文件已保存至{}'.format(file_name))


    def build_password(self):
        password_size = 8
        choice_pool = 'abcdefghijklmnopqrstuvwsyz23456789'
        password = ''
        for i in range(password_size):
            password += choice_pool[random.randint(0, len(choice_pool)-1)]
        return password
