const app = getApp();
// download.zhiqiyun.com  域名
const env = {
	NODE_ENV: 'pota',
	dev: {
		apiUrl: 'https://unwx.e-chinalife.com/hktonline'
	},
	prd: {
		apiUrl: 'https://apimall.zhiqiyun.com',
	},
	pota: {
		apiUrl: 'http://192.168.110.180:8098' ,//wjg
		// apiUrl: 'http://10.17.56.92:8098' ,//人寿内网
		// apiUrl: 'http://10.17.56.104:8005' ,//人寿内网
		// apiUrl: 'http://10.20.147.226:8080' ,//人寿内网
		// apiUrl:''
	}
}

var header = {
	'content-type': 'application/x-www-form-urlencoded',
}

/**小程序配置 */
const publics = {
	picUrls: 'https://zhiqiyun.oss-cn-hangzhou.aliyuncs.com/static/', //图片地址
	'mapLBSKEY': 'XTABZ-5K3RW-MZVRD-3ZS33-GC5RE-YOBEG',
}
/*
 * 获取token
 */
const getToken = (success) => {
	let token = getStorage('AUTH_TOKEN');
	if (token) {
		success.call(this, token);
		return false;
	} else {
		loadToken(data => {
			success.call(this, data);
		});
	}

}
const loadToken = (success) => {
	let that = this
	uni.request({
		url: env[env.NODE_ENV].apiUrl + '/api/access_token',
		data: {},
		method: 'get',
		header: header,
		success(json) {
			if (json.statusCode !== 200) return msg(json.data.message);
			if (json.data.code !== 0) return msg(json.data.msg)
			setStorage('AUTH_TOKEN', json.data.data);
			success.call(that, json.data.data);
		},
		fail() {
			msg('access_token 获取失败');
		}
	})
}

const clearValueEmpty = (data) => {
	let keyValue = {};
	for (let key in data) {
		let value = typeof data[key];
		if (value == 'string' && value) {
			if (data[key] != 'undefined' && data[key] != " " && data[key] != undefined && data[key] != null) {
				keyValue[key] = data[key];
			}
		} else if (value == 'number' && value != null) {
			keyValue[key] = data[key];
		} else if (value == 'boolean') {
			keyValue[key] = data[key];
		} else {
			if (data[key]) keyValue[key] = data[key];
		}
	}
	return keyValue;
}

/**
 * 公共请求
 * 
 * @param {*} url  请求url
 * @param {*} data 请求参数
 * @param {*} method 请求方法
 * @param {*} success 成功函数
 * @param {*} isLoad 是否显示加载提示
 */
const baseRequest = (url, data, method, success, isLoad) => {
	getToken(token => {
		if (isLoad) {
			load('加载中')
		}
		header.authorityToken = token;
		// if (url.indexOf('/v3') != -1 || url.indexOf('/paper/create') != -1) {
		// 	header['content-type'] = 'application/json;charset=UTF-8'
		// } else {
		// 	header['content-type'] = 'application/x-www-form-urlencoded'
		// }
		header['content-type'] = 'application/json;charset=UTF-8'
		try {
			var device_info = {};
			//第三放巨量投放渠道标记
			var pickleChannel = getStorage('pickleChannel');
			device_info.pickleChannel = pickleChannel;
			var packageChannel = getStorage('packageChannel');
			device_info.packageChannel = packageChannel;
			var deviceinfoString = JSON.stringify(device_info);
			deviceinfoString = deviceinfoString.replace(/{/g, '').replace(/}/g, '').replace(/:/g, '=')
				.replace(
					/,/g,
					';').replace(/"/g,
					'');
			header['device-info'] = deviceinfoString;
		} catch (e) {}
		console.log('H5请求url===>',env[env.NODE_ENV].apiUrl + url,'请求方式 '+method)
		console.log('H5请求data===>',clearValueEmpty(data))
		uni.request({
			url: env[env.NODE_ENV].apiUrl + url,
			data: clearValueEmpty(data),
			method: method,
			header: header,
			success(json) {
				if (isLoad) {
					uni.hideLoading();
				}
				if (json.statusCode !== 200) return msg(json.data.message);
				if (json.data.code !== 0) {
					return msg(json.data.msg)
				}
				let data = json.data.data;
				if (typeof data === 'string' && data.indexOf("{") === 0) {
					data = JSON.parse(data);
				}
				console.log('H5请求返回===>',data)
				success.call(this, data);
			},
			fail() {
				if (isLoad) {
					uni.hideLoading();
				}
			},
		})
	})
}

