const Util = require('../../utils/util.js');
const Service = require('../../utils/service.js');
const Tim = require('../../utils/tim.js');
const App = getApp();
import TIM from 'tim-wx-sdk';
Page({
  data: {
    noRecord: {
      winH: null,
    },
    noSrc: '/images/sqicon@2x.png',
    sessionList: [],
    val: '',
    huan: true,
    btnFlag: true,
    unitid: '',
    showview: false,
  },
  onLoad: function (options) {
    var that = this;
    that.getHeight();
  },
  onShow: function () {
    var that = this;
    that.login = that.selectComponent("#login");
    that.modal = that.selectComponent("#modal");
    that.answer = that.selectComponent("#answer");
    wx.login({
      success: function (msg) {
        Service.getOpenId(msg.code).then((res) => {
          wx.setStorageSync('user', res)
          return Service.getUserData(res.openid)
        }).then((res) => {
          if (Util.isEmpty(res.unionid)) {
            that.login.showLogin();
            console.log(1)
            that.setData({
              showview: true,
            })
          } else {
            wx.setStorageSync('data', res)
            if (!App.globalData.isLogin) {
              Service.getUserSig(res.unionid).then((res) => {
                return Tim.login(res.data.userid, res.data.sign)
              }).then(function (imResponse) {
                console.log('%c登录成功', "color:#04BE02", imResponse);
                if (imResponse.data.repeatLogin === true) {
                  // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
                  console.log('"%c本次登录操作为重复登录', "color:#ff0000", imResponse.data.errorInfo);
                }
              }).catch(function (imError) {
                console.log('"%c登录失败', "color:#ff0000", imError); // 登录失败
                console.warn('login error:', imError); // 登录失败的相关信息
              });
            }
            that.setData({
              userInfo: res,
            })
            // that.resultNot(res.openid);
            that.timer();
          }
        }).catch(error => {
          console.error("我的服务登录", error)
        })
      }
    })
  },
  /**
   * 等待登录成功后调用
   */
  timer() {
    let that = this;
    let timer = setInterval(() => {
      if (App.globalData.isLogin) {
        that.sessionList();
        clearInterval(timer)
      }
    }, 500);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    Tim.tim.off(TIM.EVENT.CONVERSATION_LIST_UPDATED, that.onConversationListUpdated);
    that.sessionList();
    setTimeout(function () {
      wx.hideNavigationBarLoading();
      // 停止下拉动作
      wx.stopPullDownRefresh();
    }, 1000)
  },
  /**
   * 页面从前台变为后台时执行
   */
  onHide: function () {
    var that = this;
    Tim.tim.off(TIM.EVENT.CONVERSATION_LIST_UPDATED, that.onConversationListUpdated);
  },
  /**
   * 页面销毁时执行
   */
  onUnload: function () {
    var that = this;
    Tim.tim.off(TIM.EVENT.CONVERSATION_LIST_UPDATED, that.onConversationListUpdated);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '我的服务',
      path: '/pages/chatNews/chatNews',
    }
  },
  //菜单栏红点提示
  resultNot(openid) {
    console.log("resultNot")
    //未做量表提醒
    var data = {
      openid: openid
    }
    Service.getNotResult(data).then((res) => {
      if (res[0].length > 0) {
        wx.showTabBarRedDot({
          index: 2
        })
      } else {
        wx.hideTabBarRedDot({
          index: 2
        })
      }
    }).catch(error => {
      console.error("菜单栏红点提示", error)
    })
  },
  //获取im会话列表
  sessionList: function () {
    let that = this;
    console.log("Tim.data.sessionList", Tim.data.sessionList)
    that.data.sessionList = Tim.data.sessionList.filter(item => {
      return item.type == "GROUP"
    });
    Tim.tim.getGroupList().then(function (imResponse) {
      console.log("群组列表", imResponse.data.groupList); // 群组列表
    }).catch(function (imError) {
      console.warn('getGroupList error:', imError); // 获取群组列表失败的相关信息
    });
    //取消在Tim.js监听的会话列表避免重复监听
    // Tim.tim.off(TIM.EVENT.CONVERSATION_LIST_UPDATED, Tim.onConversationListUpdated);
    that.getServiceList();
    //重新监听会话列表
    Tim.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, that.onConversationListUpdated);
  },
  /**
   * 监听会话列表实例
   * @param {} event 
   */
  onConversationListUpdated: function (event) {
    let that = this;
    console.log("%c收到会话列表更新通知", "color:#2684ff", event)
    that.data.sessionList = event.data.filter(item => {
      return item.type == "GROUP"
    });
    // that.data.sessionList = event.data;
    that.getServiceList();
    // 收到会话列表更新通知，可通过遍历 event.data 获取会话列表数据并渲染到页面
    // event.name - TIM.EVENT.CONVERSATION_LIST_UPDATED
    // event.data - 存储 Conversation 对象的数组 - [Conversation]
  },

  //去聊天页面
  goChat: Util.debouce(function (e) {
    // console.log(e);
    wx.showLoading();
    let item = e.currentTarget.dataset.item;
    var datas = {};
    var user = wx.getStorageSync('user');
    datas.openid = user.openid;
    if (!user.openid) return;
    let t_unionid = item.consultant_unionid;
    wx.navigateTo({
      url: '/packageA/chat/chat?t_unionid=' + t_unionid + '&groupID=' + item.groupProfile.groupID + '&orderId=' + item.id,
    })
    wx.hideLoading();
  }, 1000, true),
  getHeight: function () {
    let that = this;
    wx.getSystemInfo({
      success: (res) => {
        that.setData({
          rpx: res.pixelRatio,
          ['noRecord.winH']: res.windowHeight,
        })
      }
    });
  },
  ///获取服务列表
  getServiceList() {
    let that = this;
    let chat = that.data.sessionList.map(item => {
      return item.groupProfile.groupID;
    })
    let data = {
      chat: chat
    }
    Service.getServiceList(data).then((res) => {
      if (res.code == 1) {
        let serviceList = that.data.sessionList.map(item => {
          res.data.some(obj => {
            if (obj.chat_id == item.groupProfile.groupID) {
              //合并群号相同的JSon对象
              item = JSON.parse((JSON.stringify(item) + JSON.stringify(obj)).replace(/}{/, ','))
              return true;
            }
          })
          //解析最新消息时间
          item.MsgTimeStamp = item.lastMessage.lastTime == 0 ? '' : Util.timestampFormat(item.lastMessage.lastTime);
          item.groupName = item.groupProfile.name;
          return item;
        });
        that.setData({
          serviceList: serviceList,
          showview: true,
        });
      } else {
        that.setData({
          serviceList: [],
          showview: true,
        });
      }
    }).catch(error => {
      console.error("获取服务列表", error)
    })
  },
    /**
   * 图片加载失败函数
   * @param {any} e 
   */
  binderrorimg(e) {
    let errorindex = e.currentTarget.dataset.errorindex;
    let   up = "serviceList[" + errorindex + "].image";
    this.setData({
      [up]: '/images/doctor_img.png'
    })
  },
  //登陆后组件回调方法刷新当前页面
  _refreshEvent() {
    console.log("刷新");
    this.onShow();
  },
})