/**
 * 首次引导页 — 选择2个免费频道
 */
const app = getApp()
const mock = require('../../utils/mock')

Page({
    data: {
        domains: mock.DOMAINS,
        selectedIds: [],
        isValid: false,
        statusBarHeight: 0
    },

    onLoad() {
        this.setData({
            statusBarHeight: app.globalData.statusBarHeight
        })
    },

    /**
     * 切换频道选中状态
     */
    onToggle(e) {
        const id = e.currentTarget.dataset.id
        let selected = this.data.selectedIds.slice()

        const idx = selected.indexOf(id)
        if (idx > -1) {
            // 取消选中
            selected.splice(idx, 1)
        } else {
            // 选中（最多2个）
            if (selected.length >= 2) {
                wx.showToast({ title: '最多选择2个免费频道', icon: 'none' })
                return
            }
            selected.push(id)
        }

        this.setData({
            selectedIds: selected,
            isValid: selected.length > 0 && selected.length <= 2
        })
    },

    /**
     * 确认选择
     */
    onConfirm() {
        if (!this.data.isValid) return

        const self = this
        this.data.selectedIds.forEach(function (id) {
            app.subscribeToDomain(id)
        })

        wx.showToast({ title: '订阅成功！', icon: 'success' })

        setTimeout(function () {
            wx.switchTab({ url: '/pages/index/index' })
        }, 800)
    }
})
