/**
 * 收听历史 — 历史 / 收藏 两 Tab
 */
const app = getApp()
const api = require('../../utils/api')
const util = require('../../utils/util')

Page({
    data: {
        tab: 'history',        // 'history' | 'favorite'
        historyList: [],
        isPlaying: false,
        loading: true
    },

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

        // 未登录则先登录
        if (!gd.isLoggedIn || !gd.token) {
            app.login().then(function () {
                self._refresh()
            }).catch(function () {
                self.setData({ loading: false })
                wx.showToast({ title: '请先登录', icon: 'none' })
            })
        } else {
            this._refresh()
        }

        this._onPlayerChange = () => this._updatePlayState()
        app.on('playerStateChange', this._onPlayerChange)
    },

    onHide() {
        if (this._onPlayerChange) app.off('playerStateChange', this._onPlayerChange)
    },

    setTab(e) {
        const tab = e.currentTarget.dataset.val
        if (tab === this.data.tab) return
        this.setData({ tab, historyList: [], loading: true })
        this._refresh()
    },

    _refresh() {
        if (this.data.tab === 'history') {
            this._loadHistory()
        } else {
            this._loadFavorites()
        }
    },

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

        api.getHistoryList({ current: 1, pageSize: 30 }).then(function (res) {
            if (res.code === 200 && res.data) {
                var list = (res.data.list || []).map(function (item) {
                    // program 嵌套在 item.program 下
                    var program = item.program || {}
                    // channel 可能为 null，channel cover 在 program.cover
                    var channel = program.channel || {}
                    return {
                        // 播放所需字段
                        id: program.id,
                        title: program.title || '未知节目',
                        channelId: program.channelId || '',
                        content: program.content || '',
                        audioId: program.audioId || '',
                        // 用历史记录的 duration（program.duration 可能是 0）
                        duration: item.duration || program.duration || 0,
                        // 显示字段
                        _domainName: channel.name || '',
                        _icon: program.cover || channel.cover || '📻',
                        _bgColor: '#FFE8CC',
                        _friendlyDate: util.getFriendlyDate(item.createdAtStr ? item.createdAtStr.substring(0, 10) : ''),
                        durationText: util.formatTime(item.duration || 0),
                        // 播放进度
                        _progress: item.progress || 0,
                        _isThisPlaying: gd.activeContent && gd.activeContent.id === program.id
                    }
                })
                self.setData({ historyList: list, isPlaying: gd.isPlaying, loading: false })
            } else {
                self.setData({ historyList: [], loading: false })
            }
        }).catch(function (err) {
            console.error('[History] 加载历史失败:', err)
            self.setData({ loading: false })
        })
    },

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

        api.getFavoriteList({ current: 1, pageSize: 30 }).then(function (res) {
            if (res.code === 200 && res.data) {
                var list = (res.data.list || []).map(function (item) {
                    var program = item.program || item
                    var channel = program.channel || {}
                    return {
                        id: program.id,
                        title: program.title || '未知节目',
                        channelId: program.channelId || '',
                        content: program.content || '',
                        audioId: program.audioId || '',
                        duration: program.duration || 0,
                        _domainName: channel.name || '',
                        _icon: program.cover || channel.cover || '📻',
                        _bgColor: '#FFE8CC',
                        _friendlyDate: util.getFriendlyDate(item.createdAtStr ? item.createdAtStr.substring(0, 10) : ''),
                        durationText: util.formatTime(program.duration || 0),
                        _isThisPlaying: gd.activeContent && gd.activeContent.id === program.id
                    }
                })
                self.setData({ historyList: list, isPlaying: gd.isPlaying, loading: false })
            } else {
                self.setData({ historyList: [], loading: false })
            }
        }).catch(function (err) {
            console.error('[History] 加载收藏失败:', err)
            self.setData({ loading: false })
        })
    },

    _updatePlayState() {
        var gd = app.globalData
        var list = this.data.historyList.map(function (item) {
            return Object.assign({}, item, {
                _isThisPlaying: gd.activeContent && gd.activeContent.id === item.id
            })
        })
        this.setData({ historyList: list, isPlaying: gd.isPlaying })
    },

    onPlay(e) {
        const id = e.currentTarget.dataset.id
        const gd = app.globalData

        if (gd.activeContent && gd.activeContent.id === id) {
            app.togglePlay()
            return
        }

        // 从列表中找到基础信息
        var base = null
        for (var i = 0; i < this.data.historyList.length; i++) {
            if (this.data.historyList[i].id === id) {
                base = this.data.historyList[i]
                break
            }
        }
        if (!base) return

        // 拉取完整节目详情（含 audio.url）再播放
        wx.showLoading({ title: '加载中' })
        api.getProgramDetail(id).then(function (res) {
            wx.hideLoading()
            if (res.code === 200 && res.data) {
                app.playContent(Object.assign({}, base, res.data))
            } else {
                wx.showToast({ title: '加载失败', icon: 'none' })
            }
        }).catch(function () {
            wx.hideLoading()
            wx.showToast({ title: '网络异常', icon: 'none' })
        })
    },

    onDeleteItem(e) {
        const id = e.currentTarget.dataset.id
        const tab = this.data.tab
        const self = this
        const label = tab === 'history' ? '历史' : '收藏'

        wx.showModal({
            title: '删除' + label,
            content: '确定删除这条' + label + '吗？',
            success(res) {
                if (!res.confirm) return
                const fn = tab === 'history'
                    ? api.deleteHistory(id)
                    : api.removeFavorite(id)

                fn.then(function (r) {
                    if (r.code === 200) {
                        // 本地即时移除
                        var list = self.data.historyList.filter(function (item) { return item.id !== id })
                        self.setData({ historyList: list })
                    } else {
                        wx.showToast({ title: r.msg || '删除失败', icon: 'none' })
                    }
                }).catch(function () {
                    wx.showToast({ title: '网络异常', icon: 'none' })
                })
            }
        })
    },

    onClear() {
        const self = this
        const tab = this.data.tab
        const label = tab === 'history' ? '收听历史' : '全部收藏'
        wx.showModal({
            title: '清空' + label,
            content: '确定要清空所有' + label + '吗？',
            success(res) {
                if (!res.confirm) return
                const fn = tab === 'history'
                    ? api.deleteAllHistory()
                    : api.removeAllFavorites()
                fn.then(function (r) {
                    if (r.code === 200) {
                        self.setData({ historyList: [] })
                    } else {
                        wx.showToast({ title: r.msg || '操作失败', icon: 'none' })
                    }
                }).catch(function () {
                    wx.showToast({ title: '网络异常', icon: 'none' })
                })
            }
        })
    },

    goDiscover() { wx.switchTab({ url: '/pages/discover/index' }) },
    goHome() { wx.switchTab({ url: '/pages/index/index' }) },
    goVip() { wx.navigateTo({ url: '/pages/vip/index' }) }
})
