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

import json
from utils.base import APIView
from alpha_types.venus import PICK_TYPE
from utils.logger import error_logger


class PickListView(APIView):
    def get(self, request):
        offset = int(request.GET.get('page', 1))
        limit = int(request.GET.get('limit', 10))
        filter = self.handle_filter(request.GET.get('filter', ""))
        try:
            data = self.rpc['venus/sun/pick/list'](offset=(offset - 1) * limit, limit=limit, filters=filter).unwrap()
        except Exception as e:
            error_logger.error(u'获取pick列表失败%s', e)
            raise
        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/pick/batch/update'](updates=updates, ids=ids).unwrap()
        except Exception as e:
            error_logger.error(u'批量更新pick列表失败%s', e)
            raise
        return {
            "message": "更新成功"
        }


class UpdateOrCreateView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        try:
            data = self.rpc['venus/sun/pick/get'](id=id).unwrap()
        except Exception as e:
            error_logger.error(u'获取%s-pcik信息失败%s' %(id, e))
            raise
        return {'data': data}

    def post(self, request):
        id = request.POST.get('id', '')
        pick_group_ids = list(set(map(lambda x: x.split(":")[0], json.loads(request.POST.get('pick_group', '[]')))))
        city_ids = list(set(map(lambda x: x.split(":")[0], json.loads(request.POST.get('city', '[]')))))
        position = request.POST.get('position')
        gender = request.POST.get('gender')
        pick_type = request.POST.get('pick_type')

        data_dict = {
            'gender': '',
            'gender_value': '',
        }

        if gender == '全部':
            data_dict['gender'] = 2
        elif gender == '男':
            data_dict['gender'] = 0
        elif gender == '女':
            data_dict['gender'] = 1
        else:
            data_dict['gender'] = gender

        if pick_type == '明星打榜':
            data_dict['pick_type'] = 1
        elif pick_type == 'PICK帖子':
            data_dict['pick_type'] = 0
        else:
            data_dict['pick_type'] = pick_type

        data = {
            'name': request.POST.get('name'),
            'desc': request.POST.get('desc'),
            'gender': data_dict['gender'] if id else gender,
            'region': city_ids,
            'pick_type': data_dict['pick_type'] if id else pick_type,
            'pick_group': pick_group_ids,
            'is_online': int(request.POST.get('is_online')),
        }
        if position:
            data.update({"position": position})
        try:
            self.rpc['venus/sun/pick/edit'](id=id, data=data).unwrap()
        except Exception as e:
            error_logger.error(u'编辑%s-pcik信息失败%s' % (id, e))
            raise
        return {
            'message': '操作成功'
        }


class PickUserListView(APIView):
    def get(self, request):
        pick_id = request.GET.get('id', 0)
        pick_type = int(request.GET.get('pick_type_origin', 0))
        offset = int(request.GET.get('page', 0))
        limit = int(request.GET.get('limit', 10))
        filters = {
            'pick_id': pick_id
        }
        dispatch_rpc_endpoint = {
            PICK_TYPE.CELEBRITY: 'venus/sun/pick/celebrity/list',
            PICK_TYPE.TOPIC: 'venus/sun/pick/topic/list'
        }
        # try:
        #     data = self.rpc['venus/sun/pick/get'](id=pick_id).unwrap()
        #     pick_type = data['pick_type_origin']
        # except:
        #     pick_type = 0

        try:
            data = self.rpc[dispatch_rpc_endpoint[pick_type]](offset=(offset - 1) * limit, limit=limit, filters=filters).unwrap()
        except Exception as e:
            error_logger.error(u'获取%s-pcik信息失败%s' % (pick_id, e))
            raise
        return data

    def post(self, request):
        celebrity_id = request.POST.get('celebrity_id', '')
        fake_pick_nums = request.POST.get('fake_pick_nums', 0)
        topic_id = request.POST.get('topic_id', '')
        pick_id = request.POST.get('pick_id', '')
        try:
            self.rpc['venus/sun/pick/add_fake_pick_nums'](celebrity_id=celebrity_id, topic_id=topic_id, pick_nums=fake_pick_nums, pick_id=pick_id).unwrap()
        except Exception as e:
            error_logger.error(u'增加fake_pick_num失败%s' ,e)
            raise
        return {
            'message': '操作失败'
        }


class PickTopicView(APIView):
    def get(self, request):
        pick_id = request.GET.get('id', 0)
        offset = int(request.GET.get('page', 0))
        limit = int(request.GET.get('limit', 10))
        filters = {
            'pick_id': pick_id
        }

        try:
            data = self.rpc['venus/sun/pick/topic/list'](
                offset=(offset - 1) * limit,
                limit=limit,
                filters=filters
            ).unwrap()
        except Exception as e:
            raise e
        return data

    def post(self, request):
        topic_id = request.POST.get('topic_id').split(":")[0]
        pick_id = request.POST.get('pick_id')
        del_ids = json.loads(request.POST.get('del_ids', '""'))
        try:
            data = self.rpc['venus/sun/pick/pick_topic'](topic_id=topic_id, pick_id=pick_id, del_ids=del_ids).unwrap()
        except Exception as e:
            raise e
        return data


class PickCelebrityListView(APIView):
    def get(self, request):
        pick_id = request.GET.get('id', 0)
        offset = int(request.GET.get('page', 0))
        limit = int(request.GET.get('limit', 10))
        filters = {
            'pick_id': pick_id
        }

        try:
            data = self.rpc['venus/sun/pick/celebrity/list'](
                offset=(offset - 1) * limit,
                limit=limit,
                filters=filters
            ).unwrap()
        except Exception as e:
            raise e
        return data

    def post(self, request):
        celebrity_id = request.POST.get('celebrity_id').split(":")[0]
        pick_id = request.POST.get('pick_id')
        del_ids = json.loads(request.POST.get('del_ids', '""'))
        try:
            data = self.rpc['venus/sun/pick/pick_celebrity'](celebrity_id=celebrity_id, pick_id=pick_id, del_ids=del_ids).unwrap()
        except Exception as e:
            error_logger.error(u'操作失败%s', e)
            raise
        return data