ssts-hospital-web-master项目实战记录二十四:项目迁移-核心模块实现(useSystemUtil)
记录时间:2024-02-29
一、useSystemUtil模块实现
utils/system/useCommonUtil.ts
import { hydate, serveWebApi } from '@/common'
// 获取当前格式化时间(毫秒级)
const getNowFormatDateMilliseconds = function () {
const dateStr = hydate(new Date()).format('YYYY-MM-DD HH:mm:ss.SSS')
return dateStr
}
// 获取当前格式化时间(秒级)
const getNowFormatDateSeconds = function () {
return hydate(new Date()).format('YYYY-MM-DD HH:mm:ss')
}
// 获取当前格式化日期
const getNowFormatDateDay = function () {
return hydate(new Date()).format('YYYY-MM-DD')
}
// 16进制转中文
const HexToGB2312 = async function (strHex: string) {
const ret = await serveWebApi(
'/api/System/HexToGB2312',
JSON.stringify({ strHex: strHex })
)
return ret
}
// 中文转16进制
const GB2312ToHex = async function (str: string) {
const ret = await serveWebApi(
'/api/System/GB2312ToHex',
JSON.stringify({ str: str })
)
return ret
}
// 从键值对数组中取值
const getValueFromKeyValueArray = function (
keyValueArray: Array<string>,
key: string
) {
let ret = ''
if (keyValueArray != undefined) {
if (keyValueArray[key] != undefined) {
ret = keyValueArray[key]
}
}
return ret
}
// 从键值对数组中取键
const getKeyFromKeyValueArray = function (
keyValueArray: Array<string>,
value: string
) {
let ret = ''
if (keyValueArray != undefined) {
for (const key in keyValueArray) {
if (keyValueArray[key] == value) {
ret = key
break
}
}
}
return ret
}
// json转xml
const json2xml = function (obj: object) {
//return _json2xml('xml', obj).replace('<xml>', '<?xml version="1.0" encoding="UTF-8" ?>');
return _json2xml('xml', obj).replace('<xml>', '').replace('</xml>', '')
function _json2xml(key: string, obj: object) {
let xml = ''
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; ++i) {
xml += _json2xml(key, obj[i])
}
return xml
} else if (typeof obj === 'object') {
for (const _key in obj) {
xml += _json2xml(_key, obj[_key])
}
return _concat(key, xml)
} else {
return _concat(key, obj)
}
}
function _concat(key: string, item: string) {
return `<${key}>${item}</${key}>`
}
}
export {
getNowFormatDateMilliseconds,
getNowFormatDateSeconds,
getNowFormatDateDay,
HexToGB2312,
GB2312ToHex,
getValueFromKeyValueArray,
getKeyFromKeyValueArray,
json2xml
}
utils/system/useTerminalUtil.ts
import { ServiceTimeConfig } from '@/types'
import { hydate } from '@/common'
// 获取服务时间(为''时,当前时间可用)
const getServiceTimeSpan = (
AMStartTime: string,
AMEndTime: string,
PMStartTime: string,
PMEndTime: string,
NightStartTime: string,
NightEndTime: string
) => {
// 构建时间段数组
const timeArray = [
[AMStartTime, AMEndTime],
[PMStartTime, PMEndTime],
[NightStartTime, NightEndTime]
]
// 检查是否有连续的时间段并合并
if (AMEndTime === PMStartTime) {
timeArray[0][1] = PMEndTime
timeArray.splice(1, 1) // 移除中间的PM开始时间
}
if (PMEndTime === NightStartTime) {
timeArray[1][1] = NightEndTime
timeArray.splice(2, 1) // 移除中间的Night开始时间
}
// 格式化当前时间
const now = hydate(new Date()).format('HH:mm')
// 遍历时间段数组,检查当前时间是否在某个时间段内
let msg = '服务时间:'
for (const [start, end] of timeArray) {
if (now >= start && now <= end) {
msg = '' // 如果在任一时间段内,则重置消息
break
} else {
msg += `[${start}~${end}]` // 如果不在,则添加到消息中
}
}
return msg
}
//获取终端服务时间配置(内部函数)
const getServiceTimeConfig = function (
serviceTimeConfig: ServiceTimeConfig
): string {
const date = new Date()
const day = date.getDay()
const dateStr = hydate(date).format('YYYY-MM-DD')
let isWorkDay = true
if (serviceTimeConfig.IsUseWeekDays === 1) {
const weekDays = serviceTimeConfig.WeekDays.split(',')
isWorkDay = !weekDays.includes(day.toString())
}
if (serviceTimeConfig.IsUseHolidays === 1) {
const holidayDays = serviceTimeConfig.HolidayDays.split(',')
isWorkDay = holidayDays.includes('isWorkDay')
}
let specificWorkDays: Set<string> | undefined
let specificRestDays: Set<string> | undefined
if (serviceTimeConfig.SpecificWorkDays) {
specificWorkDays = new Set(serviceTimeConfig.SpecificWorkDays.split(';'))
isWorkDay = isWorkDay && !specificWorkDays.has(dateStr)
}
if (serviceTimeConfig.SpecificRestDays) {
specificRestDays = new Set(serviceTimeConfig.SpecificRestDays.split(';'))
isWorkDay = isWorkDay || specificRestDays.has(dateStr)
}
let msg = ''
if (!isWorkDay) {
msg = `[${dateStr}]已配置为休息日!`
} else {
const timeStr = hydate(date).format('HH:mm:ss')
const isServiceTime =
(timeStr >= serviceTimeConfig.AMStartTime &&
timeStr <= serviceTimeConfig.AMEndTime) ||
(timeStr >= serviceTimeConfig.PMStartTime &&
timeStr <= serviceTimeConfig.PMEndTime) ||
(timeStr >= serviceTimeConfig.NightStartTime &&
timeStr <= serviceTimeConfig.NightEndTime)
if (!isServiceTime) {
msg = getServiceTimeSpan(
serviceTimeConfig.AMStartTime,
serviceTimeConfig.AMEndTime,
serviceTimeConfig.PMStartTime,
serviceTimeConfig.PMEndTime,
serviceTimeConfig.NightStartTime,
serviceTimeConfig.NightEndTime
)
}
}
return msg
}
export { getServiceTimeSpan, getServiceTimeConfig }
utils/system/useDeviceUtil.ts
// 获取设备英文名称
const getDeviceName = function (
deviceName: string,
dictDeviceNameList: string[]
): string {
return dictDeviceNameList.includes(deviceName)
? dictDeviceNameList[dictDeviceNameList.indexOf(deviceName)]
: ''
}
// 获取设备中文名称
const getDeviceCnName = function (
deviceName: string,
dictDeviceCnNameList: string[]
): string {
return dictDeviceCnNameList.includes(deviceName)
? dictDeviceCnNameList[dictDeviceCnNameList.indexOf(deviceName)]
: ''
}
// 获取设备状态
const getDeviceStatus = function (
deviceName: string,
deviceStatusMappers: any
): string {
return deviceStatusMappers[deviceName]
? deviceStatusMappers[deviceName]()
: ''
}
// 更新设备错误信息
const updateDeviceError = function updateDeviceError(
error: string,
deviceCnName: string,
statusDesc: string
): string {
return error.trim() === ''
? `${deviceCnName}:${statusDesc}`
: `${error}\r\n${deviceCnName}:${statusDesc}`
}
export { getDeviceName, getDeviceCnName, getDeviceStatus, updateDeviceError }
utils/system/useBusinessUtil.ts
import { hydate } from '@/common'
// 根据身份证号获取性别名称
const getSexNameByIdCardNo = function (IdCardNo: string) {
const sexCode = parseInt(
IdCardNo.substring(IdCardNo.length - 2, IdCardNo.length - 1),
10
)
let sexName = ''
if (sexCode % 2 == 1) {
sexName = '男'
} else {
sexName = '女'
}
return sexName
}
// 根据身份证号获取出生日期(Date类型)
const getBirthDateByIdCardNo = function (IdCardNo: string) {
// 15位身份证号码:第7、8位为出生年份(两位数),第9、10位为出生月份,第11、12位代表出生日
// 18位身份证号码:第7、8、9、10位为出生年份(四位数),第11、第12位为出生月份,第13、14位代表出生日期,第17位代表性别,奇数为男,偶数为女。
const len = (IdCardNo + '').length
let strBirthday = ''
if (len == 18) {
// 处理18位的身份证号码从号码中得到生日和性别代码
strBirthday =
IdCardNo.substring(6, 10) +
'/' +
IdCardNo.substring(10, 12) +
'/' +
IdCardNo.substring(12, 14)
}
if (len == 15) {
let birthdayValue = ''
birthdayValue = IdCardNo.charAt(6) + IdCardNo.charAt(7)
if (parseInt(birthdayValue) < 10) {
strBirthday =
'20' +
IdCardNo.substring(6, 8) +
'/' +
IdCardNo.substring(8, 10) +
'/' +
IdCardNo.substring(10, 12)
} else {
strBirthday =
'19' +
IdCardNo.substring(6, 8) +
'/' +
IdCardNo.substring(8, 10) +
'/' +
IdCardNo.substring(10, 12)
}
}
// 时间字符串里,必须是“/”
const birthDate = new Date(strBirthday)
return birthDate
}
// 根据身份证号获取年龄
const getAgeByIdCardNo = function (IdCardNo: string) {
// 15位身份证号码:第7、8位为出生年份(两位数),第9、10位为出生月份,第11、12位代表出生日
// 18位身份证号码:第7、8、9、10位为出生年份(四位数),第11、第12位为出生月份,第13、14位代表出生日期,第17位代表性别,奇数为男,偶数为女。
const len = (IdCardNo + '').length
let strBirthday = ''
if (len == 18) {
// 处理18位的身份证号码从号码中得到生日和性别代码
strBirthday =
IdCardNo.substring(6, 10) +
'/' +
IdCardNo.substring(10, 12) +
'/' +
IdCardNo.substring(12, 14)
}
if (len == 15) {
let birthdayValue = ''
birthdayValue = IdCardNo.charAt(6) + IdCardNo.charAt(7)
if (parseInt(birthdayValue) < 10) {
strBirthday =
'20' +
IdCardNo.substring(6, 8) +
'/' +
IdCardNo.substring(8, 10) +
'/' +
IdCardNo.substring(10, 12)
} else {
strBirthday =
'19' +
IdCardNo.substring(6, 8) +
'/' +
IdCardNo.substring(8, 10) +
'/' +
IdCardNo.substring(10, 12)
}
}
// 时间字符串里,必须是“/”
const birthDate = new Date(strBirthday)
const nowDateTime = new Date()
let age = nowDateTime.getFullYear() - birthDate.getFullYear()
// 再考虑月、天的因素;.getMonth()获取的是从0开始的,这里进行比较,不需要加1
if (
nowDateTime.getMonth() < birthDate.getMonth() ||
(nowDateTime.getMonth() == birthDate.getMonth() &&
nowDateTime.getDate() < birthDate.getDate())
) {
age--
}
return age
}
// 根据出生日期获取年龄
const getAgeByBirthDate = function (strBirthDate: string) {
let age = 0
let birthDate = new Date()
let strBirthday = ''
const nowDateTime = new Date()
if (strBirthDate.indexOf('/') > -1) {
strBirthday = strBirthDate
} else if (strBirthDate.indexOf('-') > -1) {
strBirthday = strBirthDate.replaceAll('-', '/')
} else {
strBirthday =
strBirthDate.substring(0, 4) +
'/' +
strBirthDate.substring(4, 6) +
'/' +
strBirthDate.substring(6, 8)
}
if (strBirthday != '') {
//时间字符串里,必须是“/”
birthDate = new Date(strBirthday)
age = nowDateTime.getFullYear() - birthDate.getFullYear()
//再考虑月、天的因素;.getMonth()获取的是从0开始的,这里进行比较,不需要加1
if (
nowDateTime.getMonth() < birthDate.getMonth() ||
(nowDateTime.getMonth() == birthDate.getMonth() &&
nowDateTime.getDate() < birthDate.getDate())
) {
age--
}
}
return age
}
// 人民币数字金额转大写
const upperMoneys = function (num: string) {
let strOutput = ''
let strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分'
num += '00'
const intPos = num.indexOf('.')
if (intPos >= 0) {
num = num.substring(0, intPos) + num.substring(intPos + 1, intPos + 3)
}
strUnit = strUnit.substr(strUnit.length - num.length)
for (let i = 0; i < num.length; i++) {
const start = parseInt(num.substring(i, i + 1))
strOutput +=
'零壹贰叁肆伍陆柒捌玖'.substring(start, start + 1) +
strUnit.substring(i, i + 1)
}
return strOutput
.replace(/零角零分$/, '整')
.replace(/零[仟佰拾]/g, '零')
.replace(/零{2,}/g, '零')
.replace(/零([亿|万])/g, '$1')
.replace(/零+元/, '元')
.replace(/亿零{0,3}万/, '亿')
.replace(/^元/, '零元')
}
// 设置身份证号中间隐藏
const setIdCardNoHidden = function (
IdCardNo: string,
left: number,
right: number
) {
if (IdCardNo.length == 15 || IdCardNo.length == 18) {
const n = IdCardNo.length - left - right
return `${IdCardNo.substring(0, left)}${new Array(n + 1).join('*')}${IdCardNo.substring(IdCardNo.length - right)}`
}
return IdCardNo
}
// 获取终端交易流水号
const getTerimnalTrace = function (TerminalNo: string) {
return `${hydate(new Date()).format('YYYYMMDDHHmmss')}${TerminalNo}`
}
// 获取适配器结果消息
const getAdapterResultMsg = function (resultCodeMsg: string) {
let resultMsg = ''
if (resultCodeMsg.startsWith('S#') || resultCodeMsg.startsWith('F#')) {
resultMsg = resultCodeMsg.substring(2)
if (resultMsg.indexOf('#') > -1) {
resultMsg = resultMsg.substring(resultMsg.indexOf('#') + 1)
}
} else {
resultMsg = resultCodeMsg
}
return resultMsg
}
// 解析结果(通过resultCodeMsg返回tradeResult、tradeResultMsg、flag)
const parseTradeResult = function (resultCodeMsg: string) {
let tradeResult = -1
let tradeResultMsg = resultCodeMsg
let flag = '2' //未明
if (resultCodeMsg.startsWith('S#')) {
flag = '0'
tradeResult = 0
tradeResultMsg = '交易成功'
} else if (resultCodeMsg.startsWith('F#')) {
flag = '1'
tradeResult = 1
tradeResultMsg = '交易失败'
} else {
flag = '2'
tradeResult = 2
tradeResultMsg = '交易异常'
}
return {
tradeResult: tradeResult,
tradeResultMsg: tradeResultMsg,
flag: flag
}
}
// 获取交易最终消息
const getTradeLastMsg = function (resultCodeMsg: string, refundMsg: string) {
let tradeLastMsg = ''
const result = parseTradeResult(resultCodeMsg)
tradeLastMsg = result['tradeResultMsg']
if (refundMsg != undefined && refundMsg != null && refundMsg != '') {
tradeLastMsg += ',' + refundMsg
}
return tradeLastMsg
}
// 获取业务最终消息
const getBusinessLastMsg = function (resultCodeMsg: string, refundMsg: string) {
let businessLastMsg = getTradeLastMsg(resultCodeMsg, refundMsg)
businessLastMsg += `<br />原因:${getAdapterResultMsg(resultCodeMsg)}`
return businessLastMsg
}
export {
getSexNameByIdCardNo,
getBirthDateByIdCardNo,
getAgeByIdCardNo,
getAgeByBirthDate,
upperMoneys,
setIdCardNoHidden,
getTerimnalTrace,
getAdapterResultMsg,
parseTradeResult,
getTradeLastMsg,
getBusinessLastMsg
}
二、调用示例
test-hook-use-system-util.vue
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useSystemUtil } from '@/utils/system'
const systemUtil = useSystemUtil()
const IdCardNo = ref('620102195603025028')
onMounted(() => {
console.log('onMounted')
})
</script>
<template>
<div>
<p>
getNowFormatDateMilliseconds:
{{ systemUtil.getNowFormatDateMilliseconds() }}
</p>
<p>IdCardNo: {{ IdCardNo }}</p>
<p>SexName: {{ systemUtil.getSexNameByIdCardNo(IdCardNo) }}</p>
<p>Age: {{ systemUtil.getAgeByIdCardNo(IdCardNo) }}</p>
</div>
</template>
<style scoped></style>
@/utils/system
三、运行测试

浙公网安备 33010602011771号