from django.db.models.base import Model
from rest_framework import serializers
from .models import *
from apps.system.serializers import OrganizationSerializer,FileListSerializer,UserSimpleSerializer,OrganizationSimpleSerializer, FileSimpleSerializer


class ContentSerializer(serializers.ModelSerializer):
    type_ = serializers.SerializerMethodField()
    class Meta:
        model = Content
        fields = '__all__'
    
    @staticmethod
    def setup_eager_loading(queryset):
        """ Perform necessary eager loading of data. """
        queryset = queryset.select_related('type')
        return queryset
    
    def get_type_ (self, obj):
        data = obj.type.name
        if obj.type.pid:
            data = obj.type.pid.name + '/' + data
        return data

class ContentListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Content
        fields = ['name', 'desc', 'id']

class TaskCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ['name', 'end_date', 'note', 'id']

class TaskListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ['name', 'end_date', 'note', 'up_rate', 'state', 'id', 'confirm_rate']
        
class RecordSerializer(serializers.ModelSerializer):
    task_ = TaskListSerializer(source='task')
    belong_dept_ = OrganizationSimpleSerializer(source='belong_dept', read_only=True)
    files_ = FileSimpleSerializer(source='files', many=True, read_only=True)
    up_user_ = UserSimpleSerializer(source='up_user', read_only = True)
    class Meta:
        model = Record
        fields = '__all__'
    
    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('task', 'content', 'belong_dept', 'up_user')
        queryset = queryset.prefetch_related('files',)
        return queryset

class RecordCreateUpdateSerializer(serializers.ModelSerializer):
    pass


class TaksDetailSerializer(serializers.ModelSerializer):
    create_by_ = UserSimpleSerializer(source='create_by', read_only = True)
    belong_dept_ = OrganizationSimpleSerializer(source='belong_dept', read_only=True)
    class Meta:
        model = Task
        fields = '__all__'

class TaskDeptSerializer(serializers.ModelSerializer):
    dept_ = OrganizationSimpleSerializer(source='dept', read_only=True)

    class Meta:
        model = TaskDept
        fields = '__all__'