<script lang="ts" setup>
import { computed, ref } from 'vue'
import { useScroll } from '@/hooks/useScroll'
import { safeAreaInsets } from '@/utils'
import { getCouponByType } from '../../api/home'
import SpendAndSaveCoupon from '../../components/spendAndSaveCoupon_large.vue'

definePage({
    style: {
        navigationBarTitleText: '',
        navigationStyle: 'custom',
        // 禁用默认下拉刷新
        enablePullDownRefresh: false,
    },
})

const params = ref()

// 使用内置的useScroll hooks
const {
    list: data, // 响应式的数据列表
    loading, // 是否加载中
    finished, // 是否已全部加载
    error, // 是否加载失败
    refresh: onRefresh, // 下拉刷新方法
    loadMore: onLoadMore, // 加载更多方法
} = useScroll({
    fetchData: async (page, pageSize) => {
        const response = await getCouponByType({
            pageNo: page,
            pageSize,
            ...params.value,
        })
        return response.records || []
    },
    pageSize: 7,
})

// 计算底部安全区高度
const safeBottomHeight = computed(() => {
    return safeAreaInsets?.bottom || 0
})

const topSafeAreaHeight = safeAreaInsets?.top || 0

// 页面加载时获取数据
onLoad((options) => {
    if (options.type) {
        params.value = options
        onRefresh()
    }
})
</script>

<template>
    <view class="page-container">
        <up-navbar title="满减券" :auto-back="true" />
        <up-status-bar />
        <scroll-view :style="{ paddingTop: `${topSafeAreaHeight}px` }" class="discount-coupon-list" scroll-y
            refresher-enabled :refresher-triggered="loading" @refresherrefresh="onRefresh" @scrolltolower="onLoadMore">
            <view class="list-content">
                <view v-for="item in data" :key="item.templateId" class="discount-coupon-item">
                    <SpendAndSaveCoupon :coupon="item" />
                </view>

                <!-- 加载状态提示 -->
                <view v-if="loading && data.length > 0" class="loadmore-container">
                    <up-loadmore status="loading" loading-text="努力加载中..." icon-size="18" />
                </view>
                <view v-else-if="finished && data.length > 0" class="loadmore-container">
                    <up-loadmore status="nomore" nomore-text="我们是有底线的" icon-size="18" />
                </view>
            </view>
        </scroll-view>

        <!-- 安全区底部占位 -->
        <view class="safe-bottom" :style="{ height: `${safeBottomHeight}px` }" />
    </view>
</template>

<style lang="scss" scoped>
.page-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.discount-coupon-list {
    flex: 1;
    overflow-y: auto;

    .list-content {
        padding-top: 20rpx;
        padding-left: 24rpx;
        padding-right: 24rpx;
        display: flex;
        flex-direction: column;
        gap: 20rpx;
    }

    .loadmore-container {
        padding: 30rpx 0;
        text-align: center;
    }
}

.safe-bottom {
    width: 100%;
    background-color: #fff;
}
</style>
