common.js 9.0 KB

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