from apps.asm.models import Asset, AssetLog, AssetCate
from apps.utils.serializers import CustomModelSerializer
from apps.utils.constants import EXCLUDE_FIELDS_DEPT, EXCLUDE_FIELDS
from rest_framework import serializers
from apps.system.models import User
from apps.wf.serializers import TicketSimpleSerializer

class AssetCateSerializer(CustomModelSerializer):
    class Meta:
        model = AssetCate
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS

class AssetSerializer(CustomModelSerializer):
    keep_dept_name = serializers.CharField(source="keep_dept.name", read_only=True)
    keeper_name = serializers.CharField(source="keeper.name", read_only=True)
    cate_name = serializers.CharField(source="cate.name", read_only=True)
    class Meta:
        model = Asset
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS

class AssetCreateSerializer(CustomModelSerializer):
    class Meta:
        model = Asset
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS


class AssetLogSerializer(CustomModelSerializer):
    keeper_name = serializers.CharField(source="keeper.name", read_only=True)
    keep_dept_name = serializers.CharField(source="keep_dept.name", read_only=True)
    ticket_ = TicketSimpleSerializer(source="ticket", read_only=True)
    class Meta:
        model = AssetLog
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS_DEPT

class AssetLogCreateSerializer(CustomModelSerializer):
    class Meta:
        model = AssetLog
        fields = ["keep_dept", "start_date", "items", "keeper", "type"]
        extra_kwargs = {"start_date": {"required": True}, "keep_dept": {"required": True}}

    def to_internal_value(self, data):
        for item in data.get("items", []):
            if item.get("keeper", None) is None:
                item["keeper"] = data.get("keeper", None)
            if item.get("keep_dept", None) is None:
                item["keep_dept"] = data["keep_dept"]
            if item.get("start_date", None) is None:
                item["start_date"] = data["start_date"]
            item["state"] = "在用"
        return super().to_internal_value(data)
    
    def validate_items(self, value):
        AssetCreateSerializer(data=value, many=True).is_valid(raise_exception=True)
        return value