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

import time
import json
from utils.base import APIView
from utils.time_utils import analysis_time


class UserListView(APIView):
    def get(self, request):
        group_id = request.GET.get('group_id', '')
        page = int(request.GET.get('page', 1))
        limit = int(request.GET.get('limit', 10))
        filter = self.handle_filter(request.GET.get('filter', ""))
        if group_id:
            filter.update({'group_id': group_id})
        try:
            data = self.rpc['venus/sun/user/list'](offset=(page-1)*limit, limit=limit, filters=filter).unwrap()
        except Exception as e:
            raise e
        return data


class UserUpdateOrCreate(APIView):
    def get(self, request):
        id = request.GET.get('id')
        try:
            data = self.rpc['venus/sun/user/get'](id=id).unwrap()
        except Exception as e:
            raise e
        return data

    def post(self, request):
        user_id = request.POST.get('id', '')
        show_time = analysis_time(request.POST.get('show_time', 0))
        tag_ids = list(set(request.POST.get('tag_ids').split(',')))
        if not user_id:
            user_id = time.time()
        data = {
            'user_id': user_id,
            'is_recommend': request.POST.get('is_recommend'),
            'profile_pic': request.POST.get('avatar')[:-2],
            'nick_name': request.POST.get('nick_name'),
            'tag_ids': list(filter(lambda x: x, tag_ids)),
            'is_puppet': request.POST.get('is_puppet'),
            'city_id': request.POST.get('city'),
            'show_time': show_time,
            'phone': request.POST.get('phone'),
            'email': request.POST.get('email'),
            'gender': request.POST.get('gender'),
            # 'group_ids': json.loads(request.POST.get('group_ids')),
        }

        try:
            self.rpc['venus/sun/user/edit'](id=id, data=data).unwrap()
        except Exception as e:
            raise e
        return {
            'message': '更新成功'
        }


class UserGroupView(APIView):
    def get(self, request):
        user_id = request.GET.get('id')
        offset = int(request.GET.get('page', 0))
        count = int(request.GET.get('limit', 10))
        filters = {'user_id': user_id}
        try:
            data = self.rpc['venus/sun/group/user/list'](filters=filters, offset=(offset - 1) * count, limit=count).unwrap()
        except Exception as e:
            raise e
        return data