import HttpClient from '@/module/request/http-client.js'
import Toast from '@/module/toast/toast.js'

const httpClient = new HttpClient()
const googleApi = {
	auth: 'https://accounts.google.com/o/oauth2/v2/auth',
	getUserInfo: 'https://www.googleapis.com/oauth2/v2/userinfo'
}

const clientId = '402236096416-lqmokpmsrkm1var22hqrkdba555v4gdm.apps.googleusercontent.com'
const responseType = 'token'
const scope = 'email profile'

export const googleAuthLogin = (options) => {
	// #ifdef H5
	const redirectUri = window.location.href.split('?')[0]
	const url = `${googleApi.auth}?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scope}&response_type=${responseType}&state=${generateNonce()}`
	window.location.href = url
	// #endif
}

export const getGoogleUserInfo = (options) => {
	return new Promise(resolve => {
		if (!options) {
			resolve({ code: 999 })
			return
		}
		httpClient.request({
			url: googleApi.getUserInfo,
			method: 'GET',
			header: {
				Authorization: `Bearer ${options.accessToken}`
			},
			dataType: 'json'
		}).then(res => {
			if (res.statusCode === 200 && res.data) {
				resolve({ code: 200, data: res.data })
			} else {
				resolve({ code: 999 })
				if (res.errMsg) {
					Toast.show(res.errMsg)
				}
			}
		}).catch(err => {
			resolve({ code: 999 })
			if (err) {
				Toast.show(JSON.stringify(err))
			}
		})
	})
}

// #state=qjenqanjbh7pgm8qama99&access_token=ya29.a0AXooCgvYMTTEyFvqhLwsGgyCgl8uybY6OafURm3hL4lUYnL2W_y_PoItN-COVUv-yZ9a1qgLxgxnpvOHnQOp6O3nDfi3S-6AAiwtfqSw2Dg9G2daspkLFBdt_V020KcJG4_mZan8OfZTGH6sEPt5Y3OFvQ8azsSDHAaCgYKATwSARESFQHGX2MiFvuPFGeD07f4oG36j8NDsg0169&token_type=Bearer&expires_in=3599&scope=email%20profile%20openid%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&authuser=0&prompt=consent

const generateNonce = () => {
  return (
    Math.random().toString(36).substring(2, 15) +
    Math.random().toString(36).substring(2, 15)
  )
}

export const searchParam = (url, key) => {
	if (!url.includes(key)) { return null }
	const urlList = url.split('#')
	const kvStr = urlList.find(el => el.includes(key))
	if (!kvStr) { return null }
	const kvList = kvStr.split('&')
	const finalStr = kvList.find(el => el.includes(key))
	if (!finalStr) { return null }
	return finalStr.split('=')[1]
}
