from apps.system.serializers import UserSimpleSerializer
import rest_framework
from rest_framework import serializers

from .models import State, Ticket, TicketFlow, Workflow, Transition, CustomField


class WorkflowSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workflow
        fields = '__all__'

class StateSerializer(serializers.ModelSerializer):
    class Meta:
        model = State
        fields = '__all__'

class WorkflowSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workflow
        fields = ['id', 'name']

class StateSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = State
        fields = ['id', 'name']

class TransitionSerializer(serializers.ModelSerializer):
    source_state_ = StateSimpleSerializer(source='source_state', read_only=True)
    destination_state_ = StateSimpleSerializer(source='destination_state', read_only=True)
    class Meta:
        model = Transition
        fields = '__all__'
    @staticmethod
    def setup_eager_loading(queryset):
        """ Perform necessary eager loading of data. """
        queryset = queryset.select_related('source_state','destination_state')
        return queryset


class CustomFieldSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomField
        fields = '__all__'

class TicketSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ticket
        fields = '__all__'

class TicketCreateSerializer(serializers.ModelSerializer):
    transition = serializers.IntegerField(label='流转ID')
    class Meta:
        model=Ticket
        fields=['title','workflow','ticket_data', 'transition']
    
    def create(self, validated_data):
        validated_data.pop('transition')
        return super().create(validated_data)

class TicketSerializer(serializers.ModelSerializer):
    workflow_ = WorkflowSimpleSerializer(source='workflow', read_only=True)
    state_ = StateSimpleSerializer(source='state', read_only=True)

    class Meta:
        model = Ticket
        fields = '__all__'
    
    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('workflow','state')
        return queryset

class TicketFlowSerializer(serializers.ModelSerializer):
    participant_ = UserSimpleSerializer(source='participant', read_only=True)
    state_ = StateSimpleSerializer(source='state', read_only=True)
    class Meta:
        model = TicketFlow
        fields = '__all__'

    