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的名称
var location = {
    latitude: 39.90877,
    longitude: 116.39695
}; //默认坐标点
const category = '生活服务,娱乐休闲';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        maringHeight: app.globalData.CustomBar,
        fieldList: [{
            type: 'text'
        }, {
            type: 'video'
        }, {
            type: 'audio'
        }, {
            type: 'map'
        }, {
            type: 'select'
        }, {
            type: 'textarea'
        }, {
            type: 'link'
        }, {
            type: 'photo'
        }, ], //允许发布的字段列表
        valueList: [], //当前添加的内容列表
        isShowInput: false, //是否显示文本输入
        isShowPhoto: false, //是否显示图片编辑框
        isShowVideo: false, //是否显示视频编辑框
        isShowLink: false, //是否显示链接输入框
        isShowSelect: false, //是否显示选项弹框
        isShowAudio: false, //是否显示录音弹框
        curTextValue: '', //当前输入的文本内容
        curLinkText: '', //当前链接输入的文本内容
        isShowEdit: false, //是否显示编辑
        currentIndex: -1, //当前点击的条目索引
        photoList: [], //当前选择的图片列表
        videoList: [], //当前选择的视频列表
        curSelPhotoDisplay: '1', //图片的显示方式 1.九宫格  2.轮播  3.轮播(自动) 4.平铺
        curVideoDisplay: '1', //视频展示方式  1.九宫格  2.平铺
        curTextAlign: '1', //文字显示排列 1.居左  2.居中 3.居右
        curFieldType: '0', //编辑选择的文件类型
        selDirection: '1', //选中的插入方向  1.插入到下面  2.插入的上面
        isInsert: false, //是否显示插入选项
        topBoxHeight: 100, //顶部类型选择框的高度
        audioFile: null, //当前的录音文件
        audioDuration: 0, //录音文件的时长
        isRecording: false, //是否正在录音
        optionsList: [{
            id: '1',
            name: '选项一',
            isSel: false
        }, {
            id: '2',
            name: '选项二',
            isSel: false
        }, {
            id: '3',
            name: '选项三',
            isSel: false
        }, {
            id: '4',
            name: '选项四',
            isSel: false
        }, {
            id: '5',
            name: '选项五',
            isSel: false
        }], //选项
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            columnId: options.id
        })
        this.checkPermission()
        wx.getLocation({
            success(res) {
                location.latitude = res.latitude
                location.longitude = res.longitude
            }
        })
        this.countBoxHeight()
    },
    countBoxHeight() {
        var _self = this
        var query = wx.createSelectorQuery()
        query.select('#top-box').boundingClientRect()
        query.exec(res => {
            _self.setData({
                topBoxHeight: res[0].height + 7
            })
        })
    },
    onShow() {
        var _self = this
        if (chooseLocation.getLocation() != null) {
            var item = chooseLocation.getLocation()
            var tempItem = {}
            tempItem['type'] = 'map'
            tempItem['value'] = item
            _self.data.valueList.push(tempItem)
            _self.setData({
                valueList: _self.data.valueList
            })
        }
        wx.getSetting({
            withSubscriptions: true,
            success(res) {
                var isAuth = res.authSetting['scope.record']
                _self.setData({
                    isAuthAudio: isAuth
                })
            }
        })

    },
    showType(e) {
        var type = e.currentTarget.dataset.type
        var _self = this
        switch (type) {
            case 'text':
            case 'textarea': //文本域
                this.setData({
                    isShowInput: true
                })
                break
            case 'video': //视频
                _self.chooseVideo()
                break
            case 'audio': //音频
                _self.checkRecordPermission()
                break
            case 'photo': //图片
                _self.chooseImg()
                break
            case 'map': //地图
                _self.doChooseLocation()
                break
            case 'select': //选项
                _self.setData({
                    isShowSelect: true
                })
                break
            case 'link': //链接
                _self.setData({
                    isShowLink: true
                })
                break
        }
    },
    //去选择图片
    chooseImg() {
        var _self = this
        wx.chooseImage({
            count: 9,
            sourceType: ['album', 'camera'],
            success: (res) => {
                // _self.doUploadImg(index, res.tempFilePaths, _self.data.uploadCount)
                //构建数据
                console.log(res)
                res.tempFilePaths.forEach(it => {
                    var tempItem = {}
                    tempItem['path'] = it
                    _self.data.photoList.push(tempItem)
                })
                _self.setData({
                    photoList: _self.data.photoList,
                    isShowPhoto: true
                })
            },
            fail: (err) => {
                if (err.errMsg.indexOf('fail cancel') == -1) {
                    wx.showToast({
                        title: '请重新选择',
                        icon: 'error'
                    })
                }
            }
        })
    },
    //去选择视频
    chooseVideo() {
        var _self = this
        wx.chooseMedia({
            count: 9,
            mediaType: ['video'],
            sourceType: ['album', 'camera'],
            maxDuration: 60,
            success(res) {
                res.tempFiles.forEach(it => {
                    var tempItem = {}
                    tempItem['path'] = it.tempFilePath
                    tempItem['coverPath'] = it.thumbTempFilePath
                    _self.data.videoList.push(tempItem)
                })
                _self.setData({
                    videoList: _self.data.videoList,
                    isShowVideo: true
                })
            },
            fail(err) {
                if (err.errMsg.indexOf('fail cancel') == -1) {
                    wx.showToast({
                        title: '请重新选择',
                        icon: 'error'
                    })
                }
            }
        })
    },
    //控制显示
    showEditBox(e) {
        var index = e.currentTarget.dataset.idx
        var _self = this
        if (_self.data.currentIndex == index) {
            this.setData({
                currentIndex: -1,
            })
        } else {
            this.setData({
                currentIndex: index
            })
        }
    },
    //选择插入的方向
    chooseDirection(e) {
        var idx = e.currentTarget.dataset.idx
        this.setData({
            selDirection: idx
        })
    },
    //选择图片的显示方式
    choosePhotoDisplay(e) {
        var type = e.currentTarget.dataset.type
        this.setData({
            curSelPhotoDisplay: type
        })
    },
    //选择视频的显示方式
    chooseVideoDisplay(e) {
        var type = e.currentTarget.dataset.type
        this.setData({
            curVideoDisplay: type
        })
    },
    //选择文字排列方式
    chooseTextAlign(e) {
        var type = e.currentTarget.dataset.type
        this.setData({
            curTextAlign: type
        })
    },
    //编辑选择出入的类型
    chooseFieldType(e) {
        var type = e.currentTarget.dataset.type
        this.setData({
            curFieldType: type
        })
    },
    //确定选择的图片
    confirmPhoto() {
        var _self = this
        if (_self.data.photoList.length > 0) {
            //上传图片
            var tempList = []
            _self.data.photoList.forEach(it => {
                var item = {}
                item['path'] = it.path
                tempList.push(item)
            })
            var tempPhoto = {}
            tempPhoto['type'] = 'photo'
            tempPhoto['valueList'] = tempList
            tempPhoto['displayType'] = _self.data.curSelPhotoDisplay
            _self.data.valueList.push(tempPhoto)
            _self.setData({
                valueList: _self.data.valueList,
                photoList: [],
                curSelPhotoDisplay: 1,
                isShowPhoto: false
            })
        } else {
            wx.showToast({
                title: '请选择图片',
                icon: 'error'
            })
        }
    },
    //确定选择的视频
    confirmVideo() {
        var _self = this
        if (_self.data.videoList.length > 0) {
            var tempList = []
            _self.data.videoList.forEach(it => {
                var item = {}
                item['path'] = it.path
                item['coverPath'] = it.coverPath
                tempList.push(item)
            })
            var tempVideo = {}
            tempVideo['type'] = 'video'
            tempVideo['valueList'] = tempList
            tempVideo['displayType'] = _self.data.curVideoDisplay
            _self.data.valueList.push(tempVideo)
            _self.setData({
                valueList: _self.data.valueList,
                videoList: [],
                curVideoDisplay: 1,
                isShowVideo: false
            })
        } else {
            wx.showToast({
                title: '请选择视频',
                icon: 'error'
            })
        }
    },
    //确定插入数据
    doInsert() {
        //根据选择的类型与方向插入数据
    },
    hideEditBox() {
        //隐藏编辑框
        this.setData({
            currentIndex: -1
        })
    },
    onClose() {
        this.setData({
            isShowInput: false,
            isShowLink: false,
            isShowSelect: false
        })
    },
    //输入框监听
    inputWatch(e) {
        var _self = this
        _self.setData({
            curTextValue: e.detail.value
        })
    },
    //链接输入框监听
    inputLink(e) {
        var _self = this
        _self.setData({
            curLinkText: e.detail.value
        })
    },
    //保存输入的链接
    doConfirmLink() {
        var _self = this
        if (_self.data.curLinkText == '') {
            wx.showToast({
                title: '请输入链接',
                icon: 'error'
            })
        } else {
            //保存
            var tempText = {}
            tempText['type'] = 'link'
            tempText['value'] = _self.data.curLinkText
            _self.data.valueList.push(tempText)
            _self.setData({
                valueList: _self.data.valueList,
                curLinkText: '',
                isShowLink: false
            })
        }
    },
    //保存输入的文本
    doConfirmInput() {
        var _self = this
        if (_self.data.curTextValue == '') {
            wx.showToast({
                title: '请输入内容',
                icon: 'error'
            })
        } else {
            //保存
            var tempText = {}
            tempText['type'] = 'text'
            tempText['value'] = _self.data.curTextValue
            var textAlign = 'left'
            console.log(_self.data.curTextAlign)
            switch (_self.data.curTextAlign) {
                case '1':
                    textAlign = 'left'
                    break
                case '2':
                    textAlign = 'center'
                    break
                case '3':
                    textAlign = 'right'
                    break
            }
            tempText['textAlign'] = textAlign
            _self.data.valueList.push(tempText)
            _self.setData({
                valueList: _self.data.valueList,
                curTextValue: '',
                isShowInput: false
            })
        }
    },
    //申请录音权限
    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,
                    })
                }
            }
        })
    },
    //预览图片
    viewPhoto(e) {
        var url = e.currentTarget.dataset.url
        wx.previewImage({
            urls: [url],
        })
    },
    //删除图片
    delPhoto(e) {
        var _self = this
        wx.showModal({
            title: '提示',
            content: '确定要删除该图片吗？',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    _self.data.photoList.splice(e.currentTarget.dataset.index, 1)
                    _self.setData({
                        photoList: _self.data.photoList
                    })
                }
            }
        })
    },
    //选择定位点
    doChooseLocation(e) {
        // var index = e.currentTarget.dataset.index
        // this.setData({
        //     curMapIndex: index
        // })
        var curLoc = JSON.stringify(location)
        wx.navigateTo({
            url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${curLoc}&category=${category}`
        });
    },
    //编辑条目
    editItem(e) {

    },
    //插入条目
    insertItem(e) {
        var _self = this
        _self.setData({
            isInsert: !_self.data.isInsert
        })
    },
    //删除条目
    delItem(e) {
        wx.showModal({
            title: '提示',
            content: '确定要删除该条数据吗?',
            success(res) {
                if (res.confirm) {

                }
            }
        })
    },
    //选项选择
    chooseTags(e) {
        var _self = this
        var idx = e.currentTarget.dataset.idx
        var item = e.currentTarget.dataset.item
        _self.data.optionsList[idx].isSel = !item.isSel
        _self.setData({
            optionsList: _self.data.optionsList
        })
    },
    //保存选定的选项
    doConfirmSel() {
        var _self = this
        var tempList = []
        _self.data.optionsList.forEach(it => {
            if (it.isSel) {
                tempList.push(it)
            }
        })
        var tempSel = {}
        tempSel['type'] = 'select'
        tempSel['valueList'] = tempList
        _self.data.valueList.push(tempSel)
        _self.data.optionsList.forEach(it => {
            it.isSel = false
        })
        _self.setData({
            valueList: _self.data.valueList,
            isShowSelect: false,
            optionsList: _self.data.optionsList
        })
    },
    //确定音频
    doConfirmAudio() {
        var _self = this
        var tempAudio = {}
        tempAudio['type'] = 'audio'
        tempAudio['value'] = _self.data.audioFile
        _self.data.valueList.push(tempAudio)
        _self.setData({
            valueList: _self.data.valueList,
            audioFile: null,
            isShowAudio: false
        })
    },
    //校验录音权限
    checkRecordPermission() {
        var _self = this
        wx.getSetting({
            success(res) {
                if (!res.authSetting['scope.record']) {
                    wx.authorize({
                        scope: 'scope.record',
                        success() {
                            _self.setData({
                                isShowAudio: true
                            })
                        }
                    })
                } else {
                    _self.setData({
                        isShowAudio: true
                    })
                }
            }
        })
    },
    //开始录音
    startRecord() {
        var _self = this
        //1.启动定时器用来记录时间
        _self.data.setInter = setInterval(
            function () {
                var audioDuration = parseInt(_self.data.audioDuration + 1);
                _self.setData({
                    audioDuration: parseInt(audioDuration),
                    isRecording: true
                });
            }, 1000)
        //2.开始录音
        _self.start()
    },
    //开始录音
    start() {
        console.log('开始录音')
        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);
        })
    },
    //结束录音
    doEndRecord() {
        var _self = this
        clearInterval(_self.data.setInter);
        //判断时长是否达到要求
        recorderManager.stop();
        recorderManager.onStop((res) => {
            //进行录音文件上传
            if (_self.data.audioDuration < 10) {
                wx.showToast({
                    title: '录音时长需大于10秒',
                    icon: 'none'
                })
            } else {
                //可以上传
                // res   tempFilePath 路径  duration 毫秒   fileSize  大小
                res.isPlay = false
                res.durationStr = _self.data.audioDuration + ''
                res.duration = _self.data.audioDuration
                res.totalDurationStr = '00:' + (_self.data.audioDuration > 9 ? _self.data.audioDuration : '0' + _self.data.audioDuration)
                res.curDurationStr = '00:00'
                res.curDuration = 0
                res.isPlay = false
                // _self.doUploadAudio(res)
                _self.setData({
                    audioFile: res
                })
            }
            _self.setData({
                audioDuration: 0,
                isRecording: false,
            })
        })
    },
    //删除录音
    delAudio() {
        var _self = this
        wx.showModal({
            title: '警告',
            content: '确定要删除该条录音吗?',
            success(res) {
                if (res.confirm) {
                    _self.setData({
                        audioFile: null
                    })
                }
            }
        })
    },
    //隐藏各类弹框
    closePop(e) {
        var type = e.currentTarget.dataset.type
        var _self = this
        if (type && type == 'audio') {
            if (_self.data.audioFile != null) {
                wx.showModal({
                    title: '警告',
                    content: '关闭录音弹窗将清除当前录制的音频文件,确定要关闭吗?',
                    success(res) {
                        if (res.confirm) {
                            _self.setData({
                                audioFile: null,
                                isShowAudio: false
                            })
                        }
                    }
                })
            } else {
                _self.setData({
                    isShowAudio: false
                })
            }
        }
        this.setData({
            isShowPhoto: false,
            isShowEdit: false,
            isShowVideo: false,
            isShowSelect: false,
        })
    },
    //音频拖动
    slider4change(e) {
        var _self = this
        var audio = e.currentTarget.dataset.item
        if (audio.isPlay) {
            innerAudioContext.seek(e.detail.value)
        }
    },
    play(e) {
        //进行播放
        var audio = e.currentTarget.dataset.item
        var _self = this
        var type = e.currentTarget.dataset.type
        var idx = e.currentTarget.dataset.idx
        if (audio.isPlay) {
            innerAudioContext.stop()
        } else {
            //找到该文件
            innerAudioContext = wx.createInnerAudioContext()
            // 播放音频文件
            innerAudioContext.src = audio.tempFilePath
            innerAudioContext.autoplay = true
        }
        //先需要停止其他录音文件的播放
        innerAudioContext.onPlay(() => {
            _self.data.audioFile.isPlay = true
            _self.setData({
                audioFile: _self.data.audioFile
            })
        });
        innerAudioContext.onStop((res) => {
            console.log('停止播放')
            //重置文件的状态
            _self.setAudioDefault()
        })
        innerAudioContext.onEnded((res) => {
            console.log('播放结束')
            //重置文件的状态
            _self.setAudioDefault()
        })
        innerAudioContext.onError((res) => {
            wx.showToast({
                title: '播放失败',
                icon: 'error'
            })
            _self.setAudioDefault()
        })
        innerAudioContext.onTimeUpdate(() => {
            _self.data.audioFile.curDuration = innerAudioContext.currentTime
            var time = Number.parseInt(_self.data.audioFile.curDuration)
            _self.data.audioFile.curDurationStr = '00:' + (time > 9 ? time : '0' + time)
            _self.setData({
                audioFile: _self.data.audioFile
            })
        })
    },
    //设置录音文件恢复初始
    setAudioDefault() {
        var _self = this
        //重置文件的状态
        _self.data.audioFile.curDurationStr = '00:00'
        _self.data.audioFile.curDuration = 0
        _self.data.audioFile.isPlay = false
        _self.setData({
            audioFile: _self.data.audioFile
        })
    },
    //倒退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
            })
        }
    },
    onUnload() {
        chooseLocation.setLocation(null)
        this.setData({
            map: null
        })
    }
})