const app = getApp()
const recorderManager = wx.getRecorderManager()
var innerAudioContext = wx.createInnerAudioContext()
const chooseLocation = requirePlugin('chooseLocation');
const key = 'Y6FBZ-GLQC3-6273Q-3DRTL-W43G5-G6BXN'; //使用在腾讯位置服务申请的key
const referer = '名片-小程序'; //调用插件的app的名称
const location = JSON.stringify({
    latitude: 39.89631551,
    longitude: 116.323459711
});
const category = '生活服务,娱乐休闲';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        uploadCount: 0,
        uploadVideoCount: 0,
        currentIndex: 0,
        columnId: '', //栏目Id
        uId: '', //内容UID
        fieldList: [], //栏目字段
        textList: [], //文本添加内容
        textareaList: [], //文本域添加内容
        audioList: [], //音频添加内容
        videoList: [], //视频添加内容
        photoList: [], //视频添加内容
        linkList: [], //连接添加内容
        locationList: [], //定位添加内容
        isShowText: false, //文本弹窗开关
        isShowDesc: false, //文本域弹窗开关
        isShowPhoto: false, //图片选择弹框
        isShowLink: false, //链接弹窗
        isShowAudio: false, //录音弹窗
        isShowVideo: false, //视频弹窗
        isShowTags: false, //多选
        tempText: '',
        tempDesc: '',
        linkStr: '',
        map: null,
        waitFlag: false,
        isStartRecord: false, //是否录音中
        speck_time: 0,
        speedStep: 5, //快进快退秒数
        setInter: '', //定时器
        currentItem: undefined,
        isAuthAudio: false,
        title: '栏目内容修改'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            columnId: options.id,
            uId: options.uid,
            title: options.title + '修改'
        })
        this.checkPermission()
        this.getMomentContent()
    },
    getMomentContent() {
        wx.showLoading({
            title: '加载中...',
        })
        var _self = this
        app.http.get(app.urls.getMomentsContent.format({
                configColumnId: _self.data.columnId,
                uid: _self.data.uId
            }), {
                header: {
                    token: app.globalData.token
                }
            })
            .then(res => {
                wx.hideLoading({})
                //构建数据
                _self.buildDetail(res.data)
            })
            .catch(err => {
                wx.hideLoading({})
                console.log(err)
            })
    },
    //构建展示数据
    buildDetail(data) {
        var _self = this
        data.list.forEach(it => {
            switch (it.dataType) {
                case '2': //图片
                    var items = it.value.split(',')
                    var tempList = []
                    items.forEach(item => {
                        var tempItem = {
                            id: item,
                            path: app.urls.baseImgUrl + item,
                        }
                        tempList.push(tempItem)
                    })
                    it.valueList = tempList
                    break
                case '4': //视频
                    var items = it.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)
                    }
                    it.valueList = tempList
                    break
                case '3': //音频
                    var items = it.value.split(',')
                    var tempList = []
                    items.forEach(item => {
                        var tempItem = {
                            id: item, //id
                            path: app.urls.baseImgUrl + item, //地址
                            isPlay: false, //是否播放中
                            duration: 100, //时长
                            curDuation: 0,
                            curDurationStr: '00:00',
                            totalDurationStr: '00:00'
                        }
                        tempList.push(tempItem)
                    })
                    it.valueList = tempList
                    break
                case '6': //定位
                    var items = it.value.split('-')
                    var tempList = []
                    items.forEach(item => {
                        var latlng = item.split(',')
                        var tempItem = {
                            name: '',
                            address: '',
                            latitude: latlng[0],
                            longitude: latlng[1],
                        }
                        tempList.push(tempItem)
                    })
                    it.valueList = tempList
                    break
                case '8': //单选
                    it.dictionariesList.forEach(ss => {
                        if (it.value.indexOf(ss.dataId) != -1) {
                            it.selValue = ss.dataName
                        }
                    })
                    break
                case '9':
                    var selValue = ''
                    it.dictionariesList.forEach(ss => {
                        if (it.value.indexOf(ss.dataId) != -1) {
                            selValue += ss.dataName + ','
                            ss.isSel = true
                        } else {
                            ss.isSel = false
                        }
                    })
                    selValue = selValue.substr(0, selValue.length - 1)
                    it.selValue = selValue
                    break
            }
        })
        _self.setData({
            fieldList: data.list
        })
    },
    showMutliSel(e) {
        this.setData({
            isShowTags: true,
            currentIndex: e.currentTarget.dataset.index
        })
    },
    //单选
    pickerChange(e) {
        var _self = this
        var index = e.currentTarget.dataset.index
        var selIndex = e.detail.value
        _self.data.fieldList[index].index = selIndex
        _self.data.fieldList[index].value = _self.data.fieldList[index].dictionariesList[selIndex].dataId
        _self.data.fieldList[index].selValue = _self.data.fieldList[index].dictionariesList[selIndex].dataName
        _self.setData({
            fieldList: _self.data.fieldList
        })
    },
    inputText(e) {
        var index = e.currentTarget.dataset.index
        var _self = this
        _self.data.fieldList[index].value = e.detail.value
        _self.setData({
            fieldList: _self.data.fieldList
        })
    },
    //申请录音权限
    checkPermission() {
        var _self = this
        wx.getSetting({
            success(res) {
                var isAuth = res.authSetting['scope.record']
                if (typeof (isAuth) == 'undefined') {
                    wx.authorize({
                        scope: 'scope.record',
                        success() {
                            _self.setData({
                                isAuthAudio: true
                            })
                        },
                        fail() {
                            _self.setData({
                                isAuthAudio: false
                            })
                        }
                    })
                } else {
                    if (!isAuth) {
                        _self.openSetting()
                    }
                }
            }
        })
    },
    openSetting() {
        wx.showModal({
            title: '提示',
            content: '发布内容需要您授权录音权限.',
            success(res) {
                if (res.confirm) {
                    wx.openSetting({
                        withSubscriptions: true,
                    })
                }
            }
        })
    },
    onShow() {
        if (chooseLocation.getLocation() != null) {
            var item = this.data.fieldList[this.data.curMapIndex]
            if (item.valueList.length < item.maxCount) {
                this.data.fieldList[this.data.curMapIndex].valueList.push(chooseLocation.getLocation())
                this.setData({
                    fieldList: this.data.fieldList
                })
            }
        }
        var _self = this
        wx.getSetting({
            withSubscriptions: true,
            success(res) {
                var isAuth = res.authSetting['scope.record']
                _self.setData({
                    isAuthAudio: isAuth
                })
            }
        })

    },
    onUnload() {
        chooseLocation.setLocation(null)
        this.setData({
            map: null
        })
    },
    //选择视频来源
    chooseVideo(e) {
        var _self = this
        var item = e.currentTarget.dataset.item
        var countNum = item.maxCount - item.valueList.length
        var index = e.currentTarget.dataset.index
        wx.chooseMedia({
            count: Number.parseInt(countNum),
            mediaType: ['video'],
            sourceType: ['camera', 'album'],
            maxDuration: 60,
            success: (res) => {
                if (res.tempFiles.length > 0) {
                    _self.doUploadVideo(index, res.tempFiles, _self.data.uploadVideoCount)
                }
            },
            fail: (err) => {
                // console.log(err)
                // wx.showToast({
                //     title: '选取视频失败,(拍摄时长:60秒)',
                //     icon: 'none'
                // })
            }
        })
    },
    //上传视频
    doUploadVideo(fieldIndex, paths, videoCount) {
        wx.showLoading({
            title: '上传中...',
        })
        let _self = this
        var count = paths.length //几次
        if (_self.data.uploadVideoCount < count) {
            app.http.upload(app.urls.doUploadVideo, {
                    path: paths[_self.data.uploadVideoCount].tempFilePath,
                    name: 'video',
                    header: {
                        token: app.globalData.token
                    }
                })
                .then(res => {
                    wx.hideLoading({})
                    //插入到集合中
                    var id = JSON.parse(res).data
                    _self.doUploadVideoImg(fieldIndex, id, paths, _self.data.uploadVideoCount)
                })
                .catch(err => {
                    wx.hideLoading({})
                    _self.setData({
                        uploadVideoCount: ++_self.data.uploadVideoCount
                    })
                    _self.doUploadVideo(fieldIndex, paths, _self.data.uploadVideoCount)
                })
        } else {
            wx.hideLoading({})
            _self.setData({
                uploadVideoCount: 0
            })
        }
    },
    //上传视频封面图片
    doUploadVideoImg(fieldIndex, videoId, videos, videoCount) {
        wx.showLoading({
            title: '上传中...',
        })
        let _self = this
        app.http.upload(app.urls.doUploadImg, {
                path: videos[_self.data.uploadVideoCount].thumbTempFilePath,
                name: 'image',
                header: {
                    token: app.globalData.token
                }
            })
            .then(res => {
                console.log(res)
                wx.hideLoading({})
                var videoUrl = app.urls.baseImgUrl + videoId
                var thumbImg = app.urls.baseImgUrl + JSON.parse(res).data
                var thumbI = JSON.parse(res).data
                var item = {
                    id: videoId,
                    thumbId: thumbI,
                    path: videoUrl,
                    imgPath: thumbImg
                }
                _self.data.fieldList[fieldIndex].valueList.push(item)
                _self.setData({
                    fieldList: _self.data.fieldList
                })
                _self.setData({
                    uploadVideoCount: ++_self.data.uploadVideoCount
                })
                _self.doUploadVideo(fieldIndex, videos, _self.data.uploadVideoCount)
            })
            .catch(err => {
                console.log(err)
                wx.hideLoading({})
                _self.setData({
                    uploadVideoCount: ++_self.data.uploadVideoCount
                })
                _self.doUploadVideo(fieldIndex, videos, _self.data.uploadVideoCount)
            })
    },
    //预览视频
    viewVideo(e) {
        var tempList = [{
            url: e.currentTarget.dataset.url,
            type: 'video'
        }]
        wx.previewMedia({
            sources: tempList,
            current: 0,
            showmenu: false
        })
    },
    //删除视频
    delVideo(e) {
        let _self = this
        var index = e.currentTarget.dataset.index
        var idx = e.currentTarget.dataset.idx
        wx.showModal({
            title: '提示',
            content: '确定要删除该视频吗？',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    _self.data.fieldList[index].valueList.splice(idx, 1)
                    _self.setData({
                        fieldList: _self.data.fieldList
                    })
                }
            }
        })
    },
    //添加链接
    addLink() {
        var _self = this
        var item = null
        for (var i = 0; i < _self.data.items.length; i++) {
            if (_self.data.items[i].type == 'LINK') {
                item = _self.data.items[i]
                break
            }
        }
        if (_self.data.linkList.length < item.count) {
            if (_self.data.linkStr == '') {
                wx.showToast({
                    title: '请输入文字内容',
                    icon: 'error'
                })
                return
            }
            _self.data.linkList.push(_self.data.linkStr)
            _self.setData({
                linkList: _self.data.linkList,
                linkStr: ''
            })
            if (_self.data.linkList.length == item.count) {
                _self.setData({
                    isShowLink: false
                })
            }
        }
    },
    //文本域添加输入的文字
    addDesc() {
        var _self = this
        var item = null
        for (var i = 0; i < _self.data.items.length; i++) {
            if (_self.data.items[i].type == 'TEXTAREA') {
                item = _self.data.items[i]
                break
            }
        }
        if (_self.data.textareaList.length < item.count) {
            if (_self.data.tempDesc == '') {
                wx.showToast({
                    title: '请输入文字内容',
                    icon: 'error'
                })
                return
            }
            _self.data.textareaList.push(_self.data.tempDesc)
            _self.setData({
                textareaList: _self.data.textareaList,
                tempDesc: ''
            })
            if (_self.data.textareaList.length == item.count) {
                _self.setData({
                    isShowDesc: false
                })
            }
        }
    },
    //添加输入的文字
    addStr() {
        var _self = this
        var item = null
        for (var i = 0; i < _self.data.items.length; i++) {
            if (_self.data.items[i].type == 'TEXT') {
                item = _self.data.items[i]
                break
            }
        }
        if (_self.data.textList.length < item.count) {
            if (_self.data.tempText == '') {
                wx.showToast({
                    title: '请输入文字内容',
                    icon: 'error'
                })
                return
            }
            _self.data.textList.push(_self.data.tempText)
            _self.setData({
                textList: _self.data.textList,
                tempText: ''
            })
            if (_self.data.textList.length == item.count) {
                _self.setData({
                    isShowText: false
                })
            }
        }
    },
    //删除
    delText(e) {
        wx.showModal({
            title: '提示',
            content: '确定要删除该条数据吗?',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    this.data.textList.splice(e.currentTarget.dataset.index, 1)
                    this.setData({
                        textList: this.data.textList
                    })
                }
            }
        })
    },
    delLink(e) {
        wx.showModal({
            title: '提示',
            content: '确定要删除该条数据吗?',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    this.data.linkList.splice(e.currentTarget.dataset.index, 1)
                    this.setData({
                        linkList: this.data.linkList
                    })
                }
            }
        })
    },
    delDesc(e) {
        wx.showModal({
            title: '提示',
            content: '确定要删除该条数据吗?',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    this.data.textareaList.splice(e.currentTarget.dataset.index, 1)
                    this.setData({
                        textareaList: this.data.textareaList
                    })
                }
            }
        })
    },
    //监听输入的文字
    textInput(e) {
        this.setData({
            [e.currentTarget.id]: e.detail.value
        })
    },
    //关闭弹窗
    onHide(e) {
        this.setData({
            isShowText: false,
            isShowDesc: false,
            isShowPhoto: false,
            isShowLink: false,
            isShowAudio: false,
            isShowVideo: false,
            isShowTags: false
        })
    },

    chooseTags(e) {
        var _self = this
        var index = e.currentTarget.dataset.idx
        _self.data.fieldList[_self.data.currentIndex].dictionariesList[index].isSel = !_self.data.fieldList[_self.data.currentIndex].dictionariesList[index].isSel
        _self.setData({
            fieldList: _self.data.fieldList
        })
        var value = ''
        var ids = ''
        _self.data.fieldList[_self.data.currentIndex].dictionariesList.forEach(it => {
            if (it.isSel) {
                value += it.dataName + ','
                ids += it.dataId + ','
            }
        })
        value = value.substr(0, value.length - 1)
        ids = ids.substr(0, ids.length - 1)
        _self.data.fieldList[_self.data.currentIndex].selValue = value
        _self.data.fieldList[_self.data.currentIndex].value = ids
        _self.setData({
            fieldList: _self.data.fieldList
        })
    },
    selTags() {
        this.setData({
            isShowTags: false
        })
    },
    //选择图片
    choosePhoto(e) {
        var _self = this
        var item = e.currentTarget.dataset.item
        var index = e.currentTarget.dataset.index
        var countNum = item.maxCount - item.valueList.length

        wx.chooseImage({
            count: Number.parseInt(countNum),
            sourceType: ['album', 'camera'],
            success: (res) => {
                _self.doUploadImg(index, res.tempFilePaths, _self.data.uploadCount)
            },
            fail: (err) => {

            }
        })
    },
    //删除图片
    delImg(e) {
        wx.showModal({
            title: '提示',
            content: '确定要删除该图片吗？',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    this.data.fieldList[e.currentTarget.dataset.itemindex].valueList.splice(e.currentTarget.dataset.index, 1)
                    this.setData({
                        fieldList: this.data.fieldList
                    })
                }
            }
        })
    },
    //预览图片
    viewImg(e) {
        var tempList = [e.currentTarget.dataset.url]
        wx.previewImage({
            urls: tempList,
            current: e.currentTarget.dataset.url
        });
    },
    doUploadImg(index, paths, curIndex) {
        wx.showLoading({
            title: '上传中...',
        })
        let _self = this
        var count = paths.length //几次
        if (_self.data.uploadCount < count) {
            app.http.upload(app.urls.doUploadImg, {
                    path: paths[_self.data.uploadCount],
                    name: 'image',
                    header: {
                        token: app.globalData.token
                    }
                })
                .then(res => {
                    wx.hideLoading({})
                    //插入到集合中
                    var id = JSON.parse(res).data
                    var pathStr = app.urls.baseImgUrl + id
                    var item = {
                        id: id,
                        path: pathStr
                    }
                    _self.data.fieldList[index].valueList.push(item)
                    _self.setData({
                        fieldList: _self.data.fieldList
                    })
                    _self.setData({
                        uploadCount: ++_self.data.uploadCount
                    })
                    _self.doUploadImg(index, paths, _self.data.uploadCount)
                })
                .catch(err => {
                    wx.hideLoading({})
                    _self.setData({
                        uploadCount: ++_self.data.uploadCount
                    })
                    _self.doUploadImg(index, paths, _self.data.uploadCount)
                })
        } else {
            wx.hideLoading({})
            _self.setData({
                uploadCount: 0
            })
        }
    },
    //地图选点
    chooseLocation(e) {
        var index = e.currentTarget.dataset.index
        this.setData({
            curMapIndex: index
        })
        wx.navigateTo({
            url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
        });
    },
    delMap(e) {
        wx.showModal({
            title: '提示',
            content: '确定要删除该条数据吗?',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    this.data.locationList.splice(e.currentTarget.dataset.index, 1)
                    this.setData({
                        locationList: this.data.locationList
                    })
                }
            }
        })
    },
    //删除视频
    delAudio(e) {
        console.log(e)
        let _self = this
        wx.showModal({
            title: '提示',
            content: '确定要删除该音频吗？',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    _self.data.fieldList[e.currentTarget.dataset.index].valueList.splice(e.currentTarget.dataset.idx, 1)
                    _self.setData({
                        fieldList: _self.data.fieldList
                    })
                }
            }
        })
    },
    doStartRecord() {
        var _self = this
        wx.getSetting({
            success(res) {
                if (!res.authSetting['scope.record']) {
                    wx.authorize({
                        scope: 'scope.record',
                        success() {
                            _self.startRecord()
                        }
                    })
                } else {
                    _self.startRecord()
                }
            }
        })
    },
    startRecord() {
        var that = this
        that.data.setInter = setInterval(
            function () {
                var speck_time = parseInt(that.data.speck_time + 1);
                that.setData({
                    speck_time: parseInt(speck_time),
                    isStartRecord: true
                });
                if (that.data.speck_time > 0 && that.data.speck_time <= 59) {
                    that.start();
                } else {
                    clearInterval(that.data.setInter);
                    // 获取到结束时间
                    that.stop();
                    wx.showToast({
                        title: '录音最长60S哦！',
                        duration: 2000,
                        icon: "none"
                    })
                }
            }, 1000);
    },
    doEndRecord() {
        var _self = this;
        clearInterval(_self.data.setInter);
        // 获取到结束时间
        if (_self.data.speck_time > 3) {
            //清除计时器  即清除setInter
            clearInterval(_self.data.setInter);
            // 获取到结束时间
            _self.stop(true);
            _self.setData({
                speck_time: "0",
                isStartRecord: false
            })
        } else {
            //清除计时器  即清除setInter
            clearInterval(_self.data.setInter);
            // 获取到结束时间
            _self.stop(false);
            wx.showToast({
                title: '录制时间过短',
                duration: 2000,
                icon: "none"
            })
            _self.setData({
                speck_time: "0",
                isStartRecord: false
            })
        }
    },
    //开始录音的时候
    start() {
        const options = {
            duration: 60000,
            format: 'mp3', //音频格式，有效值 aac/mp3
        }
        //开始录音
        recorderManager.start(options);
        recorderManager.onStart(() => {
            console.log('recorder start')
        });
        //错误回调
        recorderManager.onError((res) => {
            console.log(res);
            _self.stop(false);
        })
    },
    //停止录音
    stop(success) {
        var _self = this
        recorderManager.stop();
        recorderManager.onStop((res) => {
            if (success) {
                //进行录音文件上传
                _self.doUploadAudio(res)
            }
        })
    },
    doUploadAudio(audio) {
        wx.showLoading({
            title: '上传中...',
        })
        let _self = this
        app.http.upload(app.urls.doUploadAudio, {
                path: audio.tempFilePath,
                name: 'audio',
                header: {
                    token: app.globalData.token
                }
            })
            .then(res => {
                wx.hideLoading({})
                if (_self.data.fieldList[_self.data.currentIndex].valueList.length < _self.data.currentItem.maxCount) {
                    wx.hideLoading({})
                    //插入到集合中
                    var id = JSON.parse(res).data
                    var pathStr = app.urls.baseImgUrl + id
                    //计算时长
                    var dur = parseInt(audio.duration / 1000)
                    var tM = parseInt(dur / 60) //分钟
                    var tS = parseInt(dur % 60) //秒
                    var totalMStr = tM > 9 ? tM : '0' + tM
                    var totalSStr = +tS > 9 ? tS : '0' + tS
                    var totalStr = totalMStr + ':' + totalSStr
                    var item = {
                        id: id, //id
                        path: pathStr, //地址
                        isPlay: false, //是否播放中
                        duration: dur, //时长
                        curDuation: 0,
                        curDurationStr: '00:00',
                        totalDurationStr: totalStr
                    }
                    _self.data.fieldList[_self.data.currentIndex].valueList.push(item)
                    _self.setData({
                        fieldList: _self.data.fieldList
                    })
                    if (_self.data.fieldList[_self.data.currentIndex].valueList.length == _self.data.currentItem.maxCount) {
                        _self.setData({
                            isShowAudio: false
                        })
                    }
                }
            })
            .catch(err => {})
    },
    play(e) {

        //进行播放
        var index = e.currentTarget.dataset.index
        var idx = e.currentTarget.dataset.idx
        var item = e.currentTarget.dataset.item
        var _self = this
        _self.data.fieldList[index].valueList.forEach(it => {
            if (it.isPlay) {
                innerAudioContext.stop()
            }
            it.isPlay = false
            it.curDuation = 0
            it.curDuationStr = '00:00'
        })
        if (!item.isPlay) {
            // innerAudioContext.stop()
            //找到该文件
            innerAudioContext = wx.createInnerAudioContext()
            // 播放音频文件
            innerAudioContext.src = _self.data.fieldList[index].valueList[idx].path
            innerAudioContext.autoplay = true
        }
        //先需要停止其他录音文件的播放

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

        innerAudioContext.onCanplay((res) => {
            // if (_self.data.waitFlag) {
            //     innerAudioContext.play()
            //     _self.setData({
            //         waitFlag: false
            //     })
            // }
        })
        innerAudioContext.onStop((res) => {
            _self.data.fieldList[index].valueList[idx].isPlay = false
            _self.data.fieldList[index].valueList[idx].curDuration = 0
            _self.data.fieldList[index].valueList[idx].curDurationStr = '00:00'
            _self.setData({
                fieldList: _self.data.fieldList,
            })
        })
        innerAudioContext.onEnded((res) => {
            _self.data.fieldList[index].valueList[idx].isPlay = false
            _self.data.fieldList[index].valueList[idx].curDuration = 0
            _self.data.fieldList[index].valueList[idx].curDurationStr = '00:00'
            _self.setData({
                fieldList: _self.data.fieldList,
            })
        })
        innerAudioContext.onError((res) => {
            _self.data.fieldList[index].valueList[idx].isPlay = false
            _self.data.fieldList[index].valueList[idx].curDuration = 0
            _self.data.fieldList[index].valueList[idx].curDurationStr = '00:00'
            _self.setData({
                fieldList: _self.data.fieldList,
            })
        })
        innerAudioContext.onSeeking(() => {
            console.log(innerAudioContext.currentTime)
        })
        innerAudioContext.onWaiting(() => {
            // innerAudioContext.pause()
            // _self.setData({
            //     waitFlag: true
            // })
        })
        innerAudioContext.onTimeUpdate(() => {
            if (innerAudioContext.duration != Infinity) {
                _self.data.fieldList[index].valueList[idx].curDuration = parseInt(innerAudioContext.currentTime)
                _self.data.fieldList[index].valueList[idx].duration = parseInt(innerAudioContext.duration)
                console.log(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.fieldList[index].valueList[idx].curDurationStr = curMStr + ':' + curSStr
                _self.data.fieldList[index].valueList[idx].totalDurationStr = totalMStr + ':' + totalSStr
                _self.setData({
                    fieldList: _self.data.fieldList
                })
            }
        })
    },
    //倒退5秒
    rewind(e) {
        var _self = this
        var index = e.currentTarget.dataset.index
        var idx = e.currentTarget.dataset.idx
        var item = e.currentTarget.dataset.item
        if (item.isPlay) {
            _self.data.fieldList[index].valueList[idx].curDuration = _self.data.fieldList[index].valueList[idx].curDuration - _self.data.speedStep
            innerAudioContext.seek(_self.data.fieldList[index].valueList[idx].curDuration)
            _self.setData({
                fieldList: _self.data.fieldList
            })
        }

    },
    //快进5秒
    speed(e) {
        var index = e.currentTarget.dataset.index
        var idx = e.currentTarget.dataset.idx
        var item = e.currentTarget.dataset.item
        var _self = this
        if (item.isPlay) {
            _self.data.fieldList[index].valueList[idx].curDuration = _self.data.fieldList[index].valueList[idx].curDuration + _self.data.speedStep
            innerAudioContext.seek(_self.data.fieldList[index].valueList[idx].curDuration)
            _self.setData({
                fieldList: _self.data.fieldList
            })
        }
    },
    slider4change(e) {
        var item = e.currentTarget.dataset.item
        if (item.isPlay) {
            innerAudioContext.seek(e.detail.value)
        }
    },
    //显示弹框
    showDialog(e) {
        console.log(e)
        this.setData({
            isShowAudio: true,
            currentItem: e.currentTarget.dataset.item,
            currentIndex: e.currentTarget.dataset.index
        })
    },
    //提交保存
    doPublish() {
        var _self = this
        if (_self.checkParams()) {
            wx.showToast({
                title: '保存中...',
            })
            var params = _self.buildParams()
            console.log(params)
            app.http.post(app.urls.doSaveMoments.format({
                    configColumnId: _self.data.columnId
                }), {
                    data: params,
                    header: {
                        token: app.globalData.token
                    }
                })
                .then(res => {
                    wx.hideLoading({})
                    let pages = getCurrentPages();
                    let beforePage = pages[pages.length - 2];
                    beforePage.setData({
                        isRefresh: true
                    })
                    wx.navigateBack({
                        delta: 1
                    })
                })
                .catch(err => {
                    wx.hideLoading({})
                    console.log(err)
                })
        }
    },
    //校验参数
    checkParams() {
        var _self = this
        var isLegal = true
        for (var i = 0; i < _self.data.fieldList.length; i++) {
            var field = _self.data.fieldList[i]
            if (field.must) {
                if (field.dataType == '1' || field.dataType == '7' || field.dataType == '8' || field.dataType == '9') {
                    if (field.value.length <= 0) {
                        wx.showToast({
                            title: '请输入或选择' + field.comment,
                            icon: 'none'
                        })
                        isLegal = false
                        break
                    }
                } else {
                    if (field.valueList.length <= 0) {
                        wx.showToast({
                            title: '请上传' + field.comment,
                            icon: 'none'
                        })
                        isLegal = false
                        break
                    }
                }
            }
        }
        return isLegal
    },
    //构建提交参数
    buildParams() {
        var _self = this
        var params = {
            uid: _self.data.uId
        }
        for (var i = 0; i < _self.data.fieldList.length; i++) {
            var field = _self.data.fieldList[i]
            if (field.dataType == '1' || field.dataType == '7' || field.dataType == '8' || field.dataType == '9') {
                if (field.value.length > 0) {
                    params[field.name] = field.value
                }
            } else {
                if (field.valueList.length > 0) {
                    var ids = ""
                    if (field.dataType == '6') {
                        field.valueList.forEach(it => {
                            ids += it.latitude + ',' + it.longitude + '-'
                        })
                    } else if (field.dataType == '4') {
                        field.valueList.forEach(it => {
                            ids += it.id + '&' + it.thumbId + ','
                        })
                    } else {
                        field.valueList.forEach(it => {
                            ids += it.id + ','
                        })
                    }
                    ids = ids.substr(0, ids.length - 1)
                    params[field.name] = ids
                }
            }
        }
        return params
    }
})