from rest_framework import serializers

from basic_info import models as basic_models
from business import services as business_services


class StatementWarehouseSerializer(serializers.ModelSerializer):
    """对账单中使用的仓库序列化器（输出完整仓库数据）"""

    type_label = serializers.CharField(source='get_type_display', read_only=True)
    mode_label = serializers.CharField(source='get_mode_display', read_only=True)

    class Meta:
        model = basic_models.WareHouse
        fields = '__all__'


class StatementRecordSerializer(serializers.Serializer):
    source_type = serializers.CharField()
    source_label = serializers.CharField()
    source_id = serializers.IntegerField()
    human_id = serializers.CharField()
    occurred_at = serializers.DateField()
    recorded_at = serializers.DateTimeField()
    status = serializers.IntegerField()
    status_label = serializers.CharField()
    counterparty = serializers.IntegerField()
    counterparty_name = serializers.CharField()
    warehouse = StatementWarehouseSerializer(allow_null=True)
    positive_amount = serializers.DecimalField(max_digits=15, decimal_places=2)
    negative_amount = serializers.DecimalField(max_digits=15, decimal_places=2)
    cumulative_amount = serializers.CharField()
    current_balance = serializers.CharField()
    arrears_amount = serializers.CharField()
    remarks = serializers.CharField(allow_blank=True)
    items = serializers.ListField(child=serializers.DictField())
    extra = serializers.DictField(required=False)


class StatementResponseSerializer(serializers.Serializer):
    counterparty = serializers.IntegerField()
    counterparty_name = serializers.CharField()
    records = StatementRecordSerializer(many=True)
    summary = serializers.SerializerMethodField()

    def get_summary(self, obj):
        summary_builder = self.context.get('summary_builder')
        if callable(summary_builder):
            return summary_builder(obj)
        return self.context.get('summary')

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if data.get('summary') is None:
            data.pop('summary', None)
        return data


class StatementRecordQuerySerializer(serializers.Serializer):
    """单条对账记录查询的参数序列化器"""

    counterparty_type = serializers.ChoiceField(
        choices=business_services.STATEMENT_COUNTERPARTY_CHOICES,
        help_text='客户/供应商类型（customer/supplier）',
    )
    counterparty_id = serializers.IntegerField(min_value=1, help_text='客户或供应商 ID')
    order_type = serializers.ChoiceField(
        choices=business_services.STATEMENT_ORDER_TYPE_CHOICES,
        help_text='来源单据类型（如 sales_order）',
    )
    order_id = serializers.IntegerField(min_value=1, help_text='来源单据 ID')

