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

from __future__ import division

from django.conf import settings
from logit import logit

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


r = settings.REDIS_CACHE


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

    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
def tourguide_wx_authorize_api(request):
    unionid = request.POST.get('unionid', '')
    openid = request.POST.get('openid', '')

    sex = request.POST.get('sex', 0)
    nickname = request.POST.get('nickname', '') or request.POST.get('screen_name', '')
    avatar = request.POST.get('headimgurl', '') or request.POST.get('profile_image_url', '')
    country = request.POST.get('country', '')
    province = request.POST.get('province', '')
    city = request.POST.get('city', '')

    try:
        user = UserInfo.objects.get(unionid=unionid)
    except UserInfo.DoesNotExist:
        return response(TourGuideStatusCode.TOURGUIDE_NOT_FOUND)

    if user.user_status != UserInfo.ACTIVATED:
        return response(TourGuideStatusCode.TOURGUIDE_NOT_ACTIVATED)

    user.openid = openid
    user.sex = sex
    user.nickname = nickname
    user.avatar = avatar
    user.country = country
    user.province = province
    user.city = city
    user.save()

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