ruoyi.js 12.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
import dayjs from 'uni_modules/uview-ui/libs/util/dayjs'
import config from '@/common/config.js'
import {
	getToken
} from '@/utils/auth'
import request from './request'
import {
	pathToBase64,
	base64ToPath
} from '@/js_sdk/mmmm-image-tools/index.js'
/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '')
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

// 表单重置
export function resetForm(refName) {
	if (this.$refs[refName]) {
		this.$refs[refName].resetFields()
	}
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
	let search = params
	search.params = typeof(search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ?
		search.params : {}
	dateRange = Array.isArray(dateRange) ? dateRange : []
	if (typeof(propName) === 'undefined') {
		search.params['beginTime'] = dateRange[0]
		search.params['endTime'] = dateRange[1]
	} else {
		search.params['begin' + propName] = dateRange[0]
		search.params['end' + propName] = dateRange[1]
	}
	return search
}

// 回显数据字典
export function selectDictLabel(datas, value) {
	if (value === undefined) {
		return ''
	}
	var actions = []
	Object.keys(datas).some((key) => {
		if (datas[key].value == ('' + value)) {
			actions.push(datas[key].label)
			return true
		}
	})
	if (actions.length === 0) {
		actions.push(value)
	}
	return actions.join('')
}

// 回显数据字典(字符串、数组)
export function selectDictLabels(datas, value, separator) {
	if (value === undefined || value.length === 0) {
		return ''
	}
	if (Array.isArray(value)) {
		value = value.join(',')
	}
	var actions = []
	var currentSeparator = undefined === separator ? ',' : separator
	var temp = value.split(currentSeparator)
	Object.keys(value.split(currentSeparator)).some((val) => {
		var match = false
		Object.keys(datas).some((key) => {
			if (datas[key].value == ('' + temp[val])) {
				actions.push(datas[key].label + currentSeparator)
				match = true
			}
		})
		if (!match) {
			actions.push(temp[val] + currentSeparator)
		}
	})
	return actions.join('').substring(0, actions.join('').length - 1)
}

// 字符串格式化(%s )
export function sprintf(str) {
	var args = arguments,
		flag = true,
		i = 1
	str = str.replace(/%s/g, function() {
		var arg = args[i++]
		if (typeof arg === 'undefined') {
			flag = false
			return ''
		}
		return arg
	})
	return flag ? str : ''
}

// 转换字符串,undefined,null等转化为""
export function parseStrEmpty(str) {
	if (!str || str == 'undefined' || str == 'null') {
		return ''
	}
	return str
}

// 数据合并
export function mergeRecursive(source, target) {
	for (var p in target) {
		try {
			if (target[p].constructor == Object) {
				source[p] = mergeRecursive(source[p], target[p])
			} else {
				source[p] = target[p]
			}
		} catch (e) {
			source[p] = target[p]
		}
	}
	return source
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
	let config = {
		id: id || 'id',
		parentId: parentId || 'parentId',
		childrenList: children || 'children'
	}

	var childrenListMap = {}
	var nodeIds = {}
	var tree = []

	for (let d of data) {
		let parentId = d[config.parentId]
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = []
		}
		nodeIds[d[config.id]] = d
		childrenListMap[parentId].push(d)
	}

	for (let d of data) {
		let parentId = d[config.parentId]
		if (nodeIds[parentId] == null) {
			tree.push(d)
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t)
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]]
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c)
			}
		}
	}

	return tree
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName]
		var part = encodeURIComponent(propName) + '='
		if (value !== null && value !== '' && typeof(value) !== 'undefined') {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && value[key] !== '' && typeof(value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']'
						var subPart = encodeURIComponent(params) + '='
						result += subPart + encodeURIComponent(value[key]) + '&'
					}
				}
			} else {
				result += part + encodeURIComponent(value) + '&'
			}
		}
	}
	return result
}

// 验证是否为blob格式
export function blobValidate(data) {
	return data.type !== 'application/json'
}

export function numberToCurrencyNo(value) {
	if (!value) return 0.00
	// 获取整数部分
	const intPart = Math.trunc(value)
	// 整数部分处理,增加,
	let intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
	if (value < 0 && !intPartFormat.startsWith('-')) {
		intPartFormat = '-' + intPartFormat
	}
	// 预定义小数部分
	let floatPart = ''
	// 将数值截取为小数部分和整数部分
	const valueArray = value.toString().split('.')
	if (valueArray.length === 2) { // 有小数部分
		floatPart = valueArray[1].toString() // 取得小数部分
		return intPartFormat + '.' + floatPart
	}
	return intPartFormat + floatPart
}

export function formatTime(date, format = 'YYYY-MM-DD HH:mm:ss') {
	if (!date) {
		return ''
	}
	return dayjs(date).format(format)
}

// 返回上一页
// export function goBack() {
// 	let canNavBack = getCurrentPages() //获取路由栈
// 	if (canNavBack && canNavBack.length > 1) { //判断是否刷新了浏览器,如果刷新了浏览器,路由栈只有当前一个
// 		uni.navigateBack({
// 			delta: 1
// 		})
// 	} else {
// 		history.back()
// 	}
// }

