let s_url = '' // 请求地址
let s_data = '' // 请求数据
let s_time = new Date() // 请求时间
const interval = 1000
const dev = 'dev'
const prod = 'prod'
const devCloud = 'dev_cloud'
// const environment = dev
// const environment = devCloud
const environment = prod
// 全局请求路径，也就是后端的请求基准路径
export let BASE_URL
export let BASE_SOCKET_URL = 'localhost'
export let BASE_URL_ML
export let BASE_URL_HSKJ
export let BASE_URL_MASTER
export let BASE_URL_BUSINESS
switch (environment) {
	case 'dev':
		BASE_URL = 'https://localhost:3005'
		BASE_SOCKET_URL = 'localhost'
		BASE_URL_ML = 'https://localhost:3005'
		BASE_URL_HSKJ = 'https://localhost:3012'
		BASE_URL_MASTER = 'https://localhost:3010'
		BASE_URL_BUSINESS = 'https://localhost:3011'
		break;
	case 'dev_cloud':
		BASE_URL = 'https://ts.willalp.com:3005'
		BASE_SOCKET_URL = 'ts.willalp.com'
		BASE_URL_ML = 'https://ts.willalp.com:3005'
		BASE_URL_HSKJ = 'https://ts.willalp.com:3012'
		BASE_URL_MASTER = 'https://ts.willalp.com:3010'
		BASE_URL_BUSINESS = 'https://ts.willalp.com:3011'
		break;
	case 'prod':
		BASE_URL = "https://master.willalp.com:3005"
		BASE_SOCKET_URL = 'master.willalp.com'
		BASE_URL_ML = 'https://master.willalp.com:3005'
		BASE_URL_HSKJ = 'https://master.willalp.com:3012' 
		BASE_URL_MASTER = 'https://master.willalp.com:3010'
		BASE_URL_BUSINESS = 'https://master.willalp.com:3011'
		break;
}


// 根据机构类型获取 baseUrl
export const getServerURl = (urlType) => {
	if (urlType === 1) {
		return BASE_URL_MASTER
	} else if (urlType === 2) {
		return BASE_URL_BUSINESS
	} else if (urlType === 3) {
		return BASE_URL_ML
	} else if (urlType === 4) {
		return BASE_URL_HSKJ
	} else {
		return BASE_URL_ML
	}
	return BASE_URL;
}


export const getUrlType = () => {
	return uni.getStorageSync('tabType')
}
// 同时发送异步代码的次数，防止一次点击中有多次请求，用于处理
let ajaxTimes = 0;
// 封装请求方法，并向外暴露该方法
export const httpRequest = (options) => {
	// 解构请求头参数
	let header = {
		...options.header
	}
	if (uni.getStorageSync('isTabLogin') === 0) {
		return
	}
	header["UserName"] = uni.getStorageSync('setUserName');
	// 当前请求不是登录和获取所有机构时的请求，在header中加上后端返回的token
	if (!options.isNotToken) {
		header["Authorization"] = "Bearer " + uni.getStorageSync('token');
		// 显示加载中 效果
		// uni.showLoading({
		// 	title: "加载中",
		// 	mask: true
		// });
	}
	if (options.urlType === 1) {
		BASE_URL = BASE_URL_MASTER
	} else if (options.urlType === 2) {
		BASE_URL = BASE_URL_BUSINESS
	} else if (options.urlType === 3) {
		BASE_URL = BASE_URL_ML
	} else if (options.urlType === 4) {
		BASE_URL = BASE_URL_HSKJ
	} else {
		BASE_URL = BASE_URL_ML
	}
	header['Content-Type'] = 'application/json';
	header['Allow-Control-Allow-Origin'] = '*';
	ajaxTimes++;

	// 间隔时间(ms)，小于此时间视为重复提交
	if (s_data === options.data && options.time - s_time < interval && s_url === options.url) {
		uni.showToast({
			duration: 2500,
			title: '数据正在处理，请勿重复提交',
			icon: 'error',
		});
		return
	} else {
		s_url = options.url; // 请求地址
		s_data = options.data; // 请求数据
		s_time = new Date(); // 请求时间
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'POST',
			data: options.data || {},
			header,
			success: (res) => {
				const data = res.data;
				let pages = getCurrentPages()
				// console.log(pages[pages.length - 1].route)
				if (data.code === 401) {
					uni.showToast({
						duration: 2500,
						title: '登录信息过期',
						icon: 'error',
					});
					uni.clearStorageSync()
					// console.log("接口：" + BASE_URL + options.url + " - 401异常")
					goto('../../pageA/login/login')
				} else if (data.code === 403) {
					uni.showToast({
						duration: 2500,
						title: '登录信息过期',
						icon: 'error',
					});
					uni.clearStorageSync()
					// console.log("接口：" + BASE_URL + options.url + " - 403异常")
					goto('../../pageA/login/login')
				} else if (data.code != 200) {
					// if (!options.isNotErrorMsg) {
					// 	uni.showToast({
					// 		duration: 1500,
					// 		title: data.msg ? data.msg : '请求失败',
					// 		icon: 'none'`
					// 	});
					// }
				}
				resolve(res)
			},
			fail: (err) => {
				resolve(err)
			},
			// 完成之后关闭加载效果
			complete: () => {
				ajaxTimes--;
				if (ajaxTimes === 0) {
					//  关闭正在等待的图标
					// uni.hideLoading();
				}
			}
		})
	})
}
// 获取所有已配置字典
export const getAllDicts = () => {
	let dictTypes = ['app_vacate_type', 'out_storage_type', 'app_msg_type', 'job_title', 'dimission_type',
		'access_stroage_type', 'sys_user_sex', 'degree_dict', 'interview_type', 'hire_result',
		"hzl_seal_use_type", "seal_type", "hzl_seal_use_address", 'hzl_file_type', 'welfare_apply_addr',
		'device_repairs_urgency_level', 'device_scrap_status', 'goods_storage_type',
		'condole_renshenshanghai_type', 'device_repairs_submit_type', 'goods_property_type'
	]
	for (var i = 0; i < dictTypes.length; i++) {
		getDicts(dictTypes[i]).then(res => {
			uni.setStorage({
				key: res.dictType,
				data: res.data
			})
		})
	}
}


