baseUtils.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. const NULL_ARR = ['空', '没', '无', '-', '—', 'null', '#N/A']
  2. /*
  3. * isBuy: 是否是立即购买
  4. * event: 触发事件
  5. * $this: 当前对象
  6. * item: 操作对象
  7. * url: 购买跳转的结算页地址
  8. * buyCount: 购买数量,不填则选择起订量
  9. * */
  10. const _buyOrCar = function (isBuy, event, $this, item, url = '/user#/order/pay/', buyCount) {
  11. if (event) event.stopPropagation()
  12. if (!$this.$store.state.option.user.logged) {
  13. $this.$http.get('/login/page', {params: {returnUrl: window.location.href}}).then(response => {
  14. if (response.data) {
  15. window.location.href = response.data.content + '&baseUrl=' + encodeURIComponent(window.location.protocol + '//' + window.location.host + response.data.baseUrl)
  16. }
  17. })
  18. } else {
  19. if (item && !$this.disabledFlag) {
  20. if (isBuy) {
  21. $this.$http.post('/trade/order/buyNow', [{
  22. uuid: item.uuid,
  23. batchCode: item.batchCode,
  24. number: buyCount || item.minBuyQty,
  25. storeid: item.storeid ? item.storeid : item.storeId,
  26. storeUuid: item.storeid ? item.storeid : item.storeId,
  27. currencyName: item.currencyName,
  28. minPackQty: item.minPackQty
  29. }])
  30. .then(response => {
  31. // window.location.href = '/user#/order/pay/' + $this.enidfilter(response.data.orderid)
  32. if (response.data.success) {
  33. if (response.data.message) {
  34. $this.$message({
  35. message: response.data.message,
  36. type: 'success'
  37. })
  38. window.setTimeout(function () {
  39. window.location.href = url + _enidfilter(response.data.data.orderid)
  40. }, 1000)
  41. } else {
  42. window.location.href = url + _enidfilter(response.data.data.orderid)
  43. }
  44. } else {
  45. if (response.data.data && response.data.data.unvailable === 1) {
  46. _setMessage($this, '产品信息已失效,请刷新页面', $this.isMobile, false)
  47. } else {
  48. _setMessage($this, response.data.message, $this.isMobile, false)
  49. }
  50. }
  51. }, err => {
  52. console.log(err)
  53. if (item.minBuyQty > item.reserve) {
  54. _setMessage($this, '商品' + item.code + '的库存已经不满足起订量', $this.isMobile, false)
  55. }
  56. })
  57. } else {
  58. // $this.$store.dispatch('user/addCar', {uuid: item.uuid, batchCode: item.batchCode, number: item.minBuyQty})
  59. $this.$http.post('/trade/cart/add', {
  60. uuid: item.uuid,
  61. batchCode: item.batchCode,
  62. number: buyCount || item.minBuyQty,
  63. storeid: item.storeid ? item.storeid : item.storeId,
  64. storeUuid: item.storeid ? item.storeid : item.storeId,
  65. currencyName: item.currencyName,
  66. minPackQty: item.minPackQty
  67. })
  68. .then(response => {
  69. if (response.data.success) {
  70. if (response.data.message) {
  71. _setMessage($this, '添加购物车成功,但商品信息有更新', $this.isMobile, true)
  72. } else {
  73. _setMessage($this, '添加购物车成功', $this.isMobile, true)
  74. }
  75. } else {
  76. // if (response.data.code === 2) {
  77. // $this.$message.error('库存已不满足起订量')
  78. // } else
  79. if (response.data.message === '该产品已失效') {
  80. _setMessage($this, response.data.message + ',请刷新页面', $this.isMobile, false)
  81. } else {
  82. _setMessage($this, response.data.message, $this.isMobile, false)
  83. }
  84. }
  85. })
  86. }
  87. }
  88. }
  89. // window.location.href = 'user#/order/pay/' + $this.enidfilter($this.buy_info.orderid)
  90. }
  91. const _enidfilter = (str) => {
  92. if (str) {
  93. let encryptStr = '' // 最终返回的加密后的字符串
  94. // 产生三位随机数
  95. let num = ''
  96. for (let i = 0; i < 3; i++) {
  97. num += Math.floor(Math.random() * 10)
  98. }
  99. encryptStr += num // 产生3位随机数
  100. // 16位加密
  101. let tempspit = ''
  102. let strspit = str.toString().toLowerCase()
  103. if (strspit.match(/^[-+]?\d*$/) === null) { // 非整数字符,对每一个字符都转换成16进制,然后拼接
  104. /**
  105. * Unicode汉字、英文字母、数字的unicode范围
  106. *汉字:[0x4e00,0x9fa5](或十进制[19968,40869])
  107. *数字:[0x30,0x39](或十进制[48, 57])
  108. *小写字母:[0x61,0x7a](或十进制[97, 122])
  109. *大写字母:[0x41,0x5a](或十进制[65, 90]
  110. * 'a'的Unicode编码:'&#97;',charCodeAt()的值是97
  111. * '码'的Unicode编码:'\u7801', new String('码').charCodeAt()的值是30721,30721的16进制表示是7801
  112. */
  113. let s = strspit.split('')
  114. for (let i = 0; i < s.length; i++) {
  115. s[i] = s[i].charCodeAt() // 先转换成Unicode编码
  116. s[i] = s[i].toString(16)
  117. // 因为在服务器是每两位当做一个字符进行解析的,所以这里每个字符的Unicode编码范围必须在0——255之间。数字和大小写满足该要求,特殊字符则不一定,如果后续有特殊字符的要求,需要重写编码器和解码器
  118. if (s[i].length === 1) {
  119. s[i] = '0' + s[i]
  120. }
  121. tempspit = tempspit + s[i]
  122. }
  123. tempspit = tempspit + '{' + 1 // 1代表字符
  124. } else { // 数字直接转换成16进制
  125. strspit = parseInt(strspit)
  126. .toString(16)
  127. tempspit = strspit + '{' + 0 // 0代表纯数字
  128. }
  129. let temp = tempspit.split('{') // 对要加密的字符转换成16进制
  130. let numLength = temp[0].length // 转换后的字符长度
  131. numLength = numLength.toString(16) // 字符长度换算成16进制
  132. if (numLength.length === 1) { // 如果是1,补一个0
  133. numLength = '0' + numLength
  134. } else if (numLength.length > 3) { // 转换后的16进制字符长度如果大于2位数,则返回,不支持
  135. return ''
  136. }
  137. encryptStr += numLength
  138. if (temp[1] === '0') {
  139. encryptStr += 0
  140. } else if (temp[1] === '1') {
  141. encryptStr += 1
  142. }
  143. encryptStr += temp[0]
  144. if (encryptStr.length < 20) { // 如果小于20位,补上随机数
  145. // 产生三位随机数
  146. let numtwo = ''
  147. for (let i = 0; i < 20 - encryptStr.length; i++) {
  148. numtwo += Math.floor(Math.random() * 10)
  149. }
  150. let ran = numtwo // 产生3位随机数
  151. encryptStr += ran
  152. }
  153. return encryptStr
  154. }
  155. }
  156. /*
  157. * @str 字符串
  158. * */
  159. const _getRealLen = function (str) {
  160. let len = 0
  161. for (let i = 0; i < str.length; i++) {
  162. if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
  163. len += 2
  164. } else {
  165. len++
  166. }
  167. }
  168. return len
  169. }
  170. /*
  171. * @str 字符串
  172. * @length 需要剪切的字符长度
  173. * */
  174. const _cutOutString = (str, length) => {
  175. for (let i = 1; i <= str.length; i++) {
  176. if (_getRealLen(str.substr(0, i)) > length) {
  177. str = str.substr(0, i - 1)
  178. break
  179. }
  180. }
  181. return str
  182. }
  183. const _spliceStr = (str, length) => {
  184. for (let i = 1; i <= str.length; i++) {
  185. if (_getRealLen(str.substr(0, i)) > length) {
  186. str = str.substr(0, i - 1) + '...'
  187. break
  188. }
  189. }
  190. return str
  191. }
  192. /*
  193. * @date 日期,既可以是Date格式,也可是字符串格式
  194. * @fmt 需要转换的格式,如 'yyyy-MM-dd hh:mm:ss'
  195. * return 转换后的字符串格式的日期
  196. * */
  197. const _formatDate = (date, fmt) => {
  198. if (!date) {
  199. return null
  200. }
  201. // fmt = fmt.replace(/-/g, '/')
  202. if (typeof date === 'string') {
  203. date = new Date(Date.parse(date.replace(/-/g, '/')))
  204. }
  205. let o = {
  206. 'M+': date.getMonth() + 1, // 月份
  207. 'd+': date.getDate(), // 日
  208. 'h+': date.getHours(), // 小时
  209. 'm+': date.getMinutes(), // 分
  210. 's+': date.getSeconds(), // 秒
  211. 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
  212. 'S': date.getMilliseconds() // 毫秒
  213. }
  214. if (/(y+)/.test(fmt)) {
  215. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  216. }
  217. for (let k in o) {
  218. if (new RegExp('(' + k + ')').test(fmt)) {
  219. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  220. }
  221. }
  222. return fmt
  223. }
  224. /*
  225. * @str 传入的字符串
  226. * */
  227. const _checkNullStr = (str) => {
  228. // NULL_ARR.map(s => {
  229. // if (str === s) {
  230. // return false
  231. // }
  232. // })
  233. for (let i = 0; i < NULL_ARR.length; i++) {
  234. if (str === NULL_ARR[i]) {
  235. return false
  236. }
  237. }
  238. return true
  239. }
  240. /*
  241. * @$this 当前上下文
  242. * @enuu 企业uu
  243. * */
  244. const _goLinkUser = ($this, enuu) => {
  245. if ($this.user.logged) {
  246. // $this.$http.get('/basic/enterprise/' + $this.storeInfo.enUU + '/info').then(response => {
  247. // if (response.data.enTel) {
  248. // $this.tel = response.data.enTel
  249. // $this.showLinkBox = true
  250. // } else {
  251. // $this.$http.get('/basic/enterprise/' + response.data.uu + '/admin').then(response => {
  252. // $this.tel = response.data.userTel
  253. // $this.showLinkBox = true
  254. // }, err => {
  255. // $this.$message.error('获取卖家联系方式失败')
  256. // console.log(err)
  257. // })
  258. // }
  259. // $this.showLinkBox = true
  260. // }, err => {
  261. // $this.$message.error('获取卖家联系方式失败')
  262. // console.log(err)
  263. // })
  264. $this.$http.get(`/basic/enterprise/${enuu}/tels`).then(response => {
  265. $this.tel = response.data.data.entel || response.data.data.adminTel
  266. $this.showLinkBox = true
  267. }, err => {
  268. $this.$message.error('获取卖家联系方式失败')
  269. throw err
  270. })
  271. } else {
  272. $this.$router.push(`/auth/login?returnUrl=${window.location.href}`)
  273. }
  274. }
  275. /*
  276. * @str: 传入的字符串
  277. * @s: 需要判断的字符串
  278. * */
  279. const _startWith = (str, s) => {
  280. let reg = new RegExp('^' + s)
  281. return reg.test(str)
  282. }
  283. /*
  284. * @path 文件路径地址
  285. * */
  286. const _judgeIsPdf = (path) => {
  287. if (path) {
  288. return path.slice(path.lastIndexOf('.')).toLowerCase() === '.pdf'
  289. } else {
  290. return false
  291. }
  292. }
  293. /*
  294. * @target 需要拷贝的对象
  295. * */
  296. const _deepCopy = (target) => {
  297. if (typeof target !== 'object') return
  298. // 判断目标类型,来创建返回值
  299. var newObj = target instanceof Array ? [] : {}
  300. for (var item in target) {
  301. // 只复制元素自身的属性,不复制原型链上的
  302. if (target.hasOwnProperty(item)) {
  303. newObj[item] = typeof target[item] === 'object' ? _deepCopy(target[item]) : target[item]
  304. }
  305. }
  306. return newObj
  307. }
  308. const _whichTransitionEvent = () => {
  309. let t
  310. let el = document.createElement('fakeelement')
  311. let transitions = {
  312. transition: 'transitionend',
  313. OTransition: 'oTransitionEnd',
  314. MozTransition: 'transitionend',
  315. WebkitTransition: 'webkitTransitionEnd'
  316. }
  317. for (t in transitions) {
  318. if (el.style[t] !== undefined) {
  319. return transitions[t]
  320. }
  321. }
  322. }
  323. /*
  324. * @str 剪切的字符串
  325. * @len 长度设置
  326. * */
  327. const _filterStringEllipsis = (str, len) => {
  328. return str ? _getRealLen(str) > len ? _cutOutString(str, len) + '...' : str : null
  329. }
  330. /*
  331. * @$this 上下文
  332. * @str 提示信息
  333. * @isMobile 是否移动端
  334. * */
  335. const _setMessage = ($this, str = '系统错误', isMobile, isSuccess = false) => {
  336. if (isMobile) {
  337. $this.setRemindText(str)
  338. } else {
  339. if (isSuccess) {
  340. $this.$message.success(str)
  341. } else {
  342. $this.$message.error(str)
  343. }
  344. }
  345. }
  346. /*
  347. * @$this 上下文
  348. * @url 权限链接
  349. * @callBack 回调
  350. * @isMobile 是否移动端
  351. * */
  352. const _getAuthority = ($this, url, callBack, isMobile) => {
  353. return $this.$http.get('/user/authentication/isauthority', {params: {resUrl: url}}).then(res => {
  354. if (res.data.status === 'fail') {
  355. _setMessage($this, res.data.msg, isMobile)
  356. } else {
  357. callBack.call($this)
  358. }
  359. }, err => {
  360. console.log(err)
  361. _setMessage($this, err.response.data, isMobile)
  362. })
  363. }
  364. // 店铺类型筛选
  365. const _storeTypeFilter = (type) => {
  366. let tmp = ''
  367. switch (type) {
  368. case 'CONSIGNMENT':
  369. tmp = '寄售'
  370. break
  371. case 'DISTRIBUTION':
  372. tmp = '经销'
  373. break
  374. case 'AGENCY':
  375. tmp = '代理'
  376. break
  377. case 'ORIGIN_FACTORY':
  378. tmp = '原厂'
  379. break
  380. }
  381. return tmp
  382. }
  383. const _getPriceByLevel = (prices, number, currency) => {
  384. let prName = currency === 'RMB' ? 'rMBPrice' : 'uSDPrice'
  385. for (let i = 0; i < prices.length; i++) {
  386. if (number >= prices[i].start && number <= prices[i].end) {
  387. return prices[i][prName]
  388. }
  389. }
  390. }
  391. const _exchangeArr = (arr, x, y) => {
  392. let tmp = arr[x]
  393. arr[x] = arr[y]
  394. arr[y] = tmp
  395. }
  396. const _filterDate = (timeStamp, type) => {
  397. if (type === 'day') {
  398. return Math.floor(timeStamp / (1000 * 60 * 60 * 24))
  399. } else if (type === 'hour') {
  400. return Math.floor((timeStamp / (1000 * 60 * 60)) % 24)
  401. } else if (type === 'minute') {
  402. return Math.floor((timeStamp / (1000 * 60)) % 60)
  403. }
  404. }
  405. const _priceFixed = (price) => {
  406. let arr = price.toString().split('.')
  407. let adder = 0
  408. let num = price
  409. if (arr[1] && arr[1].length > 2) {
  410. adder = 0.01
  411. num = Number(arr[0] + '.' + arr[1].substring(0, 2))
  412. }
  413. return Number((num + adder).toFixed(2))
  414. }
  415. const _onFileUpload = ($this, file) => {
  416. if (file && file.size > 3 * 1024 * 1024) {
  417. _setMessage($this, '上传文件不得超过3M', $this.isMobile)
  418. } else {
  419. let param = new FormData()
  420. param.append('file', file, file.name)
  421. param.append('chunk', '0')
  422. let promises = []
  423. if (file.type !== 'application/pdf') {
  424. let config = {
  425. headers: {'Content-Type': 'multipart/form-data'}
  426. }
  427. promises.push($this.$http.post('/api/images', param, config))
  428. } else {
  429. let config = {
  430. headers: {'Content-Type': file.type}
  431. }
  432. promises.push($this.$http.post('/file', param, config))
  433. }
  434. return Promise.all(promises)
  435. }
  436. }
  437. // 排除空格的空字符串
  438. const _isEmptyStr = (str) => {
  439. return !str || !str.trim()
  440. }
  441. /*
  442. * 获取某个时间段去除时分秒的时间戳(目前写死八点)
  443. * @date 默认当天 Date格式
  444. * */
  445. const _getClearDay = (date = new Date()) => {
  446. return new Date(_formatDate(date, 'yyyy-MM-dd')).getTime() - 8 * 60 * 60 * 1000
  447. }
  448. /*
  449. * 获取某个时间段的23:59:59(目前写死0点)
  450. * @date 默认当天 Date格式
  451. * */
  452. const _getFullDay = (date = new Date()) => {
  453. return new Date((typeof date === 'object' ? date.getTime() : date) + 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000)
  454. }
  455. export default {
  456. // 获取字符串字符长度
  457. getRealLen: _getRealLen,
  458. // 根据字符长度剪切字符
  459. cutOutString: _cutOutString,
  460. // 订单号转换
  461. enidfilter: _enidfilter,
  462. // 根据字符长度剪切字符串
  463. spliceStr: _spliceStr,
  464. // 格式化日期,返回字符串
  465. formatDate: _formatDate,
  466. // 检查空字符串或规定状态下空字符
  467. checkNullStr: _checkNullStr,
  468. // 联系卖家
  469. goLinkUser: _goLinkUser,
  470. // 判断字符串开头
  471. startWith: _startWith,
  472. // 根据path文件名来判断文件是否是PDF文件
  473. judgeIsPdf: _judgeIsPdf,
  474. // 深拷贝对象
  475. deepCopy: _deepCopy,
  476. whichTransitionEvent: _whichTransitionEvent,
  477. // 立即购买或加入购物车
  478. buyOrCar: _buyOrCar,
  479. // 截取字符长度并补充省略号
  480. filterStringEllipsis: _filterStringEllipsis,
  481. // 获取url权限
  482. getAuthority: _getAuthority,
  483. // 获得店铺类型中文名
  484. storeTypeFilter: _storeTypeFilter,
  485. // 通过分段数量获取分段价格
  486. getPriceByLevel: _getPriceByLevel,
  487. // 交换数组元素位置
  488. exchangeArr: _exchangeArr,
  489. // 根据时间戳提取天数、时、分
  490. filterDate: _filterDate,
  491. // 计算标准订单金额
  492. priceFixed: _priceFixed,
  493. // 统一通知框
  494. setMessage: _setMessage,
  495. // 文件上传
  496. onFileUpload: _onFileUpload,
  497. isEmptyStr: _isEmptyStr,
  498. // 获取00:00:00的时间
  499. getClearDay: _getClearDay,
  500. // 获取23:59:59的时间
  501. getFullDay: _getFullDay
  502. }