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

from __future__ import division

from django.conf import settings
from django.db import transaction
from logit import logit

from account.models import TourGuideInfo, UserInfo
from utils.error.errno_utils import TourGuideStatusCode
from utils.error.response_utils import response
from utils.redis.rprofile import set_profile_info


@logit
def tourguide_submit_api(request):
    """ 导游信息提交 """
    unionid = request.POST.get('unionid', '')
    openid = request.POST.get('openid', '')
    phone = request.POST.get('phone', '')

    serverIds = request.POST.getlist('serverIds[]', [])

    # TODO: get tour guide photo from wx server

    if TourGuideInfo.objects.filter(phone=phone).exclude(unionid=unionid).exists():
        return response(TourGuideStatusCode.TOURGUIDE_PHONE_ALREADY_EXISTS)

    fields = {
        'name': request.POST.get('name', ''),
        'sex': int(request.POST.get('sex', 1)),
        'phone': phone,
        'location': request.POST.get('location', ''),
        'no': request.POST.get('no', ''),
        'user_status': TourGuideInfo.UNVERIFIED,
    }

    tourguide, created = TourGuideInfo.objects.get_or_create(unionid=unionid, defaults=fields)
    # 状态为 UNVERIFIED 的允许修改, 其他需要登录导游 APP 进行信息的修改
    if tourguide.user_status not in [TourGuideInfo.UNVERIFIED, TourGuideInfo.REFUSED]:
        return response(TourGuideStatusCode.TOURGUIDE_ALREADY_NOT_UNVERIFIED)
    if not created:
        for key, value in fields.iteritems():
            setattr(tourguide, key, value)
        tourguide.save()

    return response(200, 'Submit Success', u'提交成功', {})


@logit
@transaction.atomic
def tourguide_wx_authorize_api(request):
    try:
        user = UserInfo.objects.select_for_update().get(unionid=request.POST.get('unionid', ''), istourguide=True, status=True)
    except UserInfo.DoesNotExist:
        return response(TourGuideStatusCode.TOURGUIDE_NOT_FOUND)

    # 用户是否激活
    if user.user_status != UserInfo.ACTIVATED:
        return response(TourGuideStatusCode.TOURGUIDE_NOT_ACTIVATED)

    # Set User Key's Value
    user.openid_tourguide = request.POST.get('openid', '')
    user.sex = request.POST.get('sex', 0)
    user.nickname = request.POST.get('nickname', '') or request.POST.get('screen_name', '')
    user.avatar = request.POST.get('headimgurl', '') or request.POST.get('profile_image_url', '')
    user.country = request.POST.get('country', '')
    user.province = request.POST.get('province', '')
    user.city = request.POST.get('city', '')
    user.save()

    set_profile_info(user)

    return response(200, 'Tour Guide Login Success', u'导游登录成功', user.data)


@logit
def tourguide_guest_login_api(request):
    try:
        user = UserInfo.objects.get(unionid=settings.PAI2_TOURGUIDE_GUEST_UNIONID, istourguide=True, status=True)
    except UserInfo.DoesNotExist:
        return response(TourGuideStatusCode.TOURGUIDE_NOT_FOUND)

    return response(200, 'Tour Guide Login Success', u'导游登录成功', user.data)
