<script>
import { ecosystem } from "../js/status"
import { Button, Icon, Toast } from 'vant'

export default {
    name: "service-info",
    components: {
        VanButton: Button,
        VanIcon: Icon
    },
    data() {
        return {
            layoutType: 'default', // 默认布局类型
            hasScrolled: false, // 记录是否已经滚动到指定位置
            // 默认数据，当ecosystem.services不可用时使用
            defaultBlocks: [
                { id: '1', position: '1', color: '#FF6B6B', text: '块一' },
                { id: '2', position: '2', color: '#4ECDC4', text: '块二' },
                { id: '3', position: '3', color: '#FFD166', text: '块三' },
                { id: '4', position: '4', color: '#FF6B6B', text: '块四' }
            ]
        }
    },
    computed: {
        blocks() {
            // 添加防御性编程，避免ecosystem.services或其子属性未定义时报错
            try {
                if (ecosystem && ecosystem.services && ecosystem.services.children) {
                    return ecosystem.services.children;
                }
            } catch (e) {
                console.error('获取ecosystem.services.children失败:', e);
            }
            return this.defaultBlocks;
        },
        // 根据路由参数计算当前应该使用的布局类型
        currentLayout() {
            const layoutType = this.$route.params.type || 'default';
            return `${layoutType}-layout`;
        },
        // 根据路由参数获取当前选中的块
        currentBlockId() {
            return this.$route.params.position;
        }
    },
    watch: {
        // // 监听路由参数变化
        // '$route.params': {
        //     handler(newParams) {
        //         if (newParams.position) {
        //             this.scrollToBlock();
        //         }
        //     },
        //     immediate: true
        // },
        // 监听当前块position变化
        'currentBlockId': function (newId) {
            if (newId) {
                this.scrollToBlock();
            }
        }
    },
    methods: {
        // 滚动到指定块
        scrollToBlock() {
            const position = this.currentBlockId;

            if (position) {
                // 重置滚动状态，确保每次都能滚动
                this.hasScrolled = false;

                // 强制回到顶部
                // window.scrollTo(0, 0);

                // 使用setTimeout确保 DOM 已经完全渲染
                this.$nextTick(() => {
                    // setTimeout(() => {
                    const element = document.getElementById(`block-${position}`);
                    if (element) {
                        // 滚动到元素位置
                        window.scrollTo({
                            top: element.offsetTop - 70,  // 偏移70px给顶部留出空间
                        });
                        this.hasScrolled = true;
                    }
                    // }, 800); // 添加短暂延迟确保DOM已更新
                });
            }
        },
        handleApplyClick() {
            const url = ecosystem.active.url 
            if (!url) {
                Toast({
                    message: "请联系您的业务员或致电95560",
                    position: "bottom"
                })
                return
            }
            globalThis.location.href = url
        },
        handleNavigator(position) {
            this.$router.replace({
                name: 'service-info',
                params: {
                    ecosystem: this.$route.params.ecosystem,
                    position: position
                }
            })
        },
        handleImageLoad() {
            const images = document.querySelectorAll('.block-image');
            const loadPromises = Array.from(images).map(img => {
                return new Promise(resolve => {
                    const checkInterval = setInterval(() => {
                        if (img.naturalHeight > 0) {
                            clearInterval(checkInterval);
                            resolve();
                        }
                    },50);
                });
            });

            Promise.all(loadPromises).then(() => {
                this.scrollToBlock()
            });

        }
    }, mounted() {
        this.handleImageLoad()
    }
}
</script>

