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

import json
from utils.base import APIView


class CelebrityListView(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/celebrity/list'](offset=(page-1)*limit, limit=limit, filters=filter).unwrap()
        except Exception as e:
            raise e
        return data

    def post(self, request):
        ids = request.POST.get('ids', '').split()
        type = request.POST.get('type', '')

        updates = {}

        if type == 'offline':
            updates['is_online'] = 0
        else:
            updates['is_online'] = 1
        try:
            self.rpc['venus/sun/celebrity/batch/update'](updates=updates, ids=ids).unwrap()
        except Exception as e:
            raise e
        return {
            "message": "更新成功"
        }


class CelebrityUpdateOrCreate(APIView):
    def get(self, request):
        id = request.GET.get('id')
        try:
            data = self.rpc['venus/sun/celebrity/get'](id=id).unwrap()
        except Exception as e:
            raise e
        return {'data': data}

    def post(self, request):
        id = request.POST.get('id', '')
        data = {
            'name': request.POST.get('name'),
            'gender': int(request.POST.get('gender')),
            'city_id': request.POST.get('city'),
            'is_online': int(request.POST.get('is_online')),
            'desc': request.POST.get('description'),
            'portrait': request.POST.get('avatar')[:-2],
            'group_ids': list(set(json.loads(request.POST.get('group_ids', [])))),
        }
        try:
            self.rpc['venus/sun/celebrity/edit'](id=id, data=data).unwrap()
        except Exception as e:
            raise e

        return {
            'message': '更新成功'
        }


class CelebrityRelatedGroup(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 = {'star_id': id}
        try:
            data = self.rpc['venus/sun/group/list'](filters=filters, offset=(offset-1) * count, limit=count).unwrap()
        except Exception as e:
            raise e
        return data
