// pages/moments/list/momentslist.js
const app = getApp()
var innerAudioContext = wx.createInnerAudioContext()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        columnId: '',
        type: '',
        speedStep: 5, //快进快退秒数
        waitFlag: false,
        configMode: '2', //1单条数据  2多条数据
        dataList: [],
        count: 2,
        isLoadMore: false,
        imgUrl: app.urls.baseImgUrl,
        isRefresh: false,
        title: '栏目内容'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let _self = this
        _self.setData({
            columnId: options.id,
            configMode: options.mode,
            type: options.type,
            title: options.title
        })
        _self.getList()
    },
    onShow() {
        if (this.data.isRefresh) {
            wx.startPullDownRefresh({})
            this.setData({
                isRefresh: false
            })
        }
    },
    //获取栏目数据
    getList() {
        var _self = this
        wx.showLoading({
            title: '加载中...',
        })
        app.http.get(app.urls.getMomentsList.format({
                configColumnId: _self.data.columnId
            }), {
                header: {
                    token: app.globalData.token
                }
            })
            .then(res => {
                wx.hideLoading({})
                // 构建数据
                // 1:文字,2:照片,3:音频,4:视频,5:链接,6:定位,7:文章
                res.data.forEach(it => {
                    it.list.forEach(item => {
                        switch (item.dataType) {
                            case '2': //图片
                                var items = item.value.split(',')
                                var tempList = []
                                for (var i = 0; i < items.length; i++) {
                                    var urls = _self.data.imgUrl + items[i]
                                    var tempItem = {
                                        path: urls,
                                        imgPath: '../../../images/ic_temp.png'
                                    }
                                    tempList.push(tempItem)
                                }
                                item.valueList = tempList
                                break
                            case '4': //视频
                                var items = item.value.split(',')
                                var tempList = []
                                for (var i = 0; i < items.length; i++) {
                                    var ss = items[i].split('&')
                                    var videoUrl = app.urls.baseImgUrl + ss[0]
                                    var imgUrl = app.urls.baseImgUrl + ss[1]
                                    var tempItem = {
                                        path: videoUrl,
                                        imgPath: imgUrl
                                    }
                                    tempList.push(tempItem)
                                }
                                item.valueList = tempList
                                break
                            case '6': //定位
                                var items = item.value.split('-')
                                var tempList = []
                                for (var i = 0; i < items.length; i++) {
                                    //截取经纬度
                                    var latlng = items[i].split(',')
                                    var tempItem = {
                                        latitude: latlng[0], //纬度
                                        longitude: latlng[1], //经度
                                    }
                                    tempList.push(tempItem)
                                }
                                item.valueList = tempList
                                break
                            case '3': //音频
                                var items = item.value.split(',')
                                var tempList = []
                                for (var i = 0; i < items.length; i++) {
                                    var urls = _self.data.imgUrl + items[i]
                                    var tempItem = {
                                        path: urls, //地址
                                        isPlay: false, //是否播放中
                                        duration: 100, //时长
                                        curDuation: 0,
                                        curDurationStr: '00:00',
                                        totalDurationStr: '00:00'
                                    }
                                    tempList.push(tempItem)
                                }
                                item.valueList = tempList
                                break
                            case '8': //单选
                                item.dictionariesList.forEach(ss => {
                                    if (item.value.indexOf(ss.dataId) != -1) {
                                        item.selValue = ss.dataName
                                    }
                                })
                                break
                            case '9':
                                item.dictionariesList.forEach(ss => {
                                    if (item.value.indexOf(ss.dataId) != -1) {
                                        ss.isSel = true
                                    } else {
                                        ss.isSel = false
                                    }
                                })
                                break
                        }
                    })
                })
                _self.setData({
                    dataList: res.data
                })
                wx.stopPullDownRefresh({})
            })
            .catch(err => {
                console.log(err)
                wx.stopPullDownRefresh({})
            })
    },
    //展开更多
    toggleHandler: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        for (var i = 0; i < that.data.trendsList.length; i++) {
            if (index == i) {
                that.data.trendsList[index].auto = true;
                that.data.trendsList[index].seeMore = false;
            }
        }
        that.setData({
            trendsList: that.data.trendsList
        })
    },
    //收起更多
    toggleContent: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        for (var i = 0; i < that.data.trendsList.length; i++) {
            if (index == i) {
                that.data.trendsList[index].auto = true;
                that.data.trendsList[index].seeMore = true;
            }
        }
        that.setData({
            trendsList: that.data.trendsList
        })
    },
    //预览图片
    viewImg(e) {
        wx.previewImage({
            urls: [e.currentTarget.dataset.url],
        })
    },
    viewVideo(e) {
        var url = e.currentTarget.dataset.url
        wx.previewMedia({
            sources: [{
                url: url,
                type: 'video'
            }],
        })
    },
    onPullDownRefresh() {
        this.getList()
    },
    onReachBottom() {
        console.log('触底了')
    },
    play(e) {
        //进行播放
        var index = e.currentTarget.dataset.index
        var item = e.currentTarget.dataset.item
        var idx = e.currentTarget.dataset.idx
        var ix = e.currentTarget.dataset.i
        var _self = this
        _self.data.dataList.forEach(it => {
            it.list.forEach(item => {
                if (item.valueList) {
                    item.valueList.forEach(ii => {
                        if (ii.isPlay) {
                            innerAudioContext.stop()
                        }
                        ii.isPlay = false
                        ii.curDuation = 0
                        ii.curDuationStr = '00:00'
                    })
                }
            })
        })
        if (!item.isPlay) {
            // innerAudioContext.stop()
            //找到该文件
            innerAudioContext = wx.createInnerAudioContext()

            // 播放音频文件
            innerAudioContext.src = _self.data.dataList[index].list[idx].valueList[ix].path
            innerAudioContext.autoplay = true
        }
        //先需要停止其他录音文件的播放

        innerAudioContext.onPlay(() => {
            _self.data.dataList[index].list[idx].valueList[ix].isPlay = true
            _self.setData({
                dataList: _self.data.dataList
            })
        });

        innerAudioContext.onCanplay((res) => {
            // if (_self.data.waitFlag) {
            //     innerAudioContext.play()
            //     _self.setData({
            //         waitFlag: false
            //     })
            // }
        })
        innerAudioContext.onStop((res) => {
            _self.data.dataList[index].list[idx].valueList[ix].isPlay = false
            _self.data.dataList[index].list[idx].valueList[ix].curDuration = 0
            _self.data.dataList[index].list[idx].valueList[ix].curDurationStr = '00:00'
            _self.setData({
                dataList: _self.data.dataList,
            })
        })
        innerAudioContext.onEnded((res) => {
            _self.data.dataList[index].list[idx].valueList[ix].isPlay = false
            _self.data.dataList[index].list[idx].valueList[ix].curDuration = 0
            _self.data.dataList[index].list[idx].valueList[ix].curDurationStr = '00:00'
            _self.setData({
                dataList: _self.data.dataList,
            })
        })
        innerAudioContext.onError((res) => {
            _self.data.dataList[index].list[idx].valueList[ix].isPlay = false
            _self.data.dataList[index].list[idx].valueList[ix].curDuration = 0
            _self.data.dataList[index].list[idx].valueList[ix].curDurationStr = '00:00'
            _self.setData({
                dataList: _self.data.dataList,
            })
        })
        innerAudioContext.onSeeking(() => {
            console.log(innerAudioContext.currentTime)
        })
        innerAudioContext.onWaiting(() => {
            // innerAudioContext.pause()
            // _self.setData({
            //     waitFlag: true
            // })
        })
        innerAudioContext.onTimeUpdate(() => {
            if (innerAudioContext.duration != Infinity) {
                _self.data.dataList[index].list[idx].valueList[ix].curDuration = parseInt(innerAudioContext.currentTime)
                _self.data.dataList[index].list[idx].valueList[ix].duration = parseInt(innerAudioContext.duration)
                var curM = parseInt(innerAudioContext.currentTime / 60) //分钟
                var curS = parseInt(innerAudioContext.currentTime % 60) //秒
                var tM = parseInt(innerAudioContext.duration / 60) //分钟
                var tS = parseInt(innerAudioContext.duration % 60) //秒
                var curMStr = curM > 9 ? curM : '0' + curM
                var curSStr = curS > 9 ? curS : '0' + curS
                var totalMStr = tM > 9 ? tM : '0' + tM
                var totalSStr = +tS > 9 ? tS : '0' + tS
                _self.data.dataList[index].list[idx].valueList[ix].curDurationStr = curMStr + ':' + curSStr
                _self.data.dataList[index].list[idx].valueList[ix].totalDurationStr = totalMStr + ':' + totalSStr
                _self.setData({
                    dataList: _self.data.dataList
                })
            }
        })
    },
    //倒退5秒
    rewind(e) {
        var _self = this
        var index = e.currentTarget.dataset.index
        var item = e.currentTarget.dataset.item
        var idx = e.currentTarget.dataset.idx
        var ix = e.currentTarget.dataset.i
        if (item.isPlay) {
            _self.data.dataList[index].list[idx].valueList[ix].curDuration = _self.data.dataList[index].list[idx].valueList[ix].curDuration - _self.data.speedStep
            innerAudioContext.seek(_self.data.dataList[index].list[idx].valueList[ix].curDuration)
            _self.setData({
                dataList: _self.data.dataList
            })
        }

    },
    //快进5秒
    speed(e) {
        var _self = this
        var index = e.currentTarget.dataset.index
        var item = e.currentTarget.dataset.item
        var idx = e.currentTarget.dataset.idx
        var ix = e.currentTarget.dataset.i
        if (item.isPlay) {
            _self.data.dataList[index].list[idx].valueList[ix].curDuration = _self.data.dataList[index].list[idx].valueList[ix].curDuration + _self.data.speedStep
            innerAudioContext.seek(_self.data.dataList[index].list[idx].valueList[ix].curDuration)
            _self.setData({
                dataList: _self.data.dataList
            })
        }
    },
    slider4change(e) {
        var index = e.currentTarget.dataset.index
        var item = e.currentTarget.dataset.item
        if (item.isPlay) {
            innerAudioContext.seek(e.detail.value)
        }
    },
    //删除
    delItem(e) {
        wx.showModal({
            title: '提示',
            content: '确定要删除该条数据吗?',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    this.doDelMoment(e.currentTarget.dataset.index)
                }
            }
        })
    },
    doDelMoment(index) {
        var _self = this
        wx.showLoading({
            title: '删除中...',
        })
        var item = _self.data.dataList[index]
        app.http.delete(app.urls.doDelMoment.format({
                configColumnId: _self.data.columnId,
                uid: item.uid
            }), {
                header: {
                    token: app.globalData.token
                }
            })
            .then(res => {
                wx.hideLoading({})
                wx.showToast({
                    title: '删除成功',
                    icon: 'success'
                })
                this.data.dataList.splice(index, 1)
                this.setData({
                    dataList: this.data.dataList
                })
                wx.startPullDownRefresh({})
            })
            .catch(err => {
                console.log(err)
                wx.hideLoading({})
            })
    },
    doPublish() {
        wx.navigateTo({
            url: '../publish/momentpublishline?id=' + this.data.columnId + '&title=' + this.data.title
        })
    },
    editMoment(e) {
        var _self = this
        var item = _self.data.dataList[e.currentTarget.dataset.index]
        wx.navigateTo({
            url: '../edit/momentedit?id=' + _self.data.columnId + '&uid=' + item.uid + '&title=' + _self.data.title
        })
    }
})