ruoyi.js 15 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
import _ from 'lodash'
import dayjs from 'dayjs'
import { ElMessageBox } from 'element-plus'

/**
 * 通用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) {
  const 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; var flag = true; var 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) {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }

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

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

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

  for (const 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 (const 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') {
            const params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}


// 返回项目路径
export function getNormalPath(p) {
  if (p.length === 0 || !p || p == 'undefined') {
    return p
  };
  const res = p.replace('//', '/')
  if (res[res.length - 1] === '/') {
    return res.slice(0, res.length - 1)
  }
  return res
}

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


export function szToHz(num) {
  const hzArr = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
  return hzArr[parseInt(num)]
}

// 金额数字转大写
export function digitUppercase(price) {
  if (price === null || price === undefined) {
    return
  }

  const fraction = ['角', '分']
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  let num = Math.abs(price)
  let s = ''
  fraction.forEach((item, index) => {
    s += (digit[Math.floor(num * 10 * (10 ** index)) % 10] + item).replace(/零./, '')
  })
  s = s || '整'
  num = Math.floor(num)
  for (let i = 0; i < unit[0].length && num > 0; i += 1) {
    let p = ''
    for (let j = 0; j < unit[1].length && num > 0; j += 1) {
      p = digit[num % 10] + unit[1][j] + p
      num = Math.floor(num / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }

  return s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
}

// export function fillImgUrl(url, prefix) {
//   prefix = prefix ? import.meta.env.VITE_APP_BASE_API + '/' + prefix : import.meta.env.VITE_APP_BASE_API
//   if (!url) {
//     return url
//   } else if (url.indexOf('data:') > -1) {
//     return url
//   } else if (url.indexOf('http') > -1) {
//     return url
//   } else {
//     if (url.indexOf('profile') > -1) {
//       return url
//     } else if (url.indexOf('/') == 0) {
//       return prefix + url
//     } else {
//       return prefix + '/' + url
//     }
//   }
// }


export function fillImgUrl(url, prefix) {
  if (!url) return url
  const baseAPI = import.meta.env.VITE_APP_BASE_API || ''
  const trimmedUrl = url.trim()
  // 处理 msr: 特殊格式
  if (trimmedUrl.startsWith('msr:')) {
    // const fileName = trimmedUrl.substring(4) // 去掉 'msr:'
    return `${baseAPI}/fileServer/download?file=${trimmedUrl}&downFlag=0`
  }
  // 完整URL直接返回
  if (/^(data:|https?:\/\/)|profile/.test(trimmedUrl)) {
    return trimmedUrl
  }
  // 普通路径拼接
  const finalPrefix = prefix ? `${baseAPI}/${prefix}` : baseAPI
  if (!finalPrefix) return trimmedUrl

  const path = trimmedUrl.startsWith('/') ? trimmedUrl : `/${trimmedUrl}`
  return finalPrefix + path
}

export function downloadFile(url, prefix) {
  // prefix = prefix ? import.meta.env.VITE_APP_BASE_API + '/' + prefix : import.meta.env.VITE_APP_BASE_API
  // if (!filePath) {
  //   return filePath
  // } else if (filePath.indexOf('http') > -1) {
  //   return filePath
  // } else {
  //   return `${prefix}/upload/getFile?fileUrl=${encodeURIComponent(filePath)}`
  // }

  if (!url) return url
  const baseAPI = import.meta.env.VITE_APP_BASE_API || ''
  const trimmedUrl = url.trim()
  // 处理 msr: 特殊格式
  if (trimmedUrl.startsWith('msr:')) {
    // const fileName = trimmedUrl.substring(4) // 去掉 'msr:'
    return `${baseAPI}/fileServer/download?file=${trimmedUrl}&downFlag=1`
  }
  // 完整URL直接返回
  if (/^(data:|https?:\/\/)|profile/.test(trimmedUrl)) {
    return trimmedUrl
  }
  // 普通路径拼接
  const finalPrefix = prefix ? `${baseAPI}/${prefix}` : baseAPI
  if (!finalPrefix) return trimmedUrl

  const path = trimmedUrl.startsWith('/') ? trimmedUrl : `/${trimmedUrl}`
  return finalPrefix + path
}

export function setIdToString(list, ...idName) {
  if (idName.length === 0) {
    idName = ['id']
  }
  _.each(list, (l) => {
    _.each(idName, (n) => {
      l[n] += ''
    })
    if (l.children && l.children.length > 0) {
      setIdToString(l.children)
    }
  })
}

export function idcFilter(val) {
  switch (val) {
    case '0':
      return '身份证'
    case '1':
      return '来往大陆(内地)通行证'
    case '2':
      return '中国护照'
    case '3':
      return '护照'
    case '4':
      return '其它'
    case '5':
      return '香港身份证'
    case '6':
      return '往来港澳台通行证识别'
  }
}

export const idcTypeList = [
  { label: '身份证', value: '0' },
  { label: '来往大陆(内地)通行证 ', value: '1' },
  // { label: '中国护照', value: '2' },
  { label: '护照', value: '3' },
  // { label: '其它', value: '4' },
  { label: '香港身份证', value: '5' }
  // { label: '往来港澳台通行证识别', value: '6' }
]

// 判断用户是否年满16岁
export function isOver16(userBirthDate) {
  // 获取当前日期
  const currentDate = new Date()

  // 将用户出生日期字符串转换为日期对象
  // const birthDate =new Date(userBirthDate)
  const birthDate = dayjs(userBirthDate).$d

  // 计算用户年龄
  let age = currentDate.getFullYear() - birthDate.getFullYear()
  // 获取当前月份和日期
  const currentMonth = currentDate.getMonth()
  const currentDay = currentDate.getDate()

  // 获取用户出生月份和日期
  const birthMonth = birthDate.getMonth()
  const birthDay = birthDate.getDate()

  // 如果当前月份小于出生月份,或者当前月份等于出生月份但当前日期小于出生日期,则年龄减1
  if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
    age--
  }

  // 判断用户是否年满16周岁
  return age >= 16
}

// 当天日最后秒
export function dateEnd(date) {
  if (date) return dayjs(date).endOf('day').format('YYYY-MM-DD HH:mm:ss')
}

// 身份证正则
export function idcCodeCheck(idcCode) {
  const pattern = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/
  return pattern.test(idcCode) && idcCode.length == 18
}

export async function customMessageBox(msg) {
  const imgBase = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAABDCAYAAADHyrhzAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFOUlEQVR4nO3ceaycUxjH8U/H0uumFEGCoogiUo3lD/yj91pjDUWIPUIiBBGJIIIm+ENsiUgIQlRbUlJrNFoVeyJt7EtL7SFqbWi5tNcfzx0zpnfuO8t53xm3vskk827nPPd3zznvc87znBmzcK+9FEgvdsOO2AabY6Oha39gJX7CN/gUSzBQlHHr51z+pugb+vRjd5SaeP5PvI1XMA8LsSqtiRXG5NAyNsAROA1HY2zCsn/Bw3hQCDSYsOym/ktZ9OIS0bzn4gRphYDxOA8v4S2cLOHfkKKgDXGpEOFWbJugzEaYjFl4D9NSFNiuGH14Fzdjq/bNaYndMAfPY1I7BbUqxljcjgXYpR0DEtKHN0U3aolWxNgJL+MijGm14pzYCHfhEWzS7MPNirE/3sC+zVZUMCfiVUxs5qFm/IyjxGutt5kKMlgi/IcfxMB7pHDGUrCHEORgvN/IA42KcZxoeqmctN9xMe7BmqrzPbgGl0vTBbfGC5iqAUEa6Sb9mC2dEIPCP7jbv4UgRLoCNySqC7YUrW9C1o1ZYkzCY8KXSMUcPJ5xz3R8lrDOCXhGRhcfSYwe0SLGJzSKECOLATyRuN7JolvWZSQxbkEeU9qvG7zvyxzqPgVn1btYT4w+nJ+DMcRMthE2z6n+29SZMgwnxga4MydD4JAG7zssp/rHiznUWgwnxqXC38+Lc7Frxj3TsHeONpyIA2tP1oqxqXjH50kvnsWeda4fgQdytgFurD1R6ztciM0KMGSicOtnCB/gR+EgHY9jFTPn2V94p/PLJ6pXunrECL5FAYZ0C/NwePmguptMs24JQQzmO5cPqsU4u3hbOk4JZ1QfEKtUUzthTRdwcvlLWYyDsF4HDBnEYjFv+LAD9RPzr4lUxOjvgBHLxCLRPmIdY3ccI8IBRdNPRYy+gitfKTzMxTXnnxTxlqKZSoixsaoRtSBm4eM6154SK+5FMoUQo63l9RZZlHG9tsXkzSSUOiVG1rjwWyFWVOjBdiXFRcC6nQkljOu0FV3CuP/FqDCuJG0c5L/M2JLEOQ7/ZUr4udNGdAm/lsTCyv+wvITPO21Fl/BFCR912oouYAW+LmGptWOe6xpLiQH0dw2G7Ecxi6hM4Z/voCHdwEIqYizooCGdZtBQYyiL8YLoLusii/AdFTFWiEWVbiG3lOhhmFX+Uh0quK9AA7IoKnl+QKRe499izFN/KW60MhvLywfVYqzBTYWb0zkGRULOP9RG4e8XOeDrAo+KZPx/qBVjAFcWZk7n+BNX154cLllltqow/SjlNsNE8OrldF0gtkmNRpbhuuEu1BNjCS7LzZzOsRpnqhOKGCn18Q4xyORB1g6lvPbOXSt2RAxLVobwOYamt4nJCmfmsYdlLq4f6YYsMX4RCWffJjKozOnqr8pPUpValIjXcaqMxe9GEuk/xqGqPLUEbC8i7rXbKSaLOVLKjX6Lhbgrs25stG++I/Imn5MuHNmPT0Qf/gHbYT9pd1S+KnI/Gsr5aGag+kAY+7T6OZzN0iPSD/NgjsjXangG3Ox/4SscgIeafK5I/sJVOEmTSwGtNMnfRHbN6WLfejexVHTnG7QQKWynf84QI//9rVScmFViO9dkMU60RLuD1fcif/QAvNhmWa2wBjOFCNO1OYVINXK/LprngeKVuTpRufVYhXuFCKeKt1LbpHZ7Xxz6bC/GlJOke/OswWtizXKmHMarPH4yopatVX5DY4oYZxrZ97ZcTBjfEr7IfGkdv7UoQozh2Ao7iK1X5W3aK8Sb6lcRDC/8TfU3QSXp+jcMjMIAAAAASUVORK5CYII='

  const htmlMessage = `
    <div style="padding: 10px 0;">
      <div style="display:flex;flex-direction: column;align-items: center; margin-bottom: 12px;">
        <img src="${imgBase}">
        <span style="font-weight: 600; color: #333;">提示</span>
      </div>
      <div style="color: #666; line-height: 1.6;">
       ${msg}
      </div>
    </div>
  `

  ElMessageBox.alert(htmlMessage, '', {
    confirmButtonText: '确定',
    type: '',
    dangerouslyUseHTMLString: true,
    closeOnClickModal: false,
    closeOnPressEscape: false,
    center: true,
    customClass: 'custom-msg-box'
  })

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' || e.keyCode === 13) {
      ElMessageBox.close()
      document.removeEventListener('keydown', handleKeyDown)
      e.preventDefault()
    }
  }

  document.addEventListener('keydown', handleKeyDown)
}

/* 判断时间是否在一个月内*/
export function isWithinCalendarMonth(time) {
  const target = new Date(time)
  if (isNaN(target.getTime())) throw new Error('无效时间')

  const now = new Date()
  const nextMonth = new Date(now)
  nextMonth.setMonth(now.getMonth() + 1)
  const lastMonth = new Date(now)
  lastMonth.setMonth(now.getMonth() - 1)

  return target >= lastMonth && target < nextMonth
}