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

from utils.base import APIView


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:
            raise e
        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:
            raise e
        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:
            raise e
        return {'data': data}

    def post(self, request):
        id = request.POST.get('id', '')
        data = {
            'name': request.POST.get('name'),
            'desc': request.POST.get('desc'),
            'gender': request.POST.get('gender'),
            'region': list(set(request.POST.get('region', '').split(','))),
            'pick_type': request.POST.get('pick_type'),
            'pick_group': list(set(request.POST.get('pick_group', '').split(','))),
            'position': request.POST.get('position'),
            'is_online': request.POST.get('is_online'),
        }
        try:
            self.rpc['venus/sun/pick/edit'](id=id, data=data).unwrap()
        except Exception as e:
            raise e
        return {
            'message': '操作成功'
        }