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

import json
from django.conf import settings
from gm_upload import upload, IMG_TYPE, upload_with_short

from utils.base import APIView
from django.contrib.auth.hashers import make_password

from utils.download import download_img_func
from utils.logger import error_logger
from utils.pic_tools import tailor_image


class UserListView(APIView):
    def get(self, request):
        group_id = request.GET.get('group_id', '')
        page = int(request.GET.get('page', 1))
        limit = int(request.GET.get('limit', 10))
        filter = self.handle_filter(request.GET.get('filter', ""))
        if group_id:
            filter.update({'group_id': group_id})
        try:
            data = self.rpc['venus/sun/user/list'](offset=(page-1)*limit, limit=limit, filters=filter).unwrap()
        except Exception as e:
            error_logger.error(u'获取用户列表失败%s', e)
            raise
        return data

    def post(self, request):
        ids = json.loads(request.POST.get('ids', '[]'))
        updates = json.loads(request.POST.get('updates', '{}'))
        try:
            self.rpc['venus/sun/user/batch/update'](updates=updates, ids=ids).unwrap()
        except Exception as e:
            error_logger.error(u'批量更新user列表失败%s', e)
            raise
        return {
            "message": "更新成功"
        }


class UserUpdateOrCreate(APIView):
    def get(self, request):
        id = request.GET.get('id')
        try:
            data = self.rpc['venus/sun/user/get'](id=id).unwrap()
        except Exception as e:
            error_logger.error(u'获取%s用户详情失败%s'%(id, e))
            raise
        return data

    def post(self, request):
        id = request.POST.get('id', '')
        user_id = request.POST.get('user_id', '')
        tag_ids = list(map(lambda x: x.split(":")[0], json.loads(request.POST.get('tags', '[]'))))
        password = make_password(settings.PUPPET_PASSWORD, None, 'pbkdf2_sha256')

        data = {
            'user_id': user_id,
            'password': password,
            'is_recommend': int(request.POST.get('is_recommend')),
            'profile_pic': request.POST.get('avatar')[:-2],
            'nick_name': request.POST.get('nick_name'),
            'tag_ids': tag_ids,
            'is_puppet': int(request.POST.get('is_puppet')),
            'city_id': request.POST.get('city', '').split(":")[0],
            'phone': request.POST.get('phone'),
            'email': request.POST.get('email'),
            'gender': request.POST.get('gender'),
        }

        try:
            self.rpc['venus/sun/user/edit'](id=id, data=data).unwrap()
        except Exception as e:
            error_logger.error(u'创建/编辑%s用户详情失败%s' % (id, e))
            raise
        return {
            'message': '更新成功'
        }


class UserGroupView(APIView):
    def get(self, request):
        user_id = request.GET.get('id')
        offset = int(request.GET.get('page', 0))
        count = int(request.GET.get('limit', 10))
        filters = {'user_id': user_id}
        try:
            data = self.rpc['venus/sun/group/user/list'](filters=filters, offset=(offset - 1) * count, limit=count).unwrap()
        except Exception as e:
            error_logger.error(u'获取小组用户详情失败%s' , e)
            raise
        return data


class UserImage(APIView):

    def post(self, request):
        image_id = request.POST.get('image_id', '')
        image_url = request.POST.get('image_url', '')
        user_id = request.POST.get('user_id', '')

        if not all([image_id, image_url, user_id]):
            error_logger.error(u'参数不完整')
            return
        err, data = self.rpc['saber/face/detect'](url=image_url).unwrap()
        if err:
            error_logger.error(u'获取人脸失败')
        faces = [
            {
                "point": [
                    item["rect"]["left"],
                    item["rect"]["top"],
                    item["rect"]["right"]-item["rect"]["left"],
                    item["rect"]["bottom"]-item["rect"]["top"],
                ]
            }
            for item in data.get("faces", [])
        ]
        try:
            point = faces[0].get('point', [])
            file_path = download_img_func(image_url, user_id, suffix="png")
            images = tailor_image(file_path, point)
            header_pic_path = images[0]
            with open(header_pic_path, 'rb') as f:
                image_url = upload_with_short(f, img_type=IMG_TYPE.USEREXTRA)[0]
        except IndexError:
            error_logger.error(u'获取人脸失败')
            return
        except:
            error_logger.error(u'上传失败')
            return

        result = self.rpc['venus/sun/user/create_update_image'](
            url=image_url, user_id=user_id).unwrap()
        return {
            'message': '创建成功' if result else '创建失败'
        }

    def get(self, request):
        user_id = request.GET.get('user_id')
        offset = int(request.GET.get('page', 1))
        count = int(request.GET.get('limit', 10))
        try:
            data = self.rpc['venus/sun/user/user_image_list'](
                user_id=user_id, offset=(offset - 1) * count, limit=count).unwrap()
        except Exception as e:
            error_logger.error(u'获取%s用户头像失败%s' % (id, e))
            raise
        return data
