tools.js 12 KB

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