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

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


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/sun/tag/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):
        ids = json.loads(request.POST.get('ids', '[]'))
        updates = json.loads(request.POST.get('updates', '{}'))
        try:
            self.rpc['venus/sun/tag/batch/update'](updates=updates, ids=ids).unwrap()
        except Exception as e:
            error_logger.error(u'批量更新标签列表失败%s', e)
            raise
        return {
            "message": "更新成功"
        }


class TagUpdateOrCreateView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        try:
            data = self.rpc['venus/sun/tag/get'](id=id).unwrap()
        except Exception as e:
            error_logger.error(u'获取标签%d信息失败%s'%(int(id), e))
            raise
        if not data:
            data = {}
        else:
            pass
        return {'data': data}

    def post(self, request):
        
        id = request.POST.get('id')
        down_tags = list(set(map(lambda x: x.split(":")[0], json.loads((request.POST.get('down_tags', '[]'))))))
        up_tags = list(set(map(lambda x: x.split(":")[0], json.loads((request.POST.get('up_tags', '[]'))))))
        tagtypes = list(set(map(lambda x: x.split(":")[0], json.loads((request.POST.get('tagtypes', '[]'))))))

        data = {
            'name': request.POST.get('name').lower(),
            'description': request.POST.get('description', ''),
            'down_tags': down_tags,
            'up_tags': up_tags,
            'tagtypes': tagtypes,
            'icon_url': request.POST.get('icon_url', '')[:-2],
            'platform': request.POST.get('platform', 1),
            'collection': request.POST.get('collection', 0),
            'alias': request.POST.get('alias', ''),
            'is_show_in_register': request.POST.get('is_show_in_register', 'false'),
            'pictorial_ids': list(
                (map(lambda x: int(x.split(":")[0]), json.loads((request.POST.get('pictorial_ids', '[]'))))))
        }
        try:
            data = self.rpc['venus/sun/tag/edit'](id=id, data=data).unwrap()
        except Exception as e:
            error_logger.error(u'创建/编辑标签%s信息失败%s' % (id, e))
            raise
        return data


class TagTypeListView(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/sun/tag/tagtype/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):
        ids = json.loads(request.POST.get('ids', '[]'))
        updates = json.loads(request.POST.get('updates', '{}'))

        try:
            self.rpc['venus/sun/tag/tagtype/batch/update'](updates=updates, ids=ids).unwrap()
        except Exception as e:
            error_logger.error(u'批量更新标签类型列表失败%s', e)
            raise
        return {
            "message": "更新成功"
        }


class TagTypeUpdateOrCreateView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        try:
            data = self.rpc['venus/sun/tag/tagtype/get'](id=id).unwrap()
        except Exception as e:
            error_logger.error(u'获取标签%d信息失败%s'%(id, e))
            raise
        if not data:
            data = {}
        else:
            pass
        return {'data': data}

    def post(self, request):
        id = request.POST.get('id')
        data = {
            'name': request.POST.get('name'),
        }
        try:
            data = self.rpc['venus/sun/tag/tagtype/edit'](id=id, data=data).unwrap()
        except Exception as e:
            error_logger.error(u'创建/编辑标签类型%d信息失败%s' % (id, e))
            raise
        return data


class TagRegisterUpdateView(APIView):

    def get(self, request):
        data = {}
        try:
            data = self.rpc['venus/sun/tag/register_tag/get']().unwrap()
        except Exception as e:
            error_logger.error(u'拉取信息失败')
            raise
        return data

    def post(self, request):
        male_ids = request.POST.get('male_ids')
        female_ids = request.POST.get('female_ids')
        try:
            self.rpc['venus/sun/tag/register_tag/update'](female_ids=female_ids, male_ids=male_ids).unwrap()
        except Exception as e:
            error_logger.error(u'配置失败')
            raise
        return {'msg': '更改成功'}


class TagFilterList(APIView):

    def get(self, request):
        filters = {}
        offset, count = get_offset_count(request)
        tag_name = request.GET.get('tag_name', None)
        tag_id = request.GET.get('tag_id', None)

        if tag_name:
            filters['tag_name'] = tag_name
        if tag_id and int(tag_id) > 0:
            filters['tag_id'] = tag_id

        data = self.rpc['venus/sun/tag/filter/list'](filters=filters, offset=offset, count=count).unwrap()

        return data


class TagFilterCreate(APIView):

    def post(self, request):
        tag_infos = json.loads(request.POST.get('tag_infos', '[]'))
        if not tag_infos:
            return {'message': '参数不完整'}
        for tag_info in tag_infos:
            tag_name = tag_info.get('tag_name', None)
            tag_id = tag_info.get('tag_id', None)
            if not tag_id or not tag_name:
                return {'message': '参数不完整'}

            data = self.rpc['venus/sun/tag/filter/add'](tag_id=tag_id, tag_name=tag_name).unwrap()
            if not data:
                return {'message': '创建失败'}

        return {'message': '创建成功'}


class TagFilterDelete(APIView):

    def post(self, request):

        ids = json.loads(request.POST.get('ids', '[]'))
        if not ids:
            return {'message': '参数不完整'}

        for id_ in ids:
            data = self.rpc['venus/sun/tag/filter/delete'](id_=id_).unwrap()

            if not data:
                return {'message': '操作失败'}

        return {'message': '操作成功'}


class TagSearchRecommendKeyword(APIView):
    def get(self, request):
        try:
            data = self.rpc['venus/sun/tag/recommend_keyword/get']().unwrap()
        except Exception as e:
            error_logger.error(u'获取搜索热门词失败%s', e)
            raise
        return data

    def post(self, request):
        # 如果有id 走update 。 否则走创建
        id = request.POST.get('id', None)
        update = request.POST.get('update', '')
        try:
            data = self.rpc['venus/sun/tag/recommend_keyword/edit'](data=update, id=id).unwrap()
        except Exception as e:
            error_logger.error(u'获取搜索热门词失败%s', e)
            raise
        return data


class SearchDefaultKeyword(APIView):
    def get(self, request):
        try:
            data = self.rpc['venus/sun/tag/search_default_keyword/get']().unwrap()
        except Exception as e:
            error_logger.error(u'获取搜索默认关键字失败%s', e)
            raise
        return data

    def post(self, request):
        id = request.POST.get('id', None)
        update = request.POST.get('update', '')
        try:
            data = self.rpc['venus/sun/tag/search_default_keyword/edit'](data=update, id=id).unwrap()
        except Exception as e:
            error_logger.error(u'更新搜索默认关键字失败%s', e)
            raise
        return data
