import Taro from '@tarojs/taro';
import { getStore } from '@tarojs/redux'
import { USER_INFO } from '@constants/user'
import { wxLogin } from '@services/login'
import ready from '@utils/ready'
let loading = false
export default function (params, callback) {
  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 } = data
        const { token, sessionKey } = miniApp
        const { dispatch } = getStore()
        Taro.setStorageSync('token', token)
        Taro.setStorageSync('sessionKey', sessionKey)

        dispatch({ type: USER_INFO, payload: { extraInfo, person, miniApp } })

        // 用户信息已授权获取成功
        if (miniAuthorized) {
          // 保存用户信息
          // dispatch({ type: USER_INFO, payload: { extraInfo, person, miniApp } })
          callback && callback(data)

        } else {
          Taro.reLaunch({
            url: '/pages/auth/index'
          })
        }
        ready.open()

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