/**
 * Request 0.0.7
 * @Class uni-app request网络请求库
 * @Author lu-ch
 * @Date 2019-07-11
 * @Email webwork.s@qq.com
 * http://ext.dcloud.net.cn/plugin?id=392
 * **/
import qs from 'qs'
import constant from '@/constant/index'
// import common from '@/utils/common'
import { parse, getCheckLogin } from '@/utils/util'

const Base64 = require('js-base64').Base64
class Request {
	config = {
		// #ifdef H5
		baseUrl: process.env.NODE_ENV == 'development' ? '/api' : constant.hostUrl,
		// #endif
		// #ifdef MP-WEIXIN
		baseUrl: constant.hostUrl,
		// #endif
		header: {
			'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
		},
		data: {},
		method: 'GET',
		dataType: 'json',  /* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: 'text',
		success() { },
		fail() { },
		complete() { }
	}

	static posUrl(url) { /* 判断url是否为绝对路径 */
		return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
	}

	interceptor = {
		request: (f) => {
			if (f && typeof f === 'function') {
				this.requestBeforeFun = f
			}
		},
		response: (f) => {
			if (f && typeof f === 'function') {
				this.requestComFun = f
			}
		}
	}

	requestBeforeFun(config, cancel) {
		let token = ''
		try {
			const st = uni.getStorageSync('token')
			if (st) {
				token = st
			}
		} catch (e) {
			console.error(e, '获取token异常')
		}
		config.header = {
			...config.header
		}
		// 将token 放入header
		if (token) {
			config.header['token'] = token
		}
		// const token = uni.getStorageSync('token')
		// config.data = JSON.stringify(config.data);
		config.headers = {
			'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
		}
		// if (token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
		// 	// axios.defaults.headers.common['token'] = token;
		// 	config.headers.token = token
		// }
		// config.headers.HkdsRequestFrom = window.location.href
		// config.header.userRegion = Base64.encode(uni.getStorageSync('userRegion')) || null
		// config.header['x-client-hash'] = uni.getStorageSync('client_hash') || null
		const userRegion = Base64.encode(uni.getStorageSync('userRegion')) || null
		// if (userRegion) {
		// 	config.header.userRegion = userRegion
		// }
		const account = uni.getStorageSync('account') || null
		if (account) {
			config.header['account'] = account
		}
		// const source = uni.getStorageSync('source') || null
		// if (source) {
		// 	config.header['source'] = source
		// }
		if (constant.source == 'mobile') {
			const shopId = uni.getStorageSync('shopId') || 0
			if (shopId) {
				config.header['shopId'] = shopId
			}
		}
		if (config.config.loading) {
			uni.showLoading({
				title: '',
				mask: true
			})
		}
		return config
	}

	requestComFun(response) {
		if (response.config.config.loading) {
			uni.hideLoading()
		}
		// const client_hash = response.header.client_hash || null
		// console.log('X-Client-Hash', response.header['X-Client-Hash'])
		// if (client_hash) {
		// 	uni.setStorageSync('client_hash', client_hash)
		// }
		return response
	}

	setConfig(f) {
		this.config = f(this.config)
	}

	request(options = {}, config) {
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = Request.posUrl(options.url) ? options.url : (options.baseUrl + options.url)
		options.data = qs.stringify(options.data) || {}
		options.header = options.header || this.config.header
		options.method = options.method || this.config.method
		return new Promise((resolve, reject) => {
			let next = true
			let _config = null
			options.complete = (response) => {
				const statusCode = response.statusCode
				response.config = _config
				//   if(config.method === 'get') {
				// 	response.config.config = config
				//   }else if(config.method === 'post'){
				// 	response.config.config.config = config
				//   }
				response.config.config = config
				response = this.requestComFun(response)
				// 全局忽略错误，在单个请求里面自行处理
				if (config.hideError) {
					resolve(response.data)
				}
				if (statusCode === 200) { // 成功
					if (response.data.code === 1) {
						resolve(response.data)
					} else {
						// 无权限或者登录过期
						if (response.data.code && response.data.code == -1) {
							uni.removeStorageSync('token')
							uni.showToast({
								title: '登陆过期，正在重新登录...',
								icon: 'none',
								mask: true
							})
							uni.removeStorageSync('token')
							setTimeout(() => {
								getCheckLogin()
								// uni.reLaunch({
								// 	url: `/pages/page/login/index`
								// })
							}, 1000)
						} else {
							if (!config.hideError) {
								// this.$msg(response.data.msg)
								uni.showToast({
									title: response.data.msg,
									icon: 'none',
									mask: true
								})
							}
							reject(response.data)
						}
					}
				} else {
					reject(response)
				}
			}
			const cancel = (t = 'handle cancel') => {
				const err = {
					errMsg: t,
					config: afC
				}
				reject(err)
				next = false
			}
			const afC = { ...this.config, ...options, config: config }
			_config = { ...afC, ...this.requestBeforeFun(afC, cancel) }
			if (!next) return
			uni.request(_config)
		})
	}

	get(url, data = {}, options = {}, config = {}) {
		// options.url = url + common.queryData(data, true)
		options.url = url + parse(data)
		options.data = {}
		options.method = 'GET'
		return this.request(options, config)
	}

	post(url, data = {}, options = {}, config = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options, config)
	}
}
export default new Request()

