/**
 * 订阅支付页
 * 接收参数：channelId, channelName, monthlyPrice, quarterlyPrice, annualPrice
 */
const app = getApp()
const api = require('../../utils/api')

Page({
    data: {
        channelId: '',
        channelName: '',
        monthlyPrice: 0,
        quarterlyPrice: 0,
        annualPrice: 0,
        selectedPlan: '',   // 'monthly' | 'quarterly' | 'annual'
        currentPrice: 0
    },

    onLoad(options) {
        // 后端价格单位为「分」，除以 100 转为「元」
        const monthly = (parseFloat(options.monthlyPrice) || 0) / 100
        const quarterly = (parseFloat(options.quarterlyPrice) || 0) / 100
        const annual = (parseFloat(options.annualPrice) || 0) / 100

        // 默认选中"包年"（如果有），否则最便宜的
        let defaultPlan = ''
        let defaultPrice = 0
        if (annual > 0) {
            defaultPlan = 'annual'
            defaultPrice = annual
        } else if (quarterly > 0) {
            defaultPlan = 'quarterly'
            defaultPrice = quarterly
        } else if (monthly > 0) {
            defaultPlan = 'monthly'
            defaultPrice = monthly
        }

        this.setData({
            channelId: options.channelId || '',
            channelName: decodeURIComponent(options.channelName || ''),
            monthlyPrice: monthly,
            quarterlyPrice: quarterly,
            annualPrice: annual,
            selectedPlan: defaultPlan,
            currentPrice: defaultPrice,
            // 预计算节省金额和月均价（WXML 不支持 .toFixed()）
            _quarterlySaving: monthly > 0 && quarterly > 0 ? Math.round(monthly * 3 - quarterly) : 0,
            _quarterlyMonthly: quarterly > 0 ? (quarterly / 3).toFixed(1) : '0',
            _annualSaving: monthly > 0 && annual > 0 ? Math.round(monthly * 12 - annual) : 0,
            _annualMonthly: annual > 0 ? (annual / 12).toFixed(1) : '0'
        })
    },

    /** 选择套餐 */
    selectPlan(e) {
        const plan = e.currentTarget.dataset.plan
        const priceMap = {
            monthly: this.data.monthlyPrice,
            quarterly: this.data.quarterlyPrice,
            annual: this.data.annualPrice
        }
        this.setData({
            selectedPlan: plan,
            currentPrice: priceMap[plan] || 0
        })
    },

    /** 发起支付 */
    onPay() {
        const { channelId, selectedPlan, currentPrice, channelName } = this.data

        if (!selectedPlan) {
            wx.showToast({ title: '请选择订阅方案', icon: 'none' })
            return
        }

        // 调用订阅/支付接口
        wx.showLoading({ title: '处理中...' })
        api.subscribeChannel({
            channelId,
            plan: selectedPlan,
            price: currentPrice
        }).then(function (res) {
            wx.hideLoading()
            if (res.code === 200) {
                wx.showToast({ title: '订阅成功！', icon: 'success' })
                setTimeout(function () {
                    wx.navigateBack()
                }, 1500)
            } else {
                wx.showToast({ title: res.msg || '订阅失败', icon: 'none' })
            }
        }).catch(function (err) {
            wx.hideLoading()
            console.error('[订阅] 失败:', err)
            wx.showToast({ title: '网络异常，请重试', icon: 'none' })
        })
    }
})
