import '@tarojs/async-await'
import Taro, { Component } from '@tarojs/taro'
import './app.scss'
import "@/styles/icon.scss";
import "@/components/wxParse/wxParse.scss";
import Index from './pages/auth/index'
import { Provider } from '@tarojs/redux'
import { parseQueryString } from '@/utils/tools'
import { trackUserSource } from '@/utils/track'
import { getCardDetail } from '@/services/card'

import {
  getCodeScene,
  savePoint,
  queryCityList,
  getPreloadData,
} from '@/services/common'

import {
  queryUserInfo
} from '@/services/user'

import {
  CITY_LIST
} from '@/constants/city'
import {
  ASSIGN_UNREADNUM,
  INCREASE_UNREADNUM
} from '@/constants/user'
import { UPDATE_PRELOAD, SYNC_SYSTEMINFO } from '@/constants/common'
import ready from '@/utils/ready'
import login from '@/utils/login'
import store from './store'
import socket from '@/utils/im'

// const store = configStore()

// for dev
global.store = store

class App extends Component {
  config = {
    debug: process.env.NODE_ENV === 'development',
    permission: {
      "scope.userLocation": {
        "desc": "你的位置信息将用于显示当前区域信息"
      }
    },
    navigateToMiniProgramAppIdList: [
      "wxb825ab501296672e",
      "wxca1e7ba3fe18ff12",
      "wx74767bf0b684f7d3",
      "wx6fa58869f7b65e7f",
      "wxc4f812079fc9ff0d",
      "wx60d176f873ca2d67",
    ],
    // eslint-disable-next-line no-undef
    pages: preval`
      const {getPages} = require('./src/routes.js')
      module.exports = getPages().pages
    `,
    // eslint-disable-next-line no-undef
    subPackages: preval`
      const {getPages} = require('./src/routes.js')
      module.exports = getPages().subPackages
    `,
    window: {
      backgroundTextStyle: 'light',
      // navigationBarBackgroundColor: '#E31F05',
      navigationBarBackgroundColor: '#BB9C79',
      navigationBarTitleText: '',
      navigationBarTextStyle: 'white',

    },
    tabBar: {
      color: '#666',
      selectedColor: '#E6380C',
      // selectedColor: '#BB9C79',

      list: [
        {
          pagePath: "pages/project/index",
          text: "首页",
          iconPath: './assets/tabbar/index1.png',
          selectedIconPath: './assets/tabbar/index2.png',
        },
        {
          pagePath: "pages/shop/index",
          text: "赚好礼",
          iconPath: './assets/tabbar/shop1.png',
          selectedIconPath: './assets/tabbar/shop2.png',
        },
        {
          pagePath: "pages/activity/activity",
          text: "活动资讯",
          iconPath: './assets/tabbar/activity1.png',
          selectedIconPath: './assets/tabbar/activity2.png',
        },
        {
          pagePath: "pages/person/index",
          text: "我的地盘",
          iconPath: './assets/tabbar/mine1.png',
          selectedIconPath: './assets/tabbar/mine2.png',
        }
      ]
    },
  }

  // 更新埋点时长
  updateTrack;

  componentDidHide() {
    if (this.updateTrack) {
      this.updateTrack()
      this.updateTrack = undefined
    }

    // ready.close()
    socket.closeSocket()
  }

