// pages/home/xx/xz/xz.js
const app = getApp();//新建页面时 默认引入
const req = app.xzjlReq();//初始化一个的request() 实例

Page({

    /**
     * 页面的初始数据
     */
    data: {
        to:'',
        from:'',
        content:'',
        audioList:[], // 音频列表
        imgList:[], // 图片列表
        sound:'',
        soundTime:'00:00:00',
        duration: '',
        minute:0, //分
        second:0, //秒
        millisecond:0, //毫秒
        showBtn:true,
        showImgBig:false, //图片太大弹层
        showSoundMore:false, //语音太多提示
        showSend:false, //寄出提示
        Preview:false, //预览
        showSound:false,
        showAlready:false,
        showImgToast:false,
        showImgToastBig:false,
        btn1:true,
        btn2:false,
        btn3:false,
        btn4:false,
        showSoundImg:true
    },
    already(){
        console.log('确定寄出');
        this.setData({showAlready:true})
        const list = [ ...this.data.audioList, ...this.data.imgList]
        list.push({
            type: 'text',
            content: this.data.content
        })
        const fromData = {
            from: this.data.from,
            to: this.data.to,
            messageList: list,
            status:'unread'
        }
        console.log(fromData);
        // 修改信札
        req.putRequest('/api/user/curt/letter',fromData).then(res => {
            console.log(res,'修改信札内容成功');
            // 修改状态
            req.patchRequest('/api/user/curt/letter/send',{}).then(res => {
                console.log(res,'信札状态修改成功');
            })
        })
    },
    closeShowImgBig(){
        this.setData({showImgBig:false})
    },
    closeShowSoundMore(){
        this.setData({showSoundMore:false})
    },
    openShowSend(){
        this.setData({showSend:true})
    },
    closeShowSend(){
        this.setData({showSend:false})
    },
    closeShowImgToast(){this.setData({showImgToast: false})},
    openPreview(){
        console.log('预览');
        this.setData({Preview:true})
    },
    ClearYl(e){
        console.log('清除语音');
        const id = e.currentTarget.dataset.id
        const list =  this.data.audioList.filter(item => {
            return item.resourceId !== id
        })
        this.setData({audioList: list})
    },
    ClearImg(e){
        console.log('清除图片');
        const id = e.currentTarget.dataset.id
        const list =  this.data.imgList.filter(item => {
            return item.resourceId !== id
        })
        this.setData({imgList: list})
    },
    goBack(){
        if (this.data.Preview) {
            this.setData({Preview: false})
        }else{
            console.log('返回');
            wx.navigateBack()
        }
    },
    // 上传图片
    addImg(){
        console.log('添加图片');
        wx.chooseMedia({
            mediaType: 'image',
            success: (res) => {
                const files = res.tempFiles[0]
                if(files.size > 5 * 1024 * 1024 ){
                    this.setData({showImgBig:true})
                }
                this.uploadFile(res.tempFiles[0].tempFilePath,'poster')
            }
        })
    },
    // 文件上传
    uploadFile(file,type) {
        wx.uploadFile({
            url: 'https://xzjl-api.windymuse.cn/api/resource',
            filePath: file,
            name: 'file',
            header: {
                'Authorization': wx.getStorageSync('token'),        
                'Content-Type': 'multipart/form-data'
            },
            formData: {
            type: type
            },
            success: (async(res) => {
                const data = JSON.parse(res.data);
                console.log(data);
                if (data.data.type === 'audio') {
                    console.log('添加音频');
                    const list = this.data.audioList
                    if(list.length >= 3){
                        this.setData({showSoundMore:true ,showSoundImg:true})
                        console.log('语音太多了');
                    }else {
                        list.push({
                            type: 'audio', 
                            resourceId: data.data.id, 
                            duration: this.data.duration,
                            extra: {duration : this.data.duration}
                    })
                        this.setData({audioList: list})
                    }
                } else if (data.data.type === 'poster') {
                    console.log('添加图片');
                    const list = this.data.imgList
                    if (list.length >= 9) {
                        this.setData({showImgToast : true})
                    }else {
                        list.push({
                            type: 'graphic',
                            resourceId: data.data.id,
                            img: data.data.abUrl,
                        })
                        this.setData({imgList: list, showImg:true})
                    }
                }
            }),
            fail(res) {
            console.log('上传失败');
            }
        });
},
    openSound(){
        console.log('添加声音');
        this.setData({showSound:true})
    },
    closeSound(){
        console.log('退出');
        this.setData({
            showSound:false,
            btn1: true,
            btn2: false,
            btn3: false,
            btn4: false,
            soundTime: '00:00:00',
            showSoundImg: true,
            minute:0, 
            second:0, 
            millisecond:0
        })
        clearInterval(this.data.timeOut)
    },
    startSound(){
        console.log('开始录音');

        this.setData({btn1: false, btn2: true, showSoundImg: false})
        let option = {
            duration:10000,     //录音的时长，之前最大值好像只有1分钟，现在最长可以录音10分钟
            format:'mp3',         //录音的格式，有aac和mp3两种   
        }
        wx.getRecorderManager().start(option)
        // 开启定时器
        this.data.timeOut = setInterval(this.counter,50)
    },
    // 计时器
    counter(){
        let second = this.data.second
        let minute = this.data.minute
        let millisecond = this.data.millisecond

        this.setData({millisecond: millisecond + 5})
        if(millisecond > 99) {
            this.setData({millisecond: 0, second : second + 1 })
        }else if(second >= 60) {
            this.setData({second: 0, minute: minute + 1})
        }else if(minute === 3) {
            this.second({soundTime: '03:00:00'})
            clearInterval(this.data.timeOut)
        }

        let time = '0' + minute
        if (second < 10) {
            time = time + ':0' + second
        }else {
            time = time + ':' + second
        }
        if (millisecond < 10){
            time = time + ':0' + millisecond
        } else {
            time = time + ':' + millisecond
        }

        this.setData({soundTime: time})
    },
    endSound(){
        console.log('结束录音');
        wx.getRecorderManager().stop()
        wx.getRecorderManager().onStop((res) => {
            console.log(res);

            const innerAudioContext = wx.createInnerAudioContext()
            innerAudioContext.src = res.tempFilePath

            this.setData({
                innerAudioContext: innerAudioContext,
                videoSrc:res.tempFilePath
            })
        })
        clearInterval(this.data.timeOut)
        this.setData({btn2:false, btn3:true, showSoundImg:true})
    },
    playVoice(){
        console.log('播放录音');
        this.data.innerAudioContext.play() 
        this.setData({btn3: false ,btn4: true})
    },
    stopVoice(){
        console.log('停止播放录音');
        this.data.innerAudioContext.stop() 
        this.setData({btn3: true ,btn4: false})
    },
    addSound(){
        if(this.data.btn3){
            console.log('添加录音');
            console.log(this.data.soundTime);
            this.setData({duration: this.data.soundTime})
            // 上传语音
            this.uploadFile(this.data.videoSrc,'audio')
            clearInterval(this.data.timeOut)
            this.setData({
                btn1:true,
                btn2:false,
                btn3:false,
                btn4:false,
                showLtqp: true,
                minute:0,
                second:0,
                millisecond:0,
                soundTime:'00:00:00'
            })
        }
    },
    logout(){
        req.deleteRequest('/api/user/logout',{}).then((res)=>{
            if(res.data.code===200){
                wx.navigateTo({
                    url: '/pages/index/index'
                  })
                  wx.showToast({
                    title:'寄出成功'
                  })
            }
        })
    },
    modify(){
        this.setData({showAlready: false, showSend: false})
    },
    getLetter(){
        console.log('获取当前用户信札内容');
        req.getRequest('/api/user/curt/letter',{}).then(res => {
            console.log(res);
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getLetter()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})