<script lang="ts" setup>
import { usePagination, useRequest } from 'alova/client'
import { storeToRefs } from 'pinia'
import { computed, ref, watch } from 'vue'
import { getAccountCount } from '@/api/home'
import { getCouponIssuerAccountByPageMap } from '@/api/income'
import IncomeItem from '@/components/IncomeItem.vue'
import MescrollUni from '@/components/mescroll.vue'
import { useShare } from '@/hooks/useShare'
import { useUserStore } from '@/store'
import { useTokenStore } from '@/store/token'
import { changtime, menuButtonInfo, rpxToPx, safeAreaInsets, systemInfo } from '@/utils'
import { getImageUrl } from '@/utils/imageUtil'

definePage({
    style: {
        navigationBarTitleText: '收益',
        navigationStyle: 'custom',
    },
})

const userStore = useUserStore()
const tokenStore = useTokenStore()
// 使用storeToRefs解构userInfo
const { userInfo } = storeToRefs(userStore)
const { hasLogin } = storeToRefs(tokenStore)

// 发券人账户表-通过userId查询账户信息
const { send: getAccountCountRequest, data: accountCountData } = useRequest(getAccountCount, {
    immediate: false,
})

// 新增：刷新状态
const refreshing = ref(false)
const activeIndex = ref(0)
const showLoading = ref(false)
const pickerDate = ref(Date.now())
const pickerShow = ref(false)
const totalAmount = ref(0)
let mescroll = null

// 新增：滚动距离和透明度
const scrollTop = ref(0)
const headerOverlayOpacity = computed(() => {
    // 当滚动距离超过150px时，完全显示纯色背景
    const headerHeightForRPX = 526
    const headerHeightForPx = rpxToPx(headerHeightForRPX)
    const maxScroll = menuButtonInfo.height + safeAreaInsets.top + 64 + (headerHeightForPx - (menuButtonInfo.height + safeAreaInsets.top + 64)) / 2
    return Math.min(scrollTop.value / maxScroll, 1)
})

// 新增：监听页面滚动
onPageScroll((e) => {
    scrollTop.value = e.scrollTop
})

const { send, data: incomeData, pageCount, loading, page, pageSize, isLastPage, refresh, reload, onSuccess, onError } = usePagination((page, pageSize) => getCouponIssuerAccountByPageMap({
    pageNo: page,
    pageSize,
    type: 1,
    status: activeIndex.value,
    year: changtime(pickerDate.value, 'YYYY'),
    month: changtime(pickerDate.value, 'MM'),
}), {
    initialPage: 1,
    initialPageSize: 10,
    append: true,
    preloadNextPage: false,
    preloadPreviousPage: false,
    total: response => response?.total || 0,
    data: response => response?.detailList || [],
    immediate: false,
})

watch(() => incomeData.value, (newVal) => {
    if (newVal.length === 0 && !loading.value) {
        mescroll.showEmpty()
    }
    else {
        mescroll.removeEmpty()
    }
})

// ============ mescroll 配置 ============
const downOption = reactive({
    use: true,
    auto: false,
    bgColor: '#ffffff',
    textColor: '#666',
    textInOffset: '下拉刷新',
    textOutOffset: '释放刷新',
    textLoading: '刷新中...',
    offset: 80,
})

const upOption = reactive({
    use: true,
    auto: false,
    noMoreSize: 7,
    isBounce: true,
    page: {
        num: page.value,
        size: pageSize.value,
    },
    empty: {
        use: true,
        tip: '暂无数据',
        btnText: '刷新试试',
        icon: '/static/images/mescroll-empty.png',
        fixed: false,
        top: '200rpx',
        zIndex: 1,
    },
    textNoMore: '--- 已经到底了 ---',
    toTop: {
        src: '/static/images/mescroll-totop.png',
        offset: 1000,
        bottom: 120,
    },
    // 开启虚拟列表优化（大数据量时）
    virtual: {
        use: false,
        rowHeight: 300,
    }
})

function mescrollInit(ref) {
    mescroll = ref
}

