华西海圻ELN前端工程
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

626 lines
15 KiB

  1. import { parseTime } from './ruoyi'
  2. import { encrypt, decrypt } from '@/utils/encryptUtil'
  3. import moment from 'moment'
  4. import { EventBus } from './eventBus'
  5. /**
  6. * 表格时间格式化
  7. */
  8. export function formatDate(cellValue) {
  9. if (cellValue == null || cellValue == '') return ''
  10. var date = new Date(cellValue)
  11. var year = date.getFullYear()
  12. var month =
  13. date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  14. var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  15. var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  16. var minutes =
  17. date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  18. var seconds =
  19. date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  20. return (
  21. year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
  22. )
  23. }
  24. /**
  25. * @param {number} time
  26. * @param {string} option
  27. * @returns {string}
  28. */
  29. export function formatTime(time, option) {
  30. if (('' + time).length === 10) {
  31. time = parseInt(time) * 1000
  32. } else {
  33. time = +time
  34. }
  35. const d = new Date(time)
  36. const now = Date.now()
  37. const diff = (now - d) / 1000
  38. if (diff < 30) {
  39. return '刚刚'
  40. } else if (diff < 3600) {
  41. // less 1 hour
  42. return Math.ceil(diff / 60) + '分钟前'
  43. } else if (diff < 3600 * 24) {
  44. return Math.ceil(diff / 3600) + '小时前'
  45. } else if (diff < 3600 * 24 * 2) {
  46. return '1天前'
  47. }
  48. if (option) {
  49. return parseTime(time, option)
  50. } else {
  51. return (
  52. d.getMonth() +
  53. 1 +
  54. '月' +
  55. d.getDate() +
  56. '日' +
  57. d.getHours() +
  58. '时' +
  59. d.getMinutes() +
  60. '分'
  61. )
  62. }
  63. }
  64. /**
  65. * @param {string} url
  66. * @returns {Object}
  67. */
  68. export function getQueryObject(url) {
  69. url = url == null ? window.location.href : url
  70. const search = url.substring(url.lastIndexOf('?') + 1)
  71. const obj = {}
  72. const reg = /([^?&=]+)=([^?&=]*)/g
  73. search.replace(reg, (rs, $1, $2) => {
  74. const name = decodeURIComponent($1)
  75. let val = decodeURIComponent($2)
  76. val = String(val)
  77. obj[name] = val
  78. return rs
  79. })
  80. return obj
  81. }
  82. /**
  83. * @param {string} input value
  84. * @returns {number} output value
  85. */
  86. export function byteLength(str) {
  87. // returns the byte length of an utf8 string
  88. let s = str.length
  89. for (var i = str.length - 1; i >= 0; i--) {
  90. const code = str.charCodeAt(i)
  91. if (code > 0x7f && code <= 0x7ff) s++
  92. else if (code > 0x7ff && code <= 0xffff) s += 2
  93. if (code >= 0xdc00 && code <= 0xdfff) i--
  94. }
  95. return s
  96. }
  97. /**
  98. * @param {Array} actual
  99. * @returns {Array}
  100. */
  101. export function cleanArray(actual) {
  102. const newArray = []
  103. for (let i = 0; i < actual.length; i++) {
  104. if (actual[i]) {
  105. newArray.push(actual[i])
  106. }
  107. }
  108. return newArray
  109. }
  110. /**
  111. * @param {Object} json
  112. * @returns {Array}
  113. */
  114. export function param(json) {
  115. if (!json) return ''
  116. return cleanArray(
  117. Object.keys(json).map((key) => {
  118. if (json[key] === undefined) return ''
  119. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  120. })
  121. ).join('&')
  122. }
  123. /**
  124. * @param {string} url
  125. * @returns {Object}
  126. */
  127. export function param2Obj(url) {
  128. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  129. if (!search) {
  130. return {}
  131. }
  132. const obj = {}
  133. const searchArr = search.split('&')
  134. searchArr.forEach((v) => {
  135. const index = v.indexOf('=')
  136. if (index !== -1) {
  137. const name = v.substring(0, index)
  138. const val = v.substring(index + 1, v.length)
  139. obj[name] = val
  140. }
  141. })
  142. return obj
  143. }
  144. /**
  145. * @param {string} val
  146. * @returns {string}
  147. */
  148. export function html2Text(val) {
  149. const div = document.createElement('div')
  150. div.innerHTML = val
  151. return div.textContent || div.innerText
  152. }
  153. /**
  154. * Merges two objects, giving the last one precedence
  155. * @param {Object} target
  156. * @param {(Object|Array)} source
  157. * @returns {Object}
  158. */
  159. export function objectMerge(target, source) {
  160. if (typeof target !== 'object') {
  161. target = {}
  162. }
  163. if (Array.isArray(source)) {
  164. return source.slice()
  165. }
  166. Object.keys(source).forEach((property) => {
  167. const sourceProperty = source[property]
  168. if (typeof sourceProperty === 'object') {
  169. target[property] = objectMerge(target[property], sourceProperty)
  170. } else {
  171. target[property] = sourceProperty
  172. }
  173. })
  174. return target
  175. }
  176. /**
  177. * @param {HTMLElement} element
  178. * @param {string} className
  179. */
  180. export function toggleClass(element, className) {
  181. if (!element || !className) {
  182. return
  183. }
  184. let classString = element.className
  185. const nameIndex = classString.indexOf(className)
  186. if (nameIndex === -1) {
  187. classString += '' + className
  188. } else {
  189. classString =
  190. classString.substr(0, nameIndex) +
  191. classString.substr(nameIndex + className.length)
  192. }
  193. element.className = classString
  194. }
  195. /**
  196. * @param {string} type
  197. * @returns {Date}
  198. */
  199. export function getTime(type) {
  200. if (type === 'start') {
  201. return new Date().getTime() - 3600 * 1000 * 24 * 90
  202. } else {
  203. return new Date(new Date().toDateString())
  204. }
  205. }
  206. /**
  207. * @param {Function} func
  208. * @param {number} wait
  209. * @param {boolean} immediate
  210. * @return {*}
  211. */
  212. export function debounce(func, wait, immediate) {
  213. let timeout, args, context, timestamp, result
  214. const later = function () {
  215. // 据上一次触发时间间隔
  216. const last = +new Date() - timestamp
  217. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  218. if (last < wait && last > 0) {
  219. timeout = setTimeout(later, wait - last)
  220. } else {
  221. timeout = null
  222. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  223. if (!immediate) {
  224. result = func.apply(context, args)
  225. if (!timeout) context = args = null
  226. }
  227. }
  228. }
  229. return function (...args) {
  230. context = this
  231. timestamp = +new Date()
  232. const callNow = immediate && !timeout
  233. // 如果延时不存在,重新设定延时
  234. if (!timeout) timeout = setTimeout(later, wait)
  235. if (callNow) {
  236. result = func.apply(context, args)
  237. context = args = null
  238. }
  239. return result
  240. }
  241. }
  242. /**
  243. * This is just a simple version of deep copy
  244. * Has a lot of edge cases bug
  245. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  246. * @param {Object} source
  247. * @returns {Object}
  248. */
  249. export function deepClone(source) {
  250. if (!source && typeof source !== 'object') {
  251. throw new Error('error arguments', 'deepClone')
  252. }
  253. const targetObj = source.constructor === Array ? [] : {}
  254. Object.keys(source).forEach((keys) => {
  255. if (source[keys] && typeof source[keys] === 'object') {
  256. targetObj[keys] = deepClone(source[keys])
  257. } else {
  258. targetObj[keys] = source[keys]
  259. }
  260. })
  261. return targetObj
  262. }
  263. /**
  264. * @param {Array} arr
  265. * @returns {Array}
  266. */
  267. export function uniqueArr(arr) {
  268. return Array.from(new Set(arr))
  269. }
  270. /**
  271. * @returns {string}
  272. */
  273. export function createUniqueString() {
  274. const timestamp = +new Date() + ''
  275. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  276. return (+(randomNum + timestamp)).toString(32)
  277. }
  278. /**
  279. * Check if an element has a class
  280. * @param {HTMLElement} elm
  281. * @param {string} cls
  282. * @returns {boolean}
  283. */
  284. export function hasClass(ele, cls) {
  285. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  286. }
  287. /**
  288. * Add class to element
  289. * @param {HTMLElement} elm
  290. * @param {string} cls
  291. */
  292. export function addClass(ele, cls) {
  293. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  294. }
  295. /**
  296. * Remove class from element
  297. * @param {HTMLElement} elm
  298. * @param {string} cls
  299. */
  300. export function removeClass(ele, cls) {
  301. if (hasClass(ele, cls)) {
  302. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  303. ele.className = ele.className.replace(reg, ' ')
  304. }
  305. }
  306. export function makeMap(str, expectsLowerCase) {
  307. const map = Object.create(null)
  308. const list = str.split(',')
  309. for (let i = 0; i < list.length; i++) {
  310. map[list[i]] = true
  311. }
  312. return expectsLowerCase ? (val) => map[val.toLowerCase()] : (val) => map[val]
  313. }
  314. export const exportDefault = 'export default '
  315. export const beautifierConf = {
  316. html: {
  317. indent_size: '2',
  318. indent_char: ' ',
  319. max_preserve_newlines: '-1',
  320. preserve_newlines: false,
  321. keep_array_indentation: false,
  322. break_chained_methods: false,
  323. indent_scripts: 'separate',
  324. brace_style: 'end-expand',
  325. space_before_conditional: true,
  326. unescape_strings: false,
  327. jslint_happy: false,
  328. end_with_newline: true,
  329. wrap_line_length: '110',
  330. indent_inner_html: true,
  331. comma_first: false,
  332. e4x: true,
  333. indent_empty_lines: true
  334. },
  335. js: {
  336. indent_size: '2',
  337. indent_char: ' ',
  338. max_preserve_newlines: '-1',
  339. preserve_newlines: false,
  340. keep_array_indentation: false,
  341. break_chained_methods: false,
  342. indent_scripts: 'normal',
  343. brace_style: 'end-expand',
  344. space_before_conditional: true,
  345. unescape_strings: false,
  346. jslint_happy: true,
  347. end_with_newline: true,
  348. wrap_line_length: '110',
  349. indent_inner_html: true,
  350. comma_first: false,
  351. e4x: true,
  352. indent_empty_lines: true
  353. }
  354. }
  355. // 首字母大小
  356. export function titleCase(str) {
  357. return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
  358. }
  359. // 下划转驼峰
  360. export function camelCase(str) {
  361. return str.replace(/_[a-z]/g, (str1) => str1.substr(-1).toUpperCase())
  362. }
  363. export function isNumberStr(str) {
  364. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
  365. }
  366. // 编码
  367. export function caesarCipher(str) {
  368. return btoa(encrypt(str))
  369. }
  370. // 解码
  371. export function caesarDecipher(str) {
  372. return decrypt(atob(str))
  373. }
  374. //比较值是否相等,不需要比较类型
  375. export const isEqual = (oldValue, nowValue) => {
  376. if (oldValue === null || nowValue === null) {
  377. return oldValue === nowValue
  378. }
  379. if (typeof oldValue === 'object' && typeof nowValue === 'object') {
  380. return JSON.stringify(oldValue) === JSON.stringify(nowValue)
  381. }
  382. return oldValue == nowValue
  383. }
  384. //计算过期时间
  385. export const getExpireDate = (
  386. startDate,
  387. effectivePeriod,
  388. effectivePeriodUnit
  389. ) => {
  390. if (effectivePeriod === 'NA' || effectivePeriodUnit === 'NA') {
  391. return 'NA'
  392. }
  393. const start = moment(startDate)
  394. const unit = effectivePeriodUnit === '天' ? 'days' : 'hours'
  395. const end = start
  396. .add(Number(effectivePeriod), unit)
  397. .format('YYYY-MM-DD HH:mm:ss')
  398. return end
  399. }
  400. export function getuuid() {
  401. return Math.random().toString(36).substring(2) + Date.now().toString(36)
  402. }
  403. // 判断值是否为空
  404. export function isValueEmpty(value) {
  405. if (
  406. value === null ||
  407. value === undefined ||
  408. value === '' ||
  409. value === false
  410. ) {
  411. return true
  412. }
  413. if (typeof value === 'string' && value.trim() === '') {
  414. return true
  415. }
  416. if (Array.isArray(value) && value.length === 0) {
  417. return true
  418. }
  419. if (Object.keys(value).length === 0 && typeof value == 'object') {
  420. return true
  421. }
  422. return false
  423. }
  424. //去重步骤里面的试剂(需要计算总和)和仪器;
  425. export function duplicateResource(sj, yq) {
  426. // 对sj数组根据type和value值去重,并将yl按单位换算后累加
  427. const sjMap = new Map()
  428. // 体积单位转换为基本单位L的倍数
  429. const volumeUnits = {
  430. pL: 1e-12,
  431. nL: 1e-9,
  432. uL: 1e-6,
  433. mL: 1e-3,
  434. L: 1
  435. }
  436. // 质量单位转换为基本单位g的倍数
  437. const massUnits = {
  438. pg: 1e-12,
  439. ng: 1e-9,
  440. ug: 1e-6,
  441. mg: 1e-3,
  442. g: 1,
  443. kg: 1e3
  444. }
  445. for (const item of sj) {
  446. const key = `${item.type}_${item.value}`
  447. console.log(item, 'item')
  448. if (sjMap.has(key)) {
  449. // 如果已存在相同type和value的项,累加yl值
  450. const existingItem = sjMap.get(key)
  451. console.log(existingItem, 'existingItem')
  452. // 根据类型选择合适的单位转换
  453. let currentItemYlInBaseUnit, existingItemYlInBaseUnit
  454. if (item.type === '1') {
  455. // 体积单位转换
  456. const currentItemYl = isNaN(parseFloat(item.yl))
  457. ? 0
  458. : parseFloat(item.yl)
  459. const existingItemYl = isNaN(parseFloat(existingItem.yl))
  460. ? 0
  461. : parseFloat(existingItem.yl)
  462. currentItemYlInBaseUnit = currentItemYl * volumeUnits[item.dw] || 0
  463. existingItemYlInBaseUnit =
  464. existingItemYl * volumeUnits[existingItem.dw] || 0
  465. } else if (item.type === '7') {
  466. // 质量单位转换
  467. const currentItemYl = isNaN(parseFloat(item.yl))
  468. ? 0
  469. : parseFloat(item.yl)
  470. const existingItemYl = isNaN(parseFloat(existingItem.yl))
  471. ? 0
  472. : parseFloat(existingItem.yl)
  473. currentItemYlInBaseUnit = currentItemYl * massUnits[item.dw] || 0
  474. existingItemYlInBaseUnit =
  475. existingItemYl * massUnits[existingItem.dw] || 0
  476. } else {
  477. // 其他类型暂不处理单位转换,直接相加
  478. const currentItemYl = isNaN(parseFloat(item.yl))
  479. ? 0
  480. : parseFloat(item.yl)
  481. const existingItemYl = isNaN(parseFloat(existingItem.yl))
  482. ? 0
  483. : parseFloat(existingItem.yl)
  484. currentItemYlInBaseUnit = currentItemYl || 0
  485. existingItemYlInBaseUnit = existingItemYl || 0
  486. }
  487. // 计算总和
  488. const totalYlInBaseUnit =
  489. currentItemYlInBaseUnit + existingItemYlInBaseUnit
  490. // 更新existingItem的yl值,保持使用第一个项目的单位作为基准单位
  491. if (item.type === '1') {
  492. existingItem.yl = (
  493. totalYlInBaseUnit / volumeUnits[existingItem.dw]
  494. ).toString()
  495. } else if (item.type === '7') {
  496. existingItem.yl = (
  497. totalYlInBaseUnit / massUnits[existingItem.dw]
  498. ).toString()
  499. } else {
  500. existingItem.yl = totalYlInBaseUnit.toString()
  501. }
  502. } else {
  503. // 如果不存在,添加新项
  504. sjMap.set(key, { ...item })
  505. }
  506. }
  507. // 将Map中的值转换回数组
  508. sj.length = 0 // 清空原数组
  509. for (const value of sjMap.values()) {
  510. sj.push(value)
  511. }
  512. // 对yq数组根据value去重
  513. yq = yq.filter(
  514. (item, index, self) =>
  515. self.findIndex((obj) => obj.value === item.value) === index
  516. )
  517. return { sj, yq }
  518. }
  519. //是不是试剂/仪器等弹窗类型
  520. export function isRegent(item, fieldCode = 'type') {
  521. const type = item[fieldCode]
  522. const typeList = [
  523. 'sj',
  524. 'gsp',
  525. 'mix',
  526. 'xj',
  527. 'xb',
  528. 'gyzj',
  529. 'mjy',
  530. 'yq',
  531. 'jcb',
  532. 'qxbd'
  533. ]
  534. return typeList.includes(type)
  535. }
  536. /**
  537. * 估算字符串在 Excel 中的显示宽度简单规则中文字符算2英文字符算1
  538. * @param {string} str 要计算的字符串
  539. * @returns {number} 估算宽度
  540. */
  541. export function getStringWidth(str) {
  542. if (!str) return 0
  543. let width = 0
  544. for (let char of str.toString()) {
  545. // 中文字符范围(可根据需要扩展)
  546. if (/[\u4e00-\u9fa5]/.test(char)) {
  547. width += 2
  548. } else {
  549. width += 1
  550. }
  551. }
  552. return width
  553. }
  554. //根据选项获取默认值,为了
  555. export const getDefaultValueByOptions = (options = []) => {
  556. const arr = []
  557. options.forEach((item) => {
  558. const { children = [], label } = item
  559. //目前只考虑2层,也不考虑label值重复的问题;
  560. if (children.length > 0) {
  561. children.forEach((child) => {
  562. arr.push({ label: child.label, checked: undefined })
  563. })
  564. } else {
  565. arr.push({ label, checked: undefined })
  566. }
  567. })
  568. return arr
  569. }
  570. // 只是更新已填写的表单数据,不触发其他事件
  571. export const justUpdateFilledFormData = () => {
  572. const params = {
  573. type: 'fieldChanged',
  574. newRecord: null,
  575. resourceList: null
  576. }
  577. EventBus.$emit('onModifyRecord', params)
  578. }
  579. export const formatNumberByDigits = (num, digits = 3) => {
  580. return num.toString().padStart(digits, '0')
  581. }