<template>
    <div class="page-container">
        <!-- 固定顶部导航栏 -->
        <NavBar class="nav-bar" />
        <van-tabs @click="onClickTab">
            <van-tab v-for="tab in tagInfo" :title="tab.tagName" :key="tab.id" :name="tab.id">
            </van-tab>
        </van-tabs>
        <!-- 使用原生 sticky 定位的公告栏 -->
        <div class="sticky-notice">
            <van-notice-bar left-icon="volume-o" :scrollable="true" text="所有标价均为款式价格，如需延长需补差价喔~~~（半贴：￥90,浅贴：￥130）" />
        </div>

        <!-- 内容容器 -->
        <div class="cards-container">
            <div class="card_loading" v-if="this.card_loading"
                style="width: 100%;display: flex;justify-content: center;">
                <van-loading size="24px">加载中...</van-loading>
            </div>
            <div class="card-grid">
                <!-- 卡片列表 -->
                <div v-for="(card, index) in cards" :key="index" class="card"
                    :class="{ 'card-active': activeCardIndex === index }" @touchstart="handleTouchStart(index)"
                    @touchend="handleTouchEnd(index)" @click="handleCardClick(card)">

                    <div class="card-image-container">
                        <van-swipe :autoplay="3000">
                            <van-swipe-item v-for="(image, imgIndex) in card.images" :key="imgIndex">
                                <van-image lazy-load fit="fill" :src="image" class="card-image">
                                    <template v-slot:loading>
                                        <van-loading type="spinner" size="20" />
                                    </template>
                                </van-image>
                            </van-swipe-item>
                        </van-swipe>
                    </div>

                    <div class="card-content">
                        <h2 class="card-title">{{ card.title }}</h2>
                        <p class="card-description">{{ card.description }}</p>
                        <div class="card-tag">
                            <van-tag v-for="(tag, tagIndex) in card.tagInfo" :key="tagIndex" round type="primary"
                                :text-color="tag.tagColor" :color="tag.tagBgColor" style="margin-left: 5px;">
                                {{ tag.tagName }}
                            </van-tag>
                        </div>
                        <div class="card-footer">
                            <span class="card-meta">
                                <span>款式价格:￥</span><i class="fa fa-calendar-o mr-1"></i> {{ card.amt }}
                            </span>
                            <div class="heart" @click.stop>
                                <label class="action-btn heart-label">
                                    <input type="checkbox" class="heart-checkbox" v-model="card.checked"
                                        @change="handleClickLove(card)">
                                    <span class="heart-btn">
                                        <span class="heart-icon"></span>
                                    </span>
                                </label>
                                <span class="like-count">{{ card.loves }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="card_loading" v-if="this.card_loading1" style="width: 100%;display: flex;justify-content: center;">
            <van-loading size="24px">加载中...</van-loading>
        </div>
        <!-- 回到顶部按钮 -->
        <div v-show="showBackToTop" class="back-to-top" @click="backToTop">
            <van-icon name="arrow-up" size="16" color="#fff" />
        </div>
        <!-- 固定底部TabBar -->
        <TabBar class="tab-bar" />
    </div>
</template>

<script>
import TabBar from '@/components/TabBar.vue';
import NavBar from '@/components/NavBar.vue';
export default {
    name: 'PortfolioPage',
    components: {
        TabBar,
        NavBar
    },
    data() {
        return {
            cards: [],
            card_loading: false,
            card_loading1: false,
            activeCardIndex: -1,
            pageNum: 1,
            pageSize: 20,
            loading: false,
            changes: [],
            totalPages: 0,
            showBackToTop: false, // 控制回到顶部按钮显示/隐藏
            scrollContainer: null,
            scrollHandler: null,
            tagInfo: [{ "id": 0, "tagName": "全部" }],
            //标签转换成对象
            idToObjectMap: {},
            tagID: 0
        };
    },
    methods: {
        async getCarts(tagID, pageNum, size) {

            try {
                this.loading = true;
                let res = null;
                if (tagID == 0) {
                    res = await this.$axios.get('/portfolio/list', {
                        params: {
                            page: pageNum,
                            size: size
                        }
                    })
                } else {
                    res = await this.$axios.get('/portfolio/getPortfolioByTag', {
                        params: {
                            tagID: tagID,
                            page: pageNum,
                            size: size
                        }
                    })
                }
                if (res.code !== 200) {
                    const errorMsg = res.msg || '获取数据失败';
                    this.$toast.fail(errorMsg);
                    return;
                }

                const records = res.data.records || [];
                if (records.length === 0) {
                    this.$toast('没有更多数据了');
                    return;
                }

                const formattedCards = records.map(item => {
                    const images = item.imgFilename
                        ? item.imgFilename.split('&&').map(filename => `${item.imgUrl}/${filename}`)
                        : [];
                    let tagInfo = [];
                    for (let tagID of item.tagId.split("&&")) {
                        tagInfo.push(this.idToObjectMap[tagID])
                    }
                    console.log(">>>>");
                    
                    console.log(tagInfo);
                    
                    return {
                        id: item.id,
                        title: item.title,
                        description: item.description,
                        images,
                        duration: '',
                        tagInfo,
                        loves: item.loves || 0,
                        changes: 0,
                        checked: false,
                        amt: item.amt || 0,
                    };
                });
                this.cards = [...this.cards, ...formattedCards];
                this.loading = false;
                this.card_loading = false;
                this.card_loading1 = false;
                this.totalPages = res.data.pages;
                this.pageNum++;

            } catch (error) {
                console.error('获取卡片数据失败:', error);
                this.loading = false;
                this.card_loading = false;

                this.$toast.fail('网络错误，请稍后重试');
            }
        },
        async getTagInfo() {
            try {
                let res = await this.$axios.get('/tagInfo/getAll');
                if (res.code !== 200) {
                    const errorMsg = res.msg || '获取数据失败';
                    this.$toast.fail(errorMsg);
                    return;
                }
                this.tagInfo = [...this.tagInfo, ...res.data];
                // 创建映射对象

                res.data.forEach(obj => {
                    this.idToObjectMap[obj.id] = obj;
                });
            } catch (error) {
                console.error('获取标签信息失败:', error);
                this.$toast.fail('网络错误，请稍后重试');
            }

        },
        //标签点击事件
        onClickTab(name, title) {
            console.log(`标签 ${title} 被点击`);
            this.card_loading = true;
            this.cards = [];
            this.tagID = name;
            this.pageNum = 1;
            this.getCarts(this.tagID, this.pageNum, this.pageSize);
        },
        /**
         * 回到顶部
         * @param index 
         */
        handleTouchStart(index) {
            this.activeCardIndex = index;
        },
        /**
         * 处理触摸结束事件
         */
        handleTouchEnd() {
            setTimeout(() => {
                this.activeCardIndex = -1;
            }, 300);
        },
        /**
         * 卡片点击事件
         * @param card 点击的卡片
         */
        handleCardClick(card) {
            console.log('点击了卡片:', card.title);
        },
        /**
         * 点赞处理
         * @param card  点击的卡片
         */
        handleClickLove(card) {
            if (card.checked) {
                card.loves++;
                card.changes++;
            } else {
                if (card.loves > 0) {
                    card.loves--;
                    card.changes--;
                }
            }
            this.changes.push({
                id: card.id,
                changes: card.changes
            });
        },

        async savaLoveChanes() {
            for (const change of this.changes) {
                try {
                    await this.$axios.post('/portfolio/addLoves', null, {
                        params: {
                            id: change.id,
                            changes: change.changes
                        }
                    });
                } catch (error) {
                    console.error('保存点赞变化失败:', error);
                    this.$toast.fail('保存点赞状态失败，请稍后重试');
                }
            }
        },

        handleScroll() {
            if (!this.scrollContainer) return;
            const scrollTop = this.scrollContainer.scrollTop;
            // 当滚动距离超过300px时显示回到顶部按钮
            this.showBackToTop = scrollTop > 300;

            const clientHeight = this.scrollContainer.clientHeight;
            const scrollHeight = this.scrollContainer.scrollHeight;

            if (scrollTop + clientHeight >= scrollHeight - 50) {
                if (this.pageNum == this.totalPages) {
                    this.$toast.fail('已经到底啦~~');
                    return;
                }
                if (!this.loading && this.pageNum < this.totalPages) {
                    this.card_loading1 = true;
                    console.log(this.tagID);
                    this.getCarts(this.tagID, this.pageNum + 1, this.pageSize);
                    console.log('加载更多数据，当前页:', this.pageNum);
                }
            }
        },
        // 回到顶部方法
        backToTop() {
            if (!this.scrollContainer) return;

            // 使用平滑滚动回到顶部
            this.scrollContainer.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        }
    },
    mounted() {
        this.getTagInfo();
        this.tagID = 0;
        this.getCarts(this.tagID, this.pageNum, this.pageSize || 2);
        this.scrollContainer = document.querySelector('.cards-container');
        if (this.scrollContainer) {
            this.scrollHandler = () => this.handleScroll();
            this.scrollContainer.addEventListener('scroll', this.scrollHandler);
        }
    },
    beforeDestroy() {
        if (this.scrollContainer && this.scrollHandler) {
            this.scrollContainer.removeEventListener('scroll', this.scrollHandler);
        }
    },
    beforeRouteLeave(to, from, next) {
        next();
        this.savaLoveChanes();
    }
};
</script>
<style lang="less" scoped>
// 变量定义
@base-bg: #f9fafb;
@card-bg: white;
@text-primary: #1f2937;
@text-secondary: #6b7280;
@accent-color: #3b82f6;
@accent-dark: #2563eb;
@danger-color: #ef4444;
@gray-light: #d1d5db;
@shadow-base: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
@shadow-active: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);

