import Aegis from './TUIKit/lib/aegis';
import TIM from './TUIKit/lib/tim-wx-sdk';
import TIMUploadPlugin from './TUIKit/lib/tim-upload-plugin';
import { API } from './utils/network/api'
import constant from './TUIKit/utils/constant';
const { GDXZ_CUSTOM_MSEEAGE } = constant;
const api = new API()
App({
  onLaunch: function (options) {
    // 判断是否由分享进入小程序
    if (options.scene != 1001) {
      this.globalData.share = true
    } else {
      this.globalData.share = false
    };
    this.globalData.scene = options.scene
    //获取设备顶部窗口的高度（不同设备窗口高度不一样，根据这个来设置自定义导航栏的高度）
    //这个最初我是在组件中获取，但是出现了一个问题，当第一次进入小程序时导航栏会把
    //页面内容盖住一部分,当打开调试重新进入时就没有问题，这个问题弄得我是莫名其妙
    //虽然最后解决了，但是花费了不少时间
    wx.getSystemInfo({
      success: (res) => {
        this.globalData.height = res.statusBarHeight
      }
    })
    wx.onCopyUrl(() => {
      console.log("onCopyUrlonCopyUrlonCopyUrl")
      setTimeout(()=>{ 
        wx.setClipboardData({ 
        data: '暂不支持分享', 
        success (res) { 
          
        }, 
        complete(){ 
          wx.hideToast() 
        } 
        }) 
        },1000) 
      return 
    })
    // console.log("download fonts from oss ");
    let loadStatus = false;
    if (!loadStatus) {
      // wx.loadFontFace({
      //   global: true,
      //   family: 'AlibabaPuHuiTi',
      //   // source: 'url("https://oss.igandan.com/app/fonts/AlibabaPuHuiTi/STXINGKA.TTF")',
      //   source: 'url("https://docwebsite.oss-cn-beijing.aliyuncs.com/app/fonts/AlibabaPuHuiTi/AlibabaPuHuiTi-2-65-Medium/AlibabaPuHuiTi-2-65-Medium.ttf")',
      //   success() {
      //     loadStatus = true;
      //     console.log("download fonts from oss success");
      //   },
      //   fail(){
      //     console.log("download fonts from oss error");
      //   },
      //   complete(){
      //     console.log("download fonts from oss complete");
      //   }
      // });
    }

    this.aegisInit()
    console.warn("app.js  wx.aegis: ", wx.aegis);

    //监听网络状态变化事件
    wx.onNetworkStatusChange(function (res) {
      // console.log("onNetworkStatusChange: ")
      // console.log(res.isConnected)
      // console.log(res.networkType)
      // wx.showToast({
      //   title: '网络类型'+res.networkType,
      // })
    })

    wx.onNetworkWeakChange(function(res){
      // console.log("onNetworkWeakChange: ")
      // console.log(res.isConnected)
      // console.log(res.networkType)
    })
  },
  onShow(){
    // this.imInit();
  },
  imInit(){
    console.log("imInit")
    let usertype = wx.getStorageSync('usertype');
    let userID = wx.getStorageSync('user_id_'+usertype);
    if(usertype != 2){//只登录医师端
      return;
    }
    
    if(userID == ""){
      return;
    }
    this.globalData.config.userID = userID;
    // let sign = genTestUserSig(this.globalData.config);
    // console.log("sign: ", sign);
    // const userSig = sign.userSig;

    if(!wx.$TUIKit){
      //获取im签名数据
      return api.getSignIM().then(response => {
        let from = response.from
        if(from != "cache"){
          wx.setStorageSync(userID + '_imsign', {"sign":response.data,"date":new Date().getTime()})
        }
        return response.data;
      }).then((userSig) => {
        // console.log("userSig: ", userSig);
        wx.$TUIKit = TIM.create({
          SDKAppID: this.globalData.config.SDKAPPID
        });
        
        wx.$chat_userID = this.globalData.config.userID;
        wx.$chat_SDKAppID = this.globalData.config.SDKAPPID;
        wx.$chat_userSig = userSig;

        wx.$TUIKitTIM = TIM;
        console.log("TIM: ", wx.$TUIKitTIM)
        wx.$TUIKit.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });            
        let login_promise = wx.$TUIKit.login({
            userID: this.globalData.config.userID,
            userSig
        });
  
        login_promise.then(function(imResponse) {
          // console.log(imResponse.data); // 登录成功
          
        }).catch(function(imError) {
          console.warn('login error:', imError); // 登录失败的相关信息
    
        });
    
        //wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.SDK_READY, this.onSDKReady);
        wx.$TUIKit.setLogLevel(3);//设置日志级别
        wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.SDK_READY, this.onSDKReady, this);
        wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, this.onTotalUnreadMessageCountUpdated);
      }).catch(errors => {console.error(errors);})
    }else{
      let promise = new Promise((resolve, reject) => {
        resolve("success");
      }).then(res => {
        // console.log("from app js:", res);
        return "from app js";
      });
      return promise;
    }
  },
  imLogout(){
    if(wx.$TUIKit){
      wx.$TUIKit.logout();
      wx.$TUIKit = undefined;
    }
    this.clearAllInterval();
    this.globalData.chat_sdk_ready = false;
  },
  clearAllInterval(){
    this.globalData.app_inter.forEach(item => {
      clearInterval(item)
    })
  },
  onTotalUnreadMessageCountUpdated(){
    // console.log("onTotalUnreadMessageCountUpdated");
    let totalUnreadCount = wx.$TUIKit.getTotalUnreadMessageCount();
      // console.log("未读消息数量：", totalUnreadCount)
  },
  onSDKReady(){
    console.log("onSDKReady from app.js");
    this.globalData.chat_sdk_ready = true;

    // let promise =  wx.$TUIKit.deleteConversation('C2C500318318078251008');
    // promise.then(function(imResponse) {
    //   // 删除会话成功
    //   const { conversationID } = imResponse.data; // 被删除的会话 ID
    // }).catch(function(imError) {
    //   console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
    // });

    // console.log("TIM.version: ", wx.$TUIKitTIM)
    // console.log("wx.$TUIKit: ",wx.$TUIKit.deleteConversation)
    // // 删除单一会话, 不清空会话历史消息
    // let promise = wx.$TUIKit.deleteConversation({conversationIDList:["C2C492404831991414785"], clearHistoryMessage: false});
    // promise.then(function(imResponse) {
    //   // 删除会话成功
    //   console.log("删除成功！！")
    //   const { conversationIDList } = imResponse.data; // 被删除的会话 ID 列表
    // }).catch(function(imError) {
    //   console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
    // });

    let usertype = wx.getStorageSync('usertype');
    let userID = wx.getStorageSync('user_id_'+usertype);
    //初始化tab-bar角标
    let index_info = wx.getStorageSync(userID+'_index_info');
    let my_info = wx.getStorageSync(userID+'_my_info');
    if(!index_info) wx.setStorageSync(userID+'_index_info',"");
    if(!my_info) wx.setStorageSync(userID+'_my_info', "");
    this.formatWenZhenInfo();
    wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.MESSAGE_RECEIVED, this.$onSystemPushReceived, this);
    //互踢
    console.log("互踢");
    wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.KICKED_OUT, this.onKickedOut,this);
  },
  onUnload(){
    wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.SDK_READY, this.onSDKReady);
    wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.MESSAGE_RECEIVED, this.$onSystemPushReceived);
    wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, this.onTotalUnreadMessageCountUpdated);
    wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.KICKED_OUT,this.$onKickedOut);
  },
  onKickedOut(){
    // console.log("onKickedOutonKickedOutonKickedOutonKickedOut");
    let usertype =  wx.getStorageSync('usertype');
    wx.setStorageSync('AUTH_TOKEN_'+usertype, "");
    wx.setStorageSync('user_id_'+usertype, "");
    wx.setStorageSync('client_user_id_'+usertype, "");
    if(wx.$TUIKit){
      wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.MESSAGE_RECEIVED, this.$onSystemPushReceived);
      wx.$TUIKit = undefined
    }
    this.globalData.chat_sdk_ready = false
     this.globalData.isLogin=false;
    this.go("/Pages/kickedout/index");
  },
  $onSystemPushReceived(e){
    // console.log("onSystemPushReceived from app.js");
    // console.log(e)
    let usertype = wx.getStorageSync('usertype');
    let userID = wx.getStorageSync('user_id_'+usertype);
    let message = e.data[0];
    // console.log(message)

    let type = message.type;
    // console.log(type);
    let unread_name = "";
    if(type == TIM.TYPES.MSG_CUSTOM){
      let payload = message.payload;
      let payloadData = payload.data;
      let payloadDataJson = JSON.parse(payloadData);
      let message_type = payloadDataJson.message_type;
      // console.log("message_type: ", message_type);
      switch (message_type) {
        case GDXZ_CUSTOM_MSEEAGE.TRABECULA:
          unread_name = userID+"_wenzhen_info"; //1、消息内页横条
          break;
        case GDXZ_CUSTOM_MSEEAGE.ORDER_EVALUATION:
          unread_name = userID+"_wenzhen_info"; //2、订单结束评价弹出
          break;
        case GDXZ_CUSTOM_MSEEAGE.DOCTOR_SYSTEM_NOTIFICATION:
          unread_name = userID+"_system_notice_unreadnnum"; //3、医生端系统通知
          break;
        case GDXZ_CUSTOM_MSEEAGE.DOCTOR_SERVICE_NOTIFICATION:
          unread_name = userID+"_service_notice_unreadnnum"; //4、医生端服务通知
          break;
        case GDXZ_CUSTOM_MSEEAGE.PRESCRIBE:
          unread_name = userID+"_wenzhen_info"; //6、处方开具成功
          break;
        default:
          break;
      }

    }else{
      unread_name = userID+"_wenzhen_info";//tabbar 问诊角标
    }
    this.formatUnReadNum(unread_name);
  },
  formatUnReadNum(name, increment=1){
    let val = wx.getStorageSync(name);
    if(val == "") val = 0;
    if(increment > 0){
      val = val + increment;
    }else{
      val = increment;
    }
    if(val == "+99") val = 100;
    if(val > 99) val = '+99';
    if(val == 0) val = '';
    wx.setStorageSync(name, val);
  },
  aegisInit() {
    wx.aegis = new Aegis({
      id: 'iHWefAYquFxvklBblC', // 项目key
      reportApiSpeed: false, // 接口测速
      reportAssetSpeed: false, // 静态资源测速
      pagePerformance: false, // 开启页面测速
    });
  },
  globalData: {
    share: false,  // 分享默认为false
    height: 0,
    scene: "",//场景值
    login_url: "/Pages/login/index",
    chat_sdk_ready: false,
    jiesuan_dialog_show: false,
    config: {
      userID: "",
      SDKAPPID: api.getIMappId(), // Your SDKAppID
      SECRETKEY: api.getIMsecretkey(), // Your secretKey
      EXPIRETIME: 604800,
    },
    app_inter: []
  },
  go(url, ...params){
    wx.navigateTo({
      url: url
    })
  },
  formatWenZhenInfo(){
    this.getConversationList();
  },
  onHide(){
    if(!this.globalData.isLogin){
      wx.setStorageSync('usertype','');
    }
  },
  getConversationList(){
    wx.$TUIKit.getConversationList().then((imResponse) => {
      // console.log("getConversationList from app js: ", imResponse.data.conversationList);
      return imResponse.data.conversationList;
    }).then(conversationList => {
      // console.log("开始查询订单状态")
      this.formatStatus(conversationList);
    }).catch(error => {
      console.error(error)
    });
  },
  formatStatus(conversationList){
    let order_inquiry_id_list = [];
    order_inquiry_id_list.push("");//初始化一个，防止失败
    conversationList.forEach(item => {
      let conversationID = item.conversationID;
      if(conversationID == "C2Cadministrator") return;//如果是管理员消息直接跳过
      let lastMessage = item.lastMessage;
      if(!lastMessage) return;
      let cloudCustomData = lastMessage.cloudCustomData;
      if(!cloudCustomData) return;
      let cloudCustomDataJson;
      try {
        cloudCustomDataJson = JSON.parse(cloudCustomData);
      } catch (error) {
        console.error(error);
        return;
      }
      let order_inquiry_id = cloudCustomDataJson.order_inquiry_id;
      order_inquiry_id_list.push(order_inquiry_id);//准备去请求后端那订单状态
    })
    //获取医生问诊消息用户属性
    api.getDoctorInquiryMessageAttr({order_inquiry_ids: order_inquiry_id_list.join(",")}).then(response => {
      let new_conversationList = [];
      if(response.data.length > 0){
        conversationList.forEach(item => {
          let conversationID = item.conversationID;
          if(conversationID == "C2Cadministrator") return;//如果是管理员消息直接跳过
          let lastMessage = item.lastMessage;
          if(!lastMessage) return;
          let cloudCustomData = lastMessage.cloudCustomData;
          if(!cloudCustomData) return;
          let cloudCustomDataJson;
          try {
            cloudCustomDataJson = JSON.parse(item.lastMessage.cloudCustomData);
          } catch (error) {
            return;
          }
          let order_inquiry_id = cloudCustomDataJson.order_inquiry_id;
          let order = response.data.find(attr_item => {
            return attr_item.order_inquiry_id == order_inquiry_id;
          })
          if(!order) return;

          let inquiry_status = order.inquiry_status;
          //inquiry_status 状态
          if(inquiry_status !=3 && inquiry_status != 4){
            return;
          }
          item.order_inquiry_id = order_inquiry_id;
          item.inquiry_status = inquiry_status;
          item.patient_age = order.patient_age;
          item.patient_name = order.patient_name;
          item.patient_sex = order.patient_sex;
          new_conversationList.push(item);
        })
        conversationList = []; 
      }
      return new_conversationList;
    }).then(new_conversationList => {
      // console.log("开始计算问诊角标");
      let wenzhen_info = 0;
      new_conversationList.forEach(item => {
        let unreadCount = item.unreadCount;
        if(unreadCount > 0){
          wenzhen_info = wenzhen_info + unreadCount;
        }else{//若为0，则继续判断订单状态
          let inquiry_status = item.inquiry_status;
          if(inquiry_status == 3){//若为待接诊，则+1
            wenzhen_info = wenzhen_info + 1;
          }
        }
      })
      // console.log("角标的数量：", wenzhen_info);
      let usertype = wx.getStorageSync('usertype');
      let userID = wx.getStorageSync('user_id_'+usertype);
      wx.setStorageSync(userID+'_wenzhen_info', wenzhen_info);

    }).catch(errors => {console.error(errors);})
  },
})