async function downCallback() {
    console.log('下拉刷新触发')

    // await refresh()
    await getAccountCountRequest()
    await refresh()
    await userStore.fetchUserInfo()
}

async function onRefresh() {
    refreshing.value = true
    await getAccountCountRequest()
    await refresh()
    await userStore.fetchUserInfo()
    refreshing.value = false
}

async function upCallback() {
    console.log('上拉加载触发')
    if (isLastPage.value) {
        console.log(mescroll)
        mescroll.endSuccess(0, false)
        return
    }

    page.value++
}

onSuccess((response) => {
    let isNextPage = isLastPage.value
    // 此处处理alova isLastPage默认值为true,首次请求出现的无法加载下一页问题
    if (pageCount.value > page.value && isLastPage.value) {
        isNextPage = false
    }
    totalAmount.value = response.data?.totalAmount || 0
    // mescroll.setPageNum(page.value - 1)
    mescroll.endSuccess(incomeData.value.length, !isNextPage)
})

onError(() => {
    console.log('请求失败')
    mescroll.endErr()
})

onShow(async () => {
    await send()
})

async function tabChange(index) {
    // 切换tab时，重置上拉加载
    // mescroll.resetUpScroll(true)
    // mescroll.showDownScroll()
    activeIndex.value = index
    mescroll.hideUpScroll()
    mescroll.scrollTo(0, 0)
    showLoading.value = true
    await reload()
    showLoading.value = false
}

async function pickerConfirm() {
    pickerShow.value = false
    mescroll.scrollTo(0, 0)
    mescroll.hideUpScroll()
    showLoading.value = true
    await reload()
    showLoading.value = false
}

onShow(async () => {
    // 登录后查询收益数据
    if (hasLogin) {
        await getAccountCountRequest()
        await send()
        // 数据会在useScroll的onMounted中自动加载，这里不需要额外调用
    }
})

// 创建分享hook实例
const { getShareConfig, getTimelineShareConfig } = useShare()

// #ifdef MP-WEIXIN
// 分享给好友生命周期函数
onShareAppMessage(async (options) => {
    return await getShareConfig()
})

// 分享到朋友圈生命周期函数
onShareTimeline(async () => {
    return await getTimelineShareConfig()
})
// #endif

const isUnlock = computed(() => accountCountData && accountCountData?.status === 0)

function goPage(page: string) {
    uni.navigateTo({
        url: `/pages-A/${page}/index`,
    })
}
</script>

