<template>
    <view class="wallet-page">
        <!-- 余额卡片 -->
        <view class="balance-card">
            <view class="card-header">
                <text>我的余额</text>
                <view class="detail-link" @click="handleWithdrawDetail">
                    提现明细
                    <u-icon name="arrow-right" color="#FFFFFF" size="26" top="4rpx"></u-icon>
                </view>
            </view>

            <view class="amount flex-c">
                <text class="number">¥ {{ restMoney }}</text>
            </view>

            <view class="balance-info  flex-c">
                (可用余额¥{{ canUseMoney }} 提现中¥{{ freezeMoney }})
            </view>

            <view class="flex-c">
                <view class="withdraw-btn" @click="handleWithdraw">
                    提现
                </view>
            </view>
        </view>

        <!-- 余额明细列表 -->
        <view class="detail-section">
            <view class="section-header">
                <text>余额明细</text>
                <view class="filter" @click="toggleFilter">
                    分类
                    <u-icon name="arrow-down" color="#333" size="26"></u-icon>
                </view>
            </view>

            <page-scroll @updateList="handleUpdateList" ref="pageRef" slotEmpty url="/token/user/accountChangeList"
                :immediate="false" bgColor="#ffffff" :height="height">
                <view class="detail-list">
                    <view class="detail-item" v-for="(item, index) in detailList" :key="index"
                        @click="goToDetail(item)">
                        <view class="item-left">
                            <text class="title">{{ item.title }}</text>
                            <text class="time">{{ item.createTime }}</text>
                        </view>
                        <view class="item-right">
                            <text :class="['amount', item.changeMoney > 0 ? 'income' : 'expense']">
                                {{ item.changeMoney }}
                            </text>
                            <text class="status" v-if="item.desc">{{ item.desc }}</text>
                        </view>
                    </view>
                </view>
            </page-scroll>
        </view>

        <!-- 分类选择弹窗 -->
        <category-popup :show.sync="showCategoryPopup" @confirm="onCategoryConfirm"></category-popup>
    </view>
</template>

<script>
import CategoryPopup from '../components/category-popup.vue'
import pageScroll from '@/components/pageScroll/index.vue'
export default {
    components: {
        CategoryPopup,
        pageScroll
    },
    data() {
        return {
            showCategoryPopup: false,
            restMoney: '0.00',
            freezeMoney: '0.00',
            canUseMoney: '0.00',
            detailList: [],
            otherParams: {
                queryTypes: ''
            },
            height: 'calc(100vh - 540rpx)'
        }
    },
    // #ifdef MP-ALIPAY
    onPullDownRefresh() {
        this.$refs.pageRef?.loadData(true)
    },
    // #endif

    onLoad() {
        this.getWithdrawInfo()
        this.$nextTick(() => {
            this.$refs.pageRef.loadData(true, { queryTypes: '' })
        })
    },
    methods: {
        async getWithdrawInfo() {
            try {
                const res = await uni.$u.http.get('/token/user/accountInfo')
                if (res.code === 200) {
                    const { userId, restMoney, freezeMoney, canUseMoney } = res.data
                    this.restMoney = restMoney
                    this.freezeMoney = freezeMoney
                    this.canUseMoney = canUseMoney
                }
            } catch (e) {
                console.error('获取提现信息失败:', e)
            }
        },
        // 分类选择
        onCategoryConfirm(selectedCategories) {
            console.log('选中的分类：', selectedCategories)
            this.otherParams.queryTypes = selectedCategories.join(',')
            this.$refs.pageRef.loadData(true, this.otherParams)
        },
        goToDetail(item) {
            if (item.desc == '待确认收款') {
                uni.$u.http.post('/token/user/withdrawConfirm', {
                    orderNo: item.orderNo
                }).then(res => {
                    if (res.code === 200) {
                        this.handleConfirmReceipt(res.data)
                    }
                }).catch(err => {
                    uni.showToast({
                        title: err.message || '确认失败',
                        icon: 'none'
                    });
                });
            }
        },
        handleWithdraw() {
            uni.navigateTo({
                url: '/pages-mine/pages/withdraw'
            })
        },
        handleWithdrawDetail() {
            uni.navigateTo({
                url: '/pages-mine/pages/withdraw-detail'
            })
        },
        toggleFilter() {
            // 实现筛选功能
            this.showCategoryPopup = !this.showCategoryPopup
        },
        // 更新列表
        handleUpdateList(data) {
            this.detailList = data
        },
        //执行微信确认收款操作
        handleConfirmReceipt(data) {
            if (wx.canIUse('requestMerchantTransfer')) {
                wx.requestMerchantTransfer({
                    mchId: data.mchId,
                    appId: data.appId,
                    package: data.packageStr,
                    success: (res) => {
                        // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
                        uni.showToast({
                            title: '确认收款成功',
                            icon: 'none'
                        })
                        // 刷新列表和余额信息
                        this.getWithdrawInfo();
                        this.$refs.pageRef.loadData(true, this.otherParams);
                    },
                    fail: (res) => {
                        console.log('fail:', res);
                    },
                });
            } else {
                wx.showModal({
                    content: '你的微信版本过低，请更新至最新版本。',
                    showCancel: false,
                });
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.wallet-page {
    height: 100vh;
    background: #F5F5F5;
    padding: 10rpx 30rpx;
    box-sizing: border-box;
    overflow: hidden;

    .balance-card {
        background: #38C148;
        border-radius: 20rpx;
        padding: 30rpx 40rpx;
        color: #FFFFFF;
        z-index: 9;
        position: sticky;
        top: 10rpx;

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 28rpx;

            .detail-link {
                display: flex;
                align-items: center;
                opacity: 0.9;
            }
        }

        .amount {
            margin: 40rpx 0 20rpx;

            .symbol {
                font-size: 40rpx;
                margin-right: 8rpx;
            }

            .number {
                font-size: 80rpx;
                font-weight: 500;
            }
        }

        .balance-info {
            font-size: 26rpx;
            opacity: 0.9;
        }

        .withdraw-btn {
            margin-top: 40rpx;
            height: 60rpx;
            line-height: 60rpx;
            text-align: center;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 14rpx;
            font-size: 28rpx;
            width: 200rpx;
        }
    }

    .detail-section {
        background: #FFFFFF;
        border-radius: 20rpx;
        margin-top: 20rpx;
        padding: 0 30rpx;
        height: calc(100vh - 400rpx);
        overflow-y: auto;

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 100rpx;
            font-size: 30rpx;
            color: #333;
            border-bottom: 1px solid #EEEEEE;

            .filter {
                display: flex;
                align-items: center;
                color: #666;
                font-size: 28rpx;
                margin-right: 8rpx;
            }
        }

        .detail-list {
            .detail-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 30rpx 0;
                border-bottom: 1px solid #EEEEEE;

                &:last-child {
                    border-bottom: none;
                }

                .item-left {
                    .title {
                        font-size: 28rpx;
                        color: #333;
                        margin-bottom: 10rpx;
                        display: block;
                    }

                    .time {
                        font-size: 24rpx;
                        color: #999;
                    }
                }

                .item-right {
                    text-align: right;

                    .amount {
                        display: block;
                        font-size: 32rpx;
                        margin-bottom: 10rpx;
                        font-weight: 500;

                        &.income {
                            color: #FF5B5B;
                        }

                        &.expense {
                            color: #38C148;
                        }
                    }

                    .status {
                        font-size: 24rpx;
                        color: #999;
                    }
                }
            }
        }
    }
}
</style>