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

from __future__ import division

import json

from django.conf import settings
from logit import logit
from TimeConvert import TimeConvert as tc

from account.models import UserInfo
from group.models import GroupInfo, GroupUserInfo
from utils.error.errno_utils import GroupStatusCode, GroupUserStatusCode, UserStatusCode
from utils.error.response_utils import response
from utils.group_photo_utils import get_current_photos
from utils.redis.rgroup import get_group_info, get_group_users_info, set_group_users_info
from utils.redis.rkeys import (GROUP_LAST_PHOTO_PK, GROUP_USERS_DELETED_SET, GROUP_USERS_PASSED_SET,
                               GROUP_USERS_QUIT_SET, GROUP_USERS_REFUSED_SET, TOUR_GUIDE_GROUP_CUR_GATHER_INFO,
                               TOUR_GUIDE_GROUP_CUR_SESSION, TOUR_GUIDE_GROUP_GEO_INFO, TOUR_GUIDE_GROUP_USER_GEO_LIST)
from utils.redis.rprofile import get_profile_by_id
from utils.redis.rtourguide import get_tour_guide_own_group


r = settings.REDIS_CACHE


@logit
def tgu_group_user_join_api(request):
    """ 旅行团用户加群 """
    admin_id = request.POST.get('admin_id', '')  # 导游唯一标识，识别二维码获取
    user_id = request.POST.get('user_id', '')
    nickname = request.POST.get('nickname', '')

    name = request.POST.get('name', '')
    phone = request.POST.get('phone', '')
    relative_persons = request.POST.get('relative_persons', '')
    authority = bool(int(request.POST.get('authority', 1)))
    remark = request.POST.get('remark', '')

    # 获取旅行团唯一标识
    group_id = get_tour_guide_own_group(admin_id)

    # 用户校验
    try:
        user = UserInfo.objects.get(user_id=user_id)
    except UserInfo.DoesNotExist:
        return response(UserStatusCode.USER_NOT_FOUND)

    # 群组校验
    try:
        group = GroupInfo.objects.get(group_id=group_id)
    except GroupInfo.DoesNotExist:
        return response(GroupStatusCode.GROUP_NOT_FOUND)

    # 群组锁定校验
    if group.group_lock:
        return response(GroupStatusCode.GROUP_HAS_LOCKED)

    # 群组用户记录创建，若记录不存在，则创建，若记录已存在，则更新
    group_user, created = GroupUserInfo.objects.get_or_create(
        group_id=group_id,
        user_id=user_id,
        defaults={
            'name': name,
            'phone': phone,
            'relative_persons': relative_persons,
            'authority': authority,
            'remark': remark,
        }
    )

    if not created:
        group_user.name = name
        group_user.phone = phone
        group_user.relative_persons = relative_persons
        group_user.authority = authority
        group_user.remark = remark
        group_user.save()

    if group_user.user_status != GroupUserInfo.PASSED:
        group_user.current_id = int(r.get(GROUP_LAST_PHOTO_PK % group_id) or -1)
        group_user.nickname = nickname or user.final_nickname
        group_user.avatar = user.avatar
        # group_user.admin = False  # Admin Field Default False, Should Not Assign
        group_user.user_status = GroupUserInfo.PASSED
        group_user.passed_at = tc.utc_datetime()
        group_user.save()

    # Redis 群组用户数据缓存
    set_group_users_info(group)

    # Redis 群组通过集合缓存
    r.srem(GROUP_USERS_REFUSED_SET % group_id, user_id)
    r.srem(GROUP_USERS_DELETED_SET % group_id, user_id)
    r.srem(GROUP_USERS_QUIT_SET % group_id, user_id)
    r.sadd(GROUP_USERS_PASSED_SET % group_id, user_id)

    curinfo = get_current_photos(group_id, user_id, group_user.current_id)

    return response(200, 'Apply Success', u'申请成功', {
        'current_id': curinfo.get('current_id', ''),
        'photos': curinfo.get('photos', ''),
        'group_id': group_id,
        'group': get_group_info(group_id),
        'user_id': user_id,
        'users': get_group_users_info(group_id, user_id),
    })


