// pages/message/message.js
const app = getApp();
import {lastSysMsg} from "../../api/msg"
import {throttle,setBarData} from "../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    systemMsg:{},
    show:false,
    isTriggered:false,
    isLock:false,
    currentConversationID:"",
    conversationUnread:0,
    conversationList:[],
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static'
  },
  confirm:throttle(function(event){
    if(event.detail){
      this.delConversation(this.data.currentConversationID);
    }
  }),
  handleLastSysMsg(){
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // });
    lastSysMsg().then(data=>{
          this.setData({
            systemMsg:data,
            isTriggered:false
          })
          // let total=app.globalData.chatNumber+app.globalData.sysNumber;
          // setBarData(total)
          //let msg=data.count;
          this.getConversationList(data.count)
        
    })
  },
  handleConfirm(event){
    let currentConversationID=event.currentTarget.dataset.id;
    let count=event.currentTarget.dataset.count;
      this.setData({
        show:true,
        conversationUnread:count,
        currentConversationID:currentConversationID
      })

  },
  watchBack(){
    // this.setData({
    //   conversationList:conversationList
    // })
    // setBarData(app.globalData.totalUnread);
    this.handleLastSysMsg();
  },
  delConversation(id){
    let promise=wx.$TUIKit.deleteConversation({conversationIDList:[id], clearHistoryMessage:false });
    promise.then(data=>{
      let conversationList=app.globalData.conversationList;
      for (let i = 0; i < conversationList.length; i++) {
          if(conversationList[i].conversationID==id){
            conversationList.splice(i,1);
            app.globalData.conversationList=conversationList;
            this.setData({
              conversationList:conversationList
            })
          }
        
      }
    }).catch((imError)=>{
      console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
    });
  },
  formatData(read){
          let totalNum=Number(app.globalData.totalNumber);
          let total=totalNum-Number(read);
          app.globalData.totalNumber=total;
          if(total>0){
            if(total<=99){
             wx.setTabBarBadge({
               index:1,
               text: total.toString()
             })
            }else{
             wx.setTabBarBadge({
               index:1,
               text:"99+"
             })
            }
          }else{
            wx.removeTabBarBadge({
              index:1
            })
          }
  },
  getConversationList(msg){
    wx.$TUIKit.getConversationList().then((res)=>{
       const {conversationList}=res.data;
       console.log(conversationList)
       let list=conversationList.filter(item=>item.conversationID!='C2Cadministrator');
       app.globalData.conversationList=list;
       this.setData({
        conversationList: list
      })
    
      let unread=0;
      list.forEach((item)=>{
        unread=unread+item.unreadCount;
      })
       let total=Number(msg)+Number(unread);
       app.globalData.totalUnread=total;
       setBarData(total);
     });
   

  },
  goChat(event){
    if(!this.data.isLock){
      this.setData({
        isLock:true
      });
      let currentConversationID=event.currentTarget.dataset.chatid;
     try {
      let custom=JSON.parse(event.currentTarget.dataset.custom);
      app.method.navigateTo({
        url: '/TUIService/pages/index?currentConversationID='+currentConversationID+'&order_inquiry_id='+custom.order_inquiry_id+'&inquiry_type='+custom.inquiry_type
      });
     } catch (error) {
        console.log(error)
     }
    }
   
  
  },
  goSysMsg(){
    app.method.navigateTo({
      url: '/patient/pages/sysMsgDetail/sysMsgDetail',
    })
  },
  handleRefresher(){
    this.setData({
      isLock:false,
      'systemMsg.count':0
    })
    this.handleLastSysMsg();
   },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.removeTabBarBadge({
      index:1
    })
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    app.globalData.origion=0;
    this.setData({
      isLock:false,
      'systemMsg.count':0,
      img_host:app.hostConfig().imghost
    }); 
    app.watch(this.watchBack.bind(this))//注册监听
    if(!app.globalData.totalUnread && app.globalData.totalUnread!=0){
      app.imLogin();
    }else{
      this.handleLastSysMsg();
    }
  },

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

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  
})