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

Page({

    /**
     * 页面的初始数据
     */
    data: {
        to:'',
        from:'',
        content:'',
        audioList:[], // 音频列表
        imgList:[], // 图片列表
        messageList: [], //消息列表
        sound:'',
        soundTime:'00:00:00',
        duration: '',
        minute:0, //分
        second:0, //秒
        millisecond:0, //毫秒
        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,
        isPlaying: false // 是否正在播放语音
    },
    already(){
        // 校验
        if (this.data.from === '') {
            wx.showToast({
                title: '寄件人不能为空',
                icon: 'error'
            })
            return this.setData({showSend: false})
        }
        if (this.data.to === '') {
            wx.showToast({
                title: '收件人不能为空',
                icon: 'error'
            })
            return this.setData({showSend: false})
        }
        if (this.data.messageList.length <= 1) {
            wx.showToast({
                title: '写点东西吧',
                icon: 'error'
            })
            return this.setData({showSend: false})
        }
        this.setData({showAlready:true})
        const fromData = {
            from: this.data.from,
            to: this.data.to,
            messageList: this.data.messageList,
            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 : !this.data.Preview})
    },
    ClearYl(e){
        console.log('清除语音');
        const id = e.currentTarget.dataset.id
        const list =  this.data.messageList.filter(item => {
            return item.resourceId !== id
        })
        this.setData({messageList: list})
    },
    ClearImg(e){
        console.log('清除图片');
        const id = e.currentTarget.dataset.id
        const list =  this.data.messageList.filter(item => {
            return item.resourceId !== id
        })
        this.setData({messageList: list})
    },
    goBack(){
        wx.reLaunch({
            url: '/pages/home/xx/index'
        })
    },
    // 获取文本框内容
    getTextValue(e){
        const index = e.currentTarget.dataset.index
        const content = e.detail.value
        const list = this.data.messageList.map(item => {
            if (item.index === index) {
                return {
                    ...item,
                    content : content
                }
            }
            return item
        })
        this.setData({messageList: list})
    },
    // 上传图片
    addImg(){
        wx.chooseImage({
            count: 9,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                console.log(res);
                const files = res.tempFiles
                files.forEach(item => {
                    if(item.size > 5 * 1024 * 1024 ){
                        return this.setData({showImgBig:true})
                    }
                    this.uploadFile(item.path,'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);
                if (data.data.type === 'audio') {
                    console.log('添加音频');
                    const list = this.data.messageList
                    const index = list.length + 1
                    const audioList = list.filter(item => {
                        return item.type === 'audio'
                    })
                    if(audioList.length >= 3){
                        this.setData({showSoundMore:true ,showSoundImg:true})
                    }else {
                        list.push({
                            type: 'audio', 
                            resourceId: data.data.id, 
                            duration: this.data.duration,
                            videoSrc: this.data.videoSrc,
                            index:index,
                            extra: {duration : this.data.ssec}
                        })
                        list.push({
                            type: 'text',
                            content: '',
                            index: index + 1
                        })
                        this.setData({messageList: list})
                    }
                } else if (data.data.type === 'poster') {
                    console.log('添加图片');
                    const list = this.data.messageList
                    const migList = list.filter(item => {
                        return item.type === 'graphic'
                    })
                    if (migList.length >= 9) {
                        this.setData({showImgToast : true})
                    }else {
                        const index = list.length + 1
                        list.push({
                            type: 'graphic',
                            resourceId: data.data.id,
                            img: data.data.abUrl,
                            index: index
                        })
                        list.push({
                            type: 'text',
                            content: '',
                            index: index + 1
                        })
                        this.setData({messageList: list, showImg:true})
                    }
                }
            }),
            fail(res) {
                console.log(res, '上传失败');
            }
        });
},
    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
        }

        let ssec = minute + '\''
        if (second < 10) {
            ssec = ssec + '0' + second + '\'\''
        }else {
            ssec = ssec + second
        }

        this.setData({
            soundTime: time,
            ssec: ssec
        })
    },
    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,
                showSound: false,
                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(){
        req.getRequest('/api/user/curt/letter',{}).then(res => {
            if (res.data.code === 200) {
                console.log(res.data.data);
                const data = res.data.data
                const id = wx.getStorageSync('xinyuan-userInfo').id
                if (!data.messageList.length) {
                    data.messageList.push({content: '', type: 'text', index: 1})
                }
                data.messageList.forEach((item, index) => {
                    item.index = index + 1
                    if (item.type === 'audio') {
                        const src = `https://xzjl-api.windymuse.cn/api/resource/${item.resourceId}?k=${id}`
                        item.videoSrc = src
                    }else if(item.type === 'graphic'){
                        const src = `https://xzjl-api.windymuse.cn/api/resource/${item.resourceId}?k=${id}`
                        item.img = src
                    }
                })
                this.setData({
                    from: data.from,
                    to: data.to,
                    messageList: data.messageList
                })
            }
        })
    },
    // 点击音频试听
    listen(e){
        if (this.data.isPlaying) {
            return; // 如果正在播放语音，则不触发事件
        }
        const id = e.currentTarget.dataset.url.resourceId
        const videoSrc = this.data.messageList.find(item => {
            return item.resourceId === id
        }).videoSrc
        console.log(videoSrc);
        const innerAudioContext = wx.createInnerAudioContext()
        innerAudioContext.src = videoSrc
        innerAudioContext.play() // 播放
        console.log('播放');
        this.setData({ isPlaying: true }); // 设置为正在播放语音
        innerAudioContext.onEnded(() => {
            this.setData({ isPlaying: false }); // 播放完毕后设置为非播放状态
        });
    },
    getUserInfo(){
        req.getRequest('/api/user/curt',{}).then(res => {
            const id = res.data.data.id
            this.setData({id:id})
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getLetter()
        this.getUserInfo()
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})