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

from utils.base import APIView


class TagListView(APIView):
    def get(self, request):
        offset = int(request.GET.get('offset', 1))
        limit = int(request.GET.get('limit', 10))
        filter = self.handle_filter(request.GET.get('filter', ""))
        try:
            data = self.rpc['venus/community/tag/get'](offset=offset, 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', '')
        filters = {}
        if type == 'offline':
            filters['is_online'] = False
        else:
            filters['is_online'] = True
        try:
            self.rpc['venus/community/tag/batch/update'](filters=filters, tag_ids=ids).unwrap()
        except Exception as e:
            raise e
        return {
            "message": "更新成功"
        }


class TagUpdateOrCreateView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        try:
            data = self.rpc['venus/community/tag/get'](id=id).unwrap()
        except Exception as e:
            raise e
        if not data:
            data = {}
        else:
            data = data['data'][0]
        return {'data': data}

    def post(self, request):
        data = {
            'name': request.POST.get('name'),
            'level': request.POST.get('level'),
            'type': request.POST.get('type'),
            'description': request.POST.get('description'),
            'down_tag': list(set(request.POST.get('down_tag', '').split(','))),
            'up_tag': list(set(request.POST.get('up_tag', '').split(','))),
        }
        try:
            self.rpc['venus/community/tag/update_or_create'](data=data).unwrap()
        except Exception as e:
            raise e
        return {
            'message': '操作成功'
        }