/**
 * 个人中心 — 用户信息 + 订阅管理 + 菜单
 * 从后端获取已订阅频道列表
 */
const app = getApp()
const api = require('../../utils/api')

Page({
    data: {
        isVip: false,
        userInfo: null,
        menuItems: [
            { id: 'vip', label: '会员中心', icon: '👑', desc: '未开通', highlight: true },
            { id: 'notification', label: '通知设置', icon: '🔔', desc: '', highlight: false },
            { id: 'help', label: '帮助与反馈', icon: '❓', desc: '', highlight: false },
            { id: 'about', label: '关于我们', icon: '📄', desc: 'v1.0.0', highlight: false }
        ]
    },

    onShow() {
        this._refresh()
        this._onSubChange = () => this._refresh()
        this._onVipChange = () => this._refresh()
        app.on('subscriptionChange', this._onSubChange)
        app.on('vipChange', this._onVipChange)
    },

    onHide() {
        if (this._onSubChange) app.off('subscriptionChange', this._onSubChange)
        if (this._onVipChange) app.off('vipChange', this._onVipChange)
    },

    _refresh() {
        const self = this
        const gd = app.globalData

        this.setData({
            isVip: gd.isVip,
            userInfo: gd.userInfo
        })

        // 更新菜单VIP状态
        var menuItems = this.data.menuItems.slice()
        menuItems[0].desc = gd.isVip ? '已开通' : '未开通'
        menuItems[0].highlight = !gd.isVip
        this.setData({ menuItems: menuItems })
    },

    onMenuTap(e) {
        const id = e.currentTarget.dataset.id
        if (id === 'vip') {
            wx.navigateTo({ url: '/pages/vip/index' })
        } else if (id === 'notification') {
            wx.openSetting({
                success(res) {
                    if (res.authSetting['scope.subscribeMessage'] !== undefined) {
                        wx.showToast({ title: '设置已更新', icon: 'none' })
                    }
                },
                fail() {
                    wx.showToast({ title: '请在系统设置中允许通知', icon: 'none' })
                }
            })
        } else if (id === 'help') {
            wx.showToast({ title: '帮助中心开发中', icon: 'none' })
        } else if (id === 'about') {
            wx.showToast({ title: '早安电台 v1.0.0', icon: 'none' })
        }
    },

    goDiscover() {
        wx.switchTab({ url: '/pages/discover/index' })
    }
})
