from django.http import JsonResponse, HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from django.forms import modelformset_factory
from rest_framework.authtoken.models import Token  # 导入 Token 模型
import json
from datetime import timedelta
from django.utils import timezone
from authentication.models import CustomToken
from django.contrib.auth.hashers import check_password, make_password  # 导入密码哈希比较方法


from .models import EcUser, ContactInfo, SchoolInfo, AcademicInfo, HealthInfo,  SelfEvaluation
from .models import HobbiesInterests, SocialPractice, FamilyInfo, AwardsPunishments

from .forms import g_models, g_form_classes

from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from authentication.authentication import CustomTokenAuthentication



def index_test(request):
    return render(request, 'index.html')


def ec_login(request):
    if request.method != 'POST':
        return render(request, 'testlogin.html')
    
    try:
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
    except json.JSONDecodeError:
        return JsonResponse({'error': 'Invalid JSON'}, status=400)
    
    if not username or not password:
        return JsonResponse({'error': 'Missing username or password'}, status=400)
    
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        
        # 生成 Token（你可以选择使用自定义的 CustomToken）
        # token, created = Token.objects.get_or_create(user=user)  # 使用 DRF 提供的 Token 模型
        # 如果你使用的是自定义的 CustomToken
        token, created = CustomToken.objects.get_or_create(user=user, defaults={'extra_info': 'your_value', 'expiration_date': timezone.now() + timedelta(days=7)})
        if not created:
            token.expiration_date = timezone.now() + timedelta(days=7)
            token.save()

        return JsonResponse({'message': 'Login Success!', 'token': token.key})  # 返回 token
        
    else:
        return JsonResponse({'error': 'Login Failed!'}, status=401)

