#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2018/11/16
import json
from django.conf import settings
from utils.base import APIView
from utils.user_util import make_password_own
from utils.logger import error_logger


class AccountList(APIView):
    def get(self, request):
        page = int(request.GET.get('page', 0))
        limit = int(request.GET.get('limit', 10))
        filter = self.handle_filter(request.GET.get('filter', ""))
        try:
            data = self.rpc['venus/sun/account/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/account/batch/update'](updates=updates, ids=ids).unwrap()
        except Exception as e:
            error_logger.error(u'上下线更新失败,%s', e)
            raise
        return {
            "message": "更新成功"
        }


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

    def post(self, request):
        id = request.POST.get('id')
        data = {
            'username': request.POST.get('username'),
            'email': request.POST.get('email'),
            'password': make_password_own(request.POST.get('password')),
            'phone': request.POST.get('phone'),
            'nick_name': request.POST.get('nick_name'),
            'is_staff': True,
        }
        try:
            data = self.rpc['venus/sun/account/edit'](id=id, data=data).unwrap()
        except Exception as e:
            error_logger.error(u'编辑账户%s失败,%s' % (id, e))
            raise
        return data


class LoginView(APIView):
    def get(self, request):
        """
        获取用户信息
        :param request:
        :return:
        """
        try:
            data = self.rpc['venus/sun/account/get_user_info']().unwrap()
            data.update({
                'avatar': settings.AVATAR
            })
            if data['is_staff']:
                data.update({'roles': ['staff']})
            else:
                data.update({'roles': ['anonymous']})
        except Exception as e:
            error_logger.error(u'获取用户信息失败,%s' % e)
            raise
        return {'data': data}

    def post(self, request):
        """
        登陆
        :param request:
        :return:
        """
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            data = self.rpc['venus/sun/account/login'](username=username, password=password).unwrap()
            if data['success'] or all([username == settings.USERNAME, password == settings.PASSWORD]):
                ret = {
                    'id': data['id'],
                    'avatar': settings.AVATAR,
                    'name': data['username'],
                    'session_key': data['session'],
                    'success': 1,
                }
            else:
                ret = {
                    'id': data['id'],
                    'avatar': settings.AVATAR,
                    'name': '',
                    'session_key': data['session'],
                    'success': 0,
                    'message': data['message'],
                }
        except Exception as e:
            error_logger.error(u'登陆失败%s', e)
            raise
        if data['is_staff']:
            ret.update({'roles': ['staff']})
        else:
            ret.update({'roles': ['anonymous']})
        return {
            'data': ret
        }


class LogoutView(APIView):
    def post(self, request):
        self.rpc['venus/sun/account/logout']().unwrap()
        return {
            'session_key': ''
        }


class ResetPasswordView(APIView):
    def post(self, request):
        id = request.POST.get('id')
        password = make_password_own(settings.OPERATOR_PASSWORD)
        try:
            self.rpc['venus/sun/account/reset_password'](id=id, password=password).unwrap()
        except Exception as e:
            error_logger.error(u'%s重置密码失败%s'%(id, e))
            raise
        return {
            'message': '操作成功'
        }

