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

from __future__ import division

import json

from django.core.serializers.json import DjangoJSONEncoder
from django_logit import logit
from django_response import response
from TimeConvert import TimeConvert as tc

from utils.error.errno_utils import GroupUserStatusCode
from utils.redis.connect import r
from utils.redis.rkeys import (TOUR_GUIDE_GROUP_CUR_SESSION, TOUR_GUIDE_GROUP_GEO_INFO, TOUR_GUIDE_GROUP_GEO_SUBMIT_DT,
                               TOUR_GUIDE_GROUP_USER_GEO_LIST)
from utils.redis.rtouruser import get_tour_user_belong_group


@logit
def geo_submit_api(request):
    user_id = request.POST.get('user_id', '')
    longitude = request.POST.get('lon', '')  # 经度
    latitude = request.POST.get('lat', '')  # 纬度

    # 获取用户当前所处旅行团
    group_id = get_tour_user_belong_group(user_id)
    if not group_id:
        return response(GroupUserStatusCode.USER_HAS_NOT_JOIN_GROUP)

    r.pipeline().geoadd(
        TOUR_GUIDE_GROUP_GEO_INFO % group_id, longitude, latitude, user_id
    ).hset(
        TOUR_GUIDE_GROUP_GEO_SUBMIT_DT % group_id, user_id, tc.utc_string(format='%Y-%m-%dT%H:%M:%SZ')
    ).execute()

    session_id = r.get(TOUR_GUIDE_GROUP_CUR_SESSION % group_id)
    r.rpush(TOUR_GUIDE_GROUP_USER_GEO_LIST % (group_id, session_id, user_id), json.dumps({
        'lon': longitude,
        'lat': latitude,
        'current_time': tc.utc_datetime(ms=False),
    }, cls=DjangoJSONEncoder))

    return response(200, 'Geo Info Submit Success', u'地理位置信息上传成功')
