import {
	Encrypt,
	UrlPath,
	Message
} from "./../commonuni"

// 请求拦截
const fetch = (action, opt) => {
	let params = opt.params
	opt.url = UrlPath.getBaseUrl() + action
	opt.method = opt.method || "GET";
	var header = {}
	let token = uni.getStorageSync("token")
	if (token != null && token != "") {
		header = {
			Authorization: 'Bearer ' + token
		}
	}
  if(opt.isFile){
	header['Content-Type'] = 'application/json; application/octet-stream'
	opt.responseType = 'arraybuffer'
	delete opt.isFile
  }
	if (!opt.url.indexOf("app-api/wxLogin") == 0 || !url.indexOf("app-api/common") == 0) {
		opt.attribute = {
			"login_user_type": 2
		}
	}
	opt.header = {
		...opt.header,
		...header,
	}
	// if (opt.method == "POST") {
	// 	if (opt.data) {
	// 		opt.data = {
	// 			data: Encrypt.AESEncode(JSON.stringify(opt.data))
	// 		}
	// 	}
	// }
	return new Promise((resolve, reject) => {
		let options = {}
		Object.keys(opt).map(key => {
			if (key !== "params") {
				return options[key] = opt[key]
			}
		})
		uni.request(options)
			.then(res => interceptorsRes(res, resolve, reject))
			.catch(err => interceptorsErr(err, reject))
	})
}

// 请求拦截
const fetchfile = (action, opt) => {
	let params = opt.params
	opt.url = UrlPath.getBaseUrl() + action
	opt.method = "POST";
	var header = {}
	let token = uni.getStorageSync("token")
	if (token != null && token != "") {
		header = {
			Authorization: 'Bearer ' + token
		}
	}
	opt.header = {
		...opt.header,
		...header,
	}
	opt.responseType = 'application/json'
	return new Promise((resolve, reject) => {
		uni.uploadFile(opt)
			.then(res => interceptorsRes(res, resolve, reject))
			.catch(err => interceptorsErr(err, reject))
	})
}


// 响应拦截
const interceptorsRes = (resp, resolve, reject) => {
	const {
		code
	} = resp.data
	if (resp.statusCode == 401 || code == 401) {
		Message.info("登录已过期,请重新登录!")
		uni.navigateTo({
			url: '../../pages/index/index'
		});
		resolve(null);
		return;
	}
	if  (resp.statusCode == '201'){
		resolve(resp.data);
		return;
	}

	if (typeof(resp.data) == 'string'){
		resp.data = JSON.parse(resp.data)
	}
	if (resp.data.code != 0){
		Message.info(resp.data.msg);
		reject(null)
		return;
	}
	if (typeof(resp.data) == "string") {
		// Encrypt.AESDecode()
		resp.data = JSON.parse(JSON.parse(resp.data), null, null);
	} else {
		// Encrypt.AESDecode()
		resp.data = resp.data.data;
	}
	resolve(resp.data)
}

// 异常处理
const interceptorsErr = (err, reject) => {
	Message.error("网络异常", err)
	reject(err)
}

export {
	fetch,
	fetchfile
}