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

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


class TopicListView(APIView):
    def get(self, request):
        pictorial_id = request.GET.get('pictorial_id', '')
        user_id = request.GET.get('user_id', '')
        page = int(request.GET.get('page', 1))
        limit = int(request.GET.get('size', 10))
        filters = json.loads(request.GET.get('filter', "{}"))
        sorts_by = list(map(lambda i: int(i), request.GET.getlist('sort_params[]', [3])))
        drop_score = request.GET.get('drop_score', None)

        if user_id:
            filters.update({'user_id': user_id})
        if pictorial_id:
            filters.update({"pictorial_id": int(pictorial_id)})
        if drop_score is not None:
            if int(drop_score) == 0:
                filters.update({'drop_score': int(drop_score)})
            elif int(drop_score) == 1:
                filters.update({'drop_score__exclude': int(drop_score)})

        res = self.rpc['physical/search/business/topic'](
            offset=(page-1) * limit,
            size=limit,
            filters=filters,
            sorts_by=sorts_by
        ).unwrap()

        topic_ids = res.get("topic_ids", [])
        total_count = res.get("total_count", 0)

        try:
            data = self.rpc['venus/sun/topic/list'](
                topic_ids=topic_ids
            ).unwrap()
        except Exception as e:
            error_logger.error(u'获取帖子列表失败%s', e)
            raise

        result = {
            "data": data.get("data", []),
            "total": total_count,
        }

        return result


class TopicImageListView(APIView):
    def get(self, request):
        pictorial_id = request.GET.get('pictorial_id', '')
        page = int(request.GET.get('page', 1))
        limit = int(request.GET.get('limit', 50))
        filters = json.loads(request.GET.get('filter', "{}"))
        sorts_by = list(map(lambda i: int(i), request.GET.getlist('sort_params[]', [3])))
        filters.update({"has_image": True})
        if pictorial_id:
            filters.update({"pictorial_id": int(pictorial_id)})

        res = self.rpc['physical/search/business/topic'](
            offset=(page-1) * limit,
            size=limit,
            filters=filters,
            sorts_by=sorts_by
        ).unwrap()

        topic_ids = res.get("topic_ids", [])
        total_count = res.get("total_count", 0)

        try:
            data = self.rpc['venus/community/topic/images_info_dict'](
                topic_ids=topic_ids
            ).unwrap()
        except Exception as e:
            error_logger.error(u'获取帖子列表失败%s', e)
            raise

        result = []
        for topic_id in topic_ids:

            imgs_info = data.get(str(topic_id), [])
            if not imgs_info:
                continue

            result.append({
                "id": topic_id,
                "img_url": imgs_info[0].get("url", "") + '-w'
            })

        result = {
            "data": result,
            "total": total_count,
        }

        return result


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', '[]'))))
        collection_tag_ids = list(map(lambda x: x.split(':')[0], json.loads(request.POST.get('collection_tags', '[]'))))
        pictorial_ids = list(json.loads(request.POST.get('pictorial_ids', '[]')))

        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', 0),
            'pictorial_ids': pictorial_ids,
            'user_id': request.POST.get('user', '').split(':')[0],
            'star_id': request.POST.get('star', '').split(':')[0],
            'tag_ids': tag_ids,
            'collection_tag_ids': collection_tag_ids,
            'is_online': int(request.POST.get('is_online', 0)),
            'drop_score': int(request.POST.get('drop_score', 0)),
            'has_image': 1 if topic_images else 0,
            'has_video': 1 if request.POST.get('video_url', '') else 0,
            'virtual_vote_num': request.POST.get('virtual_vote_num', ''),
            'is_home': int(request.POST.get('is_home', 0)),
        }
        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()
        updates = self.handle_filter(request.POST.get('updates', "{}"))
        extra = json.loads(request.POST.get('extra', '{}'))
        try:
            self.rpc['venus/sun/topic/batch/update'](updates=updates, ids=ids, extra=extra).unwrap()
        except Exception as e:
            error_logger.error(u'批量更新帖子失败%s', e)
            raise
        return {
            "message": "更新成功"
        }


class TopicRelatePictorialInfo(APIView):

    def get(self, request):
        id_ = request.GET.get('id')
        offset, count = get_offset_count(request)
        try:
            data = self.rpc['venus/sun/topic/relate_pictorial_info'](id_=id_, offset=offset, count=count).unwrap()
        except Exception as e:
            error_logger.error(u'获取帖子画报列表失败%s', e)
            raise
        return {'data': data}
