index.vue 12.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
<!--
 * @Date: 2022-09-19 14:11:06
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-07-03 21:32:33
 * @FilePath: /jgdl/src/pages/myFavorites/index.vue
 * @Description: 我的关注页面
-->
<template>
    <view class="flex flex-col bg-white min-h-screen">
        <!-- Favorites List -->
        <view class="flex-1">
            <!-- 滚动列表 -->
            <scroll-view
                class="favorites-list"
                :style="scrollStyle"
                :scroll-y="true"
                @scrolltolower="loadMore"
                @scroll="scroll"
                :lower-threshold="50"
                :enable-flex="false"
            >
                <view class="space-y-4">
                    <view
                        v-for="item in favorites"
                        :key="item.id"
                        @tap="() => onItemClick(item)"
                        style="border-bottom: 1px solid #e5e7eb"
                    >
                        <view class="flex p-4">
                            <view class="w-24 h-24 relative">
                                <image
                                    :src="item.imageUrl"
                                    :alt="item.name"
                                    mode="aspectFill"
                                    class="w-full h-full object-cover rounded-lg"
                                />
                            </view>
                            <view class="flex-1 ml-4">
                                <text class="font-medium text-base block">{{ item.name }}</text>
                                <text class="text-sm text-gray-500 mt-1 block">{{ item.details }}</text>
                                <view class="mt-2 flex justify-between items-center">
                                    <view>
                                        <text class="text-orange-500 font-bold">
                                            ¥{{ item.price.toLocaleString() }}
                                        </text>
                                        <text class="text-gray-400 text-xs line-through ml-2">
                                            ¥{{ item.originalPrice.toLocaleString() }}
                                        </text>
                                    </view>
                                    <nut-button
                                        @click.stop="handleUnfollowClick(item.id)"
                                        size="small"
                                        type="default"
                                        class="px-3 py-1 border border-gray-300 rounded-full text-sm"
                                    >
                                        取消关注
                                    </nut-button>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- Loading indicator -->
                <view v-if="loading" class="loading-container py-4 text-center">
                    <text class="loading-text text-gray-500">加载中...</text>
                </view>

                <!-- 没有更多数据 -->
                <view v-if="!hasMore && favorites.length > 0" class="no-more-container py-4 text-center">
                    <text class="text-gray-400 text-sm">没有更多数据了</text>
                </view>

                <!-- Empty State -->
                <view
                    v-if="favorites.length === 0 && !loading"
                    class="flex flex-col items-center justify-center h-64"
                >
                    <text class="text-gray-500">暂无关注的车辆</text>
                </view>
            </scroll-view>
        </view>


        <!-- Confirmation Modal -->
        <nut-dialog
            v-model:visible="showConfirmModal"
            title="温馨提示"
            content="确定要取消关注此车辆吗?"
            cancel-text="取消"
            ok-text="确认"
            @cancel="showConfirmModal = false"
            @ok="confirmUnfollow"
        />

        <!-- 成功提示 -->
        <nut-toast
            v-model:visible="toastVisible"
            :msg="toastMessage"
            :type="toastType"
        />
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import './index.less'

// ==================== API相关 ====================
/**
 * API服务 - 为真实API预留空间
 */
const apiService = {
    /**
     * 获取我的关注列表
     * @param {number} page - 页码
     * @param {number} pageSize - 每页数量
     * @returns {Promise} API响应
     */
    async getFavoritesList(page = 1, pageSize = 10) {
        // TODO: 替换为真实API调用
        // return await request.get('/api/favorites', { page, pageSize })

        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 800 + Math.random() * 400))

        // 模拟API响应数据
        return {
            code: 200,
            data: {
                list: generateMockData(page, pageSize),
                total: 50, // 模拟总数
                hasMore: page < 5 // 模拟是否还有更多数据
            },
            message: 'success'
        }
    },

    /**
     * 取消关注车辆
     * @param {string} carId - 车辆ID
     * @returns {Promise} API响应
     */
    async unfollowCar(carId) {
        // TODO: 替换为真实API调用
        // return await request.delete(`/api/favorites/${carId}`)

        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500))

        // 模拟API响应
        return {
            code: 200,
            data: null,
            message: '取消关注成功'
        }
    }
}

// ==================== 响应式数据 ====================
/**
 * 我的关注列表数据
 */
const favorites = ref([])

/**
 * 加载状态
 */
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)

/**
 * 确认弹窗显示状态
 */
const showConfirmModal = ref(false)

/**
 * 当前选中要取消关注的车辆ID
 */
const selectedId = ref(null)

/**
 * Toast提示
 */
const toastVisible = ref(false)
const toastMessage = ref('')
const toastType = ref('success')

/**
 * 滚动样式 - 考虑header和TabBar的高度
 */
const scrollStyle = computed(() => {
    return {
        height: 'calc(100vh)' // 减去header和TabBar的高度
    }
})

// ==================== 数据处理方法 ====================
/**
 * 生成模拟数据
 * @param {number} page - 页码
 * @param {number} size - 每页数量
 * @returns {Array} 模拟数据数组
 */
