import request from './request'

export default function (config) {
	return new Promise((resolve, reject) => {
		const refreshToken = uni.getStorageSync('refreshToken')
		request.post("/Token/Gen", { RefreshToken: refreshToken, grant_type: 2 }, false)
			.then(tokenResult => {
				if (tokenResult && !tokenResult.error) {
					const { access_token: new_access_token, refreshToken: newRefreshToken } = tokenResult
					uni.setStorageSync('accessToken', new_access_token)
					uni.setStorageSync('refreshToken', newRefreshToken)
					return true
				}
			})
			.then(r => {
				if (r) {
					config.header.Authorization = "Bearer " + uni.getStorageSync('accessToken')
					uni.request(config).then((res, err) => {
						if (res.statusCode !== 200) {
							uni.showToast({
								title: '请求错误: ' + res.statusCode,
								icon: 'error'
							})
							return
						}

						resolve(res)
					})
				}
			})
	})
}
