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 { getQueryString } from '@utils/tools'

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

import {
  queryUserInfo
} from '@services/user'

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

const store = configStore()

class App extends Component {
  config = {
    debug: false,
    permission: {
      "scope.userLocation": {
        "desc": "你的位置信息将用于显示当前区域信息"
      }
    },
    pages: [
      'pages/project/index',
      'pages/person/customerAnalysis/followUpCustomer/index',
      'pages/person/customerAnalysis/transactionCustomer/index',
      'pages/person/customerAnalysis/myCustomer',
      'pages/shop/index',
      'pages/activity/activity',
      'pages/activity/myActivity',
      'pages/person/index',
      'pages/person/customerAnalysis/index',
      'pages/person/profile/index',
      'pages/person/profile/detail/index',
      'pages/project/detail/index',
      'pages/activity/assemblePage',
      'pages/activity/assistancePage',
      'pages/person/spread/index',
      'pages/card/index',
      'pages/agent/become/index',
      'pages/im/list/index',
      'pages/agent/invitation/index',
      'pages/agent/client/index',
      'pages/person/myGuest/index',
      'pages/person/personDetail/index',
      'pages/person/personDetail/editDetail/index',
      'pages/person/login/index',
      'pages/person/myGuest/editGuest/index',
      'pages/shop/rule/index',
      'pages/person/authorize/index',
      'pages/project/map/index',
      'pages/agent/index',
      'pages/shop/integralDetail/index',
      'pages/auth/index',
      'pages/card/list/index',
      'pages/agent/recommend/index',
      // 'pages/activity/index',
      'pages/report/index',
      'pages/project/list/index',
      'pages/report/login/index',
      'pages/project/floor/index',
      'pages/im/index',
      'pages/activity/detail/index',
      'pages/activity/detail/assistance',
      'pages/activity/detail/assemble',
      'pages/news/detail/index',
      'pages/shop/record/index',
      'pages/card/register/index',
      'pages/report/detail/index',
      'pages/policy/index',
      'pages/policy/detail/index',
      'pages/toolKit/index',
      'pages/toolKit/calculateResult/index',
      'pages/project/album/index',
      // 'pages/news/index',
      'pages/person/favorite/index',
      'pages/city/index',
      'pages/agent/progress/index',
      'pages/shop/detail/index',
      'pages/signin/index',
      'pages/card/fans/index',
      'pages/person/feedback/index',

      'pages/checkin/index',
      'pages/checkin/checkinsuccess/index',
      // 'pages/checkin/unregistered/index',

    ],
    window: {
      backgroundTextStyle: 'light',
      navigationBarBackgroundColor: '#BB9C79',
      navigationBarTitleText: '橙蕉',
      navigationBarTextStyle: 'white',

    },
    tabBar: {
      color: '#666',
      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',
        }
      ]
    },
  }
  componentDidHide() {
    ready.close()
    // socket.closeSocket()
  }

  componentDidShow() {
    console.info('app componentDidShow')
    console.info('router1', this.$router.params)
    console.info('ready status1', ready)

    // 获取城市列表
    queryCityList().then(payload => {
      store.dispatch({ type: CITY_LIST, payload })

      // 获取router参数
      this.getRouterParams().then(router => {
        Taro.setStorageSync('router', router)
        console.info('router2:', router)
        console.info('-----------')
        const { query: payload } = router
        // login
        login(payload, res => {
          // 获取未读消息
          const { person: { personId } } = res
          queryUserInfo(personId).then(info => {
            const { unReadNum } = info
            store.dispatch({ type: ASSIGN_UNREADNUM, payload: { unReadNum } });
            socket.createSocket({ id: personId });
            socket.wss.onMessage(data => {
              store.dispatch({ type: INCREASE_UNREADNUM })
            })
          })

          const data = Object.assign({}, payload, {
            event: 'start',
            propertyName: '进入小程序',
            data: ''
          })
          savePoint(data)
        })
      })
    })

    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()
          }
        }
      })
    })
  }
  componentDidMount() {
    console.info('app componentDidMount')
  }
  componentWillMount() {
    console.info('app componentWillMount')
  }

  getRouterParams() {
    return new Promise(resolve => {
      const router = this.$router.params
      let { query: { scene: paramsId } } = router

      if (paramsId) {
        // 扫码进入
        getCodeScene(paramsId).then(res => {
          let params = JSON.parse(res).scene
          let _from = getQueryString(params, 'from')
          let _recommender = getQueryString(params, 'recommender')
          let id = getQueryString(params, 'id')
          let agentCode = getQueryString(params, 'agentCode')
          router.query = Object.assign(router.query, {
            id,
            paramsId,
            from: _from,
            recommender: _recommender,
            params,
            targetId: id,
            agentCode
          })

          resolve(router)
        })
      } else {
        router.query = Object.assign(router.query, {
          paramsId: router.query.id ? router.query.id : '',
          from: 'search',
          recommender: router.query.recommender ? router.query.recommender : ''
        })

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

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