#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/1/11

import os
import json
from gm_upload import upload
from django.conf import settings
from django.core.management import BaseCommand
from api.models.user import UserExtra
from api.models.person import Person
from facialactivity.models import ActivityUserImage
from api.tool.person import update_password
from rpc.tool.random_tool import random_str


UPLOAD_TYPE = 5
TEMP_IMAGE = list()
IMAGE_TYPE_LIST = ["jpg", "jpeg", "png"]
IMAGE_DIRS = os.path.join(settings.BASE_DIR, "new_spring_activity_image")


def read_file(path):
    if not os.path.exists(path):
        print('文件路径不存在, 请确认后再操作')
        return
    with open(path) as f:
        user_list = json.loads(f.read())
    print("文件读取完毕....")

    return user_list


def search_image(path):
    """
    找到image所在目录, 并且返回该目录下所有的图片
    :param path:
    :return:
    """
    for filename in os.listdir(path):
        prefix, image_type = filename.split('.')
        if image_type in IMAGE_TYPE_LIST:
            yield filename, prefix.split('_')[-1]


def read_imagedata(filepath):
    """
    读取图片，返回二进制流
    :param path:
    :param mode:
    :return:
    """
    if not filepath:
        return

    full_path = os.path.join(IMAGE_DIRS, filepath)

    if not os.path.exists(full_path):
        return
    with open(full_path, "rb+") as f:
        return f.read()


def sendto_qiniu(data):
    """
    将图片二进制流发送到七牛，获取图片地址
    :param data:
    :return:
    """
    if not data:
        return

    return upload(data, img_type=UPLOAD_TYPE)


def create_user(last_name, portrait='', is_puppet=False, username=None):
    password = random_str(8)
    user = UserExtra.create_user(username or random_str(32), '', password)
    user.last_name = last_name
    user.userextra.portrait = portrait
    user.userextra.save()
    user.save()

    person = Person.objects.create(phone=None, user=user, is_puppet=is_puppet)
    update_password(user.person, password)

    return {'msg': '创建马甲成功', 'user_id': person.user_id}


def traverse_dirs(path):
    for image, level_type in search_image(path):
        TEMP_IMAGE.append([sendto_qiniu(read_imagedata(image)), level_type])


def bulk_create_data(user_name_list):
    temp_list = list()
    for _data in user_name_list:
        try:
            user_id = create_user(
                last_name=_data.get('last_name'),
                portrait=_data.get('imgUrl'),
                is_puppet=True
            ).get('user_id')

            o = ActivityUserImage(
                user_id=user_id,
                image_url=_data.get('imgUrl'),
                level=_data.get('image_type'),
                is_vest=True
            )
            temp_list.append(o)
        except Exception as e:
            print('image: %s, level_type: %s, create failed......' %(_data.get('imgUrl'), _data.get('image_type')))
    ActivityUserImage.objects.bulk_create(temp_list)


class Command(BaseCommand):
    def handle(self, *args, **options):
        print('--------start read file data -----------')
        user_name_list = read_file('new_spring_user_info.txt')
        print('--------end read file data -----------')
        print('--------start bulk create data-----------')
        bulk_create_data(user_name_list)
        print('--------end bulk create data-----------')