@logit
def tgu_group_user_update_api(request):
    """ 旅行团用户更新 """
    group_id = request.POST.get('group_id', '')
    admin_id = request.POST.get('admin_id', '')  # 导游唯一标识
    user_id = request.POST.get('user_id', '')

    name = request.POST.get('name', '')
    phone = request.POST.get('phone', '')
    relative_persons = request.POST.get('relative_persons', '')
    authority = bool(int(request.POST.get('authority', 1)))
    remark = request.POST.get('remark', '')

    # 群组校验
    try:
        group = GroupInfo.objects.get(group_id=group_id)
    except GroupInfo.DoesNotExist:
        return response(GroupStatusCode.GROUP_NOT_FOUND)

    # 权限校验
    if admin_id:
        if not GroupUserInfo.objects.filter(group_id=group_id, user_id=admin_id, subadmin=True, status=True).exists():
            return response(GroupStatusCode.NO_UPDATE_PERMISSION)
    else:
        if not GroupUserInfo.objects.filter(group_id=group_id, user_id=user_id, status=True).exists():
            return response(GroupStatusCode.NO_UPDATE_PERMISSION)

    # 权限
    try:
        group_user = GroupUserInfo.objects.get(group_id=group_id, user_id=user_id, status=True)
    except GroupUserInfo.DoesNotExist:
        return response(GroupUserStatusCode.GROUP_USER_NOT_FOUND)

    # 用户信息更新
    # TODO: Whether sync name and phone to UserInfo or not?
    if name:
        group_user.name = name
    if phone:
        group_user.phone = phone
    if relative_persons:
        group_user.relative_persons = relative_persons
    if authority:
        group_user.authority = authority
    if remark:
        group_user.remark = remark
    group_user.save()

    # Redis 群组用户数据缓存
    group_users = set_group_users_info(group)

    return response(200, 'Update Group Success', u'群组更新成功', {
        'group_id': group_id,
        'group': group.data,
        'users': group_users,
    })


@logit
def tgu_group_user_locations_api(request):
    """ 旅行团所有用户位置信息 """
    group_id = request.POST.get('group_id', '')
    admin_id = request.POST.get('admin_id', '')  # 导游唯一标识

    # 权限校验
    if not GroupUserInfo.objects.filter(group_id=group_id, user_id=admin_id, subadmin=True, status=True).exists():
        return response(GroupStatusCode.NO_LOCATION_PERMISSION)

    # 获取集合经纬度
    gather_info = json.loads(r.get(TOUR_GUIDE_GROUP_CUR_GATHER_INFO % group_id) or '{}')

    # [['x', 0.33, (2.68220901489e-06, 1.26736058093e-06)], []]
    locations = r.georadius(TOUR_GUIDE_GROUP_GEO_INFO % group_id, gather_info.get('gather_lon', 0), gather_info.get('gather_lat', 0), '+inf', unit='m', withdist=True, withcoord=True, sort='ASC')
    # [{'location_info': ['x', 0.33, (2.68220901489e-06, 1.26736058093e-06)], 'user_info': {}}, {}]
    locations = [{
        'location_info': loc,
        'user_info': get_profile_by_id(loc[0])
    } for loc in locations]

    return response(200, 'Get Tour Guide Group All User Location Success', u'获取旅行团用户地理位置信息成功', {
        'group_id': group_id,
        'locations': locations,
    })


@logit
def tgu_group_user_location_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 GroupUserInfo.objects.filter(group_id=group_id, user_id=admin_id, subadmin=True, status=True).exists():
        return response(GroupStatusCode.NO_LOCATION_PERMISSION)

    session_id = r.get(TOUR_GUIDE_GROUP_CUR_SESSION % group_id)
    locations = r.lrange(TOUR_GUIDE_GROUP_USER_GEO_LIST % (group_id, session_id, user_id), 0, -1)

    return response(200, 'Get Tour Guide Group User Location Success', u'获取旅行团用户地理位置信息成功', {
        'group_id': group_id,
        'user_id': user_id,
        'locations': [json.loads(loc) for loc in locations]
    })