// 页面容器（最外层）
.page-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    max-width: 800px;
    margin: 0 auto;

    // 粘性公告栏
    .sticky-notice {
        position: sticky;
        top: 50px;
        z-index: 100;
        margin-bottom: 10px;
    }

    // 卡片容器（滚动区域）
    .cards-container {
        padding: 10px;
        overflow: auto;

        // 卡片网格布局
        .card-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 5px;

            // // 移动端适配
            // @media (max-width: 600px) {
            //     grid-template-columns: 1fr;
            // }

            // 卡片样式（核心内容区）
            .card {
                background-color: @card-bg;
                border-radius: 16px;
                overflow: hidden;
                box-shadow: @shadow-base;
                transition: all 0.3s ease;
                cursor: pointer;
                padding-bottom: 5px;
                // 悬停与激活状态
                &:hover {
                    transform: translateY(-5px);
                    box-shadow: @shadow-active;
                }

                &.card-active {
                    transform: translateY(-5px);
                    box-shadow: @shadow-active;
                }

                // 卡片图片容器
                .card-image-container {
                    position: relative;

                    .card-image {
                        width: 100%;
                        min-height: 100px;
                    }

                    // 卡片标签
                    .card-tag {
                        transform: translateX(-5px);
                    }
                }

                // 卡片内容区（标题、描述、底部）
                .card-content {
                    padding: 5px;
                    position: relative;
                    // 卡片标题
                    .card-title {
                        padding-left: 5px;
                        font-size: 1.2rem;
                        font-weight: bold;
                        color: @text-primary;
                        margin-bottom: 10px;
                    }

                    // 卡片描述
                    .card-description {
                        padding-left: 5px;
                        color: @text-secondary;
                        text-wrap: balance;
                        margin-bottom: 10px;
                        line-height: 1.5;
                        font-size: 1rem;
                    }

                    // 卡片底部（价格与点赞）
                    .card-footer {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        margin-top: 12px;
                        position: relative;
                        bottom: 0px;

                        // 价格信息
                        .card-meta {
                            color: #FFFAFA;
                            font-weight: 500;
                            font-size: 0.9rem;
                            background-color: #8470FF;
                            border-radius: 8px;
                            padding: 5px;
                            // 日历图标
                            .fa {
                                margin-right: 1px;
                            }
                        }

                        // 点赞区域
                        .heart {
                            display: flex;
                            align-items: center;
                            gap: 4px;

                            // 点赞数量
                            .like-count {
                                font-size: 13px;
                                color: @text-secondary;
                            }

                            // 点赞按钮容器
                            .action-btn {
                                position: relative;
                                cursor: pointer;
                            }

                            // 隐藏原生复选框
                            .heart-checkbox {
                                position: absolute;
                                opacity: 0;
                                cursor: pointer;
                                height: 0;
                                width: 0;
                            }

                            // 点赞按钮样式
                            .heart-btn {
                                position: relative;
                                width: 10px;
                                height: 10px;
                                transition: transform 0.2s;
                                display: inline-flex;
                                align-items: center;
                                justify-content: center;

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

                            // 爱心图标
                            .heart-icon {
                                position: absolute;
                                top: 0;
                                left: -5px;
                                width: 100%;
                                height: 100%;
                                transition: color 0.3s;
                                display: flex;
                                align-items: center;
                                justify-content: center;

                                &::before {
                                    content: '❤';
                                    font-size: 1.25rem;
                                    color: @gray-light;
                                    transition: color 0.3s, transform 0.3s;
                                    position: relative;
                                    line-height: 1;
                                    vertical-align: middle;
                                    transform-origin: center;
                                }
                            }

                            // 选中状态（点赞效果）
                            .heart-checkbox:checked~.heart-btn .heart-icon::before {
                                color: @danger-color;
                                animation: heartBeat 0.5s cubic-bezier(0.17, 0.89, 0.32, 1.49);
                            }
                        }
                    }
                }
            }
        }

        // 加载动画（备用）
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100px;
        }
    }

    // 回到顶部按钮样式
    .back-to-top {
        position: fixed;
        bottom: 60px;
        right: 20px;
        background-color: rgba(243, 148, 227, 0.8); // 使用主色调
        width: 30px;
        height: 30px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        z-index: 100;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        transition: all 0.3s ease;

        &:hover {
            background-color: @accent-dark;
            transform: translateY(-2px);
        }
    }
}

// 爱心动画
@keyframes heartBeat {
    0% {
        transform: scale(1);
    }

    25% {
        transform: scale(1.3);
    }

    50% {
        transform: scale(1);
    }

    75% {
        transform: scale(1.2);
    }

    100% {
        transform: scale(1);
    }
}
</style>