import { Component } from 'react'
import { Provider } from 'react-redux'
import Taro from '@tarojs/taro'
import { getLocation, getRouterParams } from '@/utils/tools'
import login from '@/utils/login'
import im from '@/utils/im'
import store from './store'
import trackUserSource from '@/utils/tracking/userSource'

import './app.scss'

class App extends Component {
  // 是否登录
  logged = false;

  // 更新埋点
  updateTracking = () => undefined;

  componentDidMount () {}

  componentDidShow (options) {
    // 保留初始场景
    Taro.setStorage({ key: 'scene', data: options.scene })
    // 埋点
    if (this.logged) {
      trackUserSource(options).then((res) => (this.updateTracking = res))
    }
  }

  componentDidHide () {
    this.updateTracking()
  }

  componentDidCatchError () {}

  loadFontFace() {
    Taro.loadFontFace({
      global: true,
      family: 'iconfont',
      // eslint-disable-next-line no-undef
      source: `url("${ICON_FONT}")`,
      success() {},
      fail: function(res) {
        console.error('加载远程字体失败:', res)
      }
    });
  }
  
  onLaunch (options) {

    console.log('【onLaunch】:', JSON.stringify(options))
    const { mode } = options
    Taro.setStorageSync('mode', mode)

    // 加载远程字体
    this.loadFontFace()

    // 当前设备相关
    Taro.getSystemInfo({
      success: (data) => {
        Taro.setStorage({ key: 'systemInfo', data })
      }
    })

    getLocation().then((loc) => {
      getRouterParams(options).then(router => {
        Taro.setStorageSync('router', router)

        const { query: payload } = router

        payload.path = router.path
        payload.scene = router.scene

        if (loc) {
          payload.lon = loc.lon
          payload.lat = loc.lat
        }

        const { path, scene, ...params } = payload

        if (mode === 'singlePage') {
          // 分享朋友圈的单页模式
          params.singleMode = true

          // login
          login(params).then(() => {
            this.logged = true
          })
        } else {
          // 非单页模式
          Taro.login({
            success: ({ code }) => {
              params.code = code

              // login
              login(params).then((res) => {
                const { person: { personId } } = res
                
                // 初始化 im
                im.init(personId)

                this.logged = true

                // 埋点
                trackUserSource(options).then((x) => (this.updateTracking = x))
              })
            }
          })
        }
      })
    })
  }

  // 在 App 类中的 render() 函数没有实际作用
  // 请勿修改此函数
  render () {
    return (
      <Provider store={store}>
        {this.props.children}
      </Provider>
    )
  }
}

export default App
