#微信小程序弹窗组件
from rest_framework import serializers
from .models import PopupImage, PopupConfig


class PopupImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PopupImage
        fields = ['url', 'text']  # 注意：前端需要 url 字段，我们序列化时映射 image_url -> url
        # 手动处理字段名映射

    url = serializers.CharField(source='image_url')


class PopupConfigSerializer(serializers.ModelSerializer):
    images = PopupImageSerializer(many=True, read_only=True)
    strategy = serializers.SerializerMethodField()

    class Meta:
        model = PopupConfig
        fields = ['popup_id', 'title', 'duration', 'force_even_muted', 'images', 'strategy']


    def get_strategy(self, obj):
        # 组装前端需要的 strategy 对象
        strategy = {
            'type': obj.strategy_type,
            'maxCount': obj.max_count,
        }
        if obj.reset_interval:
            strategy['resetInterval'] = obj.reset_interval
        return strategy