#! /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
from alpha_types.venus import USER_EXTRA_TYPE


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)
        product_id = request.GET.get('product_id', 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)})
        if filters.get("is_finished") is not None:
            filters["is_finished"] = True if filters.get("is_finished") else False

        user_type = filters.pop("user_type") if filters.get("user_type") else None

        if user_type:
            if int(user_type) == USER_EXTRA_TYPE.COMMON:
                filters["is_shadow"] = 0
                filters["is_edit"] = 0
            elif int(user_type) == USER_EXTRA_TYPE.SHADOW:
                filters["is_shadow"] = 1
            elif int(user_type) == USER_EXTRA_TYPE.KOL:
                filters["is_kol"] = 1
            elif int(user_type) == USER_EXTRA_TYPE.EDIT:
                filters["is_edit"] = 1

        if filters.get("has_product") is not None:
             filters["has_product"] = bool(filters["has_product"])

        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, pictorial_id=pictorial_id, product_id=product_id,
            ).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', '[]'))))
        body_esthetics_tag_ids = list(
            map(lambda x: x.split(':')[0], json.loads(request.POST.get('body_esthetics_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)),
            'is_recommend': int(request.POST.get('is_recommend', 0)),
            'body_esthetics_tag_ids': body_esthetics_tag_ids,
            'product_id': request.POST.get('product_id'),
            'have_face': int(request.POST.get('have_face', 0)),
            'is_finished': int(request.POST.get('is_finished', 1)),
        }
        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 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}


class TopicBallot(APIView):

    def post(self, request):
        id_ = request.POST.get('id')
        pictorial_id = request.POST.get('pictorial_id')
        ballot_num = request.POST.get('ballot_num')

        try:
            self.rpc['venus/sun/topic/ballot'](id_=id_, pictorial_id=pictorial_id, ballot_num=ballot_num).unwrap()
        except Exception as e:
            error_logger.error(u'批量更新帖子失败%s', e)
            raise
        return {
            "message": "更新成功"
        }


class TopicProductAdd(APIView):
    """帖子添加商品关系"""

    def post(self, request):
        ids = json.loads(request.POST.get('ids', '[]'))
        product_id = request.POST.get('product_id')

        try:
            self.rpc['venus/sun/topic/add_product'](ids=ids, product_id=product_id).unwrap()
        except Exception as e:
            error_logger.error(u'编辑%s帖子信息失败%s' % (ids, e))
            raise
        return {
            'message': '更新成功'
        }


class TopicProductDel(APIView):
    """帖子删除商品关系"""

    def post(self, request):
        ids = json.loads(request.POST.get('ids', '[]'))
        product_id = request.POST.get('product_id')

        try:
            self.rpc['venus/sun/topic/del_product'](ids=ids, product_id=product_id).unwrap()
        except Exception as e:
            error_logger.error(u'编辑%s帖子信息失败%s' % (ids, e))
            raise
        return {
            'message': '更新成功'
        }


class TopicBallotBatch(APIView):
    """帖子批量投票"""

    def post(self, request):

        ids = json.loads(request.POST.get('ids', '[]'))
        ballot_num = int(request.POST.get('ballot_num', 0))

        try:
            self.rpc['venus/sun/topic/ballot_batch'](ids=ids, ballot_num=ballot_num).unwrap()
        except Exception as e:
            error_logger.error(u'编辑%s帖子信息失败%s' % (ids, e))
            raise
        return {
            'message': '更新成功'
        }
