#! /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 TopicListView(APIView):
    def get(self, request):
        user_id = request.GET.get('user_id', '')
        group_id = request.GET.get('group_id', '')
        offset = int(request.GET.get('page', 0))
        limit = int(request.GET.get('limit', 10))
        filter = self.handle_filter(request.GET.get('filter', ""))
        if user_id:
            filter.update({'user_id': user_id})
        if group_id:
            filter.update({'group_id': group_id})
        try:
            data = self.rpc['venus/sun/topic/list'](offset=(offset - 1) * limit, limit=limit, filters=filter).unwrap()
        except Exception as e:
            error_logger.error(u'获取帖子列表失败%s', e)
            raise
        return data


class TopicUpdateOrCreateView(APIView):
    def get(self, request):
        id = request.GET.get('id')

        try:
            data = self.rpc['venus/sun/topic/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', '')
        topic_images = list(map(lambda x: x[:-2], json.loads(request.POST.get('topic_images', []))))
        tag_ids = list(map(lambda x: x.split(':')[0], json.loads(request.POST.get('tags', '[]'))))
        data = {
            'topic_images': topic_images,
            'video_url': request.POST.get('video_url', ''),
            'posting_time': request.POST.get('posting_time'),
            'content': request.POST.get('content', ''),
            'content_level': request.POST.get('content_level', ''),
            'group_id': request.POST.get('group', '').split(':')[0],
            'user_id': request.POST.get('user', '').split(':')[0],
            'star_id': request.POST.get('star', '').split(':')[0],
            'tag_ids': tag_ids,
            'is_online': int(request.POST.get('is_online')),
        }
        try:
            self.rpc['venus/sun/topic/edit'](id=id, data=data).unwrap()
        except Exception as e:
            error_logger.error(u'创建/编辑%s-帖子信息失败%s' % (id, e))
            raise
        return {
            'message': '更新成功'
        }


class ReplyUpdateOrCreateView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        offset = int(request.GET.get('page', 0))
        limit = int(request.GET.get('limit', 10))
        filter = self.handle_filter(request.GET.get('filter', ""))
        filter.update({'topic_id': id})
        try:
            data = self.rpc['venus/sun/topic/reply/list'](offset=(offset-1) * limit, limit=limit, filters=filter).unwrap()
        except Exception as e:
            error_logger.error(u'回复帖子失败%s' , e)
            raise
        return data

    def post(self, request):
        reply_ids = json.loads(request.POST.get('reply_ids', []))
        try:
            self.rpc['venus/sun/topic/reply/batch_delete'](ids=reply_ids).unwrap()
        except Exception as e:
            error_logger.error(u'批量更新帖子失败%s', e)
            raise
        return {
            'message': '操作成功'
        }


class ReplyCreate(APIView):
    def post(self, request):
        request.POST.get('be_replied_id', None)
        data = {
            'user_id': request.POST.get('user_id').split(':')[0],
            'replied_id': request.POST.get("replied_id", None),
            'topic_id': request.POST.get("topic_id", None),
            'content': request.POST.get('content'),
            'replied_user_id': request.POST.get('replied_user_id', None)
        }
        try:
            data = self.rpc['venus/sun/topic/reply/edit'](id=None, data=data).unwrap()
        except Exception as e:
            error_logger.error(u'编辑帖子失败%s', e)
            raise
        return {'data': data}


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

