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

from curtail_uuid import CurtailUUID
from django.contrib.auth.hashers import check_password, make_password
from django.contrib.auth.models import Group, User
from django.http import JsonResponse
from rest_framework import viewsets
from TimeConvert import TimeConvert as tc

from account.models import LensmanInfo, UserInfo, UserLoginLogInfo
from account.serializers import GroupSerializer, LensmanInfoSerializer, UserInfoSerializer, UserSerializer
from operation.models import GuestEntranceControlInfo
from utils.error.errno_utils import LensmanStatusCode, UserStatusCode
from utils.error.response_utils import response
from utils.ip_utils import ip_addr
from utils.redis.rversion import get_guest_entrance_control
from utils.version_utils import is_version_match


# curl -X POST -F username=xxxxxxx -F password=xxxxxxx http://api.pai.ai/login
def lensman_login_api(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')

    try:
        lensman = LensmanInfo.objects.get(username=username)
    except LensmanInfo.DoesNotExist:
        return response(LensmanStatusCode.LENSMAN_NOT_FOUND)

    if not check_password(password, lensman.encryption):
        return response(LensmanStatusCode.LENSMAN_PASSWORD_ERROR)

    return JsonResponse({
        'status': 200,
        'message': u'登录成功',
        'data': {
            'user': lensman.lensman_id
        },
    })


def user_is_registered_api(request):
    username = request.POST.get('username', '')
    return JsonResponse({
        'status': 200,
        'message': '',
        'data': {
            'registered': UserInfo.objects.filter(username=username).exists(),
        }
    })


def user_signup_api(request):
    user_id = request.POST.get('user_id', '')
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')

    if UserInfo.objects.filter(username=username).exists():
        return response(UserStatusCode.USERNAME_HAS_REGISTERED)

    # 判断 user_id 是否存在并且为分配用户，如果存在并且为分配用户，则直接在该帐户上更新，否则则直接创建帐户
    signup_ip, signup_at = ip_addr(request), tc.utc_datetime()

    try:
        user = UserInfo.objects.get(user_id=user_id)
    except UserInfo.DoesNotExist:
        user = None

    if user and user.user_status == UserInfo.ASSIGN:
        user.user_from = UserInfo.APP_USER,
        user.username = username
        user.password = make_password(password, None, 'pbkdf2_sha256')
        user.user_status = UserInfo.ACTIVATED
        user.signup_ip = signup_ip
        user.signup_at = signup_at
        user.save()
    else:
        user = UserInfo.objects.create(
            user_id=CurtailUUID.uuid(UserInfo, 'user_id'),
            user_from=UserInfo.APP_USER,
            username=username,
            password=make_password(password, None, 'pbkdf2_sha256'),
            user_status=UserInfo.ACTIVATED,
            signup_ip=signup_ip,
            signup_at=signup_at,
        )

    return JsonResponse({
        'status': 200,
        'message': u'注册成功',
        'data': user.data,
    })


def user_login_api(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')

    try:
        user = UserInfo.objects.get(username=username)
    except UserInfo.DoesNotExist:
        return response(UserStatusCode.USER_NOT_FOUND)

    login_ip, login_at = ip_addr(request), tc.utc_datetime()

    if not check_password(password, user.password):
        UserLoginLogInfo.objects.create(
            user_id=user.user_id,
            login_ip=login_ip,
            login_result=UserLoginLogInfo.PWD_ERROR
        )
        return response(UserStatusCode.USER_PASSWORD_ERROR)

    UserLoginLogInfo.objects.create(
        user_id=user.user_id,
        login_ip=login_ip,
        login_result=UserLoginLogInfo.SUCCESS
    )

    user.login_ip = login_ip
    user.login_at = login_at
    user.save()

    return JsonResponse({
        'status': 200,
        'message': u'登录成功',
        'data': user.data,
    })


def wx_authorize_api(request):
    user_id = request.POST.get('user_id', '')
    wx_uid = request.POST.get('wx_uid', '')

    unionid = request.POST.get('unionid', '')

    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', '')

    # 判断 wx_uid 是否已经存在，如果已经存在，则直接返回改帐户信息
    try:
        user = UserInfo.objects.get(wx_uid=wx_uid)
    except UserInfo.DoesNotExist:
        user = None

    if user:
        user.unionid = unionid
        user.sex = sex
        user.nickname = nickname
        user.avatar = avatar
        user.country = country
        user.province = province
        user.city = city
        user.save()

        return JsonResponse({
            'status': 200,
            'message': u'登录成功',
            'data': user.data,
        })

    # wx_uid 不存在
    # 判断 user_id 是否存在并且为分配用户，如果存在并且为分配用户，则直接在该帐户上更新，否则则直接创建帐户

    signup_ip, signup_at = ip_addr(request), tc.utc_datetime()

    try:
        user = UserInfo.objects.get(user_id=user_id)
    except UserInfo.DoesNotExist:
        user = None

    if user and user.user_status == UserInfo.ASSIGN:
        user.user_from = UserInfo.WX_USER
        user.wx_uid = wx_uid
        user.unionid = unionid
        user.sex = sex
        user.nickname = nickname
        user.avatar = avatar
        user.country = country
        user.province = province
        user.city = city
        user.signup_ip = signup_ip
        user.signup_at = signup_at
        user.save()
    else:
        user = UserInfo.objects.create(
            user_id=CurtailUUID.uuid(UserInfo, 'user_id'),
            user_from=UserInfo.WX_USER,
            wx_uid=wx_uid,
            unionid=unionid,
            sex=sex,
            nickname=nickname,
            avatar=avatar,
            country=country,
            province=province,
            city=city,
            user_status=UserInfo.ACTIVATED,
            signup_ip=signup_ip,
            signup_at=signup_at,
        )

    return JsonResponse({
        'status': 200,
        'message': u'登录成功',
        'data': user.data,
    })


def guest_status_api(request):
    """ 游客状态 """
    gen = get_guest_entrance_control()

    # 是否配置游客入口控制信息
    if not gen:
        return response(UserStatusCode.GUEST_NOT_ALLOWED)

    # 平台校验
    platform = gen.get('platform', '')
    if request.Android:
        if platform not in [GuestEntranceControlInfo.ADR, GuestEntranceControlInfo.BOTH]:
            return response(UserStatusCode.GUEST_NOT_ALLOWED)
    else:
        if platform not in [GuestEntranceControlInfo.IOS, GuestEntranceControlInfo.BOTH]:
            return response(UserStatusCode.GUEST_NOT_ALLOWED)

    # 版本校验
    if not is_version_match(request, gen):
        return response(UserStatusCode.GUEST_NOT_ALLOWED)

    return JsonResponse({
        'status': 200,
        'message': u'游客登录开启',
        'data': {},
    })


def guest_login_api(request):
    """ 游客登录 """
    gen = get_guest_entrance_control()

    # 是否配置游客入口控制信息
    if not gen:
        return response(UserStatusCode.GUEST_NOT_ALLOWED)

    # 平台校验
    platform = gen.get('platform', '')
    if request.Android:
        if platform not in [GuestEntranceControlInfo.ADR, GuestEntranceControlInfo.BOTH]:
            return response(UserStatusCode.GUEST_NOT_ALLOWED)
    else:
        if platform not in [GuestEntranceControlInfo.IOS, GuestEntranceControlInfo.BOTH]:
            return response(UserStatusCode.GUEST_NOT_ALLOWED)

    # 版本校验
    if not is_version_match(request, gen):
        return response(UserStatusCode.GUEST_NOT_ALLOWED)

    # 通用唯一识别码 (Universally Unique Identifier)
    uuid = request.POST.get('uuid', '')
    # 游客字段
    fields = {
        'user_id': CurtailUUID.uuid(UserInfo, 'user_id'),
        'user_from': UserInfo.GUEST_USER,
        'uuid': uuid,
        'nickname': u'游客',
        'user_status': UserInfo.ACTIVATED,
    }
    # 若 uuid 存在，则 get_or_create，否则 create
    if uuid:
        user, created = UserInfo.objects.get_or_create(user_from=UserInfo.GUEST_USER, uuid=uuid, defaults=fields)
        if created:
            user.nickname = u'游客{}'.format(user.pk)
            user.save()
    else:
        user = UserInfo.objects.create(**fields)
        user.nickname = u'游客{}'.format(user.pk)
        user.save()

    return JsonResponse({
        'status': 200,
        'message': u'游客登录成功',
        'data': user.data,
    })


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-pk')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


class LensmanInfoViewSet(viewsets.ModelViewSet):
    queryset = LensmanInfo.objects.all().order_by('-pk')
    serializer_class = LensmanInfoSerializer


class UserInfoViewSet(viewsets.ModelViewSet):
    queryset = UserInfo.objects.all().order_by('-pk')
    serializer_class = UserInfoSerializer
