mixin.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. import {isIos, judgeIosPermission, requestAndroidPermission, gotoAppPermissionSetting} from "./permission"
  2. import {cfg, fileUrl, serverUrl} from "./https";
  3. const msg = (title, icon = 'none', duration = 1800, mask = false) => {
  4. //统一提示方便全局修改
  5. if (Boolean(title) === false) {
  6. return;
  7. }
  8. uni.showToast({
  9. title,
  10. duration,
  11. mask,
  12. icon
  13. });
  14. };
  15. const isEmptyOrNull = function (exp) {
  16. return !exp || typeof (exp) == "undefined" || exp.length === 0 || exp == '' || JSON.stringify(exp) == "{}";
  17. };
  18. const fillUrl = function (url) {
  19. if (!url) {
  20. return "";
  21. }
  22. if (url.indexOf("http") === 0) {
  23. return url;
  24. } else {
  25. return fileUrl + url;
  26. }
  27. };
  28. const getData = function (key, callback) {
  29. uni.getStorage({
  30. key: key,
  31. success: function (res) {
  32. if (!!callback) {
  33. callback(null, [res.data]);
  34. }
  35. }
  36. });
  37. };
  38. const formatDateTime = date => {
  39. if (!date) {
  40. return "";
  41. }
  42. if (!date instanceof Number && !date instanceof Date) {
  43. return date;
  44. }
  45. date = new Date(date);
  46. const year = date.getFullYear();
  47. const month = date.getMonth() + 1;
  48. const day = date.getDate();
  49. const hour = date.getHours();
  50. const minute = date.getMinutes();
  51. const second = date.getSeconds();
  52. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  53. };
  54. const formatDate = date => {
  55. if (!date) {
  56. return "";
  57. }
  58. if (!date instanceof Number && !date instanceof Date) {
  59. return date;
  60. }
  61. date = new Date(date);
  62. const year = date.getFullYear();
  63. const month = date.getMonth() + 1;
  64. const day = date.getDate();
  65. const hour = date.getHours();
  66. const minute = date.getMinutes();
  67. const second = date.getSeconds();
  68. return [year, month, day].map(formatNumber).join('-');
  69. };
  70. const formatNumber = n => {
  71. n = n.toString();
  72. return n[1] ? n : '0' + n
  73. };
  74. const fmtMoney = v => {
  75. let value = v || 0;
  76. return (Number(value) / 100).toFixed(2);
  77. };
  78. /**
  79. * 根据key查找数据中对应角标
  80. */
  81. const getDataIndex = (key, data) => {
  82. var value = '';
  83. var i = 0;
  84. while (i < data.length) {
  85. if (key == data[i].key) {
  86. value = i;
  87. break;
  88. } else {
  89. i++;
  90. }
  91. }
  92. return value;
  93. };
  94. const getDictValue = (type, code, dict) => {
  95. if (!dict || !code) {
  96. return "";
  97. }
  98. let dictList = dict[type];
  99. if (!isEmptyOrNull(dictList)) {
  100. for (let i = 0; i < dictList.length; i++) {
  101. if (dictList[i].code == code) {
  102. return dictList[i].value;
  103. }
  104. }
  105. }
  106. return "";
  107. };
  108. const contains = (array, element, key) => {
  109. if (!isEmptyOrNull(array)) {
  110. for (let i = 0; i < array.length; i++) {
  111. if (!key) {
  112. if (array[i] == element) {
  113. return true;
  114. }
  115. } else if (key) {
  116. if (element.constructor != Object && array[i][key] == element) {
  117. return true;
  118. } else if (element.constructor == Object && array[i][key] == element[key]) {
  119. return true;
  120. }
  121. }
  122. }
  123. }
  124. return false;
  125. };
  126. const gm = {
  127. data() {
  128. return {
  129. shareOptions: {}
  130. }
  131. },
  132. onShareAppMessage() {
  133. return {
  134. title: this.shareOptions.title,
  135. path: this.shareOptions.path,
  136. imageUrl: this.shareOptions.imageUrl,
  137. success: function (res) {
  138. console.log("share success", res)
  139. }
  140. }
  141. },
  142. filters: {
  143. fmtUrl(url) {
  144. return fillUrl(url);
  145. },
  146. fmtDate(date) {
  147. return formatDate(date);
  148. },
  149. fmtDateTime(date) {
  150. return formatDateTime(date);
  151. },
  152. fmtMoney(money) {
  153. return fmtMoney(money);
  154. },
  155. fmtDict(code, type) {
  156. var dataList = uni.getStorage("dataList");
  157. return getDictValue(type, code, dataList);
  158. },
  159. fmtHisDate(t) {
  160. if (t === null || t === undefined) {
  161. return '';
  162. }
  163. const date = new Date(t * 1000);
  164. const year = date.getFullYear();
  165. const month = date.getMonth() + 1;
  166. const day = date.getDate();
  167. const hour = date.getHours();
  168. const minute = date.getMinutes();
  169. const today = new Date();
  170. const ty = today.getFullYear();
  171. const tm = today.getMonth() + 1;
  172. const td = today.getDate();
  173. if (year === ty && month === tm && day === td) {
  174. return [hour, minute].map(n => {
  175. n = n.toString();
  176. return n[1] ? n : '0' + n;
  177. }).join(':');
  178. }
  179. return [month, day].map(n => {
  180. n = n.toString();
  181. return n[1] ? n : '0' + n;
  182. }).join('-') + " " + [hour, minute].map(n => {
  183. n = n.toString();
  184. return n[1] ? n : '0' + n;
  185. }).join(':');
  186. },
  187. },
  188. methods: {
  189. toPage(url){
  190. var tabPages =["pages/index/index","pages/category/category","pages/cart/cart","pages/account/center"]
  191. if(tabPages.findIndex(item=>url.indexOf(item)>-1)>-1){
  192. uni.switchTab({url:url});
  193. }else{
  194. uni.navigateTo({url:url});
  195. }
  196. },
  197. copy(obj) {
  198. var newobj = obj.constructor === Array ? [] : {};
  199. if (typeof obj !== 'object') {
  200. return;
  201. }
  202. for (var i in obj) {
  203. newobj[i] = typeof obj[i] === 'object' ? this.copy(obj[i]) : obj[i];
  204. }
  205. return newobj
  206. },
  207. getPrePage(delta=1) {
  208. let pages = getCurrentPages();
  209. pages.forEach(item=>console.log("route--->",item.route))
  210. let prePage = pages[pages.length - (delta+1)];
  211. // #ifdef H5
  212. return prePage;
  213. // #endif
  214. return prePage.$vm;
  215. },
  216. getUrl(url) {
  217. if (url.indexOf("http") === 0) {
  218. return url;
  219. } else {
  220. return serverUrl + url;
  221. }
  222. },
  223. isNull(val) {
  224. return isEmptyOrNull(val);
  225. },
  226. contains(array, element, key) {
  227. return contains(array, element, key);
  228. },
  229. stopEvent(e) {
  230. console.log("stop event")
  231. e.stopPrevent();
  232. },
  233. uploadImages(count, scallback, fcallback) {
  234. let result = [];
  235. this.checkPermission("camera", () => {
  236. this.checkPermission("storage", () => {
  237. uni.chooseImage({
  238. count: count, //默认9
  239. sizeType: ['original', 'compressed'],
  240. sourceType: ['album'],
  241. success: (res) => {
  242. uni.showLoading({title: "图片上传中"});
  243. const files = res.tempFilePaths;
  244. let length = files.length;
  245. for (let i = 0; i < files.length; i++) {
  246. let fp = files[i];
  247. const formData = {
  248. thumb_mode: 1,
  249. 'X-Token': uni.getStorageSync(cfg.key.token) || ""
  250. };
  251. uni.uploadFile({
  252. url: cfg.api.uploadUrl,
  253. filePath: fp,
  254. name: 'file',
  255. formData: formData,
  256. success: (uploadFileRes) => {
  257. result.unshift(JSON.parse(uploadFileRes.data).result.uuid);
  258. },
  259. complete: () => {
  260. length--;
  261. if (length <= 0) {
  262. uni.hideLoading();
  263. setTimeout(() => {
  264. if (scallback) {
  265. console.log(result)
  266. scallback.call(null, result);
  267. }
  268. }, 100)
  269. }
  270. }
  271. });
  272. }
  273. }
  274. });
  275. });
  276. })
  277. },
  278. uploadVideo(callback) {
  279. this.checkPermission("camera", () => {
  280. this.checkPermission("storage", () => {
  281. uni.chooseVideo({
  282. count: 1, //默认9
  283. sourceType: ['camera', 'album'],
  284. maxDuration: 30,
  285. success: (res) => {
  286. if (res.size > 51200000) {
  287. this.$dialog.success("只能上传小于50M的视频!");
  288. return;
  289. }
  290. uni.showLoading({
  291. title: '视频上传中'
  292. });
  293. const formData = {
  294. thumb_mode: 1,
  295. 'X-Token': uni.getStorageSync(cfg.key.token) || ""
  296. };
  297. uni.uploadFile({
  298. url: cfg.api.uploadUrl,
  299. filePath: res.tempFilePath,
  300. name: 'file',
  301. formData: formData,
  302. success: (uploadFileRes) => {
  303. callback(uploadFileRes);
  304. uni.hideLoading();
  305. },
  306. complete: () => {
  307. uni.hideLoading();
  308. }
  309. });
  310. }
  311. });
  312. })
  313. })
  314. },
  315. payRequest(payType, payInfo, scallback, fcallback) {
  316. let _this = this;
  317. //1微信 2-支付宝
  318. if (payType === 1) {
  319. // fcallback.apply();
  320. uni.requestPayment({
  321. provider: 'wxpay',
  322. orderInfo: payInfo.wxpay,
  323. success: function (res) {
  324. scallback.apply();
  325. },
  326. fail: function (err) {
  327. console.log('fail:' + JSON.stringify(err));
  328. fcallback.apply();
  329. }
  330. });
  331. } else if (payType === 2) {
  332. uni.requestPayment({
  333. provider: 'alipay',
  334. orderInfo: payInfo.alipay.orderString,
  335. success: function (res) {
  336. scallback.apply();
  337. },
  338. fail: function (err) {
  339. console.log('fail:' + JSON.stringify(err));
  340. fcallback.apply();
  341. }
  342. });
  343. }
  344. },
  345. getDate(date, type) {
  346. let year = date.getFullYear();
  347. let month = date.getMonth() + 1;
  348. let day = date.getDate();
  349. if (type === 'start') {
  350. year = year - 60;
  351. } else if (type === 'end') {
  352. year = year + 2;
  353. }
  354. month = month > 9 ? month : '0' + month;
  355. day = day > 9 ? day : '0' + day;
  356. return `${year}年${month}月`;
  357. },
  358. getTimestamp(timestamp) {
  359. function zeroize(num) {
  360. return (String(num).length === 1 ? '0' : '') + num;
  361. }
  362. var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
  363. var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
  364. var tmDate = new Date(timestamp); // 参数时间戳转换成的日期对象
  365. var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
  366. if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
  367. return '今天';
  368. } else {
  369. var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
  370. if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
  371. return '昨天';
  372. } else if (curDate.getFullYear() == Y) {
  373. return zeroize(m) + '月' + zeroize(d) + '日 ';
  374. } else {
  375. return Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ';
  376. }
  377. }
  378. },
  379. isPhoneNumber(phone) {
  380. const reg = /^((0\d{2,3}-?\d{7,8})|(1\d{10}))$/; //校验手机号和固定电话
  381. return reg.test(phone);
  382. },
  383. isBankCardNo(bankNo) {
  384. var num = /^\d*$/;
  385. return !(bankNo.length < 16 || bankNo.length > 19 || !num.test(bankNo));
  386. },
  387. throttle(fn, wait = 500, isImmediate = false) {
  388. let flag = true;
  389. if (isImmediate) {
  390. return function () {
  391. if (flag) {
  392. fn.apply(this, arguments);
  393. flag = false;
  394. setTimeout(() => {
  395. flag = true
  396. }, wait)
  397. }
  398. }
  399. }
  400. return function () {
  401. if (flag == true) {
  402. flag = false
  403. setTimeout(() => {
  404. fn.apply(this, arguments)
  405. flag = true
  406. }, wait)
  407. }
  408. }
  409. },
  410. debounce(fn, wait = 500, isImmediate = false) {
  411. let timerId = null;
  412. let flag = true;
  413. if (isImmediate) {
  414. return function () {
  415. clearTimeout(timerId);
  416. if (flag) {
  417. fn.apply(this, arguments);
  418. flag = false
  419. }
  420. timerId = setTimeout(() => {
  421. flag = true
  422. }, wait)
  423. }
  424. }
  425. return function () {
  426. clearTimeout(timerId);
  427. timerId = setTimeout(() => {
  428. fn.apply(this, arguments)
  429. }, wait)
  430. }
  431. },
  432. /**
  433. * APP权限校验 https://ext.dcloud.net.cn/plugin?id=594
  434. * @param permissionId
  435. * @param scallback
  436. * @param fcallback
  437. */
  438. checkPermission(permissionId, scallback, fcallback) {
  439. let _this = this;
  440. //location 位置
  441. // push 推送(限iOS,注意Android上推送并不是一个权限)
  442. // camera 摄像头
  443. // photoLibrary 相册
  444. // record 麦克风
  445. // contact 通讯录
  446. // calendar 日历
  447. // memo 备忘录
  448. //#ifdef APP-PLUS
  449. let msg = "";
  450. if (isIos) {
  451. let ret = judgeIosPermission(permissionId);
  452. if (ret) {
  453. if (scallback) {
  454. scallback.apply();
  455. }
  456. } else {
  457. _this.askToPermission(msg, fcallback);
  458. }
  459. } else {
  460. if (permissionId == 'camera') {
  461. msg = "相机";
  462. permissionId = "android.permission.CAMERA";
  463. }
  464. if (permissionId == 'storage') {
  465. msg = "存储";
  466. permissionId = "android.permission.READ_EXTERNAL_STORAGE";
  467. }
  468. if (permissionId == 'location') {
  469. msg = "定位";
  470. permissionId = "android.permission.ACCESS_FINE_LOCATION";
  471. }
  472. requestAndroidPermission(permissionId).then(res => {
  473. console.log("android permission resp:" + JSON.stringify(res))
  474. if (res == 1) {
  475. if (scallback) {
  476. scallback.apply();
  477. }
  478. } else {
  479. _this.askToPermission(msg, fcallback);
  480. }
  481. })
  482. }
  483. //#endif
  484. //#ifndef APP-PLUS
  485. if (scallback) {
  486. scallback.apply();
  487. }
  488. //#endif
  489. },
  490. askToPermission(msg, fcallback) {
  491. uni.showModal({
  492. content: "您未授予应用" + msg + "相关权限,是否前往APP设置?",
  493. success: ms => {
  494. if (ms.confirm) {
  495. try {
  496. gotoAppPermissionSetting();
  497. } catch (e) {
  498. console.error(e)
  499. }
  500. } else if (ms.cancel) {
  501. //do nothing
  502. if (fcallback) {
  503. fcallback.apply();
  504. }
  505. }
  506. }
  507. });
  508. },
  509. }
  510. };
  511. export {gm, msg};