<template>
    <view class="user-page">
        <view class="user-header" :style="{ paddingTop: statusBarHeight + 'px' }">
            <view class="user-header__top">
                <view class="user-header__title">我的</view>
                <view class="user-header__actions">
                    <view class="user-header__setting" @tap="goPage('/pages/user_set/user_set')">
                        <u-icon name="setting" color="#fff" size="32" />
                    </view>
                </view>
            </view>

            <view v-if="isLogin" class="user-info" @tap="goPage('/pages/user_data/user_data')">
                <image class="user-info__avatar" :src="userInfo.avatar || defaultAvatar" mode="aspectFill" />
                <view class="user-info__detail">
                    <view class="user-info__name-row">
                        <text class="user-info__name">{{ userInfo.nickname || '用户' }}</text>
                        <view v-if="userInfo.vip_info?.is_vip" class="user-info__badge user-info__badge--vip">{{
                            userInfo.vip_info.vip_level_name }}</view>
                        <view v-if="!userInfo.is_bind_mobile" class="user-info__badge user-info__badge--unverified"
                            @tap.stop="goPage(`/pages/bind_mobile/bind_mobile?from=verify&mobile=${userInfo.mobile}`)">
                            未验证号码</view>
                    </view>
                    <text class="user-info__id">ID: {{ userInfo.sn || '' }}</text>
                </view>
                <view class="user-info__arrow">
                    <u-icon name="arrow-right" color="rgba(255,255,255,0.6)" size="28" />
                </view>
            </view>

            <view v-else class="user-info" @tap="goPage('/pages/login/login')">
                <image class="user-info__avatar" :src="defaultAvatar" mode="aspectFill" />
                <view class="user-info__detail">
                    <text class="user-info__name">点击登录</text>
                    <text class="user-info__id user-info__id--guest">登录后享受更多服务</text>
                </view>
                <view class="user-info__arrow">
                    <u-icon name="arrow-right" color="rgba(255,255,255,0.6)" size="28" />
                </view>
            </view>

            <view class="user-stats">
                <view class="user-stats__item" @tap="goPage('/pages/my_follow/my_follow?type=follow')">
                    <text class="user-stats__num">{{ stats.follow_count }}</text>
                    <text class="user-stats__label">关注</text>
                </view>
                <view class="user-stats__item" @tap="goPage('/pages/my_follow/my_follow?type=fans')">
                    <text class="user-stats__num">{{ stats.fans_count }}</text>
                    <text class="user-stats__label">粉丝</text>
                </view>
                <view class="user-stats__item" @tap="goPage('/pages/collection/collection')">
                    <text class="user-stats__num">{{ stats.collect_count }}</text>
                    <text class="user-stats__label">收藏</text>
                </view>
                <view class="user-stats__item" @tap="openPointsBuy">
                    <text class="user-stats__num user-stats__num--points">{{ stats.user_points }}</text>
                    <text class="user-stats__label">积分</text>
                    <text v-if="isLogin" class="user-stats__buy">购买</text>
                </view>
            </view>
        </view>

        <view class="user-vip-wrap">
            <vip-card :vip-info="userInfo.vip_info" />
        </view>

        <view class="assistant-entry" @tap="goPage('/pages/ai_assistant/ai_assistant')">
            <view class="assistant-entry__icon">AI</view>
            <view class="assistant-entry__body">
                <text class="assistant-entry__title">世博头条 AI 助手</text>
                <text class="assistant-entry__desc">免费咨询站内资讯、赛事、社区、彩票和行情</text>
            </view>
            <u-icon name="arrow-right" size="28" color="#185dff" />
        </view>

        <view class="assistant-entry chat-entry" @tap="openChatList">
            <view class="assistant-entry__icon chat-entry__icon">聊</view>
            <view class="assistant-entry__body">
                <text class="assistant-entry__title">私聊消息</text>
                <text class="assistant-entry__desc">查看好友和关注用户的私聊</text>
            </view>
            <view v-if="stats.chat_unread_count > 0" class="chat-entry__badge">
                <text>{{ stats.chat_unread_count > 99 ? '99+' : stats.chat_unread_count }}</text>
            </view>
            <u-icon name="arrow-right" size="28" color="#185dff" />
        </view>

        <view class="user-menu">
            <!-- 我的服务（从后台装修配置读取） -->
            <view v-if="serviceMenu.enabled && serviceMenu.data.length" class="user-menu__group">
                <!-- 横排样式 -->
                <view v-if="serviceMenu.style === 1" class="user-menu__grid">
                    <view v-for="(item, idx) in serviceMenuList" :key="idx" class="user-menu__grid-item"
                        @tap="goLink(item.link)">
                        <image v-if="item.image" :src="getImageUrl(item.image)" class="user-menu__grid-icon"
                            mode="aspectFit" />
                        <text class="user-menu__grid-text">{{ item.name }}</text>
                    </view>
                </view>
                <!-- 竖排样式 -->
                <template v-else>
                    <view v-for="(item, idx) in serviceMenuList" :key="idx" class="user-menu__item"
                        @tap="goLink(item.link)">
                        <image v-if="item.image" :src="getImageUrl(item.image)" class="user-menu__item-icon"
                            mode="aspectFit" />
                        <text class="user-menu__text">{{ item.name }}</text>
                        <u-icon name="arrow-right" size="24" color="#ccc" />
                    </view>
                </template>
            </view>

            <!-- 个人中心广告图（从后台装修配置读取） -->
            <view v-if="bannerData.enabled && bannerList.length" class="user-banner">
                <swiper class="user-banner__swiper" :autoplay="true" :interval="4000" :circular="true" indicator-dots
                    indicator-color="rgba(255,255,255,0.4)" indicator-active-color="#fff">
                    <swiper-item v-for="(item, idx) in bannerList" :key="idx" @tap="goLink(item.link)">
                        <image :src="getImageUrl(item.image)" class="user-banner__img" mode="aspectFill" />
                    </swiper-item>
                </swiper>
            </view>

        </view>
    </view>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/user'
