common.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import router from '../../router'
  2. import store from '../../store'
  3. import constant from './constant'
  4. const vKey = location.host
  5. export function uid() {
  6. return this.uid()
  7. }
  8. export function bid() {
  9. return this.bid()
  10. }
  11. export default {
  12. // ================================Common Use==============================================
  13. transDate: function(val, pattern) {
  14. if (val) {
  15. const time = new Date()
  16. time.setTime(val)
  17. if (time instanceof Date) {
  18. return this.formatDate((pattern) || 'yyyy-MM-dd', time)
  19. }
  20. }
  21. return ''
  22. },
  23. transDateStr: function(val, pattern) {
  24. if (val) {
  25. const time = new Date(val)
  26. return this.transDate(time, pattern)
  27. }
  28. return ''
  29. },
  30. transServDate: function(val) {
  31. return this.transDate(val, constant.DATE_PATTERN.DATE_TIME_h)
  32. },
  33. transTime(val, pattern) {
  34. if (val) {
  35. const time = new Date();
  36. time.setTime(val);
  37. if (time instanceof Date) {
  38. return this.formatDate(pattern || "yyyy-MM-dd hh:mm:ss", time);
  39. }
  40. }
  41. return "";
  42. },
  43. transMinute(val, pattern) {
  44. if (val) {
  45. const time = new Date();
  46. time.setTime(val);
  47. if (time instanceof Date) {
  48. return this.formatDate(pattern || "yyyy-MM-dd hh:mm:ss", time);
  49. }
  50. }
  51. return "";
  52. },
  53. isArrayFn: function(value) {
  54. if (typeof Array.isArray === 'function') {
  55. return Array.isArray(value)
  56. } else {
  57. return Object.prototype.toString.call(value) === '[object Array]'
  58. }
  59. },
  60. checkLoginStatus: async function(statusCode) {
  61. if (statusCode && statusCode === -401) {
  62. this.logout()
  63. }
  64. },
  65. logout: async function() {
  66. await store.dispatch('user/logout')
  67. const userType = this.currUserType()
  68. if (userType === '2') {
  69. router.push('/bizLogin')
  70. } else {
  71. router.push('/login')
  72. }
  73. },
  74. transDcMap: function(arr) {
  75. const tMap = {}
  76. if (arr) {
  77. arr.forEach(item => {
  78. tMap[item.value] = item.label
  79. })
  80. }
  81. return tMap
  82. },
  83. myBrowser: function() {
  84. const userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
  85. // console.log('userAgent:', userAgent)
  86. const isOpera = userAgent.indexOf('Opera') > -1
  87. if (isOpera) {
  88. return 'Opera'
  89. } // 判断是否Opera浏览器
  90. if (userAgent.indexOf('Firefox') > -1) {
  91. return 'FF'
  92. } // 判断是否Firefox浏览器
  93. if (userAgent.indexOf('Chrome') > -1) {
  94. return 'Chrome'
  95. }
  96. if (userAgent.indexOf('Safari') > -1) {
  97. return 'Safari'
  98. } // 判断是否Safari浏览器
  99. if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
  100. return 'IE'
  101. } // 判断是否IE浏览器
  102. return ''
  103. },
  104. isIE: function() {
  105. if (!!window.ActiveXObject || 'ActiveXObject' in window) { return true } else { return false }
  106. },
  107. uuid: function(len, radix) {
  108. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  109. var uuid = []; var i
  110. radix = radix || chars.length
  111. if (len) {
  112. // Compact form
  113. for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
  114. } else {
  115. // rfc4122, version 4 form
  116. var r
  117. // rfc4122 requires these characters
  118. uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
  119. uuid[14] = '4'
  120. // Fill in random data. At i==19 set the high bits of clock sequence as
  121. // per rfc4122, sec. 4.1.5
  122. for (i = 0; i < 36; i++) {
  123. if (!uuid[i]) {
  124. r = 0 | Math.random() * 16
  125. uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
  126. }
  127. }
  128. }
  129. return uuid.join('')
  130. },
  131. castEval: function(val) {
  132. return val ? eval('(' + val + ')') : val
  133. },
  134. castString: function(val) {
  135. return JSON.stringify(val)
  136. },
  137. getRandomNumberByRange: function(start, end) {
  138. return Math.floor(Math.random() * (end - start) + start)
  139. },
  140. getUrlParam: function(name) {
  141. return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
  142. },
  143. // 金额格式化,整数部分每3位用逗号分隔,支持带有正负号以及小数部分
  144. formatMoney: function(amt) {
  145. if (!amt) return ''
  146. if (amt.length <= 3) {
  147. return amt
  148. }
  149. if (!/^(\+|-)?(\d+)(\.\d+)?$/.test(amt)) {
  150. return amt
  151. }
  152. var a = RegExp.$1; var b = RegExp.$2; var c = RegExp.$3
  153. var re = new RegExp()
  154. re.compile('(\\d)(\\d{3})(,|$)')
  155. while (re.test(b)) {
  156. b = b.replace(re, '$1,$2$3')
  157. }
  158. return a + '' + b + '' + c
  159. },
  160. formatDate: function(fmt, date) { // author: meizz
  161. var o = {
  162. 'M+': date.getMonth() + 1, // 月份
  163. 'd+': date.getDate(), // 日
  164. 'h+': date.getHours(), // 小时
  165. 'm+': date.getMinutes(), // 分
  166. 's+': date.getSeconds(), // 秒
  167. 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
  168. 'S': date.getMilliseconds() // 毫秒
  169. }
  170. if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) }
  171. for (var k in o) {
  172. if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
  173. }
  174. return fmt
  175. },
  176. nvl_money: function(val) {
  177. if (val) {
  178. return '¥' + this.formatMoney(val)
  179. }
  180. return ''
  181. },
  182. nvl_num: function(val) {
  183. return val === 0 ? 0 : val.toFixed(2)
  184. },
  185. hashCode: function(str) {
  186. let hash = 0
  187. if (str.length === 0) return hash
  188. for (let i = 0; i < str.length; i++) {
  189. const char = str.charCodeAt(i)
  190. hash = ((hash << 5) - hash) + char
  191. hash = hash & hash // Convert to 32bit integer
  192. }
  193. return hash
  194. },
  195. parseTime: function(time, pattern) {
  196. if (arguments.length === 0 || !time) {
  197. return null
  198. }
  199. const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  200. let date
  201. if (typeof time === 'object') {
  202. date = time
  203. } else {
  204. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  205. time = parseInt(time)
  206. } else if (typeof time === 'string') {
  207. time = time.replace(new RegExp(/-/gm), '/')
  208. }
  209. if ((typeof time === 'number') && (time.toString().length === 10)) {
  210. time = time * 1000
  211. }
  212. date = new Date(time)
  213. }
  214. const formatObj = {
  215. y: date.getFullYear(),
  216. m: date.getMonth() + 1,
  217. d: date.getDate(),
  218. h: date.getHours(),
  219. i: date.getMinutes(),
  220. s: date.getSeconds(),
  221. a: date.getDay()
  222. }
  223. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  224. let value = formatObj[key]
  225. // Note: getDay() returns 0 on Sunday
  226. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
  227. if (result.length > 0 && value < 10) {
  228. value = '0' + value
  229. }
  230. return value || 0
  231. })
  232. return time_str
  233. },
  234. // ================================System Use==============================================
  235. setUser: function(value) {
  236. localStorage.setItem(this.UserKey(), JSON.stringify(value))
  237. },
  238. currUser: function() {
  239. const userKey = localStorage.getItem(this.UserKey())
  240. if (userKey) {
  241. const user = JSON.parse(userKey || '')
  242. // //console.log('curr user:', user)
  243. if (user) {
  244. return user
  245. }
  246. }
  247. // this.logout()
  248. return null
  249. },
  250. uid: function() {
  251. return this.currUser() ? this.currUser().id : null
  252. },
  253. isAdmin: function() {
  254. return this.uid() === '1'
  255. },
  256. isAdminRole: function() {
  257. if (this.currUser().dataRoles['DATA']) {
  258. return this.currUser().dataRoles['DATA'].includes('ADMIN_DATA')
  259. }
  260. return false
  261. },
  262. setBiz: function(value) {
  263. localStorage.setItem(this.BizKey(), JSON.stringify(value))
  264. },
  265. currBiz: function() {
  266. return JSON.parse(localStorage.getItem(this.BizKey()) || null)
  267. },
  268. bid: function() {
  269. return this.currBiz() ? this.currBiz().id : null
  270. },
  271. setUserType: function(value) {
  272. localStorage.setItem(vKey + '_' + constant.KEY_USER_TYPE, value)
  273. },
  274. currUserType: function() {
  275. return localStorage.getItem(vKey + '_' + constant.KEY_USER_TYPE) || '1'
  276. },
  277. setCode: function(value) {
  278. localStorage.setItem(constant.KEY_CODE, value)
  279. },
  280. currCode: function() {
  281. return localStorage.getItem(constant.KEY_CODE) || null
  282. },
  283. setMenu: function(value) {
  284. localStorage.setItem(this.MenuKey(), JSON.stringify(value))
  285. },
  286. currMenu: function() {
  287. const menuVal = this.getMenuVal()
  288. if (menuVal && menuVal !== 'undefined') {
  289. return JSON.parse(menuVal)
  290. } else {
  291. return []
  292. }
  293. },
  294. getMenuVal: function() {
  295. return localStorage.getItem(this.MenuKey())
  296. },
  297. removeStorage: function(_key) {
  298. localStorage.removeItem(_key)
  299. },
  300. // ================================ Common Key ==============================================
  301. // UserKey: function() {
  302. // return window.location.host + '_' + constant.KEY_USER + this.currUserType()
  303. // },
  304. //
  305. // MenuKey: function() {
  306. // return window.location.host + '_' + constant.KEY_USER + this.currUserType() + '_' + constant.KEY_USER_MENU
  307. // },
  308. UsrPwdKey: function(_usr) {
  309. return this.hashCode(window.location.host + '_' + _usr + '_password')
  310. },
  311. UserKey: function() {
  312. return this.hashCode(window.location.host + '_' + constant.KEY_USER + this.currUserType())
  313. },
  314. BizKey: function() {
  315. return this.hashCode(window.location.host + '_' + constant.KEY_BIZ + this.currUserType())
  316. },
  317. MenuKey: function() {
  318. return this.hashCode(window.location.host + '_' + constant.KEY_USER + this.currUserType() + '_' + constant.KEY_USER_MENU)
  319. },
  320. replaceFileUrl: function(urlPath) {
  321. if (urlPath != null && urlPath !== '') {
  322. urlPath = urlPath.replaceAll('/server/FileController/download/', constant.BASE_URI + '/FileController/download/')
  323. }
  324. return urlPath
  325. },
  326. isValidCoordinate(lng, lat) {
  327. if (!lng || !lat) {
  328. return false
  329. }
  330. if (lng.toString().substring(0, lng.toString().lastIndexOf('.')).length !== 8) {
  331. return false
  332. }
  333. return lat.toString().substring(0, lat.toString().lastIndexOf('.')).length === 7
  334. },
  335. isValidCoordinateBack(lng, lat) {
  336. if (lat === 0 || lng === 0) {
  337. return false
  338. }
  339. // 校验纬度是否在 -90 到 90 之间
  340. if (lat < -90 || lat > 90) {
  341. return false
  342. }
  343. // 校验经度是否在 -180 到 180 之间
  344. return !(lng < -180 || lng > 180)
  345. },
  346. getHoursDifference(date1, date2) {
  347. const timeDiff = Math.abs(date2 - date1)
  348. return Math.floor(timeDiff / (60 * 60 * 1000))
  349. },
  350. transCGCS2000toWGS84(x, y) {
  351. // 大地2000,平面坐标转经纬度,3度带
  352. // 3.1415926535898/180.0
  353. const iPI = 0.0174532925199433
  354. // 3度带
  355. // const zoneWide = 40
  356. // 长半轴
  357. const a = 6378137
  358. // 扁率
  359. const f = 1 / 298.257222101
  360. const projNo = parseInt(x / 1000000)
  361. let longitude0 = projNo * 3
  362. longitude0 = longitude0 * iPI
  363. const X0 = projNo * 1000000 + 500000
  364. const Y0 = 0
  365. const xval = x - X0
  366. const yval = y - Y0
  367. const e2 = 2 * f - f * f
  368. const e1 = (1.0 - Math.sqrt(1 - e2)) / (1.0 + Math.sqrt(1 - e2))
  369. const ee = e2 / (1 - e2)
  370. const M = yval
  371. const u = M / (a * (1 - e2 / 4 - 3 * e2 * e2 / 64 - 5 * e2 * e2 * e2 / 256))
  372. const fai = u + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.sin(2 * u) + (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) * Math.sin(4 * u) + (151 * e1 * e1 * e1 / 96) * Math.sin(6 * u) + (1097 * e1 * e1 * e1 * e1 / 512) * Math.sin(8 * u)
  373. const C = ee * Math.cos(fai) * Math.cos(fai)
  374. const T = Math.tan(fai) * Math.tan(fai)
  375. const NN = a / Math.sqrt(1.0 - e2 * Math.sin(fai) * Math.sin(fai))
  376. const R = a * (1 - e2) / Math.sqrt((1 - e2 * Math.sin(fai) * Math.sin(fai)) * (1 - e2 * Math.sin(fai) * Math.sin(fai)) * (1 - e2 * Math.sin(fai) * Math.sin(fai)))
  377. const D = xval / NN
  378. const longitude1 = longitude0 + (D - (1 + 2 * T + C) * D * D * D / 6 + (5 - 2 * C + 28 * T - 3 * C * C + 8 * ee + 24 * T * T) * D * D * D * D * D / 120) / Math.cos(fai)
  379. const latitude1 = fai - (NN * Math.tan(fai) / R) * (D * D / 2 - (5 + 3 * T + 10 * C - 4 * C * C - 9 * ee) * D * D * D * D / 24 + (61 + 90 * T + 298 * C + 45 * T * T - 256 * ee - 3 * C * C) * D * D * D * D * D * D / 720)
  380. return { lng: longitude1 / iPI, lat: latitude1 / iPI }
  381. },
  382. beforeUploadJustWordExcel(file) {
  383. const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
  384. const whiteList = ['pdf', 'doc', 'docx', 'xls', 'xlsx']
  385. if (whiteList.indexOf(fileSuffix) === -1) {
  386. this.$message.error('上传文件只能是 pdf、doc、docx、xls、xlsx格式')
  387. return false
  388. }
  389. const isLt2M = file.size / 1024 / 1024 < 50
  390. if (!isLt2M) {
  391. this.$message.error('上传文件大小不能超过 5MB')
  392. return false
  393. }
  394. }
  395. }