# 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

import requests
import time
# 使用方式 python manage.py create_fake_user_2
class Command(BaseCommand):

    def handle(self, *args, **options):
        print('start....')

        self.create_users()

    def create_users(self):
        ts = int(time.time())
        r = requests.get('http://dev.c.xxapi.cn/v1/auth/users').json()
        num = len(r)
        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()
            nick = r[i]['nick']
            portrait = r[i]['portrait']

            try:
                with transaction.atomic():
                    user = UserExtra.create_user(nick, email, password, login_auth_type,portrait=portrait)
                    p = create_person_by_phone(ts+i, user, platform, password, area_id)
                    if p:
                        p.is_puppet = True
                        p.save(update_fields=['is_puppet'])
            except Exception as e:
                print('<{0}> failed with {1}'.format(nick, e))
            else:
                export_row = [
                    user.id,
                    nick,
                    portrait,
                ]
                export_result.append(export_row)
                open(u'{}.csv'.format(export_path), 'a+').write(export_result.csv)
                export_result.pop()
                success_list.append(p)
                print '生成第{0}个马甲用户,ID:{1} 昵称:{2}'.format(i + 1, user.id,user.username)

            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