class MyProtectedUserLogout(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
    
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            # 删除与当前用户相关的 Token
            CustomToken.objects.filter(user=user).delete()

            # 进行登出操作
            logout(request)

            return JsonResponse({'message': 'Logout Successful'}, status=200)
        else:
            return JsonResponse({'error': 'User not authenticated'}, status=400)



def all_info_form(request, user_id):
    try:
        user = EcUser.objects.get(id=user_id)
    except EcUser.DoesNotExist:
        return render(request, 'error.html', {"message": "User not found"})

    instances = {}
    for key, model in g_models.items():
        if key in ['hobbies_interests', 'social_practice', 'family_info', 'awards_punishments']:
            instances[key] = model.objects.filter(user=user)  # 处理一对多关系
        else:
            instance, _ = model.objects.get_or_create(user=user)
            instances[key] = instance

    if request.method == 'GET':
        # 初始化所有表单
        forms = {}
        for form_key, form_class in g_form_classes.items():
            if form_key in ['hobbies_interests_form', 'social_practice_form', 'family_info_form', 'awards_punishments_form']:
                queryset = instances[form_key[:-5]]  # 获取对应模型的查询集

                # 如果查询集为空，设置 extra=1 来允许添加空表单
                if queryset.exists():
                    formset_class = modelformset_factory(queryset.model, form=form_class, extra=0)
                else:
                    formset_class = modelformset_factory(queryset.model, form=form_class, extra=1)
                
                # 使用 formset 渲染表单
                forms[form_key] = formset_class(queryset=queryset)
            else:
                forms[form_key] = form_class(instance=instances[form_key[:-5]])

        return render(request, 'all_info_form.html', {'user': user, **forms})

    else:
        return HttpResponse("Not implemented")


def all_info_edit(request, user_id, model_name):

    try:
        user = EcUser.objects.get(id=user_id)
    except EcUser.DoesNotExist:
        return render(request, 'error.html', {"message": "User not found"})

    instances = g_models[model_name].objects.filter(user=user)  # 处理一对多关系
    print(instances)
    formset_class = modelformset_factory(model=g_models[model_name], form=g_form_classes[model_name + '_form'], extra=0)
    formset = formset_class(request.POST, queryset=instances)
    print(instances)
    if formset.is_valid():
        instances = formset.save(commit=False)
        instances[0].user = user
        formset.save()
    else:
        return render(request, 'all_info_result.html', {'user': user, "model_name": model_name, "formset": formset})
    
    return render(request, 'all_info_result.html', {'user': user, "model_name": model_name, "formset": None})


# ================= API 接口 =================
# +++++++++++++++++++++++++++++++++++++++++++=


class MyProtectedUserInfo(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
    
    def get(self, request):
        # 返回用户的 ID、用户名、剩余次数和主题列表
        return JsonResponse({"user_id": request.user.id, 
                             "name": request.user.name,
                             "username": request.user.username, 
                             "remain_count": request.user.subject_usage_count,
                             "subject": list(request.user.subjects.values_list('name', flat=True)),
                             "fill_status": 
                                {
                                    "contact_info": ContactInfo.objects.filter(user=request.user).exists(),
                                    "scholar_info": SchoolInfo.objects.filter(user=request.user).exists(),
                                    "academic_info": AcademicInfo.objects.filter(user=request.user).exists(),
                                    "health_info": HealthInfo.objects.filter(user=request.user).exists(),
                                    "self_evaluation": SelfEvaluation.objects.filter(user=request.user).exists(),
                                    "family_info": FamilyInfo.objects.filter(user=request.user).exists(),
                                    "hobbies_interests": HobbiesInterests.objects.filter(user=request.user).exists(),
                                    "social_practice": SocialPractice.objects.filter(user=request.user).exists(),
                                    "awards_punishments": AwardsPunishments.objects.filter(user=request.user).exists(),
                                }
                             })



class MyProtectedBasicUserInfo(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
    
    def get(self, request):
        user = request.user
        # 获取用户信息并返回 JSON 格式
        user_info = EcUser.objects.filter(id=user.id).first()
        if user_info:
            response_data = {
                "name": user_info.name,
                "gender": user_info.get_gender_display(),
                "age": user_info.age,
                "ethnicity": user_info.ethnicity,
                "dob": user_info.dob,
                "id_card_number": user_info.id_card_number,
                "political_status": user_info.political_status
            }
            return JsonResponse(response_data)
        else:
            return JsonResponse({"error": "No user info found"}, status=404)

    def post(self, request):
        user = request.user
        # 处理 POST 请求，更新用户信息
        try:
            data = json.loads(request.body)
            name = data.get("name")
            gender = data.get("gender")
            age = data.get("age")
            ethnicity = data.get("ethnicity")
            dob = data.get("dob")
            id_card_number = data.get("id_card_number")
            political_status = data.get("political_status")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)

        # 查找或创建 EcUser
        try:
            user_info = EcUser.objects.get(id=user.id)
        except EcUser.DoesNotExist:
            return JsonResponse({"error": "User not found"}, status=404)

        # 更新用户信息
        user_info.name = name
        user_info.gender = gender
        user_info.age = age
        user_info.ethnicity = ethnicity
        user_info.dob = dob
        user_info.id_card_number = id_card_number
        user_info.political_status = political_status
        user_info.save()

        return JsonResponse({"message": "User info updated successfully"})


def api_contact_info_test(req):
    return render(req, 'api_contact_info_test.html')

class MyProtectedApiContactInfo(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
    
    def get(self, request):
        user = request.user
        # 获取联系信息并返回 JSON 格式
        contact_info = ContactInfo.objects.filter(user=user).first()
        if contact_info:
            response_data = {
                "home_address": contact_info.home_address,
                "parent_contact": contact_info.parent_contact,
                "student_contact": contact_info.student_contact,
                "email": contact_info.email
            }
            return JsonResponse(response_data)
        else:
            return JsonResponse({"error": "No contact info found"}, status=404)
    
    def post(self, request):
        user = request.user
        # 处理 POST 请求，更新用户的联系信息
        try:
            data = json.loads(request.body)
            home_address = data.get("home_address")
            parent_contact = data.get("parent_contact")
            student_contact = data.get("student_contact")
            email = data.get("email")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)

        # 查找或创建 ContactInfo
        contact_info, created = ContactInfo.objects.get_or_create(user=user)
        contact_info.home_address = home_address
        contact_info.parent_contact = parent_contact
        contact_info.student_contact = student_contact
        contact_info.email = email
        contact_info.save()

        return JsonResponse({"message": "Contact info updated successfully"})

def api_school_info_test(req):
    return render(req, 'api_school_info_test.html')

class MyProtectedApiSchoolInfo(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
        
    def get(self, request):
        user = request.user
        # 获取学校信息并返回 JSON 格式
        school_info = SchoolInfo.objects.filter(user=user).first()
        if school_info:
            response_data = {
                "school_name": school_info.school_name,
                "grade": school_info.grade,
                "class_name": school_info.class_name,
                "admission_date": school_info.admission_date,
                "expected_graduation_date": school_info.expected_graduation_date
            }
            return JsonResponse(response_data)
        else:
            return JsonResponse({"error": "No school info found"}, status=404)
    def post(self, request):
        user = request.user
        # 处理 POST 请求，更新学校信息
        try:
            data = json.loads(request.body)
            school_name = data.get("school_name")
            grade = data.get("grade")
            class_name = data.get("class_name")
            admission_date = data.get("admission_date")
            expected_graduation_date = data.get("expected_graduation_date")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)

        # 查找或创建 SchoolInfo
        school_info, created = SchoolInfo.objects.get_or_create(user=user)
        school_info.school_name = school_name
        school_info.grade = grade
        school_info.class_name = class_name
        school_info.admission_date = admission_date
        school_info.expected_graduation_date = expected_graduation_date
        school_info.save()

        return JsonResponse({"message": "School info updated successfully"})



def api_academic_info_test(req):
    return render(req, 'api_academic_info_test.html')


class MyProtectedApiAcademicInfo(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
        
    def get(self, request):
        user = request.user
        
        # 获取学习情况信息并返回 JSON 格式
        academic_info = AcademicInfo.objects.filter(user=user).first()
        if academic_info:
            response_data = {
                "last_semester_score": str(academic_info.last_semester_score),
                "this_semester_score": str(academic_info.this_semester_score),
                "class_ranking": academic_info.class_ranking,
                "strong_subject": academic_info.strong_subject,
                "weak_subject": academic_info.weak_subject
            }
            return JsonResponse(response_data)
        else:
            return JsonResponse({"error": "No academic info found"}, status=404)

    def post(self, request):
        user = request.user
        # 处理 POST 请求，更新用户的学习情况信息
        try:
            data = json.loads(request.body)
            last_semester_score = data.get("last_semester_score")
            this_semester_score = data.get("this_semester_score")
            class_ranking = data.get("class_ranking")
            strong_subject = data.get("strong_subject")
            weak_subject = data.get("weak_subject")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)

        # 查找或创建 AcademicInfo
        academic_info, created = AcademicInfo.objects.get_or_create(user=user)
        academic_info.last_semester_score = last_semester_score
        academic_info.this_semester_score = this_semester_score
        academic_info.class_ranking = class_ranking
        academic_info.strong_subject = strong_subject
        academic_info.weak_subject = weak_subject
        academic_info.save()

        return JsonResponse({"message": "Academic info updated successfully"})



def api_health_info_test(req):
    return render(req, 'api_health_info_test.html')


class MyProtectedApiHealthInfo(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
        
    def get(self, request):
        user = request.user
        
        # 获取健康信息并返回 JSON 格式
        health_info = HealthInfo.objects.filter(user=user).first()
        if health_info:
            response_data = {
                "height": str(health_info.height),
                "weight": str(health_info.weight),
                "blood_type": health_info.blood_type,
                "medical_history": health_info.medical_history,
                "disability_status": health_info.disability_status,
                "disability_category": health_info.disability_category,
                "disability_grade": health_info.disability_grade
            }
            return JsonResponse(response_data)
        else:
            return JsonResponse({"error": "No health info found"}, status=404)

    def post(self, request):

        user = request.user
        # 处理 POST 请求，更新用户的健康信息
        try:
            data = json.loads(request.body)
            height = data.get("height")
            weight = data.get("weight")
            blood_type = data.get("blood_type")
            medical_history = data.get("medical_history")
            disability_status = data.get("disability_status")
            disability_category = data.get("disability_category")
            disability_grade = data.get("disability_grade")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)

        # 查找或创建 HealthInfo
        health_info, created = HealthInfo.objects.get_or_create(user=user)
        health_info.height = height
        health_info.weight = weight
        health_info.blood_type = blood_type
        health_info.medical_history = medical_history
        health_info.disability_status = disability_status
        health_info.disability_category = disability_category
        health_info.disability_grade = disability_grade
        health_info.save()

        return JsonResponse({"message": "Health info updated successfully"})


def api_self_evaluation_test(req):
    return render(req, 'api_self_evaluation_test.html')

class MyProtectedApiSelfEvaluationInfo(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
            
    def get(self, request):
        user = request.user

        # 获取自我评价信息并返回 JSON 格式
        self_evaluation = SelfEvaluation.objects.filter(user=user).first()
        if self_evaluation:
            response_data = {
                "strengths": self_evaluation.strengths,
                "weaknesses": self_evaluation.weaknesses,
                "study_attitude": self_evaluation.study_attitude,
                "future_plans": self_evaluation.future_plans
            }
            return JsonResponse(response_data)
        else:
            return JsonResponse({"error": "No self evaluation found"}, status=404)

    def post(self, request):
        user = request.user

        # 处理 POST 请求，更新用户的自我评价信息
        try:
            data = json.loads(request.body)
            strengths = data.get("strengths")
            weaknesses = data.get("weaknesses")
            study_attitude = data.get("study_attitude")
            future_plans = data.get("future_plans")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)

        # 查找或创建 SelfEvaluation
        self_evaluation, created = SelfEvaluation.objects.get_or_create(user=user)
        self_evaluation.strengths = strengths
        self_evaluation.weaknesses = weaknesses
        self_evaluation.study_attitude = study_attitude
        self_evaluation.future_plans = future_plans
        self_evaluation.save()

        return JsonResponse({"message": "Self evaluation updated successfully"})
    

# =================== 以下字段是 一对多 ===================
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++

def api_hobbies_interests_test(req):
    return render(req, 'api_hobbies_interests_test.html')

class MyProtectedApiHobbiesInterests(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
    def get(self, request):
        user = request.user

        # 获取该用户的所有兴趣爱好信息
        hobbies_interests = HobbiesInterests.objects.filter(user=user)
        if hobbies_interests.exists():
            response_data = []
            for entry in hobbies_interests:
                response_data.append({
                    "interests": entry.interests,
                    "extracurricular_activities": entry.extracurricular_activities
                })
            return JsonResponse(response_data, safe=False)
        else:
            return JsonResponse({"error": "No hobbies and interests found"}, status=404)

    def post(self, request):
        user = request.user
        # 处理 POST 请求，创建新的兴趣爱好记录
        try:
            data = json.loads(request.body)
            interests = data.get("interests")
            extracurricular_activities = data.get("extracurricular_activities")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)

        # 创建新的 HobbiesInterests 记录
        new_entry = HobbiesInterests.objects.create(
            user=user,
            interests=interests,
            extracurricular_activities=extracurricular_activities
        )
        return JsonResponse({"message": "Hobbies and interests added successfully"})


def api_social_practice_test(req):
    return render(req, 'api_social_practice_test.html')

class MyProtectedSocialPractice(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
        
    def get(self, request):
        user = request.user

        # 获取该用户的所有社会实践记录
        social_practices = SocialPractice.objects.filter(user=user)
        if social_practices.exists():
            response_data = []
            for entry in social_practices:
                response_data.append({
                    "activity_name": entry.activity_name,
                    "activity_date": entry.activity_date,
                    "activity_location": entry.activity_location,
                    "activity_description": entry.activity_description,
                    "activity_outcome": entry.activity_outcome
                })
            return JsonResponse(response_data, safe=False)
        else:
            return JsonResponse({"error": "No social practice records found"}, status=404)

    def post(self, request):
        user = request.user
        # 处理 POST 请求，创建新的社会实践记录
        try:
            data = json.loads(request.body)
            activity_name = data.get("activity_name")
            activity_date = data.get("activity_date")
            activity_location = data.get("activity_location")
            activity_description = data.get("activity_description")
            activity_outcome = data.get("activity_outcome")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)

        # 创建新的 SocialPractice 记录
        new_entry = SocialPractice.objects.create(
            user=user,
            activity_name=activity_name,
            activity_date=activity_date,
            activity_location=activity_location,
            activity_description=activity_description,
            activity_outcome=activity_outcome
        )
        return JsonResponse({"message": "Social practice record added successfully"})


def api_family_info_test(req):
    return render(req, 'api_family_info_test.html')

class MyProtectedFamilyInfo(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
      
    def get(self, request):
        user = request.user

        # 获取该用户的家庭情况记录
        family_info = FamilyInfo.objects.filter(user=user).first()
        if family_info:
            response_data = {
                "family_member": family_info.family_member,
                "economic_status": family_info.economic_status
            }
            return JsonResponse(response_data)
        else:
            return JsonResponse({"error": "No family info found"}, status=404)

    def post(self, request):
        user = request.user
        # 处理 POST 请求，创建或更新家庭情况记录
        try:
            data = json.loads(request.body)
            family_member = data.get("family_member")
            economic_status = data.get("economic_status")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)

        # 创建或更新 FamilyInfo 记录
        family_info, created = FamilyInfo.objects.get_or_create(user=user)
        family_info.family_member = family_member
        family_info.economic_status = economic_status
        family_info.save()

        return JsonResponse({"message": "Family info updated successfully"})


def api_awards_punishments_test(req):
    return render(req, 'api_awards_punishments_test.html')

class MyProtectedAwardsPunishments(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
     
    def get(self, request):
        user = request.user

        # 获取该用户的奖惩情况记录
        awards_punishments = AwardsPunishments.objects.filter(user=user)
        if awards_punishments.exists():
            response_data = [
                {
                    "award_name": ap.award_name,
                    "award_date": ap.award_date,
                    "award_organization": ap.award_organization,
                    "discipline_date": ap.discipline_date,
                    "discipline_issue": ap.discipline_issue,
                    "discipline_outcome": ap.discipline_outcome
                } for ap in awards_punishments
            ]
            return JsonResponse(response_data, safe=False)
        else:
            return JsonResponse({"error": "No awards or punishments found"}, status=404)

    def post(self, request):
        user = request.user
        # 处理 POST 请求，创建或更新奖惩情况记录
        try:
            data = json.loads(request.body)
            award_name = data.get("award_name")
            award_date = data.get("award_date")
            award_organization = data.get("award_organization")
            discipline_date = data.get("discipline_date")
            discipline_issue = data.get("discipline_issue")
            discipline_outcome = data.get("discipline_outcome")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)

        # 创建或更新 AwardsPunishments 记录
        awards_punishment = AwardsPunishments.objects.create(
            user=user,
            award_name=award_name,
            award_date=award_date,
            award_organization=award_organization,
            discipline_date=discipline_date,
            discipline_issue=discipline_issue,
            discipline_outcome=discipline_outcome
        )

        return JsonResponse({"message": "Awards and punishments info updated successfully"})
