import router from './utils/router.js'
import TIM from './miniprogram_npm/tim-wx-sdk/index'

 import TIMUploadPlugin from './miniprogram_npm/tim-upload-plugin/index'
import {lastSysMsg} from "/api/msg"

import {
  imSign
} from "./api/common"
import {
  loginout
} from "./api/personCenter"
import {
  setBarData
} from "./utils/util"
import {
  hostConfig
} from "./utils/config"
const myconfig = hostConfig();


//   require.async('./TUICallKit/TUICallService/index').then(res => {
//     wx.TUICallKitServer = res.TUICallKitServer;
//   }).catch(({mod, errMsg}) => {
//     console.error(`path: ${mod}, ${errMsg}`)
//   })
  // import { TUICallKitServer } from "./TUICallKit/TUICallService/index";
//   import { CallManager } from './TUICallKit/TUICallService/serve/callManager';
// // 实例化
// wx.callManager = new CallManager();
//import { genTestUserSig } from './debug/GenerateTestUserSig';
//进去小程序方式origion //  0 正常进入 // 1分享  //2 订阅消息 
App({
  onLaunch: function (options) {
    console.log('applaunch');
    console.log(options)
    if(options.scene=1065 && options.query && options.query.doctor_id){
      wx.redirectTo({
        url: '/patient/pages/expertDetail/expertDetail?doctor_id='+options.query.doctor_id,
      })
    }
    // 绑定分享参数
    wx.onCopyUrl(() => {
      setTimeout(() => {
        wx.setClipboardData({
          data: '暂不支持分享',
          success(res) {},
          complete() {
            wx.hideToast()
          }
        })
      }, 1000)
      return
    })
  },
  onShow: function (options) {
    console.log('appshow');
    console.log(options)
    if (options.scene == 1007 || options.scene == 1008) {
      this.globalData.origion = 1;
    } else if (options.scene == 1014 || options.scene == 1017) {
      this.globalData.origion = 2;
    } else {
      this.globalData.origion = 0;
    };
    if(this.isHasToken()){
        this.imLogin(options);
    }
    

  },
  method: router,
  hostConfig: hostConfig,
  imLogin(options={},type=1,callback=()=>{}) {
    imSign().then(data => {
      wx.$TUIKit = TIM.create({
        SDKAppID: this.globalData.config.SDKAPPID,
      });
      //const userSig = genTestUserSig(this.globalData.config).userSig;
      wx.$chat_SDKAppID = this.globalData.config.SDKAPPID;
      wx.$TUIKitTIM = TIM;

      wx.$chat_userID = this.globalData.config.userID;
      //wx.$chat_userSig = userSig;
      wx.$TUIKit.registerPlugin({
        'tim-upload-plugin': TIMUploadPlugin
      });
      const {
        envVersion
      } = wx.getAccountInfoSync().miniProgram;
      if (envVersion == 'release') {
        wx.$TUIKit.setLogLevel(1);
      } else {
        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(async (res) => {
          console.log("登录成功");
          wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.SDK_READY, this.onSDKReady);
          console.log('userSig:'+data)
          await require.async('./TUICallKit/TUICallService/serve/callManager').then(res => {
            wx.callManager = new res.CallManager();
          }).catch(({mod, errMsg}) => {
            console.error(`path: ${mod}, ${errMsg}`)
          })
         await wx.callManager.init({
            sdkAppID: Number(this.globalData.config.SDKAPPID),   // 请填入 sdkAppID
            userID: wx.getStorageSync('USER_ID'),    // 请填入 userID
            userSig: data,   // 请填入 userSig
            globalCallPagePath: "TUICallKit/pages/globalCall/globalCall",
            tim: wx.$TUIKit
    })
          callback();
        }).catch(function (imError) {
          console.warn('login error:', imError); // 登录失败的相关信息
          if(type==1){
            wx.showToast({
              title: '登陆失败',
              icon:"none"
            })
          };
           if(!(options.path=="patient/pages/mobileLogin/mobileLogin" || options.path=='patient/pages/login/login')){
            wx.navigateTo({
              url: '/patient/pages/login/login',
            })
           }
         
        });
       
      } else {
        console.log("IM未登录")
      }
    })
  },
  onUnload() {
    wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.SDK_READY, this.onSDKReady);
    wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.ERROR, this.errorMsg);
    wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.KICKED_OUT, this.onKickOut);
    wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, this.onTotalUnreadMessageCountUpdated);
  },
  onSDKReady() {
      console.log('sdk已经ready')
    this.getLastMsg();
    wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.ERROR, this.errorMsg, this);
    wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.KICKED_OUT, this.onKickOut, this);
    wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, this.onTotalUnreadMessageCountUpdated, this);
  },
  errorMsg(event) {
    wx.showToast({
      title: event.data.message,
      icon: 'none'
    })
  },
  onTotalUnreadMessageCountUpdated(event) {
    this.globalData.allCount = event.data;
    this.getLastMsg();
  },
  onKickOut(event) {
    this.handleLogout();
  },
  isHasToken(){
    let token='';
    const { envVersion } = wx.getAccountInfoSync().miniProgram;
    if(envVersion=='release'){
      token = wx.getStorageSync('AUTH_TOKEN');
    }else{
      token = wx.getStorageSync('DEV_AUTH_TOKEN');
    }
    if(token){
        return true
    }else {
        return false;
    }
  },
  async handleLogout() {
    if (wx.$TUIKit) {
      wx.$TUIKit.destroy();
    };
    //wx.callManager.logout();
    wx.callManager.destroyed();
    loginout().then(data => {
      this.globalData.totalUnread = 0;
      this.globalData.conversationList = [];
      wx.clearStorageSync();
      wx.reLaunch({
        url: '/patient/pages/login/login',
        complete() {
          wx.showToast({
            title: '账号在其他端登录',
            duration: 3000,
            icon: 'none'
          });
        }
      })
    })
  },
  getConversationList(msg) {
    wx.$TUIKit.getConversationList().then((res) => {
      const {
        conversationList
      } = res.data;
      let list = conversationList.filter(item => item.conversationID != 'C2Cadministrator');
      let unRead = 0;
      list.forEach((item) => {
        unRead = unRead + item.unreadCount;
      })
      this.globalData.conversationList = list;
      this.globalData.totalUnread = Number(unRead) + msg;
      setBarData(Number(unRead) + msg);
    });
  },
  getLastMsg() {
    lastSysMsg().then(data => {
      let msg = data.count;
      //this.globalData.sysNumber=msg;
      this.getConversationList(msg);
    }).catch(() => {
      let msg = 0;
      this.globalData.sysNumber = 0;
      this.getConversationList(msg)
    })
  },
  watch: function (callback) {
    var obj = this.globalData;
    Object.defineProperty(obj, "allCount", {
      configurable: true,
      enumerable: true,
      set: function (value) {
        this._name = value;
        callback(value);
      },
      get: function () {
        // 可以在这里打印一些东西，然后在其他界面调用getApp().globalData.name的时候，这里就会执行。
        return this._name
      }
    })
  },
  globalData: {
    config: {
      userID: wx.getStorageSync('USER_ID'), //User ID
      SECRETKEY: myconfig.SECRETKEY, //'a5bcd8c583181cf004e9d91a47687d719d4b5d2a10ce33fbee95d587889447d8', // Your secretKey //fc45ab469ca632a700166973d87b3a6f56a855cb92d7cffb54e4d37135c097da
      SDKAPPID: myconfig.SDKAPPID, //1400796919,// Your SDKAppID  //1400798221
      EXPIRETIME: 604800,
    },
    conversationList: [], //会话列表
    imghost: "",
    host: '',
    origion: 0,
    allCount: 0, //总会话数，监听需要,
    totalUnread: 0

  }
});