<template>
    <view class="profile-container" :style="{ minHeight: `calc(100vh - 100rpx)` }">
        <!-- <up-pull-refresh :refreshing="refreshing" :threshold="60" @refresh="onRefresh"> -->
        <!-- 顶部区域 -->
        <view class="income-header"
            :style="{ background: `url(${getImageUrl('@img/income/income-bg.png')})`, backgroundSize: '100% 110%', backgroundPosition: 'left bottom', backgroundRepeat: 'no-repeat' }">
            <view class="income-header-avatar-info"
                :style="{ paddingTop: `calc(${safeAreaInsets.top}px + ${menuButtonInfo.height}px)` }">
                <view class="income-header-balance">
                    当前账户余额（元）
                </view>
                <view class="income-header-balance-num">
                    <view class="income-header-balance-num-amount">
                        {{ accountCountData?.balance || 0 }}
                    </view>
                    <view class="income-header-balance-num-btns">
                        <view v-if="isUnlock" class="income-header-balance-num-btn js" @click="goPage('unlockRewards')">
                            解锁
                        </view>
                    </view>
                </view>
            </view>
            <view class="income-header-tips">
                <view class="income-header-tips-item">
                    <view class="income-header-tips-item-num">
                        {{ accountCountData?.withdrawableAmount || 0 }}
                    </view>
                    <view class="income-header-tips-item-des">
                        可提现金额
                    </view>
                </view>
                <view class="income-header-tips-item">
                    <view class="income-header-tips-item-num">
                        {{ accountCountData?.unsettledAmount || 0 }}
                    </view>
                    <view class="income-header-tips-item-des">
                        未结算金额
                    </view>
                </view>
                <view class="income-header-tips-item">
                    <view class="income-header-tips-item-num">
                        {{ accountCountData?.totalCommission || 0 }}
                    </view>
                    <view class="income-header-tips-item-des">
                        累计收益
                    </view>
                </view>
            </view>
        </view>
        <!-- 公告 -->
        <view v-if="isUnlock" class="income-header-notice">
            <view class="income-header-notice-icon">
                <image :src="getImageUrl('@img/income/notice.png')" mode="aspectFit" />
            </view>
            <view class="income-header-notice-content">
                在考核周期内未达标已锁定收益，<text>前往查看~</text>
            </view>
        </view>
        <!-- 菜单 -->
        <view class="income-header-menu" :style="{ marginTop: isUnlock ? '24rpx' : '-50rpx' }">
            <view class="income-header-overlay"
                :style="{ opacity: headerOverlayOpacity, height: `calc(${menuButtonInfo.bottom + 4}px + 50rpx)` }" />
            <!-- 结算筛选 -->
            <view class="income-header-menu-filter" :style="{ top: `${menuButtonInfo.bottom + 4}px` }">
                <view class="income-header-menu-filter-item" :class="[activeIndex === 0 ? 'active' : '']"
                    @click="tabChange(0)">
                    待结算
                </view>
                <view class="income-header-menu-filter-item" :class="[activeIndex === 1 ? 'active' : '']"
                    @click="tabChange(1)">
                    已结算
                </view>
            </view>
            <!-- 时间筛选 -->
            <view class="income-menu-time-filter" :style="{ top: `calc(${menuButtonInfo.bottom + 4}px + 90rpx)` }">
                <view class="income-menu-time-filter-text" @click="pickerShow = true">
                    <text>{{ changtime(pickerDate) }}</text>
                    <up-icon name="arrow-down" color="#666666" size="14" />
                    <up-datetime-picker v-model="pickerDate" :show="pickerShow" mode="year-month" close-on-click-overlay
                        @confirm="pickerConfirm" @cancel="pickerShow = false" />
                </view>
                <view>
                    合计：￥{{ totalAmount }}
                </view>
            </view>
            <view class="income-menu-list">
                <mescroll-uni id="mescrollContainer" :down="downOption" :up="upOption" :fixed="false"
                    :is-show-empty="true" @init="mescrollInit" @down="downCallback" @up="upCallback"
                    @emptyclick="reload">
                    <view v-for="item in incomeData" :key="item.userId" class="income-content-item">
                        <income-item :data="item" :type="activeIndex" />
                    </view>
                    <!-- 滚动区域内的loading遮罩 -->
                    <view v-if="showLoading && loading" class="loading-mask">
                        <view class="loading-spinner" />
                        <text class="loading-text">加载中...</text>
                    </view>
                </mescroll-uni>
            </view>
        </view>
        <!-- </up-pull-refresh> -->
    </view>
</template>

