tools.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. let carmera = uni.requireNativePlugin('ziteng-maskcamera')
  2. let cameraModule = uni.requireNativePlugin("SMUniPlugin-CameraModule")
  3. // 处理数字千位分隔符 num 数值,decimal要保留的小数位数
  4. export const toThousands = (num, decimal) => {
  5. if (decimal) {
  6. num = formatDecimal(num, decimal)
  7. }
  8. return num.toString().replace(/\d+/, function (n) { // 先提取整数部分
  9. return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
  10. return $1 + ','
  11. })
  12. })
  13. }
  14. // 保留decimal位小数(不四舍五入) num 数值,decimal要保留的小数位数
  15. export const formatDecimal = function (num, decimal) {
  16. num = num.toString()
  17. const index = num.indexOf('.')
  18. if (index !== -1) {
  19. num = num.substring(0, decimal + index + 1)
  20. } else {
  21. num = num.substring(0)
  22. }
  23. return parseFloat(num).toFixed(decimal)
  24. }
  25. export function objToUrl(obj) {
  26. let uri = '';
  27. let keys = Object.keys(obj);
  28. keys.forEach(item => {
  29. uri += '&' + item + '=' + obj[item];
  30. });
  31. uri = uri.substr(1);
  32. return uri;
  33. }
  34. // 获取地址栏参数
  35. export function getQueryString(url, name) {
  36. var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)")
  37. var r = url.substr(1).match(reg)
  38. if(r!=null) return unescape(r[2])
  39. return null
  40. }
  41. // 节流函数
  42. export function throttle(fn, gaptime) {
  43. if (gaptime == null || gaptime == undefined) {
  44. gaptime = 200
  45. }
  46. let _lastTime = null
  47. return function() {
  48. let _nowTime = +new Date()
  49. if (_nowTime - _lastTime > gaptime || !_lastTime) {
  50. fn.apply(this, arguments)
  51. _lastTime = _nowTime
  52. }
  53. }
  54. }
  55. //延迟函数
  56. export function delayDel(fn) {
  57. setTimeout(()=>{
  58. fn();
  59. },80)
  60. }
  61. // 图片转Base64,pad 平台
  62. export const imgToBase64 = function (path,callback){
  63. // plus.nativeUI.previewImage([path]);
  64. // return
  65. plus.io.resolveLocalFileSystemURL(path, function (entry) {
  66. // 可通过entry对象操作文件
  67. entry.file(function (file){
  68. var fileReader = new plus.io.FileReader()
  69. fileReader.readAsDataURL(file, 'utf-8')
  70. fileReader.onloadend = function (evt) {
  71. let result = evt.target.result
  72. callback(1,result.split(',')[1])
  73. // remove this file
  74. entry.remove( function ( entry ) {
  75. console.log( "Remove succeeded" );
  76. }, function ( e ) {
  77. console.log( e.message );
  78. });
  79. }
  80. fileReader.onerror = function (e){
  81. callback(0,'文件读取失败')
  82. }
  83. })
  84. }, function (e) {
  85. console.log(JSON.stringify(e))
  86. uni.showToast({icon: 'none',title: 'Resolve file URL failed: ' + e.message})
  87. })
  88. }
  89. // 打开摄像头
  90. export const openCamera = function (type,callback){
  91. let carNumberOptions = {
  92. widthRatio: 0.8,
  93. heightRatio: 0.2,
  94. showText: '请将车牌号码对准框中'
  95. }
  96. let carVinNumberOptions = {
  97. widthRatio: 0.9,
  98. heightRatio: 0.1,
  99. showText: '请将车辆VIN码对准框中'
  100. }
  101. let option = (type == 'searchCar' || type == 'carNumber') ? carNumberOptions : carVinNumberOptions
  102. // 竖屏 false,横屏 true
  103. let isLandscape = false
  104. //安卓摄像头
  105. if(uni.getSystemInfoSync().platform === 'android'){
  106. option.isLandscape = isLandscape
  107. carmera.show(option,function(result){
  108. console.log(result)
  109. if(result.msg != 'backCancel'){
  110. callback(result.data)
  111. }
  112. })
  113. }
  114. // ios 摄像头
  115. if(uni.getSystemInfoSync().platform == 'ios'){
  116. let screenWidth = uni.getSystemInfoSync().screenWidth
  117. let screenHeight = uni.getSystemInfoSync().screenHeight
  118. let [w,h,x,y] = [0,0,0,0]
  119. // 横屏
  120. if(isLandscape){
  121. h = screenWidth*option.widthRatio*1.2
  122. w = screenHeight*option.heightRatio
  123. x = (screenWidth - w)/2
  124. y = (screenHeight - h)/2
  125. }else{
  126. // 竖屏
  127. w = screenWidth*option.widthRatio
  128. h = screenHeight*option.heightRatio
  129. x = (screenWidth - w)/2
  130. y = (screenHeight - h)/2 - 50
  131. }
  132. cameraModule.showCamera({
  133. 'showTitle': option.showText,
  134. 'size': [w, h],
  135. 'orign': [x, y],
  136. 'isLandscape': isLandscape
  137. },
  138. (result) => {
  139. callback('file://'+result)
  140. })
  141. }
  142. }
  143. /**
  144. * @param {*} obj1 对象
  145. * @param {*} obj2 对象
  146. * @description 遍历赋值
  147. */
  148. export const objExtend = (obj1, obj2) => {
  149. for (let a in obj1){
  150. obj2[a] = obj1[a]
  151. }
  152. return obj2
  153. }
  154. // 正则验证车牌,验证通过返回true,不通过返回false
  155. export const isLicensePlate = function (str) {
  156. return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(str)
  157. }
  158. /**
  159. * 校验身份证号合法性
  160. */
  161. export const checkIdNumberValid = (tex) => {
  162. // var tip = '输入的身份证号有误,请检查后重新输入!'
  163. let num = tex
  164. num = num.toUpperCase()
  165. let len = num.length
  166. let re
  167. if (len == 0) return true
  168. // 身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X。
  169. if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))){
  170. return false
  171. }
  172. // 验证前两位地区是否有效
  173. let aCity = {11: '北京',12: '天津',13: '河北',14: '山西',15: '内蒙古',21: '辽宁',22: '吉林',23: '黑龙江',31: '上海',32: '江苏',33: '浙江',
  174. 34: '安徽',35: '福建',36: '江西',37: '山东',41: '河南',42: '湖北',43: '湖南',44: '广东',45: '广西',46: '海南',50: '重庆',51: '四川',
  175. 52: '贵州',53: '云南',54: '西藏',61: '陕西',62: '甘肃',63: '青海',64: '宁夏',65: '新疆',71: '台湾',81: '香港',82: '澳门',91: '国外'}
  176. if (aCity[parseInt(num.substr(0, 2))] == null){
  177. return false
  178. }
  179. // 当身份证为15位时的验证出生日期。
  180. if (len == 15){
  181. re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/)
  182. let arrSplit = num.match(re)
  183. // 检查生日日期是否正确
  184. let dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
  185. let bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]))
  186. if (!bGoodDay){
  187. return false
  188. }
  189. }
  190. // 当身份证号为18位时,校验出生日期和校验位。
  191. if (len == 18){
  192. re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/)
  193. let arrSplit = num.match(re)
  194. // 检查生日日期是否正确
  195. let dtmBirth = new Date(arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
  196. let bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]))
  197. if (!bGoodDay){
  198. return false
  199. } else {
  200. // 检验18位身份证的校验码是否正确。
  201. // 校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
  202. let valnum
  203. let arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  204. let arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
  205. let nTemp = 0
  206. let i
  207. for (i = 0; i < 17; i++){
  208. nTemp += num.substr(i, 1) * arrInt[i]
  209. }
  210. valnum = arrCh[nTemp % 11]
  211. if (valnum != num.substr(17, 1)){
  212. return false
  213. }
  214. }
  215. }
  216. return true
  217. }
  218. // 正则有效手机号码
  219. export const isvalidPhone = function (str) {
  220. const reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
  221. return reg.test(str)
  222. }
  223. // 日期格式化
  224. export const formatSubmitDate = (val, type) => {
  225. if (val == null || val == '' || val == undefined) {
  226. return ''
  227. } else {
  228. let _date = new Date(val)
  229. let _year = _date.getFullYear()
  230. let _montn = (_date.getMonth() + 1) < 10 ? '0' + (_date.getMonth() + 1) : (_date.getMonth() + 1)
  231. let _day = _date.getDate() < 10 ? '0' + _date.getDate() : _date.getDate()
  232. let _hour = _date.getHours() < 10 ? '0' + _date.getHours() : _date.getHours()
  233. let _minutes = _date.getMinutes() < 10 ? '0' + _date.getMinutes() : _date.getMinutes()
  234. let _seconds = _date.getSeconds() < 10 ? '0' + _date.getSeconds() : _date.getSeconds()
  235. if (type == 'minutes') return _year + '-' + _montn + '-' + _day + ' ' + _hour + ':' + _minutes
  236. else if (type == 'seconds') return _year + '-' + _montn + '-' + _day + ' ' + _hour + ':' + _minutes + ':' + _seconds
  237. else return _year + '-' + _montn + '-' + _day
  238. }
  239. }
  240. /**
  241. * //设置应用版本号对应的缓存信息
  242. * @param {Object} currTimeStamp 当前获取的时间戳
  243. */
  244. export const setStorageForAppVersion = function(currTimeStamp){
  245. uni.setStorage({
  246. key: 'tip_version_update_time',
  247. data: currTimeStamp,
  248. success: function () {
  249. console.log('setStorage-success');
  250. }
  251. });
  252. }
  253. /**
  254. * 进行版本型号的比对 以及下载更新请求
  255. * @param {Object} server_version 服务器最新 应用版本号
  256. * @param {Object} curr_version 当前应用版本号
  257. * isQzgx 是否强制更新
  258. * callback 登录
  259. */
  260. export const checkVersionToLoadUpdate = function(newVersion,type,callback){
  261. if(newVersion.version == '2001'||newVersion.version == '2002'){
  262. newVersion.version = 201
  263. }
  264. const curVer = getApp().globalData.version // 当前版本信息
  265. console.log(newVersion,curVer,callback)
  266. if(!newVersion || !curVer){
  267. callback()
  268. return
  269. }
  270. const curr_version = curVer && curVer.version ? curVer.version.replace(/\./g,'') : ''
  271. const server_version = newVersion && newVersion.version ? newVersion.version : '' // 最新版本信息
  272. const isQzgx = newVersion && newVersion.forceUpgrade != 1
  273. let isWifi = plus.networkinfo.getCurrentType()!=3 ? '有新的版本发布,检测到您目前非Wifi连接,' : '有新的版本发布,'
  274. let msg = isWifi + (!isQzgx ? '请立即更新?' : '是否立即更新版本?')
  275. // 下载app并安装
  276. let downloadApp = function(downloadApkUrl){
  277. uni.showLoading({
  278. title: '正在更新中...',
  279. mask: true,
  280. });
  281. var dtask = plus.downloader.createDownload( downloadApkUrl, {}, function ( d, status ) {
  282. // 下载完成
  283. if ( status == 200 ) {
  284. plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename),{},{},function(error){
  285. uni.showToast({
  286. icon: 'none',
  287. title: '安装失败',
  288. duration: 1500
  289. });
  290. })
  291. uni.hideLoading()
  292. } else {
  293. uni.showToast({
  294. icon: 'none',
  295. title: '更新失败',
  296. duration: 1500
  297. });
  298. }
  299. });
  300. dtask.start();
  301. }
  302. // 打开ios 应用市场
  303. let openIosAppSotre = function(downloadUrl){
  304. //在App Store Connect中的App Store下的app信息,可找到appleId
  305. plus.runtime.launchApplication({
  306. action: downloadUrl
  307. }, function(e) {
  308. console.log('Open system default browser failed: ' + e.message);
  309. })
  310. }
  311. console.log(server_version,curr_version)
  312. if(Number(server_version) > Number(curr_version)){
  313. uni.showModal({
  314. title: msg,
  315. content: '更新内容:'+newVersion.upgradeContent,
  316. showCancel: isQzgx,
  317. confirmText:'立即更新',
  318. cancelText:'稍后进行',
  319. success: function (res) {
  320. if (res.confirm) {
  321. // 清空缓存token
  322. let tmp = uni.getStorageSync('lifeData');
  323. tmp = tmp ? tmp : {};
  324. tmp['vuex_token'] = '';
  325. uni.setStorageSync('lifeData', tmp);
  326. if(curVer.platform == 'android'){
  327. //设置 最新版本apk的下载链接
  328. downloadApp(newVersion.attachment);
  329. }else{
  330. openIosAppSotre(newVersion.downloadUrl)
  331. }
  332. } else if (res.cancel) {
  333. console.log('稍后更新');
  334. callback()
  335. }
  336. }
  337. });
  338. uni.hideLoading();
  339. }else{
  340. if(type){
  341. uni.showToast({
  342. icon: 'none',
  343. title: '已是最新版本',
  344. duration: 1500
  345. });
  346. }else{
  347. callback()
  348. }
  349. }
  350. }
  351. // 确认弹框
  352. export const clzConfirm = function(opts){
  353. // #ifndef APP-PLUS
  354. uni.showModal({
  355. title: opts.title,
  356. content: opts.content,
  357. showCancel: opts.showCancel,
  358. confirmText: opts.confirmText || '确定',
  359. cancelText: opts.cancelText || '取消',
  360. success: opts.success,
  361. })
  362. // #endif
  363. // #ifdef APP-PLUS
  364. if(opts.showCancel==false){
  365. if(!opts.buttons){
  366. opts.buttons = ["确定"]
  367. }
  368. }
  369. plus.nativeUI.confirm(
  370. opts.content,
  371. opts.success,
  372. {"title":opts.title,"buttons": opts.buttons || ["确定","取消"]},
  373. )
  374. // #endif
  375. }
  376. // 小数点后两位
  377. export const numberToFixed = function (val, num, max) {
  378. let maxNums = max || 100000000
  379. let _value = val + ''
  380. _value = _value.replace(/[^\d.]/g, '')// 清楚数字和.以外的字数
  381. _value = _value.replace(/^\./g, '')
  382. _value = _value.replace(/\.{2,}/g, '')// 保留第一个,清楚多余的
  383. if (num == 1)_value = _value.replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3')
  384. else if (num == 3)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d).*$/, '$1$2.$3')
  385. else if (num == 4)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3')
  386. else if (num == 5)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d\d\d).*$/, '$1$2.$3')
  387. else if (num == 0)_value = _value.indexOf('.') >= 0 ? _value.split('.')[0] : _value
  388. else _value = _value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
  389. // console.log(_value,maxNums,Number(_value)>Number(maxNums),'_value')
  390. return Number(_value)>Number(maxNums) ? maxNums : _value
  391. }
  392. // 保存图片到阿里云
  393. export const saveImgToAliOss = function(src,callback){
  394. console.log(src,getApp().globalData.baseUrl,'getApp().globalData.baseUrl')
  395. const authorization = getApp().globalData.token
  396. uni.uploadFile({
  397. url: getApp().globalData.baseUrl + 'upload/', //自行修改各自的对应的接口
  398. filePath: src,
  399. name: 'file',
  400. header: {'X-AUTH-TOKEN':authorization},
  401. success: (uploadFileRes) => {
  402. if (uploadFileRes) {
  403. let res = JSON.parse(uploadFileRes.data);
  404. callback(res)
  405. }
  406. uni.showToast({
  407. icon: 'none',
  408. title: uploadFileRes ? '保存图片成功' : '保存图片失败'
  409. })
  410. },
  411. fail:(error) => {
  412. console.log(error)
  413. }
  414. });
  415. }
  416. // 点击消息打开对应的页面
  417. export const openMessagePage = function(data){
  418. // 急送订单
  419. if (data.extras.bizType == 'TEMP_ORDER') {
  420. uni.navigateTo({ url: '/pages/sales/edit?pageType=detail&data='+JSON.stringify({ salesBillSn: data.extras.bizSn }) })
  421. }
  422. // 补货订单
  423. if (data.extras.bizType == 'SHELF_REPLENISH') {
  424. // uni.navigateTo({ url: '/pages/replenishmentManage/replenishmentList?billState=ALL' })
  425. uni.navigateTo({url: '/pages/soldOut/shelfList'})
  426. }
  427. // 货架订单
  428. if (data.extras.bizType == 'SHELF_ORDER') {
  429. uni.navigateTo({ url: '/pages/shelfOrder/orderDetail?pageType=detail&orderBillSn='+data.extras.bizSn })
  430. }
  431. // 货架异常
  432. if (data.extras.bizType == 'SHELF_WARN') {
  433. const shelfName = data.content.split('已经超过')[0]
  434. uni.navigateTo({ url: '/pages/shelfOrder/shelfOrder?bizType=SHELF_WARN&shelfSn='+data.extras.bizSn+'&shelfName='+shelfName })
  435. }
  436. }