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

Page({

    /**
     * 页面的初始数据
     */
    data: {
        img:'',
        letterMsg:{},
        showLetter: true,
        showMore: false,
        showDel:false,
        showEdit: true,
        imgList:[],
        audioList:[],
        messageList: [],
        playVideos: true,
        letterId: 0,
        hy: false
    },
    openLetter(){
        this.setData({showLetter: !this.data.showLetter}),
        req.patchRequest('/api/user/curt/letter/read',{}).then(res => {
            console.log(res,'已读信札');
        })
    },
    openMore(){this.setData({showMore: !this.data.showMore})},
    openDel(){this.setData({showDel: !this.data.showDel})},
    getLetterMsg(id){
        console.log('获取信札');
        req.getRequest('/api/user/curt/letter',{}).then(res => {
            console.log(res);
            const { messageList } = res.data.data
            // 获取创建时间
            const date = new Date(res.header.Date);
            // 获取年月日时分秒等信息
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const hour = date.getHours();
            const minute = date.getMinutes();
            const formattedDate = `${year}年${month}月${day}日 ${hour}:${minute}`;
            this.setData({
                letterMsg: res.data.data,
                time: formattedDate
            })
            // 判断是否有图片
            console.log(messageList);
            messageList.forEach(item => {
                if(item.type === 'graphic') {
                    item.img = `https://xzjl-api.windymuse.cn/api/resource/${item.resourceId}?k=${id}`
                }else if(item.type === 'audio') {
                    item.audio = `https://xzjl-api.windymuse.cn/api/resource/${item.resourceId}?k=${id}`
                }
            })
            this.setData({messageList: messageList})
        })
    },
    getUserInfo(){
        req.getRequest('/api/user/curt',{}).then(res => {
            const id = res.data.data.id
            this.getLetterMsg(id)
        })
    },
    // 播放录音
    playVideos(e){
        if (this.data.playVideos) {
            this.setData({playVideos: false})
            const innerAudioContext = wx.createInnerAudioContext()
            console.log(e.currentTarget.dataset.url.videoSrc);
            if (e.currentTarget.dataset.url.videoSrc) {
                innerAudioContext.src = e.currentTarget.dataset.url.videoSrc
            }
            if (e.currentTarget.dataset.url.audio) {
                innerAudioContext.src = e.currentTarget.dataset.url.audio
            }
            innerAudioContext.play()
            innerAudioContext.onEnded(() => {
                this.setData({playVideos: true})
            })
        }
    },
    // 重置信札
    resetLetter(){
        const id = this.data.letterId
        // 判断单人状态信札跳转还是情侣状态
        if (id) {
            // 删除消息
            console.log('删除消息');
            if (id == -1) {
                // 重置信札
                req.putRequest('/api/user/curt/letter/reset',{}).then( res => {
                    if (res.data.code === 200) {
                        wx.switchTab({
                            url: '/pages/home/xx/lindex/lindex'
                        })
                    }
                })
            }else if(id == -2) {
                wx.showToast({
                    title: '不能烧毁情侣信札',
                    icon: 'none'
                })
                this.setData({showDel : false})
            }else {
                req.deleteRequest(`/api/user/curt/message/${id}`,{}).then(res => {
                    console.log(res);
                    if (res.data.code === 200) {
                        wx.showToast({
                            title: '信件已烧毁',
                            icon: 'success'
                        })
                        setTimeout(() => {
                            if (this.data.hy) {
                                wx.redirectTo({
                                    url: '/pages/home/xx/hy/index'
                                })
                            }else {
                                wx.redirectTo({
                                    url: '/pages/home/xx/lindex/lindex'
                                })
                            }
                        }, 1000);
                    }
                    if (res.data.code === 1007) {
                        wx.showToast({
                            title: '不能删除情侣信札',
                            icon: 'none'
                        })
                        this.setData({showDel : false})
                    }
                })
            }
        }else {
            // 重置信札
            req.putRequest('/api/user/curt/letter/reset',{}).then( res => {
                if (res.data.code === 200) {
                    wx.switchTab({
                        url: '/pages/home/xy/index'
                    })
                }
            })
        }
    },
    go2Back(){
        if (this.data.letterId) {
            if (this.data.hy) {
                wx.redirectTo({
                    url: '/pages/home/xx/hy/index'
                })
            }else {
                wx.redirectTo({
                    url: '/pages/home/xx/lindex/lindex'
                })
            }
        }else {
            wx.switchTab({
                url: '/pages/home/xy/index'
            })
        }
    },

    // 修改信札
    editXz(){
        wx.redirectTo({
            url: '/pages/home/xx/xz/xz'
        })
    },

    // 获取情侣状态下信札内容
    getLetterDetail(id){
        if (id == -1) {
            this.getUserInfo()
        }else if (id == -2) {
            console.log('获取情侣信札内容');
            this.getLoveLetter()
        }else {
            req.getRequest(`/api/user/curt/message/${id}`,{}).then(res => {
                if(res.data.code === 200){
                    const letter = res.data.data.letter
                    const messages = letter.messages.map(item => {
                        if (item.extra && item.extra.videoSrc) {
                            return {
                                ...item,
                                videoSrc: item.extra.videoSrc
                            }
                        }
                        if (item.extra && item.extra.img) {
                            return {
                                ...item,
                                img: item.extra.img
                            }
                        }
                        if (item.content) {
                            return item
                        }
                    })
                    this.setData({
                        from: letter.from,
                        to: letter.to,
                        messageList: messages
                    })
    
                    // 判断是否为情侣信札 是就更改信札状态
                    const userInfo = wx.getStorageSync('xinyuan-userInfo')
                    const userId = userInfo.id
                    if (res.data.data.fromUserid !== userId && res.data.data.status === 'unread') {
                        req.patchRequest(`/api/user/curt/message/${id}/read`)
                    }
                }else{
                    wx.showToast({
                        title: '获取信札内容失败',
                        icon: 'error'
                    })
                }
            })
        }
    },

    // 获取情侣内容
    getLoveLetter(){
        const userInfo = wx.getStorageSync('xinyuan-userInfo')
        const id = userInfo.loverId
        req.getRequest('/api/user/curt/lover/letter',{}).then(res => {
            console.log(res);
            const { messageList } = res.data.data
            // 获取创建时间
            const date = new Date(res.header.Date);
            // 获取年月日时分秒等信息
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const hour = date.getHours();
            const minute = date.getMinutes();
            const formattedDate = `${year}年${month}月${day}日 ${hour}:${minute}`;
            this.setData({
                letterMsg: res.data.data,
                time: formattedDate
            })
            // 判断是否有图片
            console.log(messageList);
            messageList.forEach(item => {
                if(item.type === 'graphic') {
                    item.img = `https://xzjl-api.windymuse.cn/api/resource/${item.resourceId}?k=${id}`
                }else if(item.type === 'audio') {
                    item.audio = `https://xzjl-api.windymuse.cn/api/resource/${item.resourceId}?k=${id}`
                }
            })
            this.setData({messageList: messageList})
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.open) {
            // 单人状态下点击【信札】跳转的页面
            this.setData({showLetter: false})
            this.getUserInfo()
        }else if (options.id) {
            this.getLetterDetail(options.id)
            this.setData({
                showLetter: false,
                showEdit: false,
                letterId: options.id
            })
            // 判断是否回忆页面跳转
            if (options.hy) {
                this.setData({hy: true})
            }
        }else {
            this.getUserInfo()
        }
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})