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

Page({

    /**
     * 页面的初始数据
     */
    data: {
        to:'',
        from:'',
        content:'',
        img:'',
        messageList:[],
        sound:'',
        soundTime:'00:00:00',
        duration: '',
        minute:0, //分
        second:0, //秒
        millisecond:0, //毫秒
        showBtn:true,
        showImg:false,
        showLtqp:false,
        showImgBig:false, //图片太大弹层
        showSoundMore:false, //语音太多提示
        showSend:false, //寄出提示
        Preview:false, //预览
        showSound:false,
        showAlready:false,
        btn1:true,
        btn2:false,
        btn3:false,
        showSoundImg:true
    },
    writeLetters(){
        console.log('写信');
        this.setData({
            showImg:false,
            showLtqp:false,
            Preview: false
        })
    },
    already(){
        console.log('确定寄出');
        this.setData({showAlready:true})
        const list = this.data.messageList
        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})
    },
    openPreview(){
        console.log('预览');
        this.setData({Preview:true})
        if(this.data.messageList.length){
            this.setData({showLtqp: true})
        }
    },
    ClearYl(){
        console.log('清除语音');
        // this.setData({showLtqp:false})
    },
    goBack(){
        console.log('返回');
        wx.navigateBack()
    },
    ClearImg(){
        console.log('清除图片');
        const list = this.data.messageList.filter(item => {
            return item.type !== "graphic"
        })
        this.setData({
            img:'',
            messageList: list,
            showImg: false
        })
        console.log(this.data.messageList);
    },
    // 上传图片
    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.messageList
                    const audio = this.data.messageList.filter(item => {
                        return item.type === 'audio'
                    })
                    // 判断语音条数大于3条
                    if(audio.length >= 3){
                        this.setData({showSoundMore:true})
                    }else {
                        list.push({
                            type: 'audio',
                            resourceId: data.data.id,
                        })
                        this.setData({
                            messageList: list
                        })
                    }
                    console.log(this.data.messageList);

                } else if (data.data.type === 'poster') {
                    console.log('添加图片');
                    const list = this.data.messageList
                    list.push({
                        type: 'graphic',
                        resourceId: data.data.id
                    })
                    this.setData({
                        img:data.data.abUrl,
                        messageList:list,
                        showImg:true
                    })
                    console.log(this.data.messageList);
                }
            }),
            // success: async res => {
            //   let data = JSON.parse(res.data);
            //   console.log(data, '111111');
            //   if (data.code == 200) {
            //       this.setData({imgUrl:data.data.abUrl})
            //       console.log('打印1111')
            //       console.log(this.data.imgUrl)
                // res.data = JSON.parse(res.data);
                // console.log(res.data);
                // if (res.data.code == 1) {
                //   console.log(res.data.data.url);
                //   this.img = this.baseUrl + res.data.data.url;
                // 图片路径
                //   this.userinfo.avatar = res.data.data.url;
                // let n = await this.$api.upload({ file: res.data.fullurl });
                // console.log(n, '上传后');
                // }
            //   }
            // },
            fail(res) {
            console.log('上传失败');
            }
        });
},
    openSound(){
        console.log('添加声音');
        this.setData({showSound:true})
    },
    closeSound(){
        this.setData({showSound:false})
    },
    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().pause()
        clearInterval(this.data.timeOut)
        this.setData({btn2:false, btn3:true, showSoundImg:true})
    },
    playVoice(){
        console.log('继续录音');
        wx.getRecorderManager().resume()
        this.data.timeOut = setInterval(this.counter,50)
        this.setData({btn2:true, btn3:false, showSoundImg:false})
    },
    addSound(){
        console.log('添加录音');
        console.log(this.data.soundTime);
        this.setData({duration: this.data.soundTime})
        wx.getRecorderManager().stop()
        clearInterval(this.data.timeOut)
        // 监听结束录音
        wx.getRecorderManager().onStop((res) => {
            console.log(res);
            this.uploadFile(res.tempFilePath,'audio')
        })
        this.setData({
            btn1:true,
            btn2:false,
            btn3:false,
            showLtqp: true,
            minute:0,
            second:0,
            millisecond:0,
            soundTime:'00:00:00'
        })
    },
    // delSound(){
    //     console.log('不添加该条语音');
    //     this.setData({
    //         sound:'',
    //         btn1:true,
    //         btn2:false,
    //         btn3:false,
    //         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:'寄出成功'
                  })
            }
           })
    },
    getLetter(){
        console.log('获取当前用户信札内容');
        req.getRequest('/api/user/curt/letter',{}).then(res => {
            console.log(res);
            // res.data.data.messageList.forEach(item => {
            //     if(item.type === 'text'){
            //         this.setData({content: item.content})
            //     }
            // })
            // this.setData({
            //     to: res.data.data.to,
            //     from: res.data.data.from,
            // })
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getLetter()
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})