import TIM from '../lib/tim-wx-sdk';
import TIMUploadPlugin from '../lib/tim-upload-plugin';
import {lastSysMsg} from "../api/msg"
import {imSign} from "../api/common"
import {loginout} from "../api/personCenter"
import {setBarData} from "./util"
 wx.$TUIKit=null;
 wx.$TUIKitTIM=null;
let appglobal=null;
function imLogin(app){
  appglobal=app;
  imSign().then(data=>{
    wx.$TUIKit = TIM.create({
      SDKAppID: appglobal.globalData.config.SDKAPPID,
    });
    //const userSig = genTestUserSig(this.globalData.config).userSig;
    wx.$chat_SDKAppID = appglobal.globalData.config.SDKAPPID;
    wx.$TUIKitTIM = TIM;
    
    wx.$chat_userID = appglobal.globalData.config.userID;
    //wx.$chat_userSig = userSig;
    wx.$TUIKit.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });
    wx.$TUIKit.setLogLevel(0);
    wx.$chat_userSig =data;
     let USER_ID=wx.getStorageSync('USER_ID');
     if(USER_ID){
      wx.$TUIKit.login({
        userID: wx.getStorageSync('USER_ID'),
        userSig:data
     }).then(res=>{
       console.log("登录成功");
//        wx.callManager.init({
//         sdkAppID: appglobal.globalData.config.SDKAPPID,   // 请填入 sdkAppID
//         userID: wx.getStorageSync('USER_ID'),    // 请填入 userID
//         userSig: data,   // 请填入 userSig
//         globalCallPagePath: "TUICallKit/pages/globalCall/globalCall",
//         tim: wx.$TUIKit
//   });
     }).catch(function(imError) {
      console.warn('login error:', imError); // 登录失败的相关信息
    });
     wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.SDK_READY,onSDKReady,this);
     wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.SDK_READY,onSDKReady);
     }else{
      console.log("IM未登录")
     }
    
  })
};
function onSDKReady(app){
  onMessageReceived();
  wx.$TUIKit.off(TIM.EVENT.ERROR,errorMsg);
  wx.$TUIKit.on(TIM.EVENT.ERROR,errorMsg,this);
  wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.MESSAGE_RECEIVED,onMessageReceived);
  wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.MESSAGE_RECEIVED,onMessageReceived,this);
  wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.KICKED_OUT,onKickOut);
  wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.KICKED_OUT,onKickOut,this);
  wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, onTotalUnreadMessageCountUpdated,this);
};
function errorMsg(event){
  wx.showToast({
    title:event.data.message,
    icon:'none'
  })
};
function onTotalUnreadMessageCountUpdated(event){
  console.log(event.data);
};
function onKickOut(event){
  wx.showToast({
    title: '账号在其他端登录，即将下线',
    icon:'none'
  });
  handleLogout();
 };
 function handleLogout(){
   if(wx.$TUIKit){
     wx.$TUIKit.destroy()
   };
   loginout().then(data => {
    appglobal.globalData.chatNumber=0;
    appglobal.globalData.sysNumber=0;
    appglobal.globalData.conversationList=[];
     wx.clearStorageSync();
     wx.reLaunch({
       url: '/pages/login/login'
     })
   })
 };

function onMessageReceived(){
  getLastMsg();
};
function getConversationList(msg){
  wx.$TUIKit.getConversationList().then((res)=>{
    const {conversationList}=res.data;
    console.log(conversationList);
    let list=conversationList.filter(item=>item.conversationID!='C2Cadministrator');
    let unRead=0;
    list.forEach((item)=>{
     unRead=unRead+item.unreadCount;
    })
     appglobal.globalData.conversationList=list;
     appglobal.globalData.chatNumber=Number(unRead);
     setBarData(Number(unRead)+msg);
  });
};
function getLastMsg(){
  lastSysMsg().then(data=>{
    let msg=data.count;
    appglobal.globalData.sysNumber=msg;
    getConversationList(msg);
  }).catch(()=>{
    let msg=0;
    appglobal.globalData.sysNumber=0;
    getConversationList(msg)
  })
};
module.exports={
  imLogin
}