from re import template
from django.db.models.base import Model
from rest_framework import serializers
from .models import *
from apps.system.serializers import FileSerializer, OrganizationSerializer,FileListSerializer,UserSimpleSerializer,OrganizationSimpleSerializer, FileSimpleSerializer
from rest_framework.exceptions import ParseError, APIException

class DocumentSerializer(serializers.ModelSerializer):

    file_ = FileSerializer(source='file', read_only=True)
    class Meta:
        model = Document
        fields = '__all__'
    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('file')
        return queryset

class InspectItemSerializer(serializers.ModelSerializer):
    cate_name = serializers.StringRelatedField(source='cate', read_only=True)
    class Meta:
        model = InspectItem
        fields = '__all__'
    
    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('cate')
        return queryset

class InspectItemSimpleSerializer(serializers.ModelSerializer):
    # cate_name = serializers.StringRelatedField(source='cate', read_only=True)
    class Meta:
        model = InspectItem
        fields = ['id', 'name', 'type', 'sortnum']
    
    # @staticmethod
    # def setup_eager_loading(queryset):
    #     queryset = queryset.select_related('cate')
    #     return queryset


class InspectTaskSerializer(serializers.ModelSerializer):
    create_by_ = UserSimpleSerializer(source='create_by', read_only=True)
    dept_count = serializers.SerializerMethodField()
    subtask_count = serializers.SerializerMethodField()
    template_name = serializers.CharField(source='template.name', read_only=True)

    class Meta:
        model = InspectTask
        fields = '__all__'
    
    def get_dept_count(self, obj):
        return InspectDept.objects.filter(subtask__inspecttask=obj, is_deleted=False).count()

    def get_subtask_count(self, obj):
        return SubInspectTask.objects.filter(inspecttask=obj, is_deleted=False).count()

    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('template',)
        return queryset

class InspectTaskSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = InspectTask
        fields = ['id', 'name', 'start_date', 'end_date']

class SubtaskListSerializer(serializers.ModelSerializer):
    inspecttask_ = InspectTaskSimpleSerializer(source='inspecttask', read_only=True)
    members = serializers.SerializerMethodField()
    depts_count = serializers.SerializerMethodField()
    class Meta:
        model = SubInspectTask
        fields = '__all__'
    
    def get_members(self, obj):
        return obj.team_subtask.values('member', 'member__name', 'type')

    def get_depts_count(self, obj):
        return obj.dept_subtask.count()
    

    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('inspecttask',)
        queryset = queryset.prefetch_related('team_subtask','dept_subtask')
        return queryset


class InspectRecordListSerializer(serializers.ModelSerializer):
    item_ = InspectItemSimpleSerializer(source='item', read_only=True)
    checker_ = UserSimpleSerializer(source='checker', read_only=True)
    class Meta:
        model = InspectRecord
        exclude = ['imgs']
    
    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('item', 'checker')
        return queryset

class InspectRecordDetailSerializer(serializers.ModelSerializer):
    item_ = InspectItemSerializer(source='item', read_only=True)
    checker_ = UserSimpleSerializer(source='checker', read_only=True)
    imgs_ = FileSimpleSerializer(source='imgs', many=True, read_only=True)
    class Meta:
        model = InspectRecord
        fields = '__all__'

    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('item', 'checker')
        queryset = queryset.prefetch_related('imgs',)
        return queryset

class InspectTeamSerializer(serializers.ModelSerializer):
    member__name = serializers.CharField(source='member.name', read_only=True)
    class Meta:
        model = InspectTeam
        fields = '__all__'

    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('member')
        return queryset

    def create(self, validated_data):
        if InspectTeam.objects.filter(subtask=validated_data.get('subtask'),member=validated_data.get('member')).exists():
            raise ParseError('成员已存在')
        if validated_data.get('type') == '组长':
            obj = InspectTeam.objects.get(type='组长', subtask=validated_data.get('subtask'))
            obj.type='组员'
            obj.save()
        return InspectTeam.objects.create(**validated_data)



class InspectDeptSerializer(serializers.ModelSerializer):
    dept__name = serializers.CharField(source='dept.name', read_only=True)
    leader = serializers.SerializerMethodField()
    class Meta:
        model = InspectDept
        fields = ('dept', 'dept__name', 'state', 'subtask', 'id', 'note', 'leader', 'start_date')

    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('dept', 'subtask')
        return queryset
    
    def get_leader(self, obj):
        try:
            pk = InspectTeam.objects.get(subtask=obj.subtask, type='组长').member.pk
            return pk
        except:
            return None


class InspectRecordCheckSerializer(serializers.ModelSerializer):
    """
    提交检查结果序列化
    """
    class Meta:
        model = InspectRecord
        fields = ['id', 'result', 'note', 'imgs']
    
    def validate_result(self, result):
        if result:
            if result == '发现':
                if not (self.initial_data['note'] or self.initial_data['imgs']):
                    raise ParseError('发现问题请填写说明或上传图片')
        else:
            raise ParseError('未填写检查结果')
        return result
    
class InspectTemplateSerializer(serializers.ModelSerializer):
    class Meta:
        model = InspectTemplate
        fields = '__all__'
