tools.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. import permision from "@/js_sdk/wa-permission/permission.js"
  2. let tools = {}
  3. /**
  4. * 大小判断
  5. * @param a
  6. * @param b
  7. * @returns {number}
  8. */
  9. tools.sortNumber = function (a, b) {
  10. return a - b;
  11. }
  12. /**
  13. * 保留两位小数
  14. * @param num
  15. * @returns {string}
  16. */
  17. tools.twoFloating = function (num) {
  18. // 获取两位小数
  19. let price = "";
  20. price = num * 1;
  21. price = String(price).split(".")[1];
  22. if (price !== undefined && price.length === 1) {
  23. price = `.${price}0`;
  24. } else {
  25. price === undefined ? (price = ".00") : (price = `.${price}`);
  26. }
  27. return price;
  28. }
  29. tools.formatDecimal = function (num, decimal) {
  30. num = num.toString()
  31. let index = num.indexOf('.')
  32. if (index !== -1) {
  33. num = num.substring(0, decimal + index + 1)
  34. } else {
  35. num = num.substring(0)
  36. }
  37. return parseFloat(num).toFixed(decimal)
  38. }
  39. /**
  40. * 错误提示
  41. * @param msg
  42. */
  43. tools.error = function (msg,icon='error') {
  44. uni.showToast({
  45. 'title': msg,
  46. 'icon': icon,
  47. 'mask': true,
  48. 'duration': 1500
  49. })
  50. }
  51. /**
  52. * 成功提示
  53. * @param msg
  54. */
  55. tools.success = function (msg,icon='success') {
  56. uni.showToast({
  57. 'title': msg,
  58. 'icon': icon,
  59. 'mask': true,
  60. 'duration': 1500
  61. })
  62. }
  63. /**
  64. * 显示Loading
  65. */
  66. tools.showLoading = function () {
  67. uni.showLoading({
  68. title: '加载中...',
  69. mask: true
  70. });
  71. }
  72. /**
  73. * 关闭Loading
  74. */
  75. tools.hideLoading = function () {
  76. uni.hideLoading();
  77. }
  78. /**
  79. * 获取时间戳(毫秒)
  80. * @returns {number}
  81. */
  82. tools.getTime = function () {
  83. return new Date().getTime();
  84. }
  85. tools.getCountDays=function (date){
  86. let curDate = new Date(date);
  87. // 获取当前月份
  88. curDate.setDate(32);
  89. // 返回当前月份的天数
  90. return 32-curDate.getDate();
  91. }
  92. /**
  93. * 获取当前年
  94. * @returns {number}
  95. */
  96. tools.getYear=function (){
  97. return new Date().getFullYear()
  98. }
  99. tools.updateVersion = function (sysVersion, appUrl) {
  100. let app_version = plus.runtime.version;
  101. console.log('版本号信息对比------------------------------' + app_version + '---------' + sysVersion)
  102. console.log(app_version < sysVersion)
  103. if (app_version < sysVersion) {
  104. uni.showLoading({
  105. title: '更新中……'
  106. })
  107. uni.downloadFile({//执行下载
  108. url: appUrl, //下载地址
  109. success: (downloadResult) => {//下载成功
  110. uni.hideLoading();
  111. if (downloadResult.statusCode === 200) {
  112. uni.showModal({
  113. title: '',
  114. content: '更新成功,确定现在重启吗?',
  115. confirmText: '重启',
  116. confirmColor: '#EE8F57',
  117. success: function (res) {
  118. if (res.confirm === true) {
  119. plus.runtime.install(//安装
  120. downloadResult.tempFilePath, {
  121. force: true
  122. },
  123. function (res) {
  124. tools.success('更新成功,重启中')
  125. plus.runtime.restart();
  126. }
  127. );
  128. }
  129. }
  130. });
  131. }
  132. }
  133. });
  134. } else {
  135. // tools.success('你已是最新版本')
  136. }
  137. }
  138. /**
  139. * uniapp html图片显示控制
  140. * @param str
  141. * @returns {*}
  142. */
  143. tools.imgDeal = function (str) {
  144. console.log(str)
  145. if(str===null || str===undefined){
  146. return '';
  147. }else {
  148. return str.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;"');
  149. }
  150. }
  151. /**
  152. * 获取平台类型 1:微信,2:支付宝
  153. * @returns {boolean|number}
  154. */
  155. tools.platformType = function () {
  156. let ua = window.navigator.userAgent.toLowerCase();
  157. if (ua.indexOf('micromessenger') != -1) {
  158. return 1;
  159. } else if (ua.indexOf('alipay') != -1) {
  160. return 2;
  161. } else {
  162. return 0;
  163. }
  164. }
  165. /**
  166. * 手机震动
  167. */
  168. tools.vibrate=function (){
  169. console.log('vibrate')
  170. // #ifndef H5
  171. let platform=uni.getSystemInfoSync().platform
  172. // #ifdef APP-PLUS
  173. if (platform === "ios") {
  174. let UIImpactFeedbackGenerator = plus.ios.importClass('UIImpactFeedbackGenerator');
  175. let impact = new UIImpactFeedbackGenerator();
  176. impact.prepare();
  177. impact.init(1);
  178. impact.impactOccurred();
  179. }
  180. if (platform === "android") {
  181. uni.vibrateShort();
  182. }
  183. // #endif
  184. //#endif
  185. }
  186. /**
  187. * 获取权限
  188. */
  189. tools.getAndroidPermission = async function(permissionName) {
  190. let ret = await permision.requestAndroidPermission(permissionName);
  191. console.log(ret)
  192. return ret;
  193. }
  194. /**
  195. * ios权限验证
  196. * @param permissionName
  197. * @returns {Promise<any>}
  198. */
  199. tools.getIosPermission = async function(permissionName) {
  200. let ret = await permision.judgeIosPermission(permissionName);
  201. console.log(ret)
  202. return ret;
  203. }
  204. /**
  205. * 获取开发平台
  206. * @returns {string}
  207. */
  208. tools.getPlatform = function () {
  209. let platForm = undefined;
  210. // #ifdef H5
  211. platForm = 'H5';
  212. //#endif
  213. // #ifdef APP-PLUS
  214. platForm = 'APP';
  215. //#endif
  216. // #ifdef APP-PLUS-NVUE
  217. platForm = 'APP';
  218. //#endif
  219. // #ifdef APP-NVUE
  220. platForm = 'APP';
  221. //#endif
  222. // #ifdef MP-WEIXIN
  223. platForm = 'MP-WEIXIN'; // 小程序
  224. //#endif
  225. // #ifdef MP-ALIPAY
  226. platForm = 'MP-ALIPAY';
  227. //#endif
  228. // #ifdef MP-BAIDU
  229. platForm = 'MP-BAIDU';
  230. //#endif
  231. // #ifdef MP-TOUTIAO
  232. platForm = 'MP-TOUTIAO';
  233. //#endif
  234. // #ifdef MP-LARK
  235. platForm = 'MP-LARK';
  236. //#endif
  237. // #ifdef MP-QQ
  238. platForm = 'MP-QQ';
  239. //#endif
  240. // #ifdef MP-KUAISHOU
  241. platForm = 'MP-KUAISHOU';
  242. //#endif
  243. // #ifdef QUICKAPP-WEBVIEW
  244. platForm = 'QUICKAPP-WEBVIEW';
  245. //#endif
  246. return platForm;
  247. }
  248. tools.leftClick = function () {
  249. let pages = getCurrentPages();
  250. if (pages.length > 1) {
  251. uni.navigateBack({
  252. delta: 1
  253. })
  254. } else {
  255. uni.reLaunch({
  256. url: '/pages/index/index'
  257. });
  258. }
  259. }
  260. tools.getDate = function (date) {
  261. let myDate = new Date();
  262. // let myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
  263. // let myMonth = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
  264. // let myToday = myDate.getDate(); //获取当前日(1-31)
  265. // let myDay = myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
  266. // let myHour = myDate.getHours(); //获取当前小时数(0-23)
  267. // let myMinute = myDate.getMinutes(); //获取当前分钟数(0-59)
  268. // let mySecond = myDate.getSeconds(); //获取当前秒数(0-59)
  269. return myDate.getFullYear() + '-' + (myDate.getMonth() + 1) + '-' + myDate.getDate()
  270. }
  271. tools.getDateArr = function (date) {
  272. let myDate = new Date(date);
  273. let myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
  274. let myMonth = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
  275. let myToday = myDate.getDate(); //获取当前日(1-31)
  276. return [myYear, myMonth>9?myMonth:'0'+myMonth , myToday>9?myToday:'0'+myToday]
  277. }
  278. tools.getRandFileName = function (filePath)
  279. {
  280. let extIndex = filePath.lastIndexOf('.');
  281. let extName = extIndex === -1 ? '' : filePath.substr(extIndex);
  282. return parseInt('' + Date.now() + Math.floor(Math.random() * 900 + 100), 10).toString(36) + extName;
  283. }
  284. /**
  285. * 自定义 获取指定日期到当前日期的 所有年 or 年月
  286. */
  287. tools.getCustomTimeList = (start,end,type)=>{
  288. let timeList = [];
  289. let s = start.split("-");
  290. let e = end.split("-");
  291. let min = new Date()
  292. let max = new Date()
  293. min.setFullYear(s[0], s[1]);
  294. max.setFullYear(e[0], e[1]);
  295. var curr = min;
  296. var str = "";
  297. while (curr <= max) {
  298. var yers = curr.getFullYear();
  299. var month = curr.getMonth();
  300. if(type === 'y-m'){
  301. if (month === 0) {
  302. str = (yers - 1) + "-" + 12;
  303. } else {
  304. str = yers + "-" + (month < 10 ? ("0" + month) : month);
  305. }
  306. timeList.push(str);
  307. curr.setMonth(month + 1);
  308. }else if(type === 'y'){
  309. if (month === 0) {
  310. str = (yers - 1)
  311. } else {
  312. str = yers
  313. }
  314. timeList.push(str);
  315. curr.setMonth(month + 1);
  316. }else{}
  317. }
  318. if(type === 'y-m'){
  319. return timeList.reverse()
  320. }else{
  321. let list = Array.from(new Set(timeList))
  322. return list.reverse()
  323. }
  324. }
  325. // 获取 当前 年-月 配合 getCustomTimeList 使用 获取end
  326. tools.getDateYM = ()=>{
  327. let DATE = new Date()
  328. let Y = DATE.getFullYear()
  329. let M = DATE.getMonth() + 1
  330. return Y + '-' + (M<10?'0'+M:M)
  331. }
  332. /**
  333. * 记录用户登录信息
  334. * @param data
  335. * @param type
  336. */
  337. tools.setLoginData = function (data) {
  338. uni.setStorageSync('user_id', data.user_id)
  339. uni.setStorageSync('token', data.access_token)
  340. uni.setStorageSync('tokenType', data.token_type)
  341. uni.setStorageSync('refreshToken', data.access_token)
  342. uni.setStorageSync('mobile', data.username)
  343. uni.setStorageSync('userId', data.user_id)
  344. tools.success('登陆成功')
  345. // setTimeout(() => {
  346. // if (data.status * 1 === 0) {
  347. // //审核状态跳转至待审核页面
  348. // uni.reLaunch({
  349. // url: '/pages/login/module/await-audit'
  350. // });
  351. // } else {
  352. // uni.reLaunch({
  353. // url: '/pages/index/home'
  354. // });
  355. // }
  356. // }, 1500)
  357. }
  358. tools.addQueryString=function (params) {
  359. let str = '';
  360. for (let Key in params) {
  361. str += Key + '=' + params[Key] + '&';
  362. }
  363. return '?' + str;
  364. //return '?' + str.substr(0, str.length -1); 严谨一些
  365. }
  366. tools.setCosToken=function (data){
  367. uni.setStorageSync('cosToken',data)
  368. }
  369. tools.delCosToken=function (data){
  370. uni.removeStorageSync('cosToken')
  371. }
  372. /**
  373. * 定位经纬度
  374. * @returns {Promise<unknown>}
  375. */
  376. tools.getLocation=async function (){
  377. return new Promise((resolve, reject)=>{
  378. //#ifdef APP-PLUS
  379. let locationData= uni.getStorageSync('locationData')
  380. console.log('locationData:',locationData)
  381. if(locationData){
  382. resolve(locationData);
  383. }else {
  384. console.log('执行获取')
  385. uni.getLocation({
  386. type: 'gcj02',
  387. success:async function (res) {
  388. console.log('当前位置的经度:' + res.longitude);
  389. console.log('当前位置的纬度:' + res.latitude);
  390. resolve({'longitude':res.longitude,'latitude':res.latitude});
  391. },
  392. fail:async function (e) {
  393. console.log(e)
  394. resolve( {'longitude':"121.631691",'latitude':'38.922691'});
  395. }
  396. });
  397. }
  398. //#endif
  399. //#ifdef H5
  400. resolve( {'longitude':"121.631691",'latitude':'38.922691'});
  401. //#endif
  402. })
  403. }
  404. /**
  405. * 计算距离
  406. * @returns {Promise<void>}
  407. */
  408. tools.getDistance=async function (lat1, lng1){
  409. let locationData=await tools.getLocation()
  410. let lat2=locationData.latitude
  411. let lng2=locationData.longitude
  412. let radLat1 = lat1*Math.PI / 180.0;
  413. let radLat2 = lat2*Math.PI / 180.0;
  414. let a = radLat1 - radLat2;
  415. let b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
  416. let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
  417. s = s *6378.137 ;// EARTH_RADIUS;
  418. s = Math.round(s * 10000) / 10000;
  419. return s;
  420. }
  421. /**
  422. * 查看大图
  423. * @param list
  424. * @param index
  425. */
  426. tools.lookBigImg = function (list, index) {
  427. uni.previewImage({
  428. current: index,//当前所点击预览的图片地址
  429. urls: list,//这就是当前行图片数据,注意一定要是数组格式
  430. indicator: 'number',
  431. loop: true
  432. });
  433. }
  434. /**
  435. * 计算年龄
  436. * @param birthYearMonthDay
  437. * @returns {number}
  438. */
  439. tools.getAge=function (birthYearMonthDay) {
  440. birthYearMonthDay=birthYearMonthDay.replace('-','/')
  441. //birthYearMonthDay必须为"1995/6/15"这种字符串格式,不可为"2020-6-15",这种格式在Safari中会报错
  442. const birthDate = new Date(birthYearMonthDay);
  443. const momentDate = new Date();
  444. momentDate.setHours(0, 0, 0, 0); //因为new Date()出来的时间是当前的时分秒。我们需要把时分秒重置为0。使后面时间比较更精确
  445. const thisYearBirthDate = new Date(
  446. momentDate.getFullYear(),
  447. birthDate.getMonth(),
  448. birthDate.getDate()
  449. );
  450. const aDate = thisYearBirthDate - birthDate;
  451. const bDate = momentDate - birthDate;
  452. let tempAge = momentDate.getFullYear() - birthDate.getFullYear();
  453. let age = null;
  454. if (bDate < aDate) {
  455. tempAge = tempAge - 1;
  456. age = tempAge < 0 ? 0 : tempAge;
  457. } else {
  458. age = tempAge;
  459. }
  460. return age;
  461. }
  462. /**
  463. * 获取costoken
  464. * @returns {{expiredTime}|any|undefined}
  465. */
  466. tools.getCosToken=function (){
  467. let cosToken= uni.getStorageSync('cosToken')
  468. if(!cosToken){
  469. return undefined
  470. }
  471. let time=new Date().getTime()
  472. if(cosToken.expiredTime && (cosToken.expiredTime*1000)-time >100000){
  473. return cosToken
  474. }else {
  475. return undefined
  476. }
  477. }
  478. /**
  479. * 封装文件结构
  480. * @param url
  481. * @param type
  482. * @returns {{serverSideEncryption: string, location, type: (string), version: string, hash: string}}
  483. */
  484. tools.setFileObj=function (url,type){
  485. url= url.replace('https://','')
  486. url= url.replace('http://','')
  487. url= url.replace('icoco-1317650740.cos.ap-guangzhou.myqcloud.com/','')
  488. return {
  489. "location":url,
  490. "hash":"abc123",
  491. "version":"1.0",
  492. "type":type===1?"PHOTO":"V",
  493. "serverSideEncryption":"AES256"
  494. }
  495. }
  496. export default tools