index.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import { parse } from 'qs';
  2. import { get, isArray, isEmpty, isObject, map, omit, pick } from 'lodash';
  3. import Moment from 'moment';
  4. import Config from '@config/config';
  5. // 遍历tree
  6. let loopTree = ({ data = [], _parent = null, childrenName = 'children', cbk = null }) => {
  7. data.map((item, index) => {
  8. item._index = _parent ? `${_parent._index}.${index}` : `${index}`;
  9. item._parentIndex = _parent && _parent._index || '';
  10. if (cbk) {
  11. cbk(item, _parent)
  12. }
  13. if (!isEmpty(item[childrenName])) {
  14. loopTree({ ...arguments[0], data: item[childrenName], _parent: omit(item, childrenName), childrenName, cbk })
  15. }
  16. })
  17. };
  18. let numberFormat = (n, d = 2, needPrefix = false, prefix = '¥') => {
  19. if (n === undefined || n === null) return '';
  20. let displayPrefix = needPrefix ? prefix : '';
  21. let s = n + '';
  22. if (!d) d = 0;
  23. if (s.indexOf('.') == -1) s += '.';
  24. s += new Array(d + 1).join('0');
  25. if (new RegExp('^(-|\\+)?(\\d+(\\.\\d{0,' + (d + 1) + '})?)\\d*$').test(s)) {
  26. let s = '0' + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true;
  27. if (a == d + 2) {
  28. a = s.match(/\d/g);
  29. if (parseInt(a[a.length - 1]) > 4) {
  30. for (var i = a.length - 2; i >= 0; i--) {
  31. a[i] = parseInt(a[i]) + 1;
  32. if (a[i] == 10) {
  33. a[i] = 0;
  34. b = i != 1;
  35. } else break;
  36. }
  37. }
  38. s = a.join('').replace(new RegExp('(\\d+)(\\d{' + d + '})\\d$'), '$1.$2');
  39. }
  40. if (b) s = s.substr(1);
  41. return displayPrefix + (pm + s).replace(/\.$/, '');
  42. }
  43. return displayPrefix + this;
  44. };
  45. /**
  46. * 在树中找到匹配当前id的层级
  47. *
  48. * @param {*} tree
  49. * @param {*} id
  50. * @twoNam 第二个需要结合筛选的入参
  51. * @returns
  52. */
  53. let findNodeTree = (tree, id, name = 'resourceUrl',c_name,twoNam="")=> {
  54. for (const node of tree) {
  55. const str_ = twoNam ? (get(node,"parentName","") + get(node,twoNam,"")+'@'+get(node, name, '')) : get(node, name, '');
  56. const key = str_;
  57. const children = c_name ? node[c_name] : get(node, 'resourceList', null);
  58. if (key === id) {
  59. return node;
  60. } else if (children) {
  61. const target = findNodeTree(children, id, name,c_name,twoNam);
  62. if (target != null) {
  63. return target;
  64. }
  65. }
  66. }
  67. return null;
  68. };
  69. let queryToObj = () => {
  70. const url = window.location.href;
  71. const result = {};
  72. const urlSplit = url.split('?');
  73. const len = urlSplit.length - 1;
  74. const queryParam = urlSplit[len] || '';
  75. queryParam
  76. .split('&')
  77. .filter(str => str !== '')
  78. .forEach(str => {
  79. const [key, value] = str.split('=');
  80. result[key] = value;
  81. });
  82. return result;
  83. };
  84. class Utils {
  85. static loopTree = loopTree;
  86. static findNodeTree = findNodeTree;
  87. static queryToObj = queryToObj;
  88. //多时区
  89. static numberFormat = numberFormat;
  90. // 从url取值 name可以参数的key,或者多个key的数组
  91. static getQueryString(name) {
  92. let search = window.location.hash.split('?')[1] || '';
  93. let res = search.match(new RegExp(`${name}=(.*?)(&|$)`));
  94. return res ? res[1] : "";
  95. }
  96. /*
  97. * dateString 只支持 2019-05-28 15:11:19 时间格式 或者 1559027246000 时间戳格式
  98. * */
  99. static timeZone(dateString, format = 'YYYY-MM-DD HH:mm:ss') {
  100. let timeObj = {
  101. timeStamp: "", //时间戳
  102. utcTime: "", //utc时间
  103. utcTimeStamp: "", // utc时间戳
  104. timeZone: "", //当前时区
  105. currentZoneTime: "", //当前时区的时间
  106. time: "",//时间戳直接转为时间
  107. };
  108. if (!dateString) return timeObj;
  109. if (dateString.indexOf("-") > -1 && dateString.length == 10) {
  110. dateString += " 00";
  111. }
  112. //如果不开启时区效果, 则取消时区转换功能
  113. // if (!Config.isTimeZone) {
  114. // timeObj.utcTime = dateString;
  115. // timeObj.currentZoneTime = dateString;
  116. // return timeObj;
  117. // }
  118. if (String(dateString).length == 10) dateString = dateString * 1000;
  119. //转为时间戳
  120. timeObj.timeStamp = Date.parse(dateString);
  121. timeObj.utcTime = Moment.utc(timeObj.timeStamp).format(format);
  122. timeObj.timeZone = new Date().getTimezoneOffset() / 60; //获取时区
  123. //当前时区时间等于 UTC时间加上时区偏差
  124. timeObj.currentZoneTime = Moment(dateString).subtract(timeObj.timeZone, 'hour').format(format);
  125. timeObj.time = Moment(dateString).format(format);
  126. return timeObj;
  127. }
  128. // let reg = new RegExp('(^|&)' + name.trim() + '=([^&]*)(&|$)');
  129. // let r = after.trim().match(reg);
  130. // if (r != null) {
  131. // return decodeURIComponent(r[2]);
  132. // } else {
  133. // return null;
  134. // }
  135. // }
  136. /*
  137. * dateString 只支持 2019-05-28 15:11:19 时间格式 或者 1559027246000 时间戳格式
  138. * */
  139. // static timeZone(dateString, format = 'YYYY-MM-DD HH:mm:ss') {
  140. // let timeObj = {
  141. // timeStamp: "", //时间戳
  142. // utcTime: "", //utc时间
  143. // utcTimeStamp: "", // utc时间戳
  144. // timeZone: "", //当前时区
  145. // currentZoneTime: "", //当前时区的时间
  146. // time: "",//时间戳直接转为时间
  147. // };
  148. // if (!dateString) return timeObj;
  149. // if (dateString.indexOf("-") > -1 && dateString.length == 10) {
  150. // dateString += " 00";
  151. // }
  152. // //如果不开启时区效果, 则取消时区转换功能
  153. // if (!Config.isTimeZone) {
  154. // timeObj.utcTime = dateString;
  155. // timeObj.currentZoneTime = dateString;
  156. // return timeObj;
  157. // }
  158. // if (String(dateString).length == 10) dateString = dateString * 1000;
  159. // //转为时间戳
  160. // timeObj.timeStamp = Date.parse(dateString);
  161. // timeObj.utcTime = Moment.utc(timeObj.timeStamp).format(format);
  162. // timeObj.timeZone = new Date().getTimezoneOffset() / 60; //获取时区
  163. // //当前时区时间等于 UTC时间加上时区偏差
  164. // timeObj.currentZoneTime = Moment(dateString).subtract(timeObj.timeZone, 'hour').format(format);
  165. // timeObj.time = Moment(dateString).format(format);
  166. // return timeObj;
  167. // }
  168. /*
  169. * 千分位组件,传入金额,返回千分位数字
  170. * number {number} 需要格式化的数字 默认0
  171. * precision {number} 需要保留的小数位,默认0
  172. * prefix {string} 是否需要加金额前缀,默认false
  173. * */
  174. static numberFormat({ number = 0, precision = 0, prefix = false }) {
  175. let isPlus = true;
  176. if (String(number).indexOf('-') > -1) {
  177. isPlus = false;
  178. number = Number(String(number).replace(/-/g, ''));
  179. }
  180. let displayPrefix = prefix ? prefix : '';
  181. number = String(number).replace(/(^\s*)|(\s*$)/g, "");
  182. if (isNaN(number) || !number) {
  183. return displayPrefix + parseFloat(0).toFixed(precision);
  184. } else {
  185. number = parseFloat(number).toFixed(precision)
  186. }
  187. number = number + '';
  188. if (number) {
  189. let nums = number.split('.');
  190. let num = nums[0].slice(nums[0].length % 3);
  191. let numBegin = nums[0].slice(0, nums[0].length % 3);
  192. number = numBegin + ((numBegin && num) ? ',' : '') + (num ? num.match(/\d{3}/g).join(',') : '') + (nums[1] ? '.' + nums[1] : '')
  193. }
  194. if (!isPlus) {
  195. number = '-' + number;
  196. }
  197. return displayPrefix + number;
  198. }
  199. /**
  200. * 字符串模板转换 ,将数据源对应{键}的值填入str
  201. *
  202. * @param {*} str 字符串
  203. * @param {*} source 数据源
  204. * @param {*} handle 处理函数
  205. * @returns
  206. */
  207. static strFormat(str, source, handle = () => { }) {
  208. if (str instanceof Function) {
  209. return str(source);
  210. } else if (!isObject(source)) {
  211. return str;
  212. }
  213. const data = { ...source };
  214. const r = /{[^}]+}/;
  215. while (r.test(str)) {
  216. const key = str
  217. .match(r)
  218. .toString()
  219. .replace('{', '')
  220. .replace('}', '');
  221. const value = get(data, key, []);
  222. const ids = this.toArray(value).filter(id => id != null);
  223. str = str.replace(r, ids.join(','));
  224. handle(key, value);
  225. }
  226. return str;
  227. }
  228. /**
  229. * 对象转换成数组
  230. * @param {*} source
  231. * @returns
  232. */
  233. static toArray = function (source) {
  234. if (source instanceof Array) {
  235. return source;
  236. } else {
  237. const result = source != null ? [source] : [];
  238. return result;
  239. }
  240. }
  241. }
  242. export default Utils;