from apps.utils.serializers import CustomModelSerializer
from apps.em.models import Equipment, EcheckRecord, EInspect, Ecate, Repair
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
from rest_framework.exceptions import ParseError
from apps.wf.serializers import TicketSimpleSerializer


class EcateSerializer(CustomModelSerializer):
    class Meta:
        model = Ecate
        fields = "__all__"
        read_only_fields = EXCLUDE_FIELDS_BASE


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)
    cate_name = serializers.CharField(source="cate.name", read_only=True)
    cate_code = serializers.CharField(source="cate.code", read_only=True)
    full_name = serializers.SerializerMethodField()

    def validate(self, attrs):
        number = attrs.get("number", None)
        if number:
            eq = Equipment.objects.get_queryset(all=True).filter(number=number).first()
            if eq and eq.is_deleted:
                eq.is_deleted = False
                eq.save(update_fields=["is_deleted"])
                raise ParseError(f"{number}已存在并恢复")

        mgroup = attrs.get("mgroup", None)
        if mgroup:
            attrs["belong_dept"] = mgroup.belong_dept
        cate = attrs.get("cate", None)
        if cate:
            attrs["type"] = cate.type
        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", "running_state"]


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


class CdSerializer(serializers.Serializer):
    method = serializers.CharField(label="方法名")


class RepairCreateSerializer(CustomModelSerializer):
    class Meta:
        model = Repair
        fields = ["id", "equipment", "fault_description", "fault_cate"]

class RepairListSerializer(CustomModelSerializer):
    equipment_fullname = serializers.StringRelatedField(source="equipment", read_only=True)
    repair_user_name = serializers.CharField(source="repair_user.name", read_only=True)
    ticket_ = TicketSimpleSerializer(source="ticket", read_only=True)

    class Meta:
        model = Repair
        fields = "__all__"
        read_only_fields = EXCLUDE_FIELDS