# -*- coding: utf-8 -*-

from __future__ import division

from logit import logit

from group.models import GroupUserInfo
from utils.admin_utils import is_group_admin
from utils.error.errno_utils import GroupStatusCode
from utils.error.response_utils import response


@logit
def tg_group_admin_list_api(request):
    """ 旅行团管理员列表 """
    group_id = request.POST.get('group_id', '')
    admin_id = request.POST.get('admin_id', '')  # 导游唯一标识

    # 权限校验
    if not is_group_admin(group_id, admin_id):
        return response(GroupStatusCode.NOT_GROUP_ADMIN)

    admins = GroupUserInfo.objects.filter(group_id=group_id, subadmin=True, status=True)
    admins = [admin.admin_info for admin in admins]

    return response(200, 'Get Tour Guide Group Admin List Success', u'获取旅行团管理员列表成功', {
        'group_id': group_id,
        'admins': admins,
    })


@logit
def tg_group_admin_recovery_api(request):
    """ 旅行团管理员权限回收，管理员主动，团成员被动 """
    group_id = request.POST.get('group_id', '')
    admin_id = request.POST.get('admin_id', '')  # 导游唯一标识
    user_id = request.POST.get('user_id', '')

    # 权限校验
    if not is_group_admin(group_id, admin_id):
        return response(GroupStatusCode.NOT_GROUP_ADMIN)

    # 管理员也不允许将自己移除
    if admin_id == user_id:
        return response(GroupStatusCode.ADMIN_CANNOT_HANDLE_SELF)

    try:
        subadmin = GroupUserInfo.objects.get(group_id=group_id, user_id=user_id, subadmin=True, admin_status=True, status=True)
    except GroupUserInfo.DoesNotExist:
        return response(GroupStatusCode.NOT_GROUP_SUBADMIN)

    # 权限回收
    subadmin.admin_status = False
    subadmin.save()

    return response(200, 'Tour Guide Group Admin Right Recovery Success', u'旅行团管理员权限回收成功')


@logit
def tg_group_admin_waiver_api(request):
    """ 旅行团管理员权限放弃 """
    group_id = request.POST.get('group_id', '')
    user_id = request.POST.get('user_id', '')

    try:
        subadmin = GroupUserInfo.objects.get(group_id=group_id, user_id=user_id, subadmin=True, admin_status=True, status=True)
    except GroupUserInfo.DoesNotExist:
        return response(GroupStatusCode.NOT_GROUP_SUBADMIN)

    # 权限回收
    subadmin.admin_status = False
    subadmin.save()

    return response(200, 'Tour Guide Group Admin Right Waiver Success', u'旅行团管理员权限放弃成功')