  componentDidShow() {

    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.info('新版本是否更新:', res.hasUpdate)
    })

    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })

    socket.reconnect()

    this.initData()
  }

  componentDidMount() {
    // console.info('app componentDidMount')
  }

  componentWillMount() {
    // 预加载数据
    this.wxPreloadData()

    // 获取系统信息
    wx.getSystemInfo({
      success: (res) => {
        store.dispatch({
          type: SYNC_SYSTEMINFO,
          payload: res,
        })
      }
    })

    // console.info('app componentWillMount', params)
    // this.initData()
  }

  componentWillUnmount() {
    if (this.updateTrack) {
      this.updateTrack()
      this.updateTrack = undefined
    }
    // this.initData()
  }

  wxPreloadData() {
    // getPreloadData({
    //   appid: wx.getAccountInfoSync().miniProgram.appId,
    //   timestamp: (new Date).valueOf(),
    // }).then((res) => {
    //   console.log('[preload]: ', res)
    //   store.dispatch({
    //     type: UPDATE_PRELOAD,
    //     payload: res,
    //   })
    // })
    // wx.setBackgroundFetchToken()
    wx.getBackgroundFetchData({
      fetchType: 'pre',
      success: (res) => {
        console.log('[preload]: ', res)
        // store.dispatch({
        //   type: UPDATE_PRELOAD,
        //   payload: res.fetchedData,
        // })
      }
    })
  }

  _mounted = false

  initData() {
    console.info('router1', this.$router)
    console.info('ready status1', ready)
    const enterOptions = wx.getEnterOptionsSync()
    console.log(enterOptions, "enterOptionsenterOptionsenterOptionsenterOptionsenterOptions")

    if (Object.keys(enterOptions.query).indexOf('recommender') > -1) {
      Taro.setStorageSync('recommender', enterOptions.query.recommender)
      Taro.setStorageSync('consultantId', enterOptions.query.consultant)
    }
    // 获取城市列表
    // queryCityList().then(payload => {
    //   store.dispatch({ type: CITY_LIST, payload })
    // })

    this.getLocation().then((loc) => {
      // 获取router参数
      this.getRouterParams().then(router => {
        Taro.setStorageSync('router', router)
        console.info('router2:', JSON.stringify(router))
        console.info('-----------')
        const { query: payload } = router

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

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

        // login
        login(payload, res => {
          // 清空本地缓存
          if (!this._mounted) {

            Taro.removeStorageSync('activityPageIndex')
            Taro.removeStorageSync('newsPageIndex')
            Taro.removeStorageSync('buildingPageIndex')
            Taro.removeStorageSync('followPageIndex')
            Taro.removeStorageSync('clinchPageIndex')
            // Taro.removeStorageSync('extendContent')
            Taro.setStorageSync('extendContent', [])
            // Taro.setStorageSync('recommender', payload.recommender)
            // Taro.setStorageSync('consultantId', payload.consultant)
            // 获取分享人
            this._mounted = true
          }
          console.log(payload, "payloadpayloadpayloadpayloadpayloadpayloadpayload啦啦啦啦啦")



          // 获取未读消息
          const { person: { personId } } = res

          queryUserInfo(personId).then(info => {
            const { unReadNum } = info
            store.dispatch({ type: ASSIGN_UNREADNUM, payload: { unReadNum } });
            socket.createSocket({ id: personId });
            socket.onMessage(data => {
              store.dispatch({ type: INCREASE_UNREADNUM })
            })
          })
          // 埋点
          // const t = setTimeout(() => {
          trackUserSource(this.$router.params).then(res => this.updateTrack = res)

          // }, 1000)
        })
      })
    })
  }


  getRouterParams() {
    return new Promise(resolve => {
      console.log('------getRouterParams------>', this.$router)
      const router = this.$router.params
      const originQuery = { ...router.query };
      let { query: { scene: paramsId, consultant }, scene } = router

      // query 里面如果跟同级场景一样, 说明是小程序原生场景值
      if (paramsId === scene) {
        paramsId = undefined
      }

      if (paramsId) {
        // 扫码进入
        getCodeScene(paramsId).then(res => {
          let params = JSON.parse(res).scene
          console.log(params, "paramsparamsparamsparamsparamsparamsparamsparamsparamsparams")

          let { from: _from, recommender: _recommender, consultant, id, ...left } = parseQueryString(params) || {}

          router.query = Object.assign(router.query, {
            originQuery,
            id,
            paramsId,
            from: _from,
            recommender: _recommender,
            consultant,
            params,
            targetId: id,
            ...left,
          })
          Taro.setStorageSync('recommender', router.query.recommender)
          Taro.setStorageSync('consultantId', router.query.consultant)
          resolve(router)
        })
      } else {

        router.query = Object.assign(router.query, {
          originQuery,
          paramsId: router.query.id || '',
          from: router.query.from || 'search',
          recommender: router.query.recommender || '',
          targetId: router.query.id || '',
          consultant: router.query.consultant || '',
        })

        resolve(router)
      }

    })
  }

  getLocation() {
    return new Promise((resolve) => {
      Taro.getLocation().then(location => {
        Taro.setStorageSync('lat', location.latitude)
        Taro.setStorageSync('lon', location.longitude)

        resolve({ lon: location.longitude, lat: location.latitude })
      }).catch(err => {
        if (err.errMsg === 'getLocation:fail auth deny') {
          Taro.showModal({
            content: '请同意授权您的定位功能',
            showCancel: false,
            duration: 3000,
          })
        } else {
          Taro.showToast({
            title: `定位失败, 请手动选择城市: ${err.errMsg}`,
            icon: 'none',
            duration: 3000,
          })
        }

        console.error(err)
        resolve()
      })
    })
  }

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

Taro.render(<App />, document.getElementById('app'))