# 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


def create_users_new(start, num):

    num = int(num)
    platform = PLATFORM_CHANNEL.UNKNOWN  # 0
    email = ''
    login_auth_type = LOGIN_AUTH_TYPE.phone  # '1'
    area_id = 1
    i = 0
    export_result = tablib.Dataset()
    export_result.headers = [
        u'用户id', u'手机号',
        u'密码',
    ]

    start = int(start)+1
    while i < num:
        password = build_password()
        phone = start + i
        str_phone = str(phone)
        try:
            with transaction.atomic():
                user = UserExtra.create_user(str_phone, email, password, login_auth_type)
                p = create_person_by_phone(str_phone, 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)
        i += 1

    export_result.title = u'新增马甲用户'
    return tablib.Databook((export_result,))


def build_password():
    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


def create_users(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 = 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))


# 使用方式 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')
        create_users(start, num)
