var gettokenid = null

/**
 * 初始化授权信息
 * @param {object} params OA系统参数
 */
function initAuthParams(params) {
	wps.PluginStorage.setItem('cookie', Base64.decode(params.cookie))
	var refcookie = Base64.decode(params.refresh_token)
	wps.PluginStorage.setItem('refurl', refcookie.split('|')[0])
	wps.PluginStorage.setItem('refresh_token', refcookie.split('|')[1])

	wps.PluginStorage.setItem(
		constStrEnum.IsSilentMode,
		params.fileparam.IsMaximization == false
	)
}

/**
 * 获取可用token
 * 青格勒 2021年5月6日
 * @returns
 */
function GetToken() {
	return new Promise(function (resolve, reject) {
		let lastExpires = wps.PluginStorage.getItem('token_expires_in')
		let token = wps.PluginStorage.getItem('cookie')
		if (token && lastExpires && lastExpires > Date.now()) {
			resolve(token.indexOf('Bearer') < 0 ? 'Bearer ' + token : token)
		} else {
			loginfo('重新获取操作token')
			//过期重新获取token
			var xhr = new XMLHttpRequest()
			var refresh_token = wps.PluginStorage.getItem('refresh_token')

			xhr.open('POST', wps.PluginStorage.getItem('refurl'))

			xhr.onreadystatechange = function () {
				var nextTime = 2e3
				if (xhr.readyState == 4) {
					if (xhr.status == 200) {
						var returnvalue = JSON.parse(xhr.response)

						let token = 'Bearer ' + returnvalue.access_token
						wps.PluginStorage.setItem('cookie', token)
						wps.PluginStorage.setItem(
							'token_expires_in',
							returnvalue.expires_in * 1000 + Date.now()
						)
						wps.PluginStorage.setItem(
							'refresh_token',
							returnvalue.refresh_token
						)

						nextTime = Math.min(
							~(1 << 31),
							returnvalue.expires_refresh * 1000 - 10000
						)

						if (!gettokenid) gettokenid = setTimeout(AutoRefreshToken, nextTime)
						resolve(token)
					} else {
						loginfo('获取token失败:' + xhr.status + ';' + xhr.responseText)
						toggleBeforeOAfterLoading()
						reject(xhr.status)
					}
				}
			}
			xhr.setRequestHeader('Cache-Control', 'no-cache')
			xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
			xhr.send('token=' + refresh_token)
		}
	})
}

/**
 * 自动刷新token
 */
function AutoRefreshToken() {
	loginfo('自动刷新refresh_token')
	var xhr = new XMLHttpRequest()
	var refcookie = wps.PluginStorage.getItem('refresh_token')
	xhr.open('POST', wps.PluginStorage.getItem('refurl'))
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			let nextTime = 300
			if (xhr.status == 200) {
				var returnvalue = JSON.parse(xhr.response)
				wps.PluginStorage.setItem(
					'cookie',
					'Bearer ' + returnvalue.access_token
				)
				wps.PluginStorage.setItem(
					'token_expires_in',
					returnvalue.expires_in * 1000 + Date.now()
				)
				wps.PluginStorage.setItem('refresh_token', returnvalue.refresh_token)

				loginfo('自动刷新refresh_token成功')

				nextTime = Math.min(
					~(1 << 31),
					returnvalue.expires_refresh * 1000 - 10000
				)

				gettokenid = setTimeout(AutoRefreshToken, nextTime)
			} else {
				logerr(`刷新token报错:${xhr.status}:${xhr.responseText}`)
				ShowConfirm(
					'由于用户身份信息失效,修改将无法提交。未防止修改丢失，请将文档另存到本地目录',
					'warning',
					{
						btns: [
							{
								key: 'saveas',
								text: '另存为',
								primary: true,
								close: true,
								callback: function () {
									var doc = GetCurrentDocument()
									var dialog = wps.Application.FileDialog(2)
									dialog.InitialFileName = doc.FullName
									if (dialog.Show() == -1) {
										dialog.Execute()
										SetDocParamsValue(doc, 'Persist', true)
										Heart.CloseOADocument(doc)
										OnWindowActivate()
									}
								},
							},
						],
					}
				)
				return
			}
		}
	}
	xhr.setRequestHeader('Cache-Control', 'no-cache')
	xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
	xhr.send('token=' + refcookie)
}
