import os 
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import FileUploadParser
from kedong.settings import MEDIA_ROOT
import time
import logging
from datetime import datetime
from django.conf import settings
from smartfarming.models.agriculture import APKLogs
from smartfarming.serializers.apk_serializers import APKLogsSerializers


config = settings.CONFIG

logger = logging.getLogger("myapp")

class NewUploadAPIView(APIView):
    # 上传apk文件
    def post(self, request):
        server_web = config.get("server_web")
        local_path = os.path.join(MEDIA_ROOT, "app")
        os.mkdir(local_path) if not os.path.exists(local_path) else None 
        file_obj = request.data['file']
        if file_obj.size > 1024 * 1024 * 200:
            return Response({"code": 2, "msg": "请上传小于200M文件"})
        try:
            proxy_front = f'{server_web}/media/app'
            stamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
            file_name = "kedong." + ((file_obj.name).split("."))[-1]
            file = os.path.join(local_path, file_name)
            old_file_name = f"{str(stamp)}-{file_name}"
            real_url = os.path.join(local_path, old_file_name)
            if os.path.exists(file):
                os.rename(file, real_url)
                download_url = f"{proxy_front}/{old_file_name}"
                app = APKLogs.objects.all().order_by("-upltime")
                if app:
                    app = app.first()
                    app.history_apk = download_url
                    app.save()
            with open(file, 'wb') as f:
                for chunk in file_obj.chunks():
                    f.write(chunk)
            url = f'{proxy_front}/{file_name}'
            return Response({"url": url, "old_url": download_url, "code": 0, "msg": "success"})
        except Exception as e:
            logger.error(e)
            return Response({"code": 2, "msg": "APK保存失败，请检查或重试"})


class APKUploadView(APIView):
    # 保存app信息
    def post(self, request):
        try:
            request_data = request.data
            apk = request_data.get('apk')
            history_qr_code = request_data.get('history_qr_code')
            mark = request_data.get("mark")
            app = APKLogs()
            app.history_apk = apk if apk else ""
            app.history_qr_code = history_qr_code if history_qr_code else ""
            app.mark = mark if mark else ""
            app.upltime = int(time.time())
            app.save()
            return Response({"code": 0, "msg": "success"})
        except Exception as e:
            logger.error(e)
            return Response({"code": 1, "msg": "保存失败"})


class APPListAPIView(APIView):
    # app信息列表
    def post(self, request):
        queryset = APKLogs.objects.all().order_by("-upltime")
        serializers = APKLogsSerializers(queryset, many=True)
        return Response({"code": 0, "msg": "success", "data": serializers.data})

