import Taro from '@tarojs/taro';
import { getStore } from '@tarojs/redux'
import { USER_INFO } from '@/constants/user'
import { wxLogin } from '@/services/login'
import { sceneInShare } from '@/utils/tools'
import ready from '@/utils/ready'
import { dispatchCitySelected } from '@/actions/city'

let loading = false
export default function (payload, callback) {
  const { path, scene, ...params } = payload

  if (loading) {
    return
  }
  loading = true
  ready.close()
  Taro.login({
    success: ({ code }) => {
      Taro.showLoading()
      params.code = code
      wxLogin(params).then(data => {
        Taro.hideLoading()

        loading = false

        const { extraInfo, miniApp, person, miniAuthorized, avatarAuth, city } = data
        const { token, sessionKey } = miniApp
        const { dispatch, getState } = getStore()

        Taro.setStorageSync('token', token)
        Taro.setStorageSync('sessionKey', sessionKey)

        dispatch({ type: USER_INFO, payload: { extraInfo, person, miniApp } })
        const { city: { curCity } } = getState()

        console.log(curCity, "curCity")

        if (!curCity || Object.keys(curCity).length == 0) {
          if (city) {
            dispatchCitySelected(city)(dispatch)
          }
        }

        // // 用户信息已授权获取成功
        // if (miniAuthorized || avatarAuth) {

        //   // 保存用户信息
        //   // dispatch({ type: USER_INFO, payload: { extraInfo, person, miniApp } })
        callback && callback(data)

        // } else {

        //   // 非扫码进入项目详情或者卡片主页, 跳转到授权头像
        //   // 否则不跳
        //   const noAuthPages = [
        //     'pages/project/detail/index',
        //     'pages/card/index',
        //   ]

        //   if (noAuthPages.indexOf(path) === -1 || !sceneInShare(scene)) {
        //     Taro.reLaunch({
        //       url: '/pages/auth/index'
        //     })
        //   }
        // }

        ready.open()

        console.info('ready status2', ready)
      })
    }
  })
}