import { onShow } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { ref, reactive, computed } from 'vue'
import { getToken } from '@/utils/auth'
import { getDecorate } from '@/api/shop'
import request from '@/utils/request'
import { useAppStore } from '@/stores/app'
import VipCard from '@/components/vip-card/vip-card.vue'

const userStore = useUserStore()
const appStore = useAppStore()
const { userInfo, isLogin } = storeToRefs(userStore)
const statusBarHeight = ref(0)

const defaultAvatar = computed(() => {
    const logo = appStore.config?.website?.shop_logo
    if (!logo) return '/static/images/avatar.png'
    if (logo.startsWith('http')) return logo
    return (appStore.config?.domain || '') + logo
})

const stats = reactive({
    follow_count: 0,
    fans_count: 0,
    collect_count: 0,
    user_points: 0,
    chat_unread_count: 0
})

const serviceMenu = reactive({
    enabled: false,
    style: 1,
    title: '我的服务',
    data: [] as any[]
})
const serviceMenuList = computed(() => serviceMenu.data.filter((item: any) => item.is_show === '1' || item.is_show === 1))

const bannerData = reactive({
    enabled: false,
    data: [] as any[]
})
const bannerList = computed(() => bannerData.data.filter((item: any) => item.is_show === '1' || item.is_show === 1))

const promptPasswordChange = (userInfoData: Record<string, any>) => {
    const mobile = String(userInfoData?.mobile || '')
    const initialPassword = mobile.slice(-6)
    const content = initialPassword
        ? `初始密码为手机号后 6 位：${initialPassword}，请尽快修改登录密码。`
        : '初始密码为手机号后 6 位，请尽快修改登录密码。'

    uni.showModal({
        title: '请修改登录密码',
        content,
        confirmText: '去修改',
        cancelText: '稍后再说',
        success: (res) => {
            if (res.confirm) {
                goPage('/pages/change_password/change_password?type=set')
            }
        }
    })
}

const fetchDecorate = async () => {
    try {
        const res = await getDecorate({ id: 2 })
        let pageData: any[] = []
        if (Array.isArray(res)) {
            pageData = res
        } else if (res?.data) {
            pageData = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
            if (!Array.isArray(pageData)) pageData = []
        }
        console.log('[user] decorate pageData:', JSON.stringify(pageData.map((w: any) => w.name)))
        const myService = pageData.find((w: any) => w.name === 'my-service')
        if (myService?.content) {
            serviceMenu.enabled = !!myService.content.enabled && myService.content.enabled !== '0'
            serviceMenu.style = myService.content.style || 1
            serviceMenu.title = myService.content.title || '我的服务'
            serviceMenu.data = myService.content.data || []
        }
        const userBanner = pageData.find((w: any) => w.name === 'user-banner')
        if (userBanner?.content) {
            bannerData.enabled = !!userBanner.content.enabled && userBanner.content.enabled !== '0'
            bannerData.data = userBanner.content.data || []
        }
    } catch (e) {
        // 装修数据获取失败时静默处理
    }
}

const getImageUrl = (path: string) => {
    if (!path) return ''
    if (path.startsWith('http')) return path
    return `http://129.204.53.249:8090${path}`
}

onShow(async () => {
    const sysInfo = uni.getSystemInfoSync()
    // #ifdef APP-PLUS || MP
    statusBarHeight.value = sysInfo.statusBarHeight || 44
    // #endif
    // #ifdef H5
    statusBarHeight.value = 0
    // #endif
    const userData = await userStore.getUser().catch(() => null)
    if (isLogin.value && userData && Object.prototype.hasOwnProperty.call(userData, 'has_password')) {
        if (Number(userData.has_password) === 0) {
            promptPasswordChange(userData)
        }
    }
    fetchDecorate()
    if (getToken()) {
        fetchStats()
    }
})

const fetchStats = async () => {
    try {
        const res: any = await request.get(
            { url: '/community/userStats' },
            { isTransformResponse: false }
        )
        if (res?.code === 1 && res.data) {
            stats.follow_count = res.data.follow_count || 0
            stats.fans_count = res.data.fans_count || 0
            stats.collect_count = res.data.collect_count || 0
            stats.user_points = res.data.user_points || 0
            stats.chat_unread_count = res.data.chat_unread_count || 0
        }
    } catch (e) {
        // 静默处理
    }
}

const openPointsBuy = () => {
    if (!isLogin.value) {
        uni.navigateTo({ url: '/pages/login/login' })
        return
    }
    uni.navigateTo({ url: '/packages/pages/points_log/points_log' })
}

const openChatList = () => {
    if (!isLogin.value) {
        uni.navigateTo({ url: '/pages/login/login' })
        return
    }
    uni.navigateTo({ url: '/pages/private_chat/list' })
}

const goPage = (url: string) => {
    uni.navigateTo({ url })
}

const goLink = (link: any) => {
    if (!link?.path) return
    uni.navigateTo({ url: link.path })
}
</script>

<style lang="scss" scoped>
.user-page {
    min-height: 100vh;
    background: #f5f5f5;
}

.user-header {
    background: linear-gradient(170deg, #185dff, #4d82ff);
    padding-bottom: 60rpx;

    &__top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16rpx 32rpx;
    }

    &__title {
        font-size: 36rpx;
        font-weight: 700;
        color: #fff;
    }

    &__setting {
        width: 64rpx;
        height: 64rpx;
        background: rgba(255, 255, 255, 0.24);
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}

.user-info {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    padding: 24rpx 32rpx;

    &__avatar {
        width: 128rpx;
        height: 128rpx;
        border-radius: 12rpx;
        flex-shrink: 0;
    }

    &__detail {
        flex: 1;
        margin-left: 24rpx;
        min-width: 0;
    }

    &__arrow {
        flex-shrink: 0;
        margin-left: 12rpx;
    }

    &__name-row {
        display: flex;
        align-items: center;
        gap: 12rpx;
    }

    &__name {
        font-size: 36rpx;
        font-weight: 600;
        color: #fff;
    }

    &__badge {
        font-size: 20rpx;
        padding: 2rpx 12rpx;
        border-radius: 16rpx;

        &--level {
            background: rgba(255, 255, 255, 0.25);
            color: #fff;
        }

        &--vip {
            background: #f0ad4e;
            color: #fff;
        }

        &--unverified {
            background: rgba(255, 80, 80, 0.8);
            color: #fff;
        }
    }

    &__id {
        font-size: 24rpx;
        color: #e6e6e6;
        margin-top: 8rpx;

        &--guest {
            margin-left: 4rpx;
        }
    }
}

.user-stats {
    display: flex;
    justify-content: space-around;
    margin: 16rpx 18rpx 0;
    background: rgba(255, 255, 255, 0.32);
    border-radius: 12rpx;
    padding: 32rpx 16rpx;

    &__item {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
    }

    &__num {
        font-size: 36rpx;
        font-weight: 700;
        color: #fff;

        &--points {
            color: #ffd700;
        }
    }

    &__label {
        font-size: 22rpx;
        color: rgba(255, 255, 255, 0.8);
        margin-top: 4rpx;
    }

    &__buy {
        margin-top: 8rpx;
        padding: 2rpx 14rpx;
        border-radius: 18rpx;
        font-size: 20rpx;
        color: #185dff;
        background: #fff;
    }
}

.points-buy {
    padding: 36rpx 32rpx 48rpx;
    background: #fff;

    &__title {
        font-size: 34rpx;
        font-weight: 700;
        color: #222;
        text-align: center;
    }

    &__desc {
        margin-top: 14rpx;
        font-size: 24rpx;
        color: #999;
        text-align: center;
    }

    &__packages {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 20rpx;
        margin-top: 36rpx;
    }

    &__package {
        height: 148rpx;
        border: 2rpx solid #edf0f5;
        border-radius: 18rpx;
        background: #f8faff;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    &__package--active {
        border-color: #185dff;
        background: #edf3ff;
    }

    &__points {
        font-size: 32rpx;
        font-weight: 700;
        color: #222;
    }

    &__money {
        margin-top: 8rpx;
        font-size: 26rpx;
        color: #185dff;
        font-weight: 600;
    }

    &__custom {
        margin: 28rpx 0 36rpx;
        padding: 22rpx 24rpx;
        border-radius: 16rpx;
        background: #f7f8fa;
        display: flex;
        align-items: center;
    }

    &__custom-label {
        font-size: 26rpx;
        color: #333;
        margin-right: 24rpx;
    }

    &__input {
        flex: 1;
        height: 52rpx;
        font-size: 28rpx;
        text-align: right;
    }
}

.user-vip-wrap {
    width: 88%;
    margin: -40rpx auto 0;
    position: relative;
    z-index: 10;
}

.assistant-entry {
    width: 88%;
    margin: 20rpx auto 0;
    padding: 24rpx;
    box-sizing: border-box;
    border-radius: 8rpx;
    background: #fff;
    border: 1rpx solid #dbe6f5;
    display: flex;
    align-items: center;
    gap: 18rpx;
    position: relative;
    z-index: 9;

    &__icon {
        width: 60rpx;
        height: 60rpx;
        border-radius: 8rpx;
        background: #185dff;
        color: #fff;
        font-size: 24rpx;
        font-weight: 700;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }

    &__body {
        flex: 1;
        min-width: 0;
    }

    &__title {
        display: block;
        font-size: 30rpx;
        font-weight: 700;
        color: #111827;
    }

    &__desc {
        display: block;
        margin-top: 6rpx;
        font-size: 23rpx;
        color: #6b7280;
        line-height: 1.4;
    }
}

.chat-entry {
    margin-top: 16rpx;

    &__icon {
        background: #111827;
    }

    &__badge {
        min-width: 34rpx;
        height: 34rpx;
        padding: 0 8rpx;
        border-radius: 17rpx;
        background: #ef4444;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;

        text {
            color: #fff;
            font-size: 20rpx;
            line-height: 1;
        }
    }
}

.user-menu {
    padding: 20rpx 24rpx 20rpx;
    margin-top: 0;
    padding-top: 20rpx;

    &__group {
        background: #fff;
        border-radius: 10rpx;
        margin-bottom: 20rpx;
        overflow: hidden;
    }

    &__item {
        display: flex;
        align-items: center;
        padding: 28rpx 28rpx;
        border-bottom: 1rpx solid #f5f5f5;

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

    &__text {
        flex: 1;
        margin-left: 20rpx;
        font-size: 28rpx;
        color: #333;
    }

    &__tag {
        font-size: 20rpx;
        color: #f0ad4e;
        background: #fff8ed;
        padding: 4rpx 12rpx;
        border-radius: 6rpx;
        margin-right: 12rpx;
    }

    &__title {
        padding: 24rpx 28rpx 16rpx;
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        border-bottom: 1rpx solid #f5f5f5;
    }

    &__grid {
        display: flex;
        flex-wrap: wrap;
        padding: 24rpx 0 8rpx;
    }

    &__grid-item {
        width: 25%;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-bottom: 24rpx;
    }

    &__grid-icon {
        width: 52rpx;
        height: 52rpx;
    }

    &__grid-text {
        font-size: 24rpx;
        color: #333;
        margin-top: 12rpx;
    }

    &__item-icon {
        width: 48rpx;
        height: 48rpx;
        flex-shrink: 0;
    }
}

.user-banner {
    margin: 0 24rpx 20rpx;
    border-radius: 16rpx;
    overflow: hidden;

    &__swiper {
        height: 200rpx;
    }

    &__img {
        width: 100%;
        height: 200rpx;
        border-radius: 16rpx;
    }
}
</style>