// 根据key查询config表数据信息
export const getAllConfigData = (key) => {
	let configDatas = ['org_dept_parent_id', 'file_approval_flow_run_key', 'biz_leave_flow_run_key',
		'reserve_consuming_flow_run_key', 'personnel_hire_approval_flow_run_key', 'reserve_return_flow_run_key',
		'reserve_register_flow_run_key', 'personnel_dimission_approval_flow_run_key',
		'interview_record_approval_flow_run_key', 'instant_notice_approval_flow_run_key',
		'shift_official_approval_flow_run_key', 'device_repairs_approval_flow_run_key',
		'use_seal_approval_flow_run_key', 'purchase_approval_flow_run_key',
		'device_scrap_approval_flow_run_key', 'contract_approval_flow_run_key'
	]
	for (var i = 0; i < configDatas.length; i++) {
		getConfigData(configDatas[i]).then(res => {
			uni.setStorage({
				data: res.msg,
				key: res.key
			})
		})
	}
}

// 通用翻译功能
export const dictTranslation = (value, dictType, type) => {
	let data = uni.getStorageSync(dictType)
	for (var i = 0; i < data.length; i++) {
		if (type === 'dept') {
			if (parseInt(value) === parseInt(data[i].deptId)) {
				return data[i].deptName;
			}
		} else if (type === 'dict') {
			if (parseInt(value) === parseInt(data[i].dictValue)) {
				return data[i].dictLabel;
			}
		} else if (type === 'post') {
			if (parseInt(value) === parseInt(data[i].postId)) {
				return data[i].postName;
			}
		}
	}
}

// 根据字典类型查询字典数据信息
export const getDicts = (dictType) => {
	let header = {
		...dictType
	}
	header["Authorization"] = "Bearer " + uni.getStorageSync('token');
	header["UserName"] = uni.getStorageSync('setUserName');
	// 当前请求不是登录和获取所有机构时的请求，在header中加上后端返回的token
	// header["Authorization"] = "Bearer " + uni.getStorageSync('token');
	header['Content-Type'] = 'application/json';
	header['Allow-Control-Allow-Origin'] = '*';
	return new Promise((resolve, reject) => {
		uni.request({
			url: getServerURl(getUrlType()) +
				'/system/dict/data/type/' + dictType,
			method: 'get',
			header,
			success: (res) => {
				res.data.dictType = dictType
				resolve(res.data);
			}
		})
	})
}


// 根据key查询config表数据信息
export const getConfigData = (key) => {
	let header = {
		...key
	}
	header["Authorization"] = "Bearer " + uni.getStorageSync('token');
	header["UserName"] = uni.getStorageSync('setUserName');
	// 当前请求不是登录和获取所有机构时的请求，在header中加上后端返回的token
	// header["Authorization"] = "Bearer " + uni.getStorageSync('token');
	header['Content-Type'] = 'application/json';
	header['Allow-Control-Allow-Origin'] = '*';
	return new Promise((resolve, reject) => {
		uni.request({
			url: getServerURl(getUrlType()) +
				'/system/config/configKey/' + key,
			method: 'get',
			header,
			success: (res) => {
				res.data.key = key
				resolve(res.data);
			}
		})
	})
}


export const showModal = (content) => {
	uni.showModal({
		title: "提示",
		content: content,
		showCancel: false,
		confirmColor: 'rgb(55,186,189)'
	})
}

export const goto = (url) => {
	uni.navigateTo({
		url: url,
		animationType: 'pop-in',
		animationDuration: 200
	});
}

export const goTab = (url) => {
	uni.switchTab({
		url: url
	});
}

export const goBack = () => {
	uni.navigateBack({
		delta: 1,
		animationType: 'pop-out',
		animationDuration: 200
	});
}
export const formatter = (type, value) => {
	if (type === 'year') {
		return `${value}年`
	}
	if (type === 'month') {
		return `${value}月`
	}
	if (type === 'day') {
		return `${value}日`
	}
	return value
}

export const dateResult = (time, mode) => {
	time = parseInt(time)
	const timeFormat = uni.$u.timeFormat
	switch (mode) {
		case 'datetime':
			return timeFormat(time, 'yyyy-mm-dd hh:MM:ss')
		case 'date':
			return timeFormat(time, 'yyyy-mm-dd')
		case 'year-month':
			return timeFormat(time, 'yyyy-mm')
		case 'time':
			return time
		default:
			return ''
	}
}
