require("./utils/string.js")
require('./utils/push_sdk.js')
require('./libs/ald-stat.js')
import {
  updataStorageData
} from './utils/storage.js'
import {
  getWxCode,
} from './utils/wx.js'
import {
  wxLogin,
} from './services/wx.js'
import {
  saveHpUserLog
} from './services/index'
var startTime = Date.now(); //启动时间
App({
  onLaunch: function (options) {
		const systemInfo = wx.getSystemInfoSync()
		console.log('微信版本=>',systemInfo.version,'小程序版本=>',systemInfo.SDKVersion)
		console.log(options);
    // 设置城市列表
    this.setAreaList();
    this.aldstat.sendEvent('小程序的启动时长', {
      time: Date.now() - startTime
    })
    getWxCode().then(code => {
      return wxLogin({
        code: code
      })
    })
      .then(res => {
        wx.aldPushSendOpenid(res.data.openId)
      })
    const userId = wx.getStorageSync("user_id");
    const userToken = wx.getStorageSync("user_token");
    const memberId = wx.getStorageSync("member_id");
    if (userId && userToken && memberId) {
      saveHpUserLog({
        user_id: userId,
        user_token: userToken,
        member_id: memberId,
        login_type: 0
      })
    }
  },
  onShow(options) {
    //群聊信息
    if (options.shareTicket) {
      this.getShareInfo(options.shareTicket)
    }
    if (!this.captchaTicketExpire) this.captchaTicketExpire = {};

    if (options.referrerInfo.appId === 'wx5a3a7366fd07e119') {
      const result = options.referrerInfo.extraData;
      console.log(result)
      if (result.ret === 0) {
        const ticket = result.ticket;
        if (!this.captchaTicketExpire[ticket]) {
          this.captchaResult = result;
          this.captchaTicketExpire[ticket] = true;
        }
      }
    }
    // 小程序版本更新
    if (wx.getUpdateManager) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate((res) => {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(() => {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: (res) => {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  wx.removeStorageSync("user_id");
                  wx.removeStorageSync("member_id");
                  wx.removeStorageSync("user_token");
                  wx.removeStorageSync("userInfo");
                  this.globalData.userId = '';
                  this.globalData.userToken = '';
                  this.globalData.memberId = '';
                  this.globalData.userInfo = null;
                  updateManager.applyUpdate()
                }
              }
            })
          })
        }
      })
      updateManager.onUpdateFailed(function () {
        // 新版本下载失败
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，部分功能可能无法使用，请升级到最新微信版本后重试。'
      })
    }
    // wx.onAppRoute((data) => {
    //   const route = getCurrentPages();
    //   const page = route[route.length - 1];
    //   if (!page.data.hasShare) {
    //     let _str = '';
    //     for (let key in data.query) {
    //       _str += `${key}=${data.query[key]}&&`
    //     }
    //     const shareTitle = this.shareTitle[page.route]
    //     page.onShareAppMessage = function (e) {
    //       return {
    //         path: `/${page.route}?${_str}`,
    //         imageUrl: page.data.shareImageUrl || '/images/happyjob/detail_share.jpg',
    //         title: shareTitle || '开心工作'
    //       }
    //     }.bind(page)
    //   }
    // });
    const date = wx.getStorageSync('detail_time');
    const _date = new Date().getTime();
    if (_date - date < 86400000) {
      wx.setStorageSync('detail_times', 0)
    }
  },
  shareTitle: {

  },
  globalData: {
    openId: '',
    userInfo: null,
    userId: '',
    userToken: '',
    memberId: "",
    sessionKey: '',
    city: updataStorageData('city') || '无锡',
    version: '1.5.0'
  },
  //页面分享
  onShareAppMessage: function () {
    wx.showShareMenu({
      withShareTicket: true,
      success: (res) => { // 成功后要做的事情
        console.log(res)
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  //获取群聊分享信息
  getShareInfo(shareTicket) {
    wx.getShareInfo({
      shareTicket: shareTicket,
      success: (res) => {
        //需后台解析数据 encryptedData iv
        console.log(res)
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {}
    })
  },
  // 跳转登录页面
  goLogin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  setAreaList() {
    if (!wx.getStorageSync('areaList')) {
      wx.setStorageSync('areaList', [{
          "countryCode": "",
          "countryName": "不限",
          "firstNameLetter": "X"
        }, {
          "countryCode": "320205",
          "countryName": "锡山区",
          "firstNameLetter": "X"
        },
        {
          "countryCode": "320206",
          "countryName": "惠山区",
          "firstNameLetter": "H"
        },
        {
          "countryCode": "320211",
          "countryName": "滨湖区",
          "firstNameLetter": "B"
        },
        {
          "countryCode": "320213",
          "countryName": "梁溪区",
          "firstNameLetter": "L"
        },
        {
          "countryCode": "320214",
          "countryName": "新吴区",
          "firstNameLetter": "X"
        },
        {
          "countryCode": "320281",
          "countryName": "江阴市",
          "firstNameLetter": "J"
        },
        {
          "countryCode": "320282",
          "countryName": "宜兴市",
          "firstNameLetter": "Y"
        }
      ])
    }
  }
})