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

from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import redirect

from account.models import UserInfo
from operation.models import FeedbackInfo, SplashInfo
from utils.error.errno_utils import UserStatusCode
from utils.error.response_utils import response
from utils.redis.rapp import get_latest_app


def upgrade_api(request):
    """
    APP 升级
    :param request:
    :return:
    """
    latest_app = get_latest_app()

    if request.iOS:
        appinfo = {
            'latest_version_code': latest_app.get('latest_ios_version_code', ''),
            'latest_version_name': latest_app.get('latest_ios_version_name', ''),
            'latest_url': latest_app.get('latest_ios_url', ''),
        }
    else:
        appinfo = {
            'latest_version_code': latest_app.get('latest_adr_version_code', ''),
            'latest_version_name': latest_app.get('latest_adr_version_name', ''),
            'latest_url': latest_app.get('latest_adr_url', ''),
        }

    return JsonResponse({
        'status': 200,
        'message': u'获取最新版信息成功',
        'data': {
            'appinfo': appinfo,
        },
    })


def splash_api(request):
    """
    启动页面
    :param request:
    :return:
    """
    splashes = SplashInfo.objects.all()
    splashes = [splash.data for splash in splashes]

    return JsonResponse({
        'status': 200,
        'message': u'获取最新版信息成功',
        'data': {
            'splashes': splashes,
        },
    })


def feedback_api(request):
    """
    用户反馈
    :param request:
    :return:
    """
    user_id = request.POST.get('user_id', '')
    feedback = request.POST.get('feedback', '')

    if not UserInfo.objects.filter(user_id=user_id).exists():
        return response(UserStatusCode.USER_NOT_FOUND)

    FeedbackInfo.objects.create(
        user_id=user_id,
        feedback=feedback
    )

    return JsonResponse({
        'status': 200,
        'message': u'反馈成功',
        'data': {
        },
    })


def download_api(request):
    """
    下载接口
    :param request:
    :return:
    """
    if request.weixin:
        return redirect(settings.DOWNLOAD_WX_URL)
    if request.iOS:
        return redirect(settings.DOWNLOAD_IOS_URL)
    return redirect(get_latest_app().get('latest_adr_url', ''))
