tools.js 14 KB

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