const app = getApp();
const time = require('../../../utils/time.js');
const ImageType = 'images';
const TextType = 'text';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    codedata: true,  //用来判断code
    frequency:true, //多次加载次数限制
    hiddenName:true, // 加载更多显示隐藏
    toView:'Stop',   //锚点
    scrollTopVal: 1,    //滚动条
    menu: false, //菜单显示隐藏
    Expression: false,  // 表情显示隐藏
    Sendoutshow: false, // 发送按钮显示隐藏
    menushow: true, //菜单按钮显示隐藏
    _width: 500, //input高度
    // uploadImages: ["/image/smyz2.png","/image/smyz1.png"], //相册放大图集
    news: '',//input消息
    KeyboardHeight: 366.66666666666674, //键盘高度
    ExpressionImg: '', //表情
    // Loadmore: true, //用来判断加载聊天记录。。每次只能执行一次
    inputValue: '',  //input 的 value 
    photo: '', //相片

    Receive_news: '', //历史消息
    UserToken: '',  //区分自己
    limit_page: 1,

    myheadurl: '', //我的头像
    headUrl: '', //他人头像

    to_id: '',    //他人
    form_id: '',   //自己

    // scrollTop:'' //下拉更多时的位置
    connectemojiO: ['😊', '😅', '😲', '😭', '😂', '😄', '😩', '😞', '😵', '😒', '😍', '😤', '😜', '😝', '😋', '😘', '😚', '😷', '😳', '😃', '😆', '😁', '😢', '😨', '😠', '😣', '😌', '😖', '😔', '😰', '😱', '😪', '😏', '😓'],


  },

  onLoad: function (options) {
    var that = this;

    that.ArrMsg = [];
    // console.log(that.data.UserToken);
    // console.log(options.headUrl);
    // console.log(options.myheadurl);
    // console.log(getApp().UserId(),'token');

    // console.log(options);
    const friend = options;

    that.setData({
      to_id: friend.to_id,  // 他人
      UserToken: getApp().UserToken(),   //自己
      myheadurl: options.myheadurl, //我的头像
      headUrl: options.headUrl, //他人头像
    })


    this.SocketSend({
      //  to_id: friend.to_id,    // 他人
      //  form_id: getApp().UserId(),   //自己
      type: 'get_history',
      page: this.data.limit_page,
      limit:10
      

    });
    getApp().Imsocket().onSocketMessageCallback = this.onSocketMessageCallback;




    
  },


  // 点击scroll-view 关闭底部菜单
  resetInputStatus: function () {
    var that = this;
    that.setData({
      menu: false, //关闭底部菜单
      Expression: false, //关闭表情
    })
  },


  // 底部菜单显示隐藏切换
  chatInputExtraClickEvent: function () {
    var that = this;
    that.setData({
      menu: !that.data.menu,
      Expression: false, //关闭表情
    })
  },



  // 关闭表情显示隐藏切换
  ExpressionClickEvent: function () {
    var that = this;
    that.setData({
      Expression: !that.data.Expression,
      menu: false, //关闭底部菜单
    })
  },





  // 相册点击放大
  enlarge: function (e) {
    var that = this;
    // console.log(that.data.uploadImages)
    console.log(e.currentTarget.dataset.src,)
    wx.previewImage({
      current: e.currentTarget.dataset.src, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.src], // 需要预览的图片http链接列表
    })


  },



  //input输入框
  Telephone: function (e) {
    var that = this;
    // console.log(e.detail.value);
    that.setData({
      news: e.detail.value,     //获取输入文字
    })


    that.Sendoutswitch(e.detail.value); // 发送键切换
  },



  // 上传图片
  chooseImageTap: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {

        wx.uploadFile({
          url: getApp().globalData.url + 'imsocket/images/chatimg',
          filePath: res.tempFilePaths[0],
          name: 'photo',
          formData: {
            key: wx.getStorageSync('access_key'),
            token: wx.getStorageSync('access_token')
          },
          success: function (res) {
            var data = JSON.parse(res.data);

            console.log(data, '图片上传成功');

            if (data.code == 201) {
              let con = data.data;
              //显示图片
              console.log(con, 1);

              // console.log(ImgRes.tempFilePaths[0], 1222222);
              that.SocketSend({ type: ImageType, content: con.img_name });

              // that.msgManager.sendMsg({ type: IMOperator.ImageType, content: con })

            } else if (data.code == 301) {
              wx.showModal({
                title: '提示',
                content: data.msg,
                showCancel: false,
              })
            }
          }, fail: function (d) {
          }
        })
        console.log(res.tempFilePaths[0]);
        // tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          photo: res.tempFilePaths[0],
          menu: false, //菜单显示隐藏
        });

      }
    })
  },



  // 重发消息
  retransmission: function () {
    wx.showModal({
      content: '重发该消息?',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },



  // 发送消息
  SocketSend: function (msg) {
    var that = this;
    msg.form_id = getApp().UserId();
    msg.to_id = that.data.to_id;

    // console.log(that.data.Receive_news);

    // { to_id: friend.to_id, form_id: getApp().UserId(), type: 'get_history' }
    // msg.type = 'get_history';
    getApp().Imsocket().sendSocketMessage({
      msg: JSON.stringify(msg),

      success: function (res) {   //发送成功

        var current_time = Date.now();
        var _time = time.TimeFormatting(current_time);   // 时间格式化
        // console.log(_time);

        // 我跟他人说话
        switch (msg.type) {

          case "alone":     //  发送文本




            
            console.log(' 发送文本');
            var obj = {     //创建对象,用来合并历史消息对象
              content: that.data.news,     //发送消息内容  
              type: 1,                            //类型 1 : 文字类型     类型 2 : 图片
              time: _time,         //时间
              isMy: true,   //自己
              send: true,   //    发送成功  为true   失败false 
            };
            let _Receive_news = that.data.Receive_news;
            _Receive_news.push(obj);   //合并历史消息对象

            console.log(_Receive_news, 'aaa');
            that.setData({
              Receive_news: _Receive_news,     //前台数据赋值 
            });

            //调用页面滚动条处理
            that.scrollbar(_Receive_news);

            break;

          case "images":   //  发送图片


            console.log(' 发送图片');

            var obj = {     //创建对象,用来合并历史消息对象
              content: that.data.photo,     //发送消息内容  
              type: 2,                            //类型 1 : 文字类型     类型 2 : 图片
              time: _time,         //时间
              isMy: true,   //自己
              send: true,   //    发送成功  为true   失败false 
            };
            let _Receive_img = that.data.Receive_news;
            _Receive_img.push(obj);   //合并历史消息对象

            console.log(_Receive_img, '发送图片');
            that.setData({
              Receive_news: _Receive_img,     //前台数据赋值 
            });

            //调用页面滚动条处理
            that.scrollbar(_Receive_img);




            break;
        }

        console.log(res, '获取历史消息成功');

      }, fail: function (res) {    //发送失败

        console.log('获取历史消息失败')

      }
    })

  },


  // 接收消息
  onSocketMessageCallback: function (e) {
    var that = this;
    let data  = JSON.parse(e);
  
     console.log(data,'接受消息成功');

    var arrData = data.data.data;

   
    switch (data.type) {
      // 接收历史消息
      case "get_history":
        // console.log(arrData,111112222);

        var _code = data.code;

        if (_code == 201){
       
        // let total = arrData.length - 1;
        // console.log(total);

          // var vasd = time.TimeFormatting(1561186210);
          // console.log(vasd)

          console.log(arrData);

        for (var index in arrData) {     //二次赋值  
          if (arrData[index].form_id == getApp().UserToken()) {   //判断  如果等于自己 true  ,等于他人  false。
            arrData[index].isMy = true;    //自己
          } else {
            arrData[index].isMy = false;   //他人
          }

          if (arrData[index].type == 2){
               arrData[index].content = data.data.url + arrData[index].content + data.data.stylename;
          }

          if (arrData[index].create_at){
            var _time = time.TimeFormatting(arrData[index].create_at);   // 时间格式化
            arrData[index].time = _time;  //时间从新赋值
          }
        
          that.ArrMsg.push(arrData[index]);

        }

        for (var index in that.ArrMsg) {     //二次赋值   把所有的数据 hooks参数 清空
              if(that.ArrMsg[index].hooks){
                that.ArrMsg[index].hooks = '';
              }
        }
     
        let Arrs1 = that.sortarr(that.ArrMsg);       //最后要展示的数据  第11条  加上 hooks= 'Stop'; 参数  用来做加载更多数据,描点到最后一条信息
        if(Arrs1[10]){
          Arrs1[10].hooks = 'Stop';
        }
    
        console.log(Arrs1, 111112222);
        

        if (that.data.limit_page == 1) {   //判断  分页 1 的时候 
          that.setData({
            Receive_news: Arrs1,        //前台数据赋值 
            scrollTopVal: that.ArrMsg.length * 999,    // 滚动条赋值
            toView: false,   //关闭锚点
          });

        }else{   
          that.setData({
            Receive_news: Arrs1,        //前台数据赋值 
            toView: 'Stop'      //开启锚点 赋值
          });
        }
    
        that.setData({     //最后关闭锚点   方便每次进来  在开启 修复 描点会闪动
          toView: false,
          frequency: true,
          hiddenName: true,    //隐藏加载更多图片  
        });


        }else{
          that.setData({ 
            hiddenName: true,    //隐藏加载更多图片  
            codedata: false     //code 301  
          });

        }
        break;


      case "alone":       // 接收他人文本

        var arrDatatext = data.data;
        console.log(arrDatatext, "aaasd");


        var current_time = Date.now();
        var _time = time.TimeFormatting(current_time);   // 时间格式化
        // console.log(_time);

        var obj = {     //创建对象,用来合并历史消息对象
          content: arrDatatext.content,   //发送消息内容
          type: 1,          //类型 1 : 文字类型     类型 2 : 图片
          time: _time,    //时间
          isMy: false,   //他人
        };

       
        let _Receive_news = that.data.Receive_news;
        if (typeof _Receive_news == 'object'){
          _Receive_news.push(obj);      //合并历史消息对象
        }

        that.setData({
          Receive_news: _Receive_news,     //前台数据赋值 
        });

        //调用页面滚动条处理
        that.scrollbar(_Receive_news);
        break;

      case "images":   // 接收他人图片
        var arrDataimg = data.data;

        console.log(arrDataimg, "接收图片");

        var current_time = Date.now();
        var _time = time.TimeFormatting(current_time);   // 时间格式化
        // console.log(_time);

        var obj = {     //创建对象,用来合并历史消息对象
          content: arrDataimg.content,   //发送消息内容
          type: 2,          //类型 1 : 文字类型     类型 2 : 图片
          time: _time,    //时间
          isMy: false,   //他人
          
        };

        let _Receive_img = that.data.Receive_news;
        _Receive_img.push(obj);      //合并历史消息对象

        that.setData({
          Receive_news: _Receive_img,     //前台数据赋值 
        });

        //调用页面滚动条处理
        that.scrollbar(_Receive_img);


        break;



    }



  },

  // 处理滚动条
  scrollbar: function (data) {
    var that = this;
    if (data) {
      let lengNum = data.length;
      //页面滚动条处理

      that.setData({
        scrollTopVal: lengNum * 999
      })
      console.log(lengNum * 999);
    }

  },

  // 发送消息事件  用来获取input数据
  Sendout: function (e) {
    var that = this;
    // console.log(that.data.news);

    let msg = {
      // to_id: that.data.to_id,
      // form_id: getApp().UserId(),
      type: 'alone',
      content: that.data.news
    };

    // console.log(msg);
    this.SocketSend(msg);

    that.setData({
      menu: false,  //隐藏底部菜单
      Expression: false,//隐藏表情栏
      inputValue: '',  //清空 input
      news: '', //清空 input内容
    })


    that.Sendoutswitch(that.data.news)  // 发送键切换

    // console.log(that.data.Receive_news)

  },

  //冒泡排序
  sortarr: function (arr) {
    for (let i = 0; i < arr.length - 1; i++) {
      for (let j = 0; j < arr.length - 1 - i; j++) {
        if (arr[j].create_at > arr[j + 1].create_at) {
          var temp = arr[j];
          arr[j] = arr[j + 1];
          arr[j + 1] = temp;
        }
      }
    }
    return arr;
  },


  //  下拉加载聊天记录
  upper: function (e) {
    var that = this;
    // console.log(e,'加载')

    if (that.data.codedata == true){
      that.setData({   //  显示加载更多图片
        hiddenName: false,
      })
    }

  
 if (that.data.frequency == true){

  //  setTimeout(function () {
        that.setData({
          limit_page: that.data.limit_page * 1 + 1,
          frequency:false
        })
        console.log(that.data.limit_page * 1 + 1)
        that.SocketSend({ type: 'get_history', page: that.data.limit_page,limit:10})
    // }, 1000);
    }
    // console.log('执行')
  },


  // 点击表情
  Expression: function (e) {
    var that = this;

    var _news = that.data.news;
    var _text = _news + e.currentTarget.dataset.id;


    console.log(that.data.news)
    console.log(_text)
    that.setData({
      news: _text,
      inputValue: _text,
    })

    that.Sendoutswitch(that.data.news) // 发送键切换
  },


  // 点击input
  bindfocusclick: function (e) {
    var that = this;
    that.setData({
      Expression: false,
      menu: false,
      KeyboardHeight: e.detail.height,
    })
    // console.log(e.detail.height);
  },

  // 发送键切换
  Sendoutswitch: function (data) {
    var that = this;
    if (data == '') {
      that.setData({
        menushow: true,   //菜单按钮显示隐藏
        Sendoutshow: false,// 发送按钮显示隐藏
        _width: 500,   // input宽度
      })
    } else {
      that.setData({
        menushow: false,   //菜单按钮显示隐藏
        Sendoutshow: true,// 发送按钮显示隐藏
        _width: 447,   // input宽度
      })
    }
  }, 
  onUnload: function (e) {
    let url = 'imsocket/imchatmessage/clearunreadmsg';
    let datas = {
      to_id: this.data.to_id, form_id: getApp().UserId()
    };
    //清除未读信息
    getApp().postRequest(url, datas, function (res) {
      console.log(res, 11111);
    })
    console.log('销毁页面');
  },
  // ceshi: function (e) {
  //   var that = this;

  //   that.setData({
  //     // mscrollTop: e.detail.scrollTop,
  //     mscrollHeight: e.detail.scrollHeight
  //   })
  //   // console.log(e.detail.scrollTop);
  //   // console.log(e.detail.scrollHeight);
  //   // console.log(e.detail);
  // }


})