const generateMockData = (page, size) => {
    const brands = ['小牛', '雅迪', '绿源', '爱玛', '台铃', '新日', '立马', '小鸟']
    const models = ['豪华版', '标准版', '运动版', '经典版', '智能版', '动力版']
    const images = [
        'https://images.unsplash.com/photo-1558981285-6f0c94958bb6?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60',
        'https://images.unsplash.com/photo-1558981403-c5f9899a28bc?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60',
        'https://images.unsplash.com/photo-1591637333184-19aa84b3e01f?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60',
        'https://images.unsplash.com/photo-1558980664-3a031cf67ea8?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60',
        'https://images.unsplash.com/photo-1567922045116-2a00fae2ed03?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60',
        'https://images.unsplash.com/photo-1573981368236-719bbb6f70f7?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60'
    ]

    const data = []
    for (let i = 0; i < size; i++) {
        const index = (page - 1) * size + i
        const brand = brands[Math.floor(Math.random() * brands.length)]
        const model = models[Math.floor(Math.random() * models.length)]
        const image = images[Math.floor(Math.random() * images.length)]
        const originalPrice = Math.floor(Math.random() * 3000) + 3000
        const price = Math.floor(originalPrice * (0.7 + Math.random() * 0.2)) // 7-9折
        const usageTime = Math.floor(Math.random() * 24) + 1 // 1-24个月
        const range = Math.floor(Math.random() * 100) + 60 // 60-160km续航

        data.push({
            id: `fav_${index + 100}`,
            name: `${brand} ${model}`,
            details: `续航${range}km | 使用${usageTime}个月`,
            price: price,
            originalPrice: originalPrice,
            imageUrl: image,
            brand: brand,
            followTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString() // 最近30天内关注
        })
    }
    return data
}

/**
 * 初始化加载数据
 */
const initData = async () => {
    loading.value = true
    try {
        const response = await apiService.getFavoritesList(1, pageSize.value)
        if (response.code === 200) {
            favorites.value = response.data.list
            hasMore.value = response.data.hasMore
            currentPage.value = 1
        } else {
            showToast('加载失败,请重试', 'error')
        }
    } catch (error) {
        console.error('加载我的关注列表失败:', error)
        showToast('网络错误,请重试', 'error')
    } finally {
        loading.value = false
    }
}

/**
 * 加载更多数据
 */
const loadMore = async () => {
    if (loading.value || !hasMore.value) return

    loading.value = true
    try {
        const nextPage = currentPage.value + 1
        const response = await apiService.getFavoritesList(nextPage, pageSize.value)

        if (response.code === 200) {
            favorites.value.push(...response.data.list)
            hasMore.value = response.data.hasMore
            currentPage.value = nextPage
        } else {
            showToast('加载失败,请重试', 'error')
        }
    } catch (error) {
        console.error('加载更多数据失败:', error)
        showToast('网络错误,请重试', 'error')
    } finally {
        loading.value = false
    }
}

// ==================== 事件处理方法 ====================
/**
 * 点击车辆项目
 * @param {Object} item - 车辆信息
 */
const onItemClick = (item) => {
    // TODO: 跳转到车辆详情页
    Taro.navigateTo({
        url: `/pages/productDetail/index?id=${item.id}`
    })
}

/**
 * 处理取消关注点击事件
 * @param {string} id - 车辆ID
 */
const handleUnfollowClick = (id) => {
    selectedId.value = id
    showConfirmModal.value = true
}

/**
 * 确认取消关注
 */
const confirmUnfollow = async () => {
    if (!selectedId.value) return

    try {
        const response = await apiService.unfollowCar(selectedId.value)

        if (response.code === 200) {
            // 从列表中移除该项
            favorites.value = favorites.value.filter(item => item.id !== selectedId.value)
            showToast('取消关注成功', 'success')
        } else {
            showToast(response.message || '取消关注失败', 'error')
        }
    } catch (error) {
        console.error('取消关注失败:', error)
        showToast('网络错误,请重试', 'error')
    } finally {
        showConfirmModal.value = false
        selectedId.value = null
    }
}

/**
 * 滚动事件处理
 */
const scroll = (e) => {
    // 可以在这里处理滚动事件,比如记录滚动位置
}

/**
 * 显示提示信息
 */
const showToast = (message, type = 'success') => {
    toastMessage.value = message
    toastType.value = type
    toastVisible.value = true
}

// ==================== 生命周期 ====================
onMounted(() => {
    initData()
})
</script>

<script>
export default {
    name: "MyFavoritesPage",
};
</script>

<style lang="less" scoped>
// 自定义样式
.object-cover {
    object-fit: cover;
}

.line-through {
    text-decoration: line-through;
}

.favorites-list {
    .loading-container {
        display: flex;
        justify-content: center;
        align-items: center;

        .loading-text {
            font-size: 28rpx;
            color: #999;
        }
    }

    .no-more-container {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 32rpx 0;

        text {
            font-size: 24rpx;
            color: #ccc;
        }
    }
}

// 关注标签样式
.absolute {
    position: absolute;
}

.top-1 {
    top: 4rpx;
}

.right-1 {
    right: 4rpx;
}

.bg-red-500 {
    background-color: #ef4444;
}

.text-white {
    color: white;
}

.text-xs {
    font-size: 20rpx;
}

.px-1 {
    padding-left: 4rpx;
    padding-right: 4rpx;
}

.rounded {
    border-radius: 8rpx;
}

.flex {
    display: flex;
}

.items-center {
    align-items: center;
}
</style>