import { logout as logoutApi } from '@/api/auth'
import { getMyProfile } from '@/api/fulfiller'
import { clearAuth, isLoggedIn } from '@/utils/auth'

export default {
    data() {
        return {
            showServicePopup: false,
            showLogoutPopup: false,
            profile: null,
            profileLoading: false
        }
    },
    onShow() {
        if (isLoggedIn()) {
            this.loadProfile()
        }
    },
    methods: {
        async loadProfile() {
            if (this.profileLoading) return
            this.profileLoading = true
            try {
                const res = await getMyProfile()
                this.profile = res.data || null
            } catch (err) {
                console.error('获取个人信息失败:', err)
            } finally {
                this.profileLoading = false
            }
        },
        navToSettings() {
            uni.navigateTo({
                url: '/pages/mine/settings/index'
            });
        },
        navToProfile() {
            uni.navigateTo({
                url: '/pages/mine/settings/profile/index'
            });
        },
        navToLevel() {
            uni.navigateTo({
                url: '/pages/mine/level/index'
            });
        },
        navToNotification() {
            uni.navigateTo({
                url: '/pages/mine/message/index'
            });
        },
        navToWallet() {
            uni.navigateTo({
                url: '/pages/mine/wallet/index'
            });
        },
        navToPoints() {
            uni.navigateTo({
                url: '/pages/mine/points/index'
            });
        },
        navToOrderStats() {
            uni.navigateTo({
                url: '/pages/mine/order-stats'
            });
        },
        navToRewards() {
            uni.navigateTo({
                url: '/pages/mine/rewards'
            });
        },
        openServicePopup() {
            this.showServicePopup = true;
        },
        closeServicePopup() {
            this.showServicePopup = false;
        },
        previewQRCode() {
            uni.previewImage({
                urls: ['/static/logo.png']
            });
        },
        openOnlineService() {
            // 模拟跳转企业微信客服
            uni.showToast({
                title: '正在跳转企业微信客服...',
                icon: 'none'
            });
        },
        callServicePhone() {
            uni.makePhoneCall({
                phoneNumber: '400-123-4567'
            });
        },
        logout() {
            this.showLogoutPopup = true;
        },
        cancelLogout() {
            this.showLogoutPopup = false;
        },
        async confirmLogout() {
            this.showLogoutPopup = false;
            try {
                await logoutApi()
            } catch (e) {
                // 即使后端退出失败，也清除本地登录态
            }
            clearAuth()
            uni.reLaunch({
                url: '/pages/login/login'
            });
        }
    }
}
