//app.js
import {
  initSocket
} from './utils/socket-handle'
import {
  loadToken, loadUserInfo
} from './utils/storage'
import ImApi from './apis/im'
import eventEmitter from './utils/eventEmitter'
import AppIMDelegate from "./delegate/app-im-delegate";
import { fotmatDate } from './utils/date'
import { autoSubcrebe } from './utils/utils'

var QQMapWX = require('/utils/qqmap-wx-jssdk.min.js')
var timer = null
App({
  onLaunch: function (options) {
    //检查是否存在新版本
    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()
    }, 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(true)
    }
},
  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 => {
        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 (now.getMonth() === new Date(item.latestMsgTime).getMonth() && now.getDate() === new Date(item.latestMsgTime).getDate()) {
        item.timeStr = fotmatDate(item.latestMsgTime, 'hh:mm')
      } else {
        item.timeStr = fotmatDate(item.latestMsgTime, 'MM/dd')
      }
      return item
    }).sort((a, b) => new Date(b.latestMsgTime) - new Date(a.latestMsgTime))
  },
  autoSubcrebe () {
    return autoSubcrebe()
  },
  globalData: {
    token: loadToken() ,
    raw_city: true,
    city: '', // 默认进入首页的地址
    province: '广东省',
    district: '',
    userinfo: loadUserInfo() || {} ,
    io: '',
    messageList: [],
    conversations: [],
    unViewMsg: 0
  }
});