import store from '@/store'
import config from '@/config'
import {
	AESDecrypt,
	AESEncypt,
	RSAEncrypt,
	RSADecrypt,
	createKey
} from '@/utils/dataParams.js'
import {
	getToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'

let timeout = 10000
const serverAddress = uni.getStorageSync('serverAddress')
const baseUrlIp = serverAddress ? serverAddress : config.baseUrl
const baseUrl = baseUrlIp + '/projects/outApi'

const request = config => {
	// console.log(config.data || config.params)
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken() && !isToken) {
		config.header['token'] = getToken()
	}
	// get请求映射params参数
	let urlOrginal = "" + config.url;
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	// console.log(config.url)
	// console.log(config.params || config.data)
	let pwdConfig = {}

	// 如果是对象形式传递的params
	if (config.formParams) {
		const encryptKey = createKey()
		pwdConfig.encryptKey = encryptKey
		for (var i in config.formParams) {
			config.formParams[i] = AESEncypt(config.formParams[i], encryptKey).data
		}
		config.header['GoWork'] = RSAEncrypt(encryptKey)
		config.data = config.formParams
	}
	if (config.data) {
		pwdConfig = AESEncypt(JSON.stringify(config.data))
		config.header['GoWork'] = RSAEncrypt(pwdConfig.encryptKey)
		config.data = pwdConfig.data;
	}
	if (!pwdConfig.encryptKey) {
		const encryptKey = createKey()
		pwdConfig.encryptKey = encryptKey
		config.header['GoWork'] = RSAEncrypt(encryptKey)
	}
	// console.log("params", config.params)
	// console.log("data", config.data)
	return new Promise((resolve, reject) => {
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: baseUrl + config.url,
				data: config.data,
				header: config.header,
				dataType: 'json',
				params: config.params
			}).then(response => {
				/* let [error, res] = response
				 if (error) {
				   toast('后端接口连接异常')
				   reject('后端接口连接异常')
				   return
				 } */
				const res = response
				const code = res.data.code || 200
				const msg = errorCode[code] || res.data.msg || errorCode['default']
				if (code === 401) {
					showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(confirmRes => {
						if (confirmRes.confirm) {
							store.dispatch('LogOut').then(storeRes => {
								uni.reLaunch({
									url: '/pages/login/index'
								})
							})
						}
					})
					reject('无效的会话,或者会话已过期,请重新登录。')
				} else if (code === 500) {
					toast(msg)
					reject('500')
				} else if (code !== 200) {
					toast(msg)
					reject(code)
				}
				if (res.data.encrypt) {
					if (pwdConfig.encryptKey == null) {
						pwdConfig.encryptKey = RSADecrypt(res.data.GoWork)
					}
					res.data.data = JSON.parse(AESDecrypt(res.data.data, pwdConfig.encryptKey))
				}
				console.log(urlOrginal)
				console.log(res.data)
				console.log("***************************************")
				resolve(res.data)
			})
			.catch(error => {
				let {
					message
				} = error
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				toast(message)
				reject(error)
			})
	})
}

export default request