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

import json
from utils.base import APIView
from utils.logger import error_logger


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

    def post(self, request):
        ids = request.POST.get('ids', '').split()
        type = request.POST.get('type')
        updates = {}
        if type == 'offline':
            updates['is_online'] = False
        elif type == 'is_recommend':
            updates['is_recommend'] = True
        else:
            updates['is_online'] = True
        try:
            self.rpc['venus/sun/group/batch/update'](updates=updates, ids=ids).unwrap()
        except Exception as e:
            error_logger.error(u'批量更新失败%s', e)
            raise
        return {
            "message": "更新成功"
        }


class GroupUpdateOrCreate(APIView):
    def get(self, request):
        id = request.GET.get('id').split(':')[0]
        try:
            data = self.rpc['venus/sun/group/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')
        star_ids = list(map(lambda x: x.split(":")[0], json.loads(request.POST.get('star', '[]'))))
        try:
            group_user_ids = list(map(lambda x: x.split(":")[0], json.loads(request.POST.get('group_users', '[]'))))
        except:
            group_user_ids = json.loads(request.POST.get('group_users', '[]'))
        data = {
            'name': request.POST.get('name', ''),
            'description': request.POST.get('description', ''),
            'creator_id': request.POST.get('user', '').split(':')[0],
            'celebrity_ids': star_ids,
            'is_online': int(request.POST.get('is_online', 0)),
            'is_recommend': int(request.POST.get('is_recommend', 0)),
            'group_user_ids':group_user_ids,
            'icon': request.POST.get('icon', '')[:-2]
        }
        try:
            self.rpc['venus/sun/group/edit'](id=id, data=data).unwrap()
        except Exception as e:
            error_logger.error(u'编辑%s用户信息失败%s' % (id, e))
            raise
        return {
            'message': '更新成功'
        }


class GroupRelatedUser(APIView):
    def get(self, request):
        id = request.GET.get('id')
        offset = int(request.GET.get('page', 0))
        count = int(request.GET.get('limit', 10))
        filters = {'group_id': 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 GroupRelatedUserGET(APIView):
    def get(self, request):
        id = request.GET.get('id', '').split(':')[0]
        try:
            data = self.rpc['venus/sun/group/user/get'](id=id).unwrap()
        except Exception as e:
            error_logger.error(u'获取小组用户信息失败%s', e)
            raise
        return [data, ]

    def post(self, request):
        group_id = request.POST.get('group_id')
        user_id = request.POST.get('user_id')
        data = {
            'role_id': request.POST.get('original_group_identify'),
        }
        try:
            self.rpc['venus/sun/group/user/edit'](id=group_id, user_id=user_id, data=data).unwrap()
        except Exception as e:
            error_logger.error(u'编辑小组用户%d信息失败%s'%(user_id, e))
            raise
        return