<script lang="ts" setup>
import { useRequest } from 'alova/client'
import { storeToRefs } from 'pinia'
import { computed, ref } from 'vue'
import { getCouponSituation } from '@/api/home'
import { getCouponIssuerApplyById } from '@/api/me'
import { LOGIN_PAGE } from '@/router/config'
import { useUserStore } from '@/store'
import { useTokenStore } from '@/store/token'

definePage({
    style: {
        navigationBarTitleText: '我的',
        navigationStyle: 'custom',
    },
})

const userStore = useUserStore()
const tokenStore = useTokenStore()
// 使用storeToRefs解构userInfo
const { userInfo } = storeToRefs(userStore)
const { hasLogin } = storeToRefs(tokenStore)
console.log('Login:', userInfo.value, hasLogin.value)

// 用户优惠券统计数据
const { send: getCouponSituationRequest, data: couponSituationData } = useRequest(getCouponSituation, {
    immediate: false,
})
// 发卷人查询审核状态
const { send: getCouponIssuerApplyByIdRequest, data: couponIssuerApplyByIdData } = useRequest(getCouponIssuerApplyById, {
    immediate: false,
})
// 昵称输入值
const nicknameInput = ref('')
onShow(() => {
    // 登录后查询收益数据
    if (hasLogin) {
        // 获取用户信息
        userStore.fetchUserInfo().then((data) => {
            // #ifdef MP-WEIXIN
            // 初始化昵称输入框
            console.log('用户信息:', data)
            nicknameInput.value = data?.userInfo.nickname || ''
            // #endif
        })
        getCouponSituationRequest()
        getCouponIssuerApplyByIdRequest()
        if (couponIssuerApplyByIdData.value?.status === '0') {
            console.log('优惠券统计数据:', couponSituationData.value)
            open()
        }
    }
})

// 微信小程序下登录
async function handleLogin() {
    // #ifdef MP-WEIXIN
    // 微信登录
    await tokenStore.wxLogin()

    // #endif
    // #ifndef MP-WEIXIN
    uni.navigateTo({
        url: `${LOGIN_PAGE}`,
    })
    // #endif
}

function handleLogout() {
    uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
            if (res.confirm) {
                // 清空用户信息
                useTokenStore().logout()
                // 执行退出登录逻辑
                uni.showToast({
                    title: '退出登录成功',
                    icon: 'success',
                })
                // #ifdef MP-WEIXIN
                // 微信小程序，去首页
                // uni.reLaunch({ url: '/pages/index/index' })
                // #endif
                // #ifndef MP-WEIXIN
                // 非微信小程序，去登录页
                // uni.navigateTo({ url: LOGIN_PAGE })
                // #endif
            }
        },
    })
}

// 顶部导航栏高度,设置banner位置
const navigationBarHeight = ref(0)
// 头像默认图片
const defaultAvatar = '../../static/images/me/me-bg.png'
// 计算头像显示
const avatarDisplay = computed(() => {
    return userInfo.value?.avatar || defaultAvatar
})
// #ifdef MP-WEIXIN
function getNavigationBarHeight() {
    uni.getSystemInfo({
        success: (res) => {
            const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
            console.log('顶部导航栏高度:', res.statusBarHeight, menuButtonInfo)
            // 顶部导航栏高度 = 状态栏高度 + 胶囊的高度
            navigationBarHeight.value = res.statusBarHeight + menuButtonInfo.height + 12
        },
    })
}
getNavigationBarHeight()

// 处理点击头像获取用户头像
async function handleGetAvatar(e) {
    const { avatarUrl } = e.detail
    if (avatarUrl) {
        userStore.setUserAvatar(avatarUrl)
        uni.showToast({
            title: '头像获取成功',
            icon: 'success',
        })
        // 验证本地存储是否已更新
        const updatedUser = uni.getStorageSync('user')
        console.log('验证本地存储头像更新:', updatedUser?.avatar)
    }
}

// 保存昵称
function saveNickname(e: any) {
    console.log('保存昵称:', e.detail)
    // 直接使用nicknameInput.value，因为input已经通过v-model绑定
    const nickname = nicknameInput.value.trim()
    if (nickname) {
        try {
            // 更新用户信息到store
            userStore.setUserInfo({
                ...userInfo.value,
                nickname,
            })

            uni.showToast({
                title: '昵称保存成功',
                icon: 'success',
                duration: 1500,
            })

            // 验证本地存储是否已更新
            const updatedUser = uni.getStorageSync('user')
            console.log('本地存储昵称已更新:', updatedUser?.nickname)
        }
        catch (error) {
            console.error('保存昵称失败:', error)
            uni.showToast({
                title: '保存失败，请重试',
                icon: 'error',
                duration: 1500,
            })
        }
    }
    else {
        uni.showToast({
            title: '昵称不能为空',
            icon: 'none',
            duration: 1500,
        })
    }
}
// #endif

const show = ref(false)
function close() {
    show.value = false
}
function open() {
    show.value = true
}
function menuClick(page) {
    if (couponIssuerApplyByIdData.value?.status === '0') {
        open()
        return
    }
    uni.navigateTo({
        url: `/pages-A/${page}/index?couponSituation=${JSON.stringify(couponSituationData.value)}`,
    })
}
</script>

