/**
 * 收听历史 — 从后端获取历史列表
 */
const app = getApp()
const api = require('../../utils/api')
const util = require('../../utils/util')

Page({
    data: {
        filter: 'all',
        cleared: false,
        historyList: [],
        isPlaying: false,
        loading: true
    },

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

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

    _refresh() {
        if (this.data.cleared) return

        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 || res.data || []

                // 附带格式化信息
                list = list.map(function (item) {
                    // 节目可能包含频道信息，根据后端返回结构适配
                    var channel = item.channel || item.program && item.program.channel || {}
                    var program = item.program || item

                    return Object.assign({}, program, {
                        _domainName: channel.name || program.channelName || '',
                        _icon: channel.icon || '🎵',
                        _bgColor: channel.bgColor || '#F0F0F0',
                        _coverUrl: (channel.cover && channel.cover.url) || channel.coverUrl || '',
                        _friendlyDate: util.getFriendlyDate(
                            program.createdAt ? program.createdAt.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 })
    },

    setFilter(e) {
        this.setData({ filter: e.currentTarget.dataset.val })
    },

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

        // 从已加载数据中查找
        var content = null
        for (var i = 0; i < this.data.historyList.length; i++) {
            if (this.data.historyList[i].id === id) {
                content = this.data.historyList[i]
                break
            }
        }
        if (!content) return

        if (gd.activeContent && gd.activeContent.id === id) {
            app.togglePlay()
        } else {
            app.playContent(content)
        }
    },

    onClear() {
        const self = this
        wx.showModal({
            title: '提示',
            content: '确定要清空所有收听历史吗？',
            success(res) {
                if (res.confirm) {
                    self.setData({ cleared: true, historyList: [] })
                }
            }
        })
    }
})
