tools.js 14 KB

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