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

    /**
     * 页面的初始数据
     */
    data: {
        innerAudioContext:'',
        formats: {},
        readOnly: false,
        placeholder: '开始输入...',
        editorHeight: 300,
        keyboardHeight: 0,
        isIOS: false,//文本编辑器相关
        placeholder:'请输入文字',
        xinzhaVisible:false,
        luYInRes:'',//点击录音弹出的录音资源
        RM:'',
        xhCstP1:[,,,,,,,,],
        xhCstP:[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,],
        timer:null,
        minute:  0,   // 分
        second: 0 ,   // 秒
        millisecond:0,
        dsQTime:'00：00：00',
        luYinStatus:0,//录音状态，0代表还没开始，1代表进行中，2代表录音完毕
        delId:'',
        luyinVisible:false,
        imgPicUrl:'',
        dkTpVisible:false,
        ztDetial:{},//打开纸条弹窗详情
        dkZtVisible:false,//打开纸条弹窗
        ztText:"",
        ztVisible:false,//写纸条弹窗
        messages:[],
        loverInfo:{},
        hasLover:false,// 是否单身
        userInfo:{}

    },
    doLuYINBoF(e){
        //先判断是开是关
        if(!e.currentTarget.dataset.bf){//此时点击为关闭
            //设置当前状态为关闭，并关闭
            this.setData({['messages['+e.currentTarget.dataset.index+'].extra.isBf']:false})
            this.data.innerAudioContext.stop() // 关闭
        }else{//此时点击为开启
            // 先设置全部为false
            for(var i =0;i<this.data.messages.length;i++){
                this.setData({['messages['+i+'].extra.isBf']:false})
            }
            //先停止
            this.data.innerAudioContext.stop()
            const innerAudioContext = wx.createInnerAudioContext({
                useWebAudioImplement: false 
            })
            this.data.innerAudioContext.src = e.currentTarget.dataset.tp
            this.setData({['messages['+e.currentTarget.dataset.index+'].extra.isBf']:true})

            this.data.innerAudioContext.play() // 播放
            // 此时需要向对应的item赋值
            
            //innerAudioContext.pause() // 暂停
            
            // innerAudioContext.stop() // 停止
            this.data.innerAudioContext.onEnded((res)=>{
                this.setData({['messages['+e.currentTarget.dataset.index+'].extra.isBf']:false})
            })
        }
        
    },
    //编辑器相关
    readOnlyChange() {
        this.setData({
          readOnly: !this.data.readOnly
        })
      },
    updatePosition(keyboardHeight) {
        const toolbarHeight = 50
        const { windowHeight, platform } = wx.getSystemInfoSync()
        let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
        this.setData({ editorHeight, keyboardHeight })
      },
      calNavigationBarAndStatusBar() {
        const systemInfo = wx.getSystemInfoSync()
        const { statusBarHeight, platform } = systemInfo
        const isIOS = platform === 'ios'
        const navigationBarHeight = isIOS ? 44 : 48
        return statusBarHeight + navigationBarHeight
      },
      onEditorReady() {
        const that = this
        wx.createSelectorQuery().select('#editor').context(function (res) {
          that.editorCtx = res.context
        }).exec()
      },
      blur() {
        this.editorCtx.blur()
      },
      format(e) {
        let { name, value } = e.target.dataset
        if (!name) return
        this.editorCtx.format(name, value)
    
      },
      onStatusChange(e) {
        const formats = e.detail
        this.setData({ formats })
      },
      insertDivider() {
        this.editorCtx.insertDivider({
          success: function () {
            console.log('insert divider success')
          }
        })
      },
      clear() {
        this.editorCtx.clear({
          success: function (res) {
            console.log("clear success")
          }
        })
      },
      removeFormat() {
        this.editorCtx.removeFormat()
      },
      insertDate() {
        const date = new Date()
        const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
        this.editorCtx.insertText({
          text: formatDate
        })
      },
      insertImage() {
        const that = this
        wx.chooseImage({
          count: 1,
          success: function (res) {
            that.editorCtx.insertImage({
              src: res.tempFilePaths[0],
              data: {
                id: 'abcd',
                role: 'god'
              },
              width: '80%',
              success: function () {
                console.log('insert image success')
              }
            })
          }
        })
      },




    do2FsLuyin(){/**发送录音按钮 */
        this.data.RM.stop();
        console.log('发送录音')
        this.setData({luyinVisible:false})
        let tt= this
        this.data.RM.onStop((res)=>{
            //录音时长判断
            console.log('发送录音了1111。。')
            // 先计算分钟
            let fz = 0
            let mz = 0
            let hm = 0
            if(res.duration>=60*1000){
                fz = Math.floor(res.duration/(60*1000))
            }
            if(res.duration>=1000){
                mz = Math.floor((res.duration-fz*60*1000)/(1000))
            }
            hm = res.duration - fz*60*1000-mz*1000
            let sec = Math.floor(res.duration/1000)
            let ssec = fz+'\''+mz+'\'\''+hm+'\'\'\''
            console.log(ssec)
            wx.uploadFile({
                url: 'https://xzjl-api.windymuse.cn/api/resource',
                filePath: res.tempFilePath,
                name: 'file',
                header: {
                    'Authorization': wx.getStorageSync('token'),        
                  'Content-Type': 'multipart/form-data'
                },
                formData: {
                  type: 'audio'
                  
                },
                success(res){
                    let data = JSON.parse(res.data);
                    let id = data.data.id
                    req.postRequest('/api/user/curt/message/lover',{"type": "audio","resourceId": id,extra:{
                        ssec:ssec,
                        isBf:false //正在播放为false
                    }}).then((res)=>{
                        tt.onLoad()
                        if(res.data.code==200){
                            console.log(res.data)
                        }
                       }).catch((err)=>{
                        console.log(err);
                    })
                },

                fail(res) {
                  showToast('图片上传失败');
                }
              })



            console.log(res)//这里是必须写完成事件的，因为最后的文件，就在这里面；
            res.tempFilePath;//是临时的文件地址
            res.duration;//录音的时长
            res.fileSize;//文件的大小
        })
    },
    doStopLuyin(){
        this.setData({luYinStatus:2})
        clearInterval(this.data.timer)
        console.log('结束录音')
        this.data.RM.pause()
    },
    doStartLuyin(){
        this.setData({RM:wx.getRecorderManager()})
        let option = {
            duration:10000,     //录音的时长，之前最大值好像只有1分钟，现在最长可以录音10分钟
            format:'mp3',         //录音的格式，有aac和mp3两种   
        }
        this.data.RM.start(option);
        console.log(this.data.RM)
        this.setData({luYinStatus:1})
        console.log('开始录音。。。')
        this.setData({
            minute:0,
            second:0,
            millisecond:0
          })
        this.data.timer = setInterval(this.counter,50)
        // 开始定时器
    },
    counter:function(){
        
        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
             })
      }
             if(second == 60){
                this.setData({
                  second : 0,
                  minute:minute+1
                })
             }
             if(this.data.minute==3){
                this.setData({
                    dsQTime:'03:00:00'
                   })
                clearInterval(this.data.timer)
            }

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

            this.setData({
                dsQTime: tt
               })
    
      
   },
    DsJs(){
        this.data.timer = setInterval(this.Dsq(),1)
    },
    Dsq(){
        console.log('开始执行')
        this.setData({second:this.data.second+1})
        this.setData({dsQTime:this.data.dsQTime+this.data.second+1})
        console.log(this.data.dsQTime)
    },
    allTap(){
        this.popover.onHide();
    },
    // 响应popover组件中的子元素点击事件
    doDelXiaoxi(){
        req.deleteRequest('/api/user/curt/message/'+this.data.delId,{}).then((res)=>{
            this.popover.onHide();
            if(res.data.code==200){
                wx.showToast({
                    title: '删除消息成功',
                    icon: 'none'
                  });
                  this.onLoad()
            }else{
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                  });
            }
           }).catch((err)=>{
            wx.showToast({
                title: '删除消息失败',
                icon: 'none'
              });
            console.log(err);
        })
    },
    onClickA: function (e) {
        wx.showToast({
          title: '你点击了A',
          icon: 'none'
        });
        // 调用自定义组件 popover 中的 onHide 方法
        this.popover.onHide();
      },
    changAn(e){
        if(!this.popover){
            this.popover = this.selectComponent('#popover');
        }
        console.log('执行了长按。。。')// +e.currentTarget.dataset['index']
        console.log(e.currentTarget.dataset['id'])
        this.setData({delId:e.currentTarget.dataset['id']})

        // 获取按钮元素的坐标信息
      let id = 'button'// 或者 e.target.id 获取点击元素的 ID 值
      console.log(e.currentTarget.dataset['index'])
      wx.createSelectorQuery().select('#' + e.currentTarget.dataset['index']).boundingClientRect(res => {
        // 调用自定义组件 popover 中的 onDisplay 方法
        this.popover.onDisplay(res);
      }).exec();

    },
    go2BcPic(){/**保存图片 */
        let that= this;
        wx.downloadFile({
        url: that.data.imgPicUrl,//图片的地址
        success:function(res){
            const tempFilePath = res.tempFilePath  //通过res中的tempFilePath 得到需要下载的图片地址
            wx.saveImageToPhotosAlbum({
                filePath: tempFilePath,  //设置下载图片的地址
            success:function(){
                wx.showToast({
                    title: '保存图片成功',
                  })
            }
            })
        }
        })

    },
    go2Reback1(){
        //wx.navigateBack({ changed: true });
        this.setData({dkTpVisible:false})
    },
    go2Reback(){
        wx.switchTab({
          url: '/pages/home/xy/index',
        })
    },
    go2SeeHxDetail(e){
        this.setData({imgPicUrl:e.currentTarget.dataset.tp})
        this.setData({dkTpVisible:true})
        console.log(e.currentTarget.dataset.tp)
        console.log('查看图片详情')
    },
    //bindtap="dKztDetial" data-xq="{{item}}"
    dKztDetial(e){/**查看详情 */
        let detail = e.currentTarget.dataset['xq']
        if(!detail.isSelf&&detail.status=='unread'){
            // 不是自己发的消息，且消息状态为未读，需要设置消息状态为已读
            ///api/user/curt/message/{id}/read
            req.patchRequest('/api/user/curt/message/'+detail.id+'/read',{}).then((res)=>{
                if(res.data.code==200){
                }
               }).catch((err)=>{
                console.log(err);
            })
        }
        if(detail.isSelf){
        }
        this.setData({dkZtVisible:true,tDetial:e.currentTarget.dataset['xq']})
    },
    doCancelDkZt(){
        this.setData({dkZtVisible:false})
    },
    openZtVisible(){/**点击纸条按钮 */
        this.setData({ztVisible:true})
    },
    doCancelZt(){/**点击纸条里面取消按钮 */
        this.setData({ztVisible:false})
    },
    doFSZt(){/**点击纸条里面发送按钮 */
        if(!this.data.ztText){
            wx.showToast({
                title:'纸条内容不能为空！',
                icon: 'none',
                duration: 1000
            })
        }else{
            req.postRequest('/api/user/curt/message/lover',{"type": "text","content": this.data.ztText}).then((res)=>{
                this.onLoad()
                if(res.data.code==200){
                    
                }
               }).catch((err)=>{
                console.log(err);
            })
            this.setData({ztVisible:false,ztText:''})
        }
        
    },
    go2Huiyi(){/**跳转到回忆页面 */
        wx.navigateTo({
            url: '/pages/home/xx/hy/index'
            })
    },
    doMessageInfo(){/**查询聊天信息 */
        req.getRequest('/api/user/curt/message/lover',{}).then((res)=>{
            if(res.data.code==200){
                this.setData({messages:res.data.data.records.reverse()})
            }
           }).catch((err)=>{
            console.log(err);
        })
    },
    doQueryInit(){
        req.getRequest('/api/user/curt',{}).then((res)=>{
            if(res.data.code==200){
                this.setData({hasLover:res.data.data.hasLover})
                this.setData({userInfo:res.data.data})
                if(!res.data.data.hasLover){
                    wx.navigateTo({
                        url: '/pages/home/xx/index'
                        })
                }
            
            }
           }).catch((err)=>{
            console.log(err);
        })

        req.getRequest('/api/user/curt/lover',{}).then((res)=>{
            if(res.data.code==200){
                this.setData({loverInfo:res.data.data})
            }
           }).catch((err)=>{
            console.log(err);
        })

        ///api/user/curt/lover


    },
    doClickHx(){
        console.log('点击了画像')
        let tt = this
        wx.chooseImage({
            count:1,//默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: res=>{
                var tempFilePaths = res.tempFilePaths;
                wx.uploadFile({
                    url: 'https://xzjl-api.windymuse.cn/api/resource',
                    filePath: tempFilePaths[0],
                    name: 'file',
                    header: {
                        'Authorization': wx.getStorageSync('token'),        
                      'Content-Type': 'multipart/form-data'
                    },
                    formData: {
                      type: 'graphic'
                    },
                    success(res){
                        console.log('执行成功了')
                        console.log(res)
                        let data = JSON.parse(res.data);
                        console.log(data, '111111');
                        let id = data.data.id
                        console.log('打印id')
                        console.log(id)
                        
                        req.postRequest('/api/user/curt/message/lover',{"type": "graphic","resourceId": id}).then((res)=>{
                            tt.onLoad()
                            if(res.data.code==200){
                                console.log(res.data)
                            }
                           }).catch((err)=>{
                            console.log(err);
                        })
                    },

                    fail(res) {
                      showToast('图片上传失败');
                    }
                  })
            }
        })
    },
    doClickYx(){
        this.setData({luyinVisible:true,luYinStatus:0,dsQTime:'00：00：00'})
        console.log('点击了音讯')
    },
    quxiaoLuyin(){/**取消录音 */
        this.setData({luyinVisible:false})
        clearInterval(this.data.timer)
    },
    fasLuyin(){/**发送录音文件 */
        clearInterval(this.data.timer)
        this.setData({luyinVisible:false})
    },
    doClickXz(){
        this.setData({xinzhaVisible:true})
        console.log('点击了信札')
        wx.navigateTo({
            url: '/pages/home/xx/lindex/lxz/lxz'
            })
    },
    doCancelXz(){
        this.setData({xinzhaVisible:false})
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('开始。。。。')
        const innerAudioContext = wx.createInnerAudioContext({
            useWebAudioImplement: false 
          })
          this.setData({innerAudioContext:innerAudioContext})
        this.popover = this.selectComponent('#popover');
        console.log('结束。。。。')
        this.doQueryInit()
        this.doMessageInfo()
        /**----------------一下为编辑器代码-----------------*/
        
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.doQueryInit()
        this.doMessageInfo()
    },

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

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        this.data.innerAudioContext.stop()
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        clearInterval(this.data.timer)
        this.data.innerAudioContext.stop()
    },

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

    },

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

    },

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

    },
    toSend(){
        wx.redirectTo({
          url: 'xz/xz'
        })
    }
})