from apps.utils.serializers import CustomModelSerializer
from apps.em.models import Equipment, EcheckRecord, EInspect
from apps.system.models import Dept
from apps.utils.constants import EXCLUDE_FIELDS, EXCLUDE_FIELDS_BASE
from rest_framework import serializers
from rest_framework.exceptions import ValidationError


class EquipmentSerializer(CustomModelSerializer):
    belong_dept = serializers.PrimaryKeyRelatedField(
        label='责任部门', queryset=Dept.objects.all())
    keeper_name = serializers.CharField(source='keeper.name', read_only=True)
    belong_dept_name = serializers.CharField(
        source='belong_dept.name', read_only=True)
    mgroup_name = serializers.CharField(source='mgroup.name', read_only=True)
    full_name = serializers.SerializerMethodField()

    def validate(self, attrs):
        mgroup = attrs.get('mgroup', None)
        if mgroup:
            attrs['belong_dept'] = mgroup.belong_dept
        return super().validate(attrs)

    def get_full_name(self, obj):
        return f'{obj.number}|{obj.name}|{obj.model}'

    class Meta:
        model = Equipment
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS + \
            ['check_date', 'next_check_date', 'keeper_name', 'belong_dept_name']


class EcheckRecordSerializer(CustomModelSerializer):
    equipment_name = serializers.StringRelatedField(source='equipment', read_only=True)

    class Meta:
        model = EcheckRecord
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS

    def validate(self, attrs):
        check_date = attrs['check_date']
        if EcheckRecord.objects.filter(check_date__gte=check_date, equipment=attrs['equipment']).exists():
            raise ValidationError('检定日期小于历史记录')
        return attrs


class EInspectSerializer(CustomModelSerializer):
    equipment_name = serializers.StringRelatedField(source='equipment', read_only=True)
    inspect_user_name = serializers.CharField(
        source='inspect_user.name', read_only=True)

    class Meta:
        model = EInspect
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS
