// app.js
import {
  CbEvents
} from 'open-im-sdk'
import openIM from "./utils/openim";
import HTTP from "./requestFn/Api"
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    // 隐藏系统tabbar
    wx.hideTabBar();
    // 获取设备信息
    this.getSystemInfo();
    this.getWxCode();
  },
  onShow: function () {
    const openim_id = wx.getStorageSync('openim_id');
    const openIMToken = wx.getStorageSync('openIMToken');
    if (openim_id) {
      this.globalData.openim_id = openim_id;
      this.globalData.openIMToken = openIMToken;
      openIM.getLoginStatus().then(res => {
        console.log("连接成功", res);
      }).catch(err => {
        console.log("连接失败", err);
        this.login();
      })
    }
  },
  onHide() {
    openIM.logout()
  },
  getSystemInfo: function () {
    let menuButtonObject = wx.getMenuButtonBoundingClientRect();
    let t = this;
    wx.getSystemInfo({
      success: function (res) {
        t.globalData.systemInfo = res;
        let statusBarHeight = res.statusBarHeight,
          navTop = menuButtonObject.top,
          navHeight = statusBarHeight + menuButtonObject.height - (menuButtonObject.top - statusBarHeight) * 2;
        t.globalData.navHeight = navHeight;
        t.globalData.navTop = navTop; //navTop
        t.globalData.windowHeight = res.windowHeight;
      }
    });
  },
  onPullDownRefresh: function () {
    this.onRefresh();
  },

  editTabbar: function () {
    let tabbar = this.globalData.tabBar;
    let currentPages = getCurrentPages();
    let _this = currentPages[currentPages.length - 1];
    let pagePath = _this.route;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (let i in tabbar.list) {
      tabbar.list[i].selected = false;
      (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    }
    _this.setData({
      tabbar: tabbar
    });
  },
  login() {
    const that = this;
    const {
      openim_id: userID,
      openIMToken: token
    } = that.globalData;
    const config = {
      userID,
      token,
      url: "wss://www.wxmini.getensh.com:60001",
      platformID: 5,
    };
    openIM.login(config).then(() => {
      openIM.getAllConversationList().then(res => {
        const str = JSON.parse(res.data);
        let openim_ids = "";
        const Session_list = str.map(item => {
          openim_ids = openim_ids+`${item.userID},`
          return {
            ...item,
            left: 0,
            latestMsg: JSON.parse(item.latestMsg)
          }
        })
        HTTP.OpenimUsers({openim_ids}).then(({list})=>{
          let result = [];
          list.map(item=>{
            Session_list.map(key=>{
              if(item.openim_id===key.userID){
                result.push({...key,faceURL:item.face_url})
              }
            })
          })
          console.log(result);
          that.globalData.Session_list = result;
        }).catch(err=>{
          that.globalData.Session_list = Session_list;
        })
      })
      openIM.getTotalUnreadMsgCount().then(res => {
        that.globalData.unreadCountHome = res.data;
        that.globalData.unreadCountNeig = res.data;
        that.globalData.unreadCountGate = res.data;
        that.globalData.unreadCountMes = res.data;
        that.globalData.unreadCountMine = res.data;
      });
      openIM.on(CbEvents.ONCONVERSATIONCHANGED, (res) => {
        const str = JSON.parse(res.data);
        const {
          Session_list
        } = that.globalData;
        let index = Session_list.findIndex((val) => val.conversationID === str[0].conversationID)
        let item = str[0];
        if (index > -1) {
          const {faceURL} = Session_list[index];
          Session_list.splice(index, 1);
          Session_list.unshift({
            ...item,
            latestMsg: JSON.parse(item.latestMsg),
            left: 0,
            faceURL
          })
        } 
        that.globalData.Session_list = Session_list
      })
      openIM.on(CbEvents.ONNEWCONVERSATION, (res) => {
        const str = JSON.parse(res.data);
        const newChat = str.map(item => {
          return {
            ...item,
            left: 0,
            latestMsg: JSON.parse(item.latestMsg)
          }
        })
        const {
          Session_list
        } = that.globalData;
        newChat.forEach((item) => {
          let index = Session_list.findIndex(e =>
            e.conversationID == item.conversationID
          )
          if (index > -1) {
            Session_list[index] = {
              ...item,
            }
          } else {
            Session_list.unshift({
              ...item
            })
          }
        })
        that.globalData.Session_list = Session_list
      })
      openIM.on(CbEvents.ONTOTALUNREADMESSAGECOUNTCHANGED, (res) => {
        that.globalData.unreadCountHome = res.data;
        that.globalData.unreadCountNeig = res.data;
        that.globalData.unreadCountGate = res.data;
        that.globalData.unreadCountMes = res.data;
        that.globalData.unreadCountMine = res.data;
      })
    })
  },
  loginout() {
    openIM.logout().then(res => {
      this.globalData.userID = "";
      this.globalData.Session_list = [];
      this.globalData.unreadCountHome = 0;
      this.globalData.unreadCountNeig = 0;
      this.globalData.unreadCountGate = 0;
      this.globalData.unreadCountMes = 0;
      this.globalData.unreadCountMine = 0;
    })
  },
  sendMessage(val, _this) {
    openIM.createTextMessage(val).then(({
      data
    }) => {
      this.crateMessage(data, _this, 'text')
    })
  },
  sendCard(cardDesc, _this, res) {
    openIM.createCardMessage(cardDesc).then(({
      data
    }) => {
      this.crateMessage(data, _this, 'card', res)
    })
  },
  crateMessage(data, _this, type, res) {
    let recvID;
    let showname;
    if (res) {
      const {
        manager_list,
      } = _this.data;
      recvID = manager_list[res.tapIndex].openim_id;
      showname = manager_list[res.tapIndex].name;
      this.globalData.userID = recvID;
    } else {
      recvID = this.globalData.userID;
    }
    const options = {
      recvID,
      groupID: "",
      message: data,
    };
    openIM.sendMessage(options).then(({
      data,
    }) => {
      if (type == "text") {
        this.handleSendMsg(data, _this)
      } else {
        const userIDList = [recvID]
        openIM.getUsersInfo(userIDList).then(({
          data
        }) => {
          let res = JSON.parse(data);
          const {
            faceURL: faceurl
          } = res[0].publicInfo;
          this.goChat(recvID, showname, faceurl);
        })
      }
    })
  },
  goChat(userID, showname, faceurl) {
    wx.navigateTo({
      url: `/page/message/pages/Chat/chat?userID=${userID}&showname=${showname}&faceurl=${faceurl}`,
    })
  },
  handleSendMsg(data, _this) {
    const that = _this;
    const {
      msgList
    } = that.data;
    let newMessage = JSON.parse(data);
    if (msgList.length > 0) {
      let {
        sendTime
      } = msgList[msgList.length - 1];
      let minutes = (newMessage.sendTime - sendTime) / 1000 / 60;
      if (minutes > 5) {
        newMessage = {
          ...newMessage,
          showTime: true
        };
      } else {
        newMessage = {
          ...newMessage,
          showTime: false
        };
      }
    } else {
      newMessage = {
        ...newMessage,
        showTime: true
      };
    }
    if (newMessage.contentType == 102) {
      newMessage = {
        ...newMessage,
        content: JSON.parse(newMessage.content)
      };
    }
    that.setData({
      msgList: [...msgList, newMessage],
      inputVal: "",
      lineCount: 1,
      textareaHeight: 8,
      toView: "msg-" + msgList.length,
    })
  },
  getMessage(flag, _this) {
    const that = _this;
    const {
      userID,
    } = this.globalData;
    const {
      msgList
    } = that.data;
    const options = {
      groupID: "",
      startClientMsgID: flag ? msgList[0].clientMsgID : '', // 上一次拉取的最后一条消息ID或空字符串,为空字符则从最新一条开始
      count: 12,
      userID,
    }
    openIM.getHistoryMessageList(options).then(({
      data
    }) => {
      let result = JSON.parse(data);
      const newMessageList = [];
      if (result.length > 0) {
        result.forEach((item, index) => {
          if ([102, 108].includes(item.contentType)) {
            item.content = JSON.parse(item.content)
          }
          if (index == 0) {
            newMessageList.push({
              ...item,
              showTime: true,
            })
          } else {
            const current = result[index].sendTime;
            let minutes;
            const lastShowTime = result[index - 1].sendTime;
            minutes = (current - lastShowTime) / 1000 / 60;
            if (minutes > 5) {
              newMessageList.push({
                ...item,
                showTime: true,
              })
            } else {
              newMessageList.push({
                ...item,
                showTime: false,
              })
            }
          }
        })
        if (flag) {
          that.setData({
            msgList: [...newMessageList, ...msgList, ],
            inputVal: ''
          })
          that.setData({
            toView: 'msg-' + [newMessageList.length - 2],
          })
        } else {
          that.setData({
            msgList: newMessageList,
            toView: 'msg-' + [newMessageList.length - 1],
          })
        }
      }
      console.log(newMessageList);
      that.setData({
        refer: false
      })
    }).catch(err => {
      console.log("获取会话列表失败", err);
    })
  },
  createImage(url, _this) {
    const that = _this;
    const {
      userID: recvID,
    } = this.globalData;
    const baseInfo = {
      uuid: "", //图片唯一id
      type: "png", //图片类型
      size: 12465, //图片大小
      width: 1080, //图片宽度
      height: 720, //图片高度
      url
    }
    const data = {
      sourcePicture: baseInfo, //原图信息
      bigPicture: baseInfo, //大图信息
      snapshotPicture: baseInfo, //缩略图信息
    }
    openIM.createImageMessage(data).then(res => {
      const options = {
        recvID,
        groupID: "",
        message: res.data,
      };
      openIM.sendMessageNotOss(options).then(({
        data,
      }) => {
        this.handleSendMsg(data, that)
      }).catch(err => {})
    })
  },
  deleteChat(conversationID, index, _this) {
    const that = _this;
    const app = this;
    openIM.deleteConversation(conversationID).then(res => {
      const {
        Session_list
      } = that.data;
      Session_list.splice(index, 1);
      that.setData({
        Session_list
      })
      app.globalData.Session_list = Session_list;
    })
  },
  //获取code
  getWxCode() {
    const that = this;
    wx.login({
      success(res) {
        that.globalData.code = res.code;
      }
    })
  },
  onRefresh: function () {
    //导航条加载动画
    wx.showNavigationBarLoading()
    //loading 提示框
    wx.showLoading({
      title: 'Loading...',
    })
    setTimeout(function () {
      wx.hideLoading();
      wx.hideNavigationBarLoading();
      //停止下拉刷新
      wx.stopPullDownRefresh();
    }, 1000)
  },
  watch: function (variate, method) {
    var obj = this.globalData;
    let val = obj[variate]; // 单独变量来存储原来的值
    Object.defineProperty(obj, variate, {
      configurable: false,
      enumerable: true,
      set: function (value) {
        val = value; // 重新赋值
        method(variate, value); // 执行回调方法
      },
      get: function () {
        return val; // 返回当前值
      }
    })
  },
  onMessage(_this) {
    const that = _this;
    openIM.on(CbEvents.ONRECVNEWMESSAGE, (res) => {
      const {
        msgList
      } = that.data;
      let data = JSON.parse(res.data);
      const {
        userID
      } = this.globalData;
      if (userID == data.sendID & data.status == 2) {
        let current = data.sendTime;
        let minutes;
        let lastShowTime = msgList[msgList.length - 1].sendTime;
        minutes = (current - lastShowTime) / 1000 / 60;
        if (minutes > 5) {
          data = {
            ...data,
            showTime: true
          }
        } else {
          data = {
            ...data,
            showTime: false
          }
        }
        if (data.contentType == 102) {
          data = {
            ...data,
            content: JSON.parse(data.content)
          }
        }
        that.setData({
          msgList: [...msgList, data],
        });
        that.setData({
          toView: "msg-" + msgList.length
        })
        if (userID) {
          this.readMessage()
        }
      }
    })
  },
  readMessage() {
    const {
      userID,
    } = this.globalData;
    const options = {
      userID,
      msgIDList: []
    }
    openIM.markC2CMessageAsRead(options)
  },
  globalData: {
    userID: "",
    baseURL: "https://www.wxmini.getensh.com/api/v1",
    code: "",
    can_pay: false,
    house_id: null,
    house_name: null,
    garden_id: null,
    garden_name: null,
    house_list: [],
    tabBar: {
      "backgroundColor": "#ffffff",
      "color": "#707070",
      "selectedColor": "#216d2a",
      "list": [{
          "pagePath": "/page/tabBar/home/index",
          "iconPath": "icon/home.png",
          "selectedIconPath": "icon/home-select.png",
          "text": "首页"
        },
        {
          "pagePath": "/page/tabBar/neighbor/index",
          "iconPath": "icon/book.png",
          "selectedIconPath": "icon/book-select.png",
          "text": "邻里"
        },
        {
          "pagePath": "/page/tabBar/gate/index",
          "iconPath": "icon/phone.png",
          "isSpecial": true,
          "text": ""
        },
        {
          "pagePath": "/page/tabBar/message/index",
          "iconPath": "icon/message.png",
          "selectedIconPath": "icon/message-select.png",
          "text": "消息"
        },
        {
          "pagePath": "/page/tabBar/mine/index",
          "iconPath": "icon/my.png",
          "selectedIconPath": "icon/my-select.png",
          "text": "我的"
        },

      ]
    },
    navHeight: 0,
    navTop: 0,
    authentication: false,
    city_name: "",
    city_code: "",
    longitude: 0,
    latitude: 0,
    client_id: "QufW7Lmgn84ZMiYQybH5MYYq",
    client_secret: "yprUS1IDQGsH4saSrx3j4YKQLsacgoFn",
    Session_list: [],
    unreadCountHome: 0,
    unreadCountNeig: 0,
    unreadCountGate: 0,
    unreadCountMes: 0,
    unreadCountMine: 0,
  },
})