import {
	getToken
} from '@/utils/auth'
import {
	getLocale
} from '@/utils/index'
import {
	$http
} from '@escook/request-miniprogram'
import store from '@/store'

class Request {
	constructor(options = {}) {
		// 请求的根路径
		this.baseUrl = options.baseUrl || ''
		// 请求的 url 地址
		this.url = options.url || ''
		// 请求方式
		this.method = 'GET'
		// 请求的参数对象
		this.data = null
		// header 请求头
		this.header = options.header || {}
		this.beforeRequest = null
		this.afterRequest = null
	}

	get(url, data = {}) {
		this.method = 'GET'
		this.url = this.baseUrl + url
		this.data = data
		return this._()
	}

	post(url, data = {}) {
		this.method = 'POST'
		this.url = this.baseUrl + url
		this.data = data
		return this._()
	}

	put(url, data = {}) {
		this.method = 'PUT'
		this.url = this.baseUrl + url
		this.data = data
		return this._()
	}

	delete(url, data = {}) {
		this.method = 'DELETE'
		this.url = this.baseUrl + url
		this.data = data
		return this._()
	}

	_() {
		// 清空 header 对象
		this.header = {}
		// 请求之前做一些事
		this.beforeRequest && typeof this.beforeRequest === 'function' && this.beforeRequest(this)
		// 发起请求
		return new Promise((resolve, reject) => {
			let weixin = wx
			// 适配 uniapp
			if (typeof uni !== 'undefined') {
				weixin = uni
			}
			weixin.request({
				url: this.url,
				method: this.method,
				data: this.data,
				header: this.header,
				success: res => {
					if (this.afterRequest) {
						this.afterRequest(res)
					}
				},
				fail: err => {
					reject(err)
				},
				complete: res => {
					resolve(res.data)
				},
			})
		})
	}
}

const request = new Request()

/**
 * 创建请求
 * @param baseURL
 */

request.baseUrl = process.env.BASE_API
request.config = {
	retry: 3,
	retryDelay: 1000,
	timeout: 50000,
}
request.beforeRequest = _request => {
	_request.header['Language-Set'] = getLocale()
	_request.header['X-Requested-With'] = 'XMLHttpRequest'
	const apiToken = getToken()
	if (apiToken) {
		_request.header.Authorization = `Bearer ${apiToken}`
	}
}
request.afterRequest = response => {
	console.log(response)
	if (response.header && response.header['authorization']) {
		// 刷新token
		const token = response.header['authorization'].replace('Bearer ', '')
		if (token !== store.getters.token) {
			store.commit('SET_TOKEN', token)
		}
	}
	const res = response.data
	if (res.ret !== 0) {
		if (res.ret === 401) {
			if (response.data.msg === 'Token has expired') {
				response.data.msg = '登录超时'
			}
			store.dispatch('fedLogOut').then(() => {
				uni.navigateTo({
					url: '/login-new'
				})
			})
		} else {
			uni.showModal({
				content: res.msg || 'Error',
				success(r) {
					if (r.confirm) {
					} else if (r.cancel) {
					}
				}
			})
		}
		return Promise.reject(new Error(res.msg || 'Error'))
	} else {
		return res
	}
}

export default request

/**
 * GET请求
 * @param {Object} url
 * @param {Object} params
 */
export const get = (url) => (params) => {
	return request.get(url, params)
}

/**
 * POST请求
 * @param {Object} url
 * @param {Object} params
 */
export const post = (url) => (params) => {
	return request.post(url, params)
}

export const link = (url) => {
	return process.env.BASE_API + url
}