from django.contrib import auth
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.authentication import BasicAuthentication, TokenAuthentication
from .serializers import UserRegisterSerializer

from django.middleware.csrf import get_token
from django.contrib.auth import login

from api.utils import *
from api.models import File, Mission, Plan, Result
import requests

import json, csv

class Results(APIView):
    def get(self, request):
        user = request.user
        try:
            missionJson = json.loads(request.GET.get('mission'))
            print(missionJson)
            mission = Mission.objects.get(id=missionJson['id'])
            if not mission in user.own_missions.all():
                return failed(message="无该任务访问权限")
        except Mission.DoesNotExist:
            return failed(message="任务不存在")
        resultsData = []
        for plan in mission.own_plans.all():
            try:
                if not plan.parent:
                    # 根节点不是实际的plan，没有result
                    continue
                result = plan.own_result
                resultsData.append({
                    'planId': plan.id,
                    'progress': result.progress,
                    'resultId': result.id,
                })
            except Result.DoesNotExist:
                resultsData.append({
                    'planId': plan.id,
                    'progress': 0,
                    'resultId': 0,
                })
        return success(data=resultsData)
