//app.js
import {
  loadToken,
  loadUserInfo
} from './utils/storage'

import ImApi from './apis/im'
import UserApi from './apis/user'
import AppIMDelegate from "./delegate/app-im-delegate";
import {
  fotmatDate
} from './utils/date'

var QQMapWX = require('/utils/qqmap-wx-jssdk.min.js')
var timer = null
App({
  onLaunch: function (options) {
    //检查是否存在新版本
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        updateManager.onUpdateReady(function () {
          wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: function (res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate()
              }
            }
          })
        })
        updateManager.onUpdateFailed(function () {
          // 新的版本下载失败
          wx.showModal({
            title: '已经有新版本了哟~',
            content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
          })
        })
      }
    })
    this.appIMDelegate = new AppIMDelegate(this);
    this.appIMDelegate.onLaunch(options);
    this.globalData.qqmapsdk = new QQMapWX({
      key: 'RG7BZ-G2KRV-XWPP2-U5GWL-WWQPF-RIBUW'
    });
    if (this.globalData.token) {
      wx.nextTick((callback => {
        this.getContact()
      }))
    }
  },
  /**
   * 当小程序启动，或从后台进入前台显示，会触发 onShow
   */
  onShow: function (options) {
    setTimeout(() => {
      this.appIMDelegate.onShow()
      wx.getUserInfo({
        complete: (res) => {
          console.log(res, 'userinfo')
        },
      })
      UserApi.getUserInfoById(this.globalData.userinfo.viewerId).then(res => {
        this.globalData.userinfo = res.data
      })
    }, 1000)
  },
  SetProvinceCity(province, city, district) {
    this.globalData.province = province;
    this.globalData.city = city;
    this.globalData.district = district;
    this.globalData.raw_city = false;
  },
  wxshowloading(title) {
    wx.showLoading({
      title: title,
      mask: true
    });
  },
  /**
   * 当小程序从前台进入后台，会触发 onHide
   */
  onHide: function () {
    this.appIMDelegate.onHide();
  },
  /**
   * 当小程序发生脚本错误，或者 api 调用失败时，会触发 onError 并带上错误信息
   */
  onError: function (msg) {
    console.log("onError")
  },
  ShowToast(title) {
    // Toast提示封装 app.showToast('')
    wx.showToast({
      title: title,
      icon: 'none',
      duration: 2000,
    })
  },

  ShowModel(title, content) {
    // Model 封装 app.ShowModel('')
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
    });
  },
  InterError(res) {
    this.ShowModel('网络错误', '请稍后再试~');
    wx.hideLoading()
  },
  makePhoneCall(phone) {
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  getIMHandler() {
    return this.appIMDelegate.getIMHandlerDelegate();
  },
  async getNewMessage(msg) {
    const {
      conversations
    } = this.globalData
    let item = conversations.find(item => item.id === msg.fromId)
    if (item) {
      item.latestMsgContent = msg.content
      item.latestMsgTime = msg.sendTime
      item.unReadNum ? item.unReadNum++ : item.unReadNum = 1
      this.globalData.conversations = this.dealConversations(conversations)
    } else {
      await this.getContact()
    }
  },
  getContact(isNewMsg) {
    return ImApi.getContacts().then(res => {
      const friends = res.data.friends
      const {
        conversations
      } = this.globalData
      this.globalData.unViewMsg = 0
      this.globalData.conversations = this.dealConversations(friends.map(item => {
        if (conversations) {
          const con = conversations.find(con => con.id === item.id)
          if (con) {
            item = Object.assign(con, item)
          } else if (isNewMsg) {
            item.unReadNum = 1
          }
          this.globalData.unViewMsg += item.unReadNum
        }
        return item
      }))
    })
  },
  dealConversations(conversations) {
    return conversations.map(item => {
      let content = item.latestMsgContent
      try {
        let parseContent = JSON.parse(content)
        if (parseContent.house_name) {
          content = `【云带看】${JSON.parse(content).house_name}`
        } else if (parseContent.duration) {
          content = '【语音】'
        } else if (parseContent.content) {
          content = '【图片】'
        }

      } catch (err) {}
      item.latestMsgContent = content
      const now = new Date()
      if (item.latestMsgTime && now.getMonth() === new Date(item.latestMsgTime).getMonth() && now.getDate() === new Date(item.latestMsgTime).getDate()) {
        item.timeStr = fotmatDate(item.latestMsgTime, 'hh:mm')
      } else if (item.latestMsgTime) {
        item.timeStr = fotmatDate(item.latestMsgTime, 'MM/dd')
      } else {
        item.timeStr = ''
      }

      return item
    }).sort((a, b) => new Date(b.latestMsgTime) - new Date(a.latestMsgTime))
  },
  globalData: {
    token: loadToken(),
    raw_city: true,
    city: '珠海', // 默认进入首页的地址
    province: '广东省',
    district: '',
    userinfo: loadUserInfo() || {},
    io: '',
    messageList: [],
    unViewMsg: 0,
    conversations: []
  }
});