<style lang="scss" scoped>
.profile-container {
    background-color: #f5f5f5;
    line-height: 1;
    display: flex;
    flex-direction: column;

    /* 添加这行，设置容器高度为视口高度 */

    .income-header {
        height: 526rpx;

        .income-header-avatar-info {
            display: flex;
            flex-direction: column;
            gap: 30rpx;
            padding: 0 24rpx;

            .income-header-balance {
                font-weight: 400;
                font-size: 26rpx;
                color: #ffffff;
            }

            .income-header-balance-num {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .income-header-balance-num-amount {
                    font-weight: 500;
                    font-size: 65rpx;
                    color: #ffffff;
                }

                .income-header-balance-num-btns {
                    display: flex;
                    gap: 15rpx;

                    .income-header-balance-num-btn {
                        padding: 20rpx 40rpx;
                        border-radius: 33rpx;
                        font-weight: 400;
                        font-size: 26rpx;

                        &.js {
                            background: #da4c47;
                            color: #ffffff;
                        }

                        &.tx {
                            background: #bfbfbf;
                            color: #747474;
                        }
                    }
                }
            }
        }

        .income-header-tips {
            height: 124rpx;
            display: flex;
            background: linear-gradient(114deg, #f67873, #fb847f, #f67873);
            border-radius: 10rpx;
            margin: 47rpx 24rpx 0 24rpx;

            .income-header-tips-item {
                flex: 1;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                gap: 15rpx;
                font-weight: 500;
                font-size: 34rpx;
                color: #ffffff;
                line-height: 1;
                position: relative;

                &:not(:last-child):after {
                    content: '';
                    position: absolute;
                    top: 50%;
                    right: 0;
                    transform: translateY(-50%);
                    width: 2px;
                    height: 40rpx;
                    background: #ffffff;
                }

                .income-header-tips-item-num {
                    font-weight: bold;
                }

                .income-header-tips-item-des {
                    font-weight: 400;
                    font-size: 24rpx;
                    color: #ffffff;
                }
            }
        }
    }

    .income-header-notice {
        margin: -50rpx 24rpx 24rpx 24rpx;
        background: #ffffff;
        border-radius: 10rpx;
        display: flex;
        align-items: center;
        gap: 20rpx;
        padding: 28rpx 20rpx;

        .income-header-notice-icon {
            width: 52rpx;
            height: 35rpx;

            image {
                width: 100%;
                height: 100%;
            }
        }

        .income-header-notice-content {
            font-weight: 400;
            font-size: 24rpx;
            color: #333333;

            text {
                color: #c52d27;
            }
        }
    }

    .income-header-menu {
        // background: #ffffff;
        border-radius: 10rpx 10rpx 0rpx 0rpx;
        margin-left: 24rpx;
        margin-right: 23rpx;
        margin-bottom: 20rpx;
        flex: 1;
        display: flex;
        flex-direction: column;
        min-height: 0;

        // 新增：吸顶区域上方的覆盖元素
        .income-header-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background-color: #ed6b66;
            border-radius: 10rpx 10rpx 0rpx 0rpx;
            z-index: 99;
            pointer-events: none; // 确保不影响点击事件
        }

        .income-header-menu-filter {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: 500;
            font-size: 32rpx;
            color: #333333;
            height: 90rpx;
            background: #ffffff;
            box-shadow: 0rpx 3rpx 7rpx 0rpx rgba(213, 213, 213, 0.29);
            border-radius: 10rpx 10rpx 0rpx 0rpx;
            position: sticky;
            top: 0;
            z-index: 100;

            .income-header-menu-filter-item {
                flex: 1;
                display: flex;
                justify-content: center;
                align-items: center;
                position: relative;
                height: 100%;

                &.active {
                    color: #ed6b66;

                    &:after {
                        content: '';
                        position: absolute;
                        bottom: 0;
                        left: 50%;
                        transform: translateX(-50%);
                        width: 67rpx;
                        height: 6rpx;
                        background: #ed6b66;
                        border-radius: 3rpx;
                    }
                }
            }
        }

        .income-menu-time-filter {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: 400;
            font-size: 24rpx;
            color: #333333;
            padding: 30rpx 20rpx 14rpx;
            background: #ffffff;
            margin-top: 4rpx;
            position: sticky;
            z-index: 100;

            .income-menu-time-filter-text {
                font-weight: 400;
                font-size: 26rpx;
                color: #000000;
                display: flex;
                align-items: center;
                gap: 12rpx;
            }
        }

        .income-menu-list {
            background: #ffffff;
            // flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;

            #mescrollContainer {
                height: 100%;
                flex: 1;
            }

            .income-content-item {
                margin-top: 20rpx;
            }

            // loading遮罩样式
            .loading-mask {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: rgba(255, 255, 255, 0.8);
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                z-index: 999;
            }

            .loading-spinner {
                width: 40rpx;
                height: 40rpx;
                border: 4rpx solid #e0e0e0;
                border-top-color: #ed6b66;
                border-radius: 50%;
                animation: spin 1s linear infinite;
            }

            .loading-text {
                margin-top: 16rpx;
                font-size: 24rpx;
                color: #666;
            }

            @keyframes spin {
                to {
                    transform: rotate(360deg);
                }
            }
        }
    }
}
</style>
