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,
        columnId: '', //栏目Id
        fieldList: [], //栏目字段
        textList: [], //文本添加内容
        textareaList: [], //文本域添加内容
        audioList: [], //音频添加内容
        videoList: [], //视频添加内容
        photoList: [], //视频添加内容
        linkList: [], //连接添加内容
        locationList: [], //定位添加内容
        isShowText: false, //文本弹窗开关
        isShowDesc: false, //文本域弹窗开关
        isShowPhoto: false, //图片选择弹框
        isShowLink: false, //链接弹窗
        isShowAudio: false, //录音弹窗
        isShowVideo: false, //视频弹窗
        tempText: '',
        tempDesc: '',
        linkStr: '',
        map: null,
        waitFlag: false,
        isStartRecord: false, //是否录音中
        speck_time: 0,
        speedStep: 5, //快进快退秒数
        setInter: '', //定时器
        currentItem: undefined,
        isAuthAudio: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            columnId: options.id
        })
        this.checkPermission()
        this.getFieldList()
    },
    getFieldList() {
        wx.showLoading({
            title: '加载中...',
        })
        var _self = this
        app.http.get(app.urls.getMomentsField.format({
                configColumnId: _self.data.columnId
            }), {
                header: {
                    token: app.globalData.token
                }
            })
            .then(res => {
                wx.hideLoading({})
                _self.setData({
                    fieldList: res.data
                })
            })
            .catch(err => {
                wx.hideLoading({})
                console.log(err)
            })
    },
    //申请录音权限
    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) {
            if (this.data.locationList.length < this.data.currentItem.count) {
                this.data.locationList.push(chooseLocation.getLocation())
                this.setData({
                    locationList: this.data.locationList
                })
            }
        }
        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 countNum = _self.data.currentItem.count - _self.data.videoList.length
        console.log(countNum)
        var type = e.currentTarget.dataset.type
        wx.chooseMedia({
            count: Number.parseInt(countNum),
            mediaType: ['video'],
            sourceType: [type],
            maxDuration: 60,
            success: (res) => {
                if (res.tempFiles.length > 0) {
                    _self.doUploadVideo(1, res.tempFiles, _self.data.uploadVideoCount)
                }
            },
            fail: (err) => {
                // console.log(err)
                // wx.showToast({
                //     title: '选取视频失败,(拍摄时长:60秒)',
                //     icon: 'none'
                // })
            }
        })
    },
    //上传视频
    doUploadVideo(type, paths, curIndex) {
        console.log(paths)
        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
                    var pathStr = app.urls.baseImgUrl + id
                    var item = {
                        id: id,
                        path: pathStr,
                        imgPath: paths[_self.data.uploadVideoCount].thumbTempFilePath
                    }
                    _self.data.videoList.push(item)
                    _self.setData({
                        videoList: _self.data.videoList
                    })
                    _self.setData({
                        uploadVideoCount: ++_self.data.uploadVideoCount
                    })
                    _self.doUploadVideo(1, paths, _self.data.uploadVideoCount)
                })
                .catch(err => {
                    wx.hideLoading({})
                    _self.setData({
                        uploadVideoCount: ++_self.data.uploadVideoCount
                    })
                    _self.doUploadVideo(1, paths, _self.data.uploadVideoCount)
                })
        } else {
            wx.hideLoading({})
            _self.setData({
                uploadVideoCount: 0
            })
        }
    },
    //预览视频
    viewVideo(e) {
        var tempList = [{
            url: e.currentTarget.dataset.url,
            type: 'video'
        }]
        wx.previewMedia({
            sources: tempList,
            current: 0,
            showmenu: false
        })
    },
    //删除视频
    delVideo(e) {
        let _self = this
        wx.showModal({
            title: '提示',
            content: '确定要删除该视频吗？',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    _self.data.videoList.splice(e.currentTarget.dataset.index, 1)
                    _self.setData({
                        videoList: _self.data.videoList
                    })
                }
            }
        })
    },
    //添加链接
    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
        })
    },
    //选择图片
    choosePhoto(e) {
        var _self = this
        var countNum = _self.data.currentItem.count - _self.data.photoList.length
        var type = e.currentTarget.dataset.type
        wx.chooseImage({
            count: Number.parseInt(countNum),
            sourceType: [type],
            success: (res) => {
                _self.doUploadImg(1, res.tempFilePaths, _self.data.uploadCount)
            },
            fail: (err) => {

            }
        })
    },
    //删除图片
    delImg(e) {
        wx.showModal({
            title: '提示',
            content: '确定要删除该图片吗？',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    this.data.photoList.splice(e.currentTarget.dataset.index, 1)
                    this.setData({
                        photoList: this.data.photoList
                    })
                }
            }
        })
    },
    //预览图片
    viewImg(e) {
        var tempList = [e.currentTarget.dataset.url]
        wx.previewImage({
            urls: tempList,
            current: e.currentTarget.dataset.url
        });
    },
    doUploadImg(type, 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.photoList.push(item)
                    _self.setData({
                        photoList: _self.data.photoList
                    })
                    _self.setData({
                        uploadCount: ++_self.data.uploadCount
                    })
                    _self.doUploadImg(1, paths, _self.data.uploadCount)
                })
                .catch(err => {
                    wx.hideLoading({})
                    _self.setData({
                        uploadCount: ++_self.data.uploadCount
                    })
                    _self.doUploadImg(1, paths, _self.data.uploadCount)
                })
        } else {
            wx.hideLoading({})
            _self.setData({
                uploadCount: 0
            })
        }
    },
    //地图选点
    chooseLocation() {
        this.data.items.forEach(it => {
            if (it.type == 'LOCATION') {
                this.setData({
                    currentItem: it
                })
            }
        })
        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) {
        let _self = this
        wx.showModal({
            title: '提示',
            content: '确定要删除该音频吗？',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    _self.data.audioList.splice(e.currentTarget.dataset.index, 1)
                    _self.setData({
                        audioList: _self.data.audioList
                    })
                }
            }
        })
    },
    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.audioList.length < _self.data.currentItem.count) {
                    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.audioList.push(item)
                    _self.setData({
                        audioList: _self.data.audioList
                    })
                    console.log(_self.data.audioList)
                    if (_self.data.audioList.length == _self.data.currentItem.count) {
                        _self.setData({
                            isShowAudio: false
                        })
                    }
                }
            })
            .catch(err => {})
    },
    play(e) {

        //进行播放
        var index = e.currentTarget.dataset.index
        var item = e.currentTarget.dataset.item
        var _self = this
        _self.data.audioList.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.audioList[index].path
            innerAudioContext.autoplay = true
        }
        //先需要停止其他录音文件的播放

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

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

    },
    //快进5秒
    speed(e) {
        var _self = this
        var index = e.currentTarget.dataset.index
        var item = e.currentTarget.dataset.item
        if (item.isPlay) {
            _self.data.audioList[index].curDuration = _self.data.audioList[index].curDuration + _self.data.speedStep
            innerAudioContext.seek(_self.data.audioList[index].curDuration)
            _self.setData({
                audioList: _self.data.audioList
            })
        }
    },
    slider4change(e) {
        var index = e.currentTarget.dataset.index
        var item = e.currentTarget.dataset.item
        if (item.isPlay) {
            innerAudioContext.seek(e.detail.value)
        }
    },
    //显示弹框
    showDialog(e) {
        var type = e.currentTarget.dataset.type
        var keyType = e.currentTarget.dataset.keytype
        console.log(e)
        this.data.items.forEach(it => {
            if (it.type == type) {
                this.setData({
                    currentItem: it
                })
                return
            }
        })
        this.setData({
            [keyType]: true
        })
    }
})