<template>
    <div>
        <!-- 根据路由参数显示不同的布局 -->
        <div class="block-container" :class="currentLayout">
            <!-- 默认布局 -->
            <template>
                <div class="default-layout">
                    <div v-for="(block, index) in blocks" :key="index" :id="`block-${index + 1}`" class="image-block">
                        <div class="image-container">
                            <img :src="block.pic" v-if="block.pic && block.pic.startsWith('http')"
                                class="block-image" />
                            <div class="placeholder-image" v-else>
                                <van-icon name="photo-o" size="48" />
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </div>

        <div class="block-navigation">
            <h3>快速导航</h3>
            <div class="nav-buttons">
                <div v-for="(block, index) in blocks" :key="index" @click="handleNavigator(index + 1)"
                    class="nav-button" :class="{ 'active': (index + 1) === parseInt(currentBlockId) }">
                    跳到{{ index + 1 }}
                </div>
            </div>
        </div>

        <div class="actionButton">
            <div class="button-wrapper">
                <div class="button" @click="handleApplyClick">立即申请</div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.block-container {
    padding: 20px;
    background-color: #f8f8f8;
}

.link-block {
    margin-bottom: 15px;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s;
    cursor: pointer;
}

.image-block {
    margin-bottom: 30px;
    padding: 10px;
    border-radius: 8px;
    transition: all 0.3s;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    &.active {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
        border: 2px solid #1890ff;
    }
}

.image-container {
    width: 100%;
    // height: 200px;
    overflow: hidden;
    border-radius: 4px;
    margin-bottom: 10px;
    background-color: #f5f5f5;
}

.block-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s;

    &:hover {
        transform: scale(1.05);
    }
}

.placeholder-image {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background-color: #eee;
    color: #999;
}

.image-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    text-align: center;
    padding: 10px 0;
    margin-top: 10px;
}

/* 网格布局 */
.grid-layout {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;

    .grid-item {
        .color-block {
            height: 250px;
            /* 增加高度 */
        }
    }
}

/* 轮播布局 */
.carousel-layout {
    overflow-x: auto;
    white-space: nowrap;

    .carousel-inner {
        display: flex;

        .carousel-item {
            flex: 0 0 auto;
            width: 80%;
            margin-right: 15px;

            .color-block {
                height: 300px;
                /* 增加高度 */
            }
        }
    }
}

/* 堆叠布局 */
.stacked-layout {
    position: relative;
    height: 400px;
    /* 增加整体高度 */

    .stacked-item {
        position: absolute;
        width: 80%;

        .color-block {
            height: 300px;
            /* 增加高度 */
        }
    }
}

/* 默认布局 */
.default-layout {
    display: flex;
    flex-direction: column;
    gap: 20px;

    .color-block {
        height: 300px;
        /* 增加高度 */
    }
}

/* 布局信息 */
.layout-info {
    background-color: #f5f5f5;
    padding: 10px;
    margin: 10px 0;
    border-radius: 8px;
    font-size: 14px;
}

/* 导航区域样式 */
.block-navigation {
    margin: 20px 0;
    padding: 15px;
    background-color: #f8f8f8;
    border-radius: 8px;

    h3 {
        margin-top: 0;
        margin-bottom: 15px;
        color: #333;
        font-size: 16px;
    }

    .nav-buttons {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;

        .nav-button {
            padding: 8px 15px;
            background-color: #eee;
            border-radius: 4px;
            color: #333;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.2s;

            &:hover {
                background-color: #ddd;
            }

            &.active {
                background-color: #4ECDC4;
                color: white;
            }
        }
    }
}

/* 按钮样式 */
.actionButton {
    position: sticky;
    bottom: 0;
    display: flex;
    justify-content: center;
    width: 100%;
    padding: 10px 0;
    // background-color: rgba(255, 255, 255, 0.9);

    .button-wrapper {
        width: 50%;
        max-width: 300px;
        position: relative;
    }

    .button {
        position: relative;
        width: 100%;
        height: 44px;
        line-height: 44px;
        text-align: center;
        color: #fff;
        font-size: 16px;
        font-weight: 500;
        background: linear-gradient(to right, #ff6b6b, #ff3e3e);
        border-radius: 22px;
        box-shadow: 0 4px 8px rgba(255, 62, 62, 0.3);
        margin-bottom: 10px;
        overflow: hidden;

        &::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(to right, #ff5252, #ff1a1a);
            border-radius: 22px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        &:active::before {
            opacity: 1;
        }
    }
}
</style>