common.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /**
  2. * 通用js方法封装处理
  3. * Copyright (c) 2019 fs
  4. */
  5. const baseURL = process.env.VUE_APP_BASE_API
  6. export function getAge(strBirthday) {
  7. var returnAge,
  8. strBirthdayArr=strBirthday.split("-"),
  9. birthYear = strBirthdayArr[0],
  10. birthMonth = strBirthdayArr[1],
  11. birthDay = strBirthdayArr[2],
  12. d = new Date(),
  13. nowYear = d.getFullYear(),
  14. nowMonth = d.getMonth() + 1,
  15. nowDay = d.getDate();
  16. if(nowYear == birthYear){
  17. returnAge = 0;//同年 则为0周岁
  18. }
  19. else{
  20. var ageDiff = nowYear - birthYear ; //年之差
  21. if(ageDiff > 0){
  22. if(nowMonth == birthMonth) {
  23. var dayDiff = nowDay - birthDay;//日之差
  24. if(dayDiff < 0) {
  25. returnAge = ageDiff - 1;
  26. }else {
  27. returnAge = ageDiff;
  28. }
  29. }else {
  30. var monthDiff = nowMonth - birthMonth;//月之差
  31. if(monthDiff < 0) {
  32. returnAge = ageDiff - 1;
  33. }
  34. else {
  35. returnAge = ageDiff ;
  36. }
  37. }
  38. }else {
  39. returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
  40. }
  41. }
  42. return returnAge;//返回周岁年龄
  43. }
  44. export function cloneObject(obj) {
  45. if (typeof obj != "object") return;
  46. return JSON.parse(JSON.stringify(obj));
  47. }
  48. // 日期格式化
  49. export function parseTime(time, pattern) {
  50. if (arguments.length === 0 || !time) {
  51. return null
  52. }
  53. const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  54. let date
  55. if (typeof time === 'object') {
  56. date = time
  57. } else {
  58. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  59. time = parseInt(time)
  60. } else if (typeof time === 'string') {
  61. time = time.replace(new RegExp(/-/gm), '/');
  62. }
  63. if ((typeof time === 'number') && (time.toString().length === 10)) {
  64. time = time * 1000
  65. }
  66. date = new Date(time)
  67. }
  68. const formatObj = {
  69. y: date.getFullYear(),
  70. m: date.getMonth() + 1,
  71. d: date.getDate(),
  72. h: date.getHours(),
  73. i: date.getMinutes(),
  74. s: date.getSeconds(),
  75. a: date.getDay()
  76. }
  77. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  78. let value = formatObj[key]
  79. // Note: getDay() returns 0 on Sunday
  80. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
  81. if (result.length > 0 && value < 10) {
  82. value = '0' + value
  83. }
  84. return value || 0
  85. })
  86. return time_str
  87. }
  88. // 表单重置
  89. export function resetForm(refName) {
  90. if (this.$refs[refName]) {
  91. this.$refs[refName].resetFields();
  92. }
  93. }
  94. // 添加日期范围
  95. export function addDateRange(params, dateRange) {
  96. var search = params;
  97. search.beginTime = "";
  98. search.endTime = "";
  99. if (null != dateRange && '' != dateRange) {
  100. search.beginTime = this.dateRange[0];
  101. search.endTime = this.dateRange[1];
  102. }
  103. return search;
  104. }
  105. // 回显数据字典
  106. export function selectDictLabel(datas, value) {
  107. var actions = [];
  108. Object.keys(datas).some((key) => {
  109. if (datas[key].dictValue == ('' + value)) {
  110. actions.push(datas[key].dictLabel);
  111. return true;
  112. }
  113. })
  114. return actions.join('');
  115. }
  116. // 回显数据字典(字符串数组)
  117. export function selectDictLabels(datas, value, separator) {
  118. var actions = [];
  119. var currentSeparator = undefined === separator ? "," : separator;
  120. var temp = value.split(currentSeparator);
  121. Object.keys(value.split(currentSeparator)).some((val) => {
  122. Object.keys(datas).some((key) => {
  123. if (datas[key].dictValue == ('' + temp[val])) {
  124. actions.push(datas[key].dictLabel + currentSeparator);
  125. }
  126. })
  127. })
  128. return actions.join('').substring(0, actions.join('').length - 1);
  129. }
  130. // 通用下载方法
  131. export function download(fileName) {
  132. window.location.href = baseURL + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true;
  133. }
  134. // 字符串格式化(%s )
  135. export function sprintf(str) {
  136. var args = arguments, flag = true, i = 1;
  137. str = str.replace(/%s/g, function () {
  138. var arg = args[i++];
  139. if (typeof arg === 'undefined') {
  140. flag = false;
  141. return '';
  142. }
  143. return arg;
  144. });
  145. return flag ? str : '';
  146. }
  147. // 转换字符串,undefined,null等转化为""
  148. export function praseStrEmpty(str) {
  149. if (!str || str == "undefined" || str == "null") {
  150. return "";
  151. }
  152. return str;
  153. }
  154. /**
  155. * 构造树型结构数据
  156. * @param {*} data 数据源
  157. * @param {*} id id字段 默认 'id'
  158. * @param {*} parentId 父节点字段 默认 'parentId'
  159. * @param {*} children 孩子节点字段 默认 'children'
  160. * @param {*} rootId 根Id 默认 0
  161. */
  162. export function handleTree(data, id, parentId, children, rootId) {
  163. id = id || 'id'
  164. parentId = parentId || 'parentId'
  165. children = children || 'children'
  166. rootId = rootId || Math.min.apply(Math, data.map(item => { return item[parentId] })) || 0
  167. //对源数据深度克隆
  168. const cloneData = JSON.parse(JSON.stringify(data))
  169. //循环所有项
  170. const treeData = cloneData.filter(father => {
  171. let branchArr = cloneData.filter(child => {
  172. //返回每一项的子级数组
  173. return father[id] === child[parentId]
  174. });
  175. branchArr.length > 0 ? father.children = branchArr : '';
  176. //返回第一层
  177. return father[parentId] === rootId;
  178. });
  179. return treeData != '' ? treeData : data;
  180. }
  181. export function dateFormat(fmt, date) {
  182. let ret="";
  183. date=new Date(date);
  184. const opt = {
  185. 'Y+': date.getFullYear().toString(), // 年
  186. 'm+': (date.getMonth() + 1).toString(), // 月
  187. 'd+': date.getDate().toString(), // 日
  188. 'H+': date.getHours().toString(), // 时
  189. 'M+': date.getMinutes().toString(), // 分
  190. 'S+': date.getSeconds().toString() // 秒
  191. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  192. }
  193. for (let k in opt) {
  194. ret = new RegExp('(' + k + ')').exec(fmt)
  195. if (ret) {
  196. fmt = fmt.replace(
  197. ret[1],
  198. ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
  199. )
  200. }
  201. }
  202. return fmt
  203. }
  204. export function formatMoney(s,dot) {
  205. s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";
  206. var l = s.split(".")[0].split("").reverse(),
  207. r = s.split(".")[1];
  208. var t = "";
  209. for(var i = 0; i < l.length; i ++ ) {
  210. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : "");
  211. }
  212. return t.split("").reverse().join("") + "." + r;
  213. }
  214. export function parseArr(str) {
  215. if(str==null||str==undefined||str==""){
  216. return []
  217. }
  218. else{
  219. var strs=str.split(",");
  220. var data=[];
  221. strs.forEach(element => {
  222. data.push(process.env.VUE_APP_BASE_API+element)
  223. });
  224. return data;
  225. }
  226. }
  227. export function parsePost(posts) {
  228. var postNames="";
  229. if (posts!=null&&posts.length>0 ) {
  230. posts.forEach(item => {
  231. postNames+=item.postName+",";
  232. })
  233. return postNames.substring(0,postNames.length-1)
  234. }
  235. return postNames;
  236. }
  237. export function formatDate(datetime) {
  238. var date = new Date(datetime);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
  239. var year = date.getFullYear(),
  240. month = ("0" + (date.getMonth() + 1)).slice(-2),
  241. sdate = ("0" + date.getDate()).slice(-2),
  242. hour = ("0" + date.getHours()).slice(-2),
  243. minute = ("0" + date.getMinutes()).slice(-2),
  244. second = ("0" + date.getSeconds()).slice(-2);
  245. // 拼接
  246. var result = year + "-"+ month +"-"+ sdate +" "+ hour +":"+ minute +":" + second;
  247. // 返回
  248. return result;
  249. }
  250. export function formatTime(timer) {
  251. // let timeStarts = startTime.getTime(); //开始时间,转换成时间戳
  252. // let timeEnds = endTime.getTime(); //结束时间,转换成时间戳
  253. //let timer = endTime - startTime //将时间戳进行相减
  254. let hour = parseInt((timer / 60 / 60 % 24));
  255. let minute = parseInt((timer / 60 % 60));
  256. let second = parseInt((timer % 60));
  257. if(hour>0){
  258. return (hour>10?hour:'0'+hour) + ':' + (minute>10?minute:'0'+minute) + ':' + (second>10?second:'0'+second);
  259. }else if(minute>0){
  260. return (minute>=10?minute:'0'+minute) + ':' + (second>=10?second:'0'+second);
  261. }else if(second>0){
  262. return '00:'+(second>=10?second:'0'+second);
  263. }
  264. }
  265. /**
  266. * 获取日期范围
  267. * @param {number} days - 从今天往前推的天数
  268. * @returns {Array} 返回格式化的日期数组 [开始日期, 结束日期]
  269. * @example
  270. * // 获取最近7天的日期范围
  271. * const dateRange = getDateRange(7);
  272. * // 返回: ["2024-01-01", "2024-01-08"]
  273. */
  274. export function getDateRange(days) {
  275. const today = new Date();
  276. const startDate = new Date();
  277. startDate.setDate(today.getDate() - days);
  278. // 格式化日期为年-月-日格式
  279. const formatDate = (date) => {
  280. const year = date.getFullYear();
  281. const month = String(date.getMonth() + 1).padStart(2, '0');
  282. const day = String(date.getDate()).padStart(2, '0');
  283. return `${year}-${month}-${day}`;
  284. };
  285. return [
  286. formatDate(startDate), // days天前
  287. formatDate(today) // 今天
  288. ];
  289. }
  290. // export function callNumber(mobile){
  291. // var that=this;
  292. // this.callMobile(mobile).then(response => {
  293. // if(response.code==200){
  294. // // var logs=response.logs;
  295. // // that.$confirm('正在呼叫'+mobile, '提示', {
  296. // // confirmButtonText: '挂断',
  297. // // cancelButtonText: '关闭',
  298. // // distinguishCancelAndClose:false,
  299. // // closeOnClickModal:false,
  300. // // showClose:false
  301. // // }).then(() => {
  302. // // //挂断
  303. // // console.log(1)
  304. // // console.log(logs)
  305. // // that.callOffMobile(logs.voiceId).then(response => {})
  306. // // }).catch(() => {
  307. // // });
  308. // that.$notify.success({
  309. // title: '正在呼叫'+mobile,
  310. // showClose: false
  311. // });
  312. // }
  313. // else{
  314. // that.$notify.error({
  315. // title: '通话',
  316. // showClose: false
  317. // });
  318. // }
  319. // });
  320. // }