tools.js 13 KB

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