const loadIng = (msg) => {
	uni.showLoading({
		title: msg,
		mask: true
	})
}

/**POST请求 */
const postRequest = (url, data, success, isLoad) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'post', success, isLoad);
}

const postRequestLoding = (url, data, success, isLoding) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'post', success, false, isLoding);
}

/**GET请求 */
const getRequest = (url, data, success, isLoad) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'get', success, isLoad);
}
/**Put请求 */
const putRequest = (url, data, success, isLoad) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'put', success, isLoad)
}
const putRequestJson = (url, data, success, isLoad) => {
	header['content-type'] = 'application/json;charset=UTF-8'
	baseRequest(url, data, 'put', success, isLoad)
}

const uploadFile = (url, data, success) => {
	// console.log(env[env.NODE_ENV].apiUrl + url, data)
	getToken(token => {
		uni.uploadFile({
			url: env[env.NODE_ENV].apiUrl + url,
			filePath: data,
			name: 'file',
			header: {
				'appId': header['appId'],
				'authorityToken': token
			},
			success(res) {
				if (res.statusCode !== 200) return msg('文件上传失败');
				let data = JSON.parse(res.data);
				if (data.code !== 0) return msg(data.msg);
				success.call(this, data.data);
			},
		})
	})
}


/**弹窗 */
const msg = (title, success) => {
	if (title) {
		uni.showToast({
			title: title,
			icon: 'none',
			success() {
				if (success) success.call(this);
			}
		});
	}
	return false;
}


const load = msg => {
	uni.showLoading({
		title: msg,
		mask: true
	})
}

// 去掉字符串中的特殊字符和转义字符
const excludeSpecial = (s) => {
	// 去掉转义字符
	//  s = s.replace(/[\'\"\\\/\b\f\n\r\t]/g, '');
	const pattern = /[`~!@#$^&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""' + - - _ % 。，、？\s]/g;
	if (s != undefined || s != null) {
		s = s.replace(pattern, "")
	}
	return s;
}

const setStorage = (key, value) => {
	uni.setStorageSync(env.NODE_ENV + "_" + key, value)
}

const getStorage = (key) => {
	return uni.getStorageSync(env.NODE_ENV + "_" + key)
}

const removeStorage = (key) => {
	return uni.removeStorageSync(env.NODE_ENV + "_" + key);
}

const silenceLogin = (saleNo) => {
	return new Promise((resolve, reject) => {
		let params = {
			saleNo: '14300364'
		}
		// if(getStorage('userInfo')){
		// 	resolve();
		// }else{
		// 	postRequest('/api/h5/login', params, data => {
		// 		if(data) setStorage('userInfo', data);
		// 		if (data.token) setStorage('AUTH_TOKEN', data.token);
		// 		resolve();
		// 	});
		// }
		postRequest('/api/h5/login', params, data => {
			if(data) setStorage('userInfo', data);
			if (data.token) setStorage('AUTH_TOKEN', data.token);
			resolve();
		});
	});
}

module.exports = {
	setStorage: setStorage,
	getStorage: getStorage,
	postRequest: postRequest,
	postRequestLoding: postRequestLoding,
	getRequest: getRequest,
	putRequest: putRequest,
	putRequestJson: putRequestJson,
	msg: msg,
	load: load,
	getToken: getToken,
	loadIng: loadIng,
	removeStorage: removeStorage,
	public: publics,
	header: header,
	excludeSpecial: excludeSpecial,
	silenceLogin:silenceLogin,
	uploadFile:uploadFile
}