export function goBack(step) {
	if (uni.getSystemInfoSync().uniPlatform === 'web') { // 判断是否在 H5 平台
		if (window.history.length > 1) {
			history.back();
		} else {
			// 处理其他情况,例如跳转到指定页面或提示用户
			console.log('无法返回上一页');
		}
	} else if (uni.getSystemInfoSync().uniPlatform === 'mp-weixin' || uni.getSystemInfoSync().uniPlatform ===
		'app') { // 判断是否在小程序平台
		uni.navigateBack({
			delta: step || 1
		});
	} else {
		// 处理其他平台,例如 App
		// 可以根据具体情况调用不同的方法来返回上一页
		console.log('当前环境不支持返回上一页操作');
	}
}


// 获取字典label
export function formatDictLabel(options, value) {
	if (!(value || value === 0) || !options) {
		return ''
	}
	const option = options.find(item => item.value === value.toString())
	return option ? option.label : value
}

// 距离换算
export function formatDistance(value) {
	if (!(value || value === 0)) {
		return '';
	}
	// if (value < 1000) {
	//   return `${value}m`;
	// } else {
	//   const kilometers = value / 1000;
	//   return `${kilometers}Km`;
	// }
	if (value < 1) {
		const meters = (value * 1000).toFixed(0);
		return `${meters}m`;
	} else {
		return `${value.toFixed(0)}km`;
	}
}
/**
 * 参数处理 根据num获取二维数组
 * @param obj值 arr数组
 */
// 根据key获取value值
export function createDoubleArray(arr, num) {
	const doubleArr = [];
	for (var i = 0; i < arr.length; i += num) { // 3个为一组转为二维数组
		doubleArr.push(arr.slice(i, i + num))
	};
	return doubleArr;
}

// 根据key获取value值
export function assignValues(obj, arr) {
	// console.log('打印obj', arr);
	const updatedArr = arr.map(item => {
		item.value = obj[item.key];
		return {
			imgSrc:item.imgSrc?item.imgSrc:'',
			type: item.type ? item.type : '',
			imgIcon: item.imgIcon ? item.imgIcon : '',
			name: item.name,
			key: item.key,
			value: Array.isArray(item.value) ? item.value : item.value === 0 ? 0 : item.value ? item.value : '— —'
		};
	});
	return updatedArr;
}

// 根据key获取key值
export function assignKeys(val) {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	const updatedArr = uuid + val;
	return updatedArr;
}


// 根据图片id返回图片url
export function fileIdToUrl(fileid) {
	let url = config.baseUrl;
	let token = getToken();
	const tpUrl = `${url}/onlinePreview?fileId=${fileid}&token=${token}`;
	console.log("图片url", tpUrl);
	return tpUrl;
}


/* 将二进制图片转换成base64显示,单图传fileId返回一张base64图片,
多图传数组,自动获取response下的fileId,返回base64图片数组 */
export async function getPhotoUrl(fileIds) {
	const baseUrl = config.baseUrl;
	const token = getToken();
	const fetchPhoto = async (fileId) => {
		const url = `${baseUrl}/system/file/v1/preview?fileId=${fileId}`;
		try {
			const response = await uni.$u.http.get(url, {
				header: {
					Authorization: 'Bearer ' + token
				},
				responseType: 'arraybuffer',
			});
			const arrayBuffer = new Uint8Array(response.data);
			let base64Url = "data:image/png;base64," + uni.arrayBufferToBase64(arrayBuffer);
			let blobUrl = await base64ToPath(base64Url);
			// console.log("转化为blob", blobUrl);
			return blobUrl
		} catch (error) {
			console.error(error);
			return null;
		}
	};

	if (Array.isArray(fileIds)) {
		this.$modal.showLoading('请稍后...')
		const promises = fileIds.map(fileIdObj => fetchPhoto(fileIdObj.response.fileId));
		const results = await Promise.all(promises);
		this.$modal.closeLoading()
		return results;
	} else {
		return await fetchPhoto(fileIds);
	}
}

//查看地址
export function viewMapLocation(longitude, latitude, address) {
	let latitudes = Number(latitude);
	let longitudes = Number(longitude);
	// 获取定位信息
	uni.getLocation({
		type: 'wgs84', //返回可以用于uni.openLocation的经纬度
		// 用户允许获取定位
		success: function(res) {
			console.log(res, '经纬度')
			if (res.errMsg == "getLocation:ok") {
				console.log(latitudes)
				console.log(longitudes)
				uni.openLocation({
					// 传入你要去的纬度
					latitude: latitudes,
					// 传入你要去的经度
					longitude: longitudes,
					// 传入你要去的地址信息 不填则为空
					name: address,
					// 缩放大小
					scale: 15,
					success: function() {
						console.log('success');
					}
				});
			}
		},
		// 用户拒绝获取定位后 再次点击触发
		fail: function(res) {
			console.log(res)
			if (res.errMsg == "getLocation:fail auth deny") {
				uni.showModal({
					content: '检测到您没打开获取信息功能权限,是否去设置打开?',
					confirmText: "确认",
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting({
								success: (res) => {
									console.log('确定');
								}
							})
						} else {
							console.log('取消');
							return false;
						}
					}
				})
			}
		}
	})
}

// 是否有街道
export function streetOrNot(data) {
	if (Array.isArray(data) && data.length === 0) {
		return false;
	}

	if (typeof data === 'string' && data.length !== 0) {
		return true;
	}

	return false;
}