<template>
    <div :class="containerClass" :style="containerStyle">
        <template v-if="hasValidImages">
            <a-image-preview-group :preview="{ visible, onVisibleChange: vis => (visible = vis) }">
                <a-image :preview="preview" v-for="(url, index) in displayedImages" :src="url"
                    :key="index" v-bind="$attrs" />
            </a-image-preview-group>
        </template>
        <template v-else>
            <div :style="placeholderStyle">
                <div :style="placeholderContentStyle">
                    {{ firstLetter }}
                </div>
            </div>
        </template>
    </div>
</template>

<script>
export default {
    name: 'PaasImageViewer',
    inheritAttrs: false,
    props: {
        src: {
            type: [String, Object, Array],
            default: null
        },
        multiple: {
            type: Boolean,
            default: false
        },
        preview: {
            type: Boolean,
            default: false
        },
        isOpen: {
            type: Boolean,
            default: false
        },
        showUrl: {
            type: String,
            default: '/system/secure/minio/preview'
        },
        openShowUrl: {
            type: String,
            default: '/system/open/minio/preview'
        },
        // 布局方向属性
        direction: {
            type: String,
            default: 'normal', // 'normal' | 'horizontal' | 'vertical' | 'grid'
            validator: function (value) {
                return ['normal', 'horizontal', 'vertical', 'grid'].indexOf(value) !== -1;
            }
        },
        // 图片尺寸属性（仅在非normal模式下生效）
        imageSize: {
            type: Object,
            default: () => ({ width: 100, height: 100 })
        },
        // 网格列数
        gridColumns: {
            type: Number,
            default: 3
        },
        // 占位符文本
        placeholderText: {
            type: String,
            default: '暂无图片'
        },
        // 首字母来源文本（用于提取首字母显示）
        firstLetterSource: {
            type: String,
            default: ''
        },
        // 占位符背景颜色
        placeholderBgColor: {
            type: String,
            default: '#f0f0f0'
        },
        // 占位符文字颜色
        placeholderTextColor: {
            type: String,
            default: '#ffffff'
        },
        // 占位符文字大小
        placeholderTextSize: {
            type: String,
            default: '24px'
        },
        // 占位符文字粗细
        placeholderTextWeight: {
            type: [String, Number],
            default: '500'
        },
        // 是否使用渐变背景
        useGradient: {
            type: Boolean,
            default: true
        },
        // 渐变背景色
        gradientBackground: {
            type: String,
            default: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
        },
        // 组件宽度
        width: {
            type: [String, Number],
            default: '100%'
        },
        // 组件高度
        height: {
            type: [String, Number],
            default: 'auto'
        }
    },
    data() {
        return {
            processedImageUrls: [],
            visible: false
        };
    },
    computed: {
        currentShowUrl() {
            return this.isOpen ? this.openShowUrl : this.showUrl;
        },

        displayedImages() {
            if (!this.processedImageUrls.length) return [];
            return this.processedImageUrls;
        },

        hasValidImages() {
            return this.displayedImages.length > 0 && this.displayedImages.some(url => url && url.trim() !== '');
        },

        // 获取首字母
        firstLetter() {
            if (this.firstLetterSource) {
                return this.firstLetterSource.charAt(0);
            }
            return this.placeholderText.charAt(0);
        },

        // 容器类名
        containerClass() {
            return [
                'paas-image-viewer-container',
                `paas-image-viewer-${this.direction}`
            ];
        },

        // 容器样式
        containerStyle() {
            const style = {};

            // 设置容器的宽度和高度
            style.width = typeof this.width === 'number' ? `${this.width}px` : this.width;
            style.height = typeof this.height === 'number' ? `${this.height}px` : this.height;

            // 确保容器不会超出预期大小
            style.minWidth = '0';
            style.minHeight = '0';
            style.maxWidth = '100%';
            style.boxSizing = 'border-box';

            if (this.direction === 'grid') {
                style.display = 'grid';
                style['grid-template-columns'] = `repeat(${this.gridColumns}, 1fr)`;
            } else if (this.direction === 'horizontal') {
                style.display = 'flex';
                style['flex-direction'] = 'row';
                style['flex-wrap'] = 'wrap';
            } else if (this.direction === 'vertical') {
                style.display = 'flex';
                style['flex-direction'] = 'column';
            } else {
                // normal模式使用默认块级布局
                style.display = 'block';
            }

            style.gap = '8px';
            return style;
        },

        // 图片样式
        imageStyle() {
            // normal模式下图片占满容器
            if (this.direction === 'normal') {
                return {
                    width: '100%',
                    height: 'auto',
                    maxWidth: '100%',
                    objectFit: 'cover',
                    cursor: 'pointer',
                    borderRadius: '4px'
                };
            }

            // 其他模式使用指定尺寸
            return {
                width: `${this.imageSize.width}px`,
                height: `${this.imageSize.height}px`,
                objectFit: 'cover',
                cursor: 'pointer',
                borderRadius: '4px'
            };
        },

        // 占位符样式
        placeholderStyle() {
            const style = {
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                borderRadius: '4px',
                width: '100%',
                height: '100%',
                minHeight: '100%', // 确保占位符填充整个容器
                boxSizing: 'border-box'
            };

            // 如果启用渐变背景，则使用渐变背景色，否则使用纯色背景
            if (this.useGradient) {
                style.background = this.gradientBackground;
            } else {
                style.backgroundColor = this.placeholderBgColor;
            }

            return style;
        },

        // 占位符内容样式
        placeholderContentStyle() {
            return {
                color: this.placeholderTextColor,
                fontSize: this.placeholderTextSize,
                fontWeight: this.placeholderTextWeight,
                textAlign: 'center'
            };
        }
    },
    watch: {
        src: {
            handler(newVal, oldVal) {
                this.processImageUrls();
            },
            immediate: true,
            deep: true
        }
    },
    methods: {
        async processImageUrls() {
            if (!this.src || this.src === '[]') {
                this.processedImageUrls = [];
                return;
            }
            
            try {
                let data = this.src;

                if (typeof data === 'string') {
                    if (data.startsWith('{') || data.startsWith('[')) {
                        data = JSON.parse(data);
                    }
                }

                if (Array.isArray(data)) {
                    const urls = await Promise.all(data.map(item => this.extractImageUrl(item)));
                    this.processedImageUrls = urls.filter(url => url);
                } else {
                    const url = await this.extractImageUrl(data);
                    this.processedImageUrls = url ? [url] : [];
                }
            } catch (e) {
                console.warn('图片数据解析失败:', e);
                if (typeof this.src === 'string') {
                    this.processedImageUrls = [this.src];
                } else {
                    this.processedImageUrls = [];
                }
            }
        },

        async extractImageUrl(data) {
            if (!data) return '';

            if (Array.isArray(data)) {
                if (data.length === 0) return '';
                data = data[0];
            }

            if (data.newName) {
                try {
                    const params = {
                        filename: data.newName,
                        originalName: data.originalName || ''
                    };

                    const res = await this.$get(this.currentShowUrl, params);

                    if (res.data && (res.data.startsWith('http') || res.data.startsWith('/'))) {
                        return res.data;
                    } else if (res.data) {
                        return res.data;
                    } else {
                        console.warn('获取图片URL失败，返回数据为空');
                        return '';
                    }
                } catch (e) {
                    console.error('获取图片URL失败:', e);
                    return '';
                }
            }

            if (data.url) {
                return data.url;
            }

            if (data.src) {
                return data.src;
            }

            if (typeof data === 'string') {
                return data;
            }

            return '';
        }
    }
};
</script>

<style scoped>
.paas-image-viewer-container {
    width: 100%;
    height: 100%;
    min-width: 0;
    min-height: 0;
    max-width: 100%;
    box-sizing: border-box;
    overflow: hidden;
    object-fit: cover;
}
</style>