import Store from '../store/store'
const publicOptions = (() => { // 获取本机的信息
	let systemInfo = uni.getSystemInfoSync()
	return {
		APPGuid: "9880519c-351d-4a05-b6ef-80db0286a7ab",
		SourcePlatform: 'minProgram', // 客户端平台
		brand: systemInfo.brand || '', // 设备名称
		model: encodeURIComponent(systemInfo.model), // 机型
		os_version: systemInfo.system, // 安卓版本号

	}
})()

export default {
	/** 
	 * 自定义post,get函数，返回Promise
	 * @param {String}      url 接口网址
	 * @param {arrayObject} data 要传的数组对象 例如: {name: '武当山道士', age: 32}
	 * +-------------------
	 * @return {Promise}    promise 返回promise供后续操作
	 */
	request: function(method, url, data, isWebApi) {

		var promise = new Promise((resolve, reject) => {
			//init
			Store.state.isLoading = true
			var that = this;
			// console.log(Store.state.userData)
			data.provinceCode = Store.state.userData.ProvinceCode || '330000' // 如果用户没有省份编码信息，则默认浙江省
			data.time = (new Date()).getTime()
			data = Object.assign(data, publicOptions);
			data.WeChat_AppId = 'wxa99ef047735c031e'
			data.WeChat_MiniProToken = Store.state.userData.WeChat_MiniProToken || ''
			data.WeChatAppId = 'wxa99ef047735c031e'

			data.memberShipId = !data.memberShipId ? (Store.state.userData.Membership_Id || '') :
				data.memberShipId // ||'3255' 1170386 1125717 //


			let requstOptions = {
				url: url,
				data: data,
				method: method,
			}

			if (method == 'POST' && !isWebApi) {
				requstOptions.header = {
					'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
				}
			}
			requstOptions.success = (res) => {

				//服务器返回数据
				if (res && (res.statusCode === 200 || res.statusCode === 304 || res.statusCode === 400)) {
					if (res.data && ((res.data.ResultCode != '999' && res.data.ResultCode != undefined) ||
						(res.data.Result_Code != '999' && res.data.Result_Code != undefined))) {
						resolve(res.data);
					} else if (typeof res.data == 'object') { // 兼容招标投标模块
						resolve(res.data);
						console.log('错误:' + (res.data.Result_Code || res.data.ResultCode) + ',' +
							(res.data.Result_Desc || res.data.ResultDesc))
					} else {
						resolve({
							ResultCode: 999,
							Result_Code: 999
						});
						uni.showToast({
							title: res.data || '服务器错误，请稍后重试',
							icon: 'none'
						})
					}
				} else {
					//返回错误提示信息
					console.log(res)
					reject(res.data);
					// reject("服务器错误，请稍后重试");
				}
			}
			requstOptions.fail = (e) => {
				resolve({
					data: {
						error: '网络连接失败，请重试'
					}
				});
				reject('网络连接失败，请重试');
			}
			requstOptions.complete = () => {
				Store.state.isLoading = false
			}
			//网络请求
			uni.request(requstOptions)
		}).catch(function(reason, request) {

			uni.showToast({
				title: reason,
				icon: 'none'
			})
		});
		return promise;
	}

}
