tools.js 12 KB

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