<template>
    <view class="profile-container">
        <!-- 顶部区域 -->
        <view class="me-header"
            style="background: url('../../static/images/me/me-bg.png') no-repeat center center; background-size: cover;">
            <view class="me-header-avatar-info" :style="{ paddingTop: `${navigationBarHeight}px` }">
                <button class="me-header-avatar" open-type="chooseAvatar" @click="handleGetAvatar">
                    <image :src="avatarDisplay" mode="aspectFill" />
                </button>
                <view class="me-header-info">
                    <view class="me-header-name">
                        <!-- #ifdef MP-WEIXIN -->
                        <input v-model="nicknameInput" type="nickname" placeholder="用户昵称"
                            placeholder-style="color: #fff; opacity: 0.7;" class="nickname-input"
                            @confirm="saveNickname" @blur="saveNickname">
                        <!-- #endif -->
                        <!-- #ifndef MP-WEIXIN -->
                        {{ userInfo.value?.nickname || '用户' }}
                        <!-- #endif -->
                    </view>
                </view>
            </view>
            <view class="me-header-tips">
                <view class="me-header-tips-item">
                    <view class="me-header-tips-item-num">
                        1,125
                    </view>
                    <view class="me-header-tips-item-des">
                        已领取
                    </view>
                </view>
                <view class="me-header-tips-item">
                    <view class="me-header-tips-item-num">
                        1,125
                    </view>
                    <view class="me-header-tips-item-des">
                        已使用
                    </view>
                </view>
                <view class="me-header-tips-item">
                    <view class="me-header-tips-item-num">
                        1,125
                    </view>
                    <view class="me-header-tips-item-des">
                        已过期
                    </view>
                </view>
            </view>
        </view>
        <!-- 菜单 -->
        <view class="me-header-menu">
            <view class="me-header-menu-item" @click="menuClick('applyForm')">
                <view class="me-header-menu-icon">
                    <image src="@/static/images/me/coupon-need.png" mode="aspectFill" />
                    <view class="me-header-menu-text">
                        发券人申请
                    </view>
                </view>
                <view class="me-header-menu-left">
                    <up-icon name="arrow-right" color="#979797" size="12" />
                </view>
            </view>
            <view class="me-header-menu-item" @click="handleLogout">
                <view class="me-header-menu-icon">
                    <image src="@/static/images/me/loginOut.png" mode="aspectFill" />
                    <view class="me-header-menu-text">
                        退出登录
                    </view>
                </view>
                <view class="me-header-menu-left">
                    <up-icon name="arrow-right" color="#979797" size="12" />
                </view>
            </view>
        </view>
        <!-- 申请中的提示框 -->
        <up-modal content="您已提交申请，请耐心等待！" title="提示" :show="show">
            <template #confirmButton>
                <view class="rounded" style="margin-top: 20rpx;" @click="show = false">
                    我知道了
                </view>
            </template>
        </up-modal>
    </view>
</template>

<style lang="scss" scoped>
// 提示框
::v-deep .u-modal {
    width: 580rpx !important;
    //   height: 376rpx !important;
    border-radius: 20rpx !important;
}

::v-deep .u-modal__title {
    font-weight: 500 !important;
    font-size: 34rpx !important;
    color: #333333 !important;
    padding-top: 29rpx !important;
    padding-bottom: 28rpx !important;
}

::v-deep .u-modal__content {
    border-top: 1px solid #eeeeee;
    border-bottom: 1px solid #eeeeee;
    padding-top: 82rpx !important;
    padding-bottom: 64rpx !important;
}

::v-deep .u-modal__content__text {
    font-weight: 500 !important;
    font-size: 32rpx !important;
    color: #333333 !important;
    text-align: center !important;
}

.rounded {
    width: 300rpx;
    line-height: 69rpx;
    background: linear-gradient(90deg, #ee6b67 0%, #ff7d78 100%);
    border-radius: 35rpx;
    font-weight: 400;
    font-size: 30rpx;
    color: #ffffff;
    text-align: center;
    margin: 0 auto;
}

.profile-container {
    font-family: Alibaba PuHuiTi;

    .me-header {
        height: 575rpx;

        .me-header-avatar-info {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            gap: 24rpx;

            .me-header-avatar {
                width: 128rpx;
                height: 128rpx;
                border-radius: 50%;
                overflow: hidden;

                image {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }

            .me-header-info {
                .me-header-name {
                    font-weight: 500;
                    font-size: 30rpx;
                    color: #ffffff;
                }
            }
        }

        .me-header-tips {
            display: flex;
            margin-top: 49rpx;

            .me-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;

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

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

    .me-header-menu {
        background: #ffffff;
        border-radius: 10rpx 10rpx 0rpx 0rpx;
        margin: -50rpx 24rpx 0;
        padding: 0 20rpx;

        .me-header-menu-item {
            height: 88rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #eeeeee;

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

            .me-header-menu-icon {
                display: flex;
                justify-content: center;
                align-items: center;
                gap: 13rpx;

                image {
                    width: 40rpx;
                    height: 40rpx;
                }

                .me-header-menu-text {
                    font-weight: 400;
                    font-size: 26rpx;
                    color: #333333;
                }
            }

            .me-header-menu-left {}
        }
    }
}

/* 昵称输入框样式 */
.nickname-input {
    width: 100%;
    height: 100%;
    font-weight: 500;
    font-size: 30rpx;
    color: #ffffff;
    background: transparent;
    border: none;
    outline: none;
    text-align: center;
}
</style>
