| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538 |
- import {isIos, judgeIosPermission, requestAndroidPermission, gotoAppPermissionSetting} from "./permission"
- import {cfg, fileUrl, serverUrl} from "./https";
- const msg = (title, icon = 'none', duration = 1800, mask = false) => {
- //统一提示方便全局修改
- if (Boolean(title) === false) {
- return;
- }
- uni.showToast({
- title,
- duration,
- mask,
- icon
- });
- };
- const isEmptyOrNull = function (exp) {
- return !exp || typeof (exp) == "undefined" || exp.length === 0 || exp == '' || JSON.stringify(exp) == "{}";
- };
- const fillUrl = function (url) {
- if (!url) {
- return "";
- }
- if (url.indexOf("http") === 0) {
- return url;
- } else {
- return fileUrl + url;
- }
- };
- const getData = function (key, callback) {
- uni.getStorage({
- key: key,
- success: function (res) {
- if (!!callback) {
- callback(null, [res.data]);
- }
- }
- });
- };
- const formatDateTime = date => {
- if (!date) {
- return "";
- }
- if (!date instanceof Number && !date instanceof Date) {
- return date;
- }
- date = new Date(date);
- const year = date.getFullYear();
- const month = date.getMonth() + 1;
- const day = date.getDate();
- const hour = date.getHours();
- const minute = date.getMinutes();
- const second = date.getSeconds();
- return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
- };
- const formatDate = date => {
- if (!date) {
- return "";
- }
- if (!date instanceof Number && !date instanceof Date) {
- return date;
- }
- date = new Date(date);
- const year = date.getFullYear();
- const month = date.getMonth() + 1;
- const day = date.getDate();
- const hour = date.getHours();
- const minute = date.getMinutes();
- const second = date.getSeconds();
- return [year, month, day].map(formatNumber).join('-');
- };
- const formatNumber = n => {
- n = n.toString();
- return n[1] ? n : '0' + n
- };
- const fmtMoney = v => {
- let value = v || 0;
- return (Number(value) / 100).toFixed(2);
- };
- /**
- * 根据key查找数据中对应角标
- */
- const getDataIndex = (key, data) => {
- var value = '';
- var i = 0;
- while (i < data.length) {
- if (key == data[i].key) {
- value = i;
- break;
- } else {
- i++;
- }
- }
- return value;
- };
- const getDictValue = (type, code, dict) => {
- if (!dict || !code) {
- return "";
- }
- let dictList = dict[type];
- if (!isEmptyOrNull(dictList)) {
- for (let i = 0; i < dictList.length; i++) {
- if (dictList[i].code == code) {
- return dictList[i].value;
- }
- }
- }
- return "";
- };
- const contains = (array, element, key) => {
- if (!isEmptyOrNull(array)) {
- for (let i = 0; i < array.length; i++) {
- if (!key) {
- if (array[i] == element) {
- return true;
- }
- } else if (key) {
- if (element.constructor != Object && array[i][key] == element) {
- return true;
- } else if (element.constructor == Object && array[i][key] == element[key]) {
- return true;
- }
- }
- }
- }
- return false;
- };
- const gm = {
- data() {
- return {
- shareOptions: {}
- }
- },
- onShareAppMessage() {
- return {
- title: this.shareOptions.title,
- path: this.shareOptions.path,
- imageUrl: this.shareOptions.imageUrl,
- success: function (res) {
- console.log("share success", res)
- }
- }
- },
- filters: {
- fmtUrl(url) {
- return fillUrl(url);
- },
- fmtDate(date) {
- return formatDate(date);
- },
- fmtDateTime(date) {
- return formatDateTime(date);
- },
- fmtMoney(money) {
- return fmtMoney(money);
- },
- fmtDict(code, type) {
- var dataList = uni.getStorage("dataList");
- return getDictValue(type, code, dataList);
- },
- fmtHisDate(t) {
- if (t === null || t === undefined) {
- return '';
- }
- const date = new Date(t * 1000);
- const year = date.getFullYear();
- const month = date.getMonth() + 1;
- const day = date.getDate();
- const hour = date.getHours();
- const minute = date.getMinutes();
- const today = new Date();
- const ty = today.getFullYear();
- const tm = today.getMonth() + 1;
- const td = today.getDate();
- if (year === ty && month === tm && day === td) {
- return [hour, minute].map(n => {
- n = n.toString();
- return n[1] ? n : '0' + n;
- }).join(':');
- }
- return [month, day].map(n => {
- n = n.toString();
- return n[1] ? n : '0' + n;
- }).join('-') + " " + [hour, minute].map(n => {
- n = n.toString();
- return n[1] ? n : '0' + n;
- }).join(':');
- },
- },
- methods: {
- toPage(url){
- var tabPages =["pages/index/index","pages/category/category","pages/cart/cart","pages/account/center"]
- if(tabPages.findIndex(item=>url.indexOf(item)>-1)>-1){
- uni.switchTab({url:url});
- }else{
- uni.navigateTo({url:url});
- }
- },
- copy(obj) {
- var newobj = obj.constructor === Array ? [] : {};
- if (typeof obj !== 'object') {
- return;
- }
- for (var i in obj) {
- newobj[i] = typeof obj[i] === 'object' ? this.copy(obj[i]) : obj[i];
- }
- return newobj
- },
- getPrePage(delta=1) {
- let pages = getCurrentPages();
- pages.forEach(item=>console.log("route--->",item.route))
- let prePage = pages[pages.length - (delta+1)];
- // #ifdef H5
- return prePage;
- // #endif
- return prePage.$vm;
- },
- getUrl(url) {
- if (url.indexOf("http") === 0) {
- return url;
- } else {
- return serverUrl + url;
- }
- },
- isNull(val) {
- return isEmptyOrNull(val);
- },
- contains(array, element, key) {
- return contains(array, element, key);
- },
- stopEvent(e) {
- console.log("stop event")
- e.stopPrevent();
- },
- uploadImages(count, scallback, fcallback) {
- let result = [];
- this.checkPermission("camera", () => {
- this.checkPermission("storage", () => {
- uni.chooseImage({
- count: count, //默认9
- sizeType: ['original', 'compressed'],
- sourceType: ['album'],
- success: (res) => {
- uni.showLoading({title: "图片上传中"});
- const files = res.tempFilePaths;
- let length = files.length;
- for (let i = 0; i < files.length; i++) {
- let fp = files[i];
- const formData = {
- thumb_mode: 1,
- 'X-Token': uni.getStorageSync(cfg.key.token) || ""
- };
- uni.uploadFile({
- url: cfg.api.uploadUrl,
- filePath: fp,
- name: 'file',
- formData: formData,
- success: (uploadFileRes) => {
- result.unshift(JSON.parse(uploadFileRes.data).result.uuid);
- },
- complete: () => {
- length--;
- if (length <= 0) {
- uni.hideLoading();
- setTimeout(() => {
- if (scallback) {
- console.log(result)
- scallback.call(null, result);
- }
- }, 100)
- }
- }
- });
- }
- }
- });
- });
- })
- },
- uploadVideo(callback) {
- this.checkPermission("camera", () => {
- this.checkPermission("storage", () => {
- uni.chooseVideo({
- count: 1, //默认9
- sourceType: ['camera', 'album'],
- maxDuration: 30,
- success: (res) => {
- if (res.size > 51200000) {
- this.$dialog.success("只能上传小于50M的视频!");
- return;
- }
- uni.showLoading({
- title: '视频上传中'
- });
- const formData = {
- thumb_mode: 1,
- 'X-Token': uni.getStorageSync(cfg.key.token) || ""
- };
- uni.uploadFile({
- url: cfg.api.uploadUrl,
- filePath: res.tempFilePath,
- name: 'file',
- formData: formData,
- success: (uploadFileRes) => {
- callback(uploadFileRes);
- uni.hideLoading();
- },
- complete: () => {
- uni.hideLoading();
- }
- });
- }
- });
- })
- })
- },
- payRequest(payType, payInfo, scallback, fcallback) {
- let _this = this;
- //1微信 2-支付宝
- if (payType === 1) {
- // fcallback.apply();
- uni.requestPayment({
- provider: 'wxpay',
- orderInfo: payInfo.wxpay,
- success: function (res) {
- scallback.apply();
- },
- fail: function (err) {
- console.log('fail:' + JSON.stringify(err));
- fcallback.apply();
- }
- });
- } else if (payType === 2) {
- uni.requestPayment({
- provider: 'alipay',
- orderInfo: payInfo.alipay.orderString,
- success: function (res) {
- scallback.apply();
- },
- fail: function (err) {
- console.log('fail:' + JSON.stringify(err));
- fcallback.apply();
- }
- });
- }
- },
- getDate(date, type) {
- let year = date.getFullYear();
- let month = date.getMonth() + 1;
- let day = date.getDate();
- if (type === 'start') {
- year = year - 60;
- } else if (type === 'end') {
- year = year + 2;
- }
- month = month > 9 ? month : '0' + month;
- day = day > 9 ? day : '0' + day;
- return `${year}年${month}月`;
- },
- getTimestamp(timestamp) {
- function zeroize(num) {
- return (String(num).length === 1 ? '0' : '') + num;
- }
- var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
- var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
- var tmDate = new Date(timestamp); // 参数时间戳转换成的日期对象
- var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
- if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
- return '今天';
- } else {
- var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
- if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
- return '昨天';
- } else if (curDate.getFullYear() == Y) {
- return zeroize(m) + '月' + zeroize(d) + '日 ';
- } else {
- return Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ';
- }
- }
- },
- isPhoneNumber(phone) {
- const reg = /^((0\d{2,3}-?\d{7,8})|(1\d{10}))$/; //校验手机号和固定电话
- return reg.test(phone);
- },
- isBankCardNo(bankNo) {
- var num = /^\d*$/;
- return !(bankNo.length < 16 || bankNo.length > 19 || !num.test(bankNo));
- },
- throttle(fn, wait = 500, isImmediate = false) {
- let flag = true;
- if (isImmediate) {
- return function () {
- if (flag) {
- fn.apply(this, arguments);
- flag = false;
- setTimeout(() => {
- flag = true
- }, wait)
- }
- }
- }
- return function () {
- if (flag == true) {
- flag = false
- setTimeout(() => {
- fn.apply(this, arguments)
- flag = true
- }, wait)
- }
- }
- },
- debounce(fn, wait = 500, isImmediate = false) {
- let timerId = null;
- let flag = true;
- if (isImmediate) {
- return function () {
- clearTimeout(timerId);
- if (flag) {
- fn.apply(this, arguments);
- flag = false
- }
- timerId = setTimeout(() => {
- flag = true
- }, wait)
- }
- }
- return function () {
- clearTimeout(timerId);
- timerId = setTimeout(() => {
- fn.apply(this, arguments)
- }, wait)
- }
- },
- /**
- * APP权限校验 https://ext.dcloud.net.cn/plugin?id=594
- * @param permissionId
- * @param scallback
- * @param fcallback
- */
- checkPermission(permissionId, scallback, fcallback) {
- let _this = this;
- //location 位置
- // push 推送(限iOS,注意Android上推送并不是一个权限)
- // camera 摄像头
- // photoLibrary 相册
- // record 麦克风
- // contact 通讯录
- // calendar 日历
- // memo 备忘录
- //#ifdef APP-PLUS
- let msg = "";
- if (isIos) {
- let ret = judgeIosPermission(permissionId);
- if (ret) {
- if (scallback) {
- scallback.apply();
- }
- } else {
- _this.askToPermission(msg, fcallback);
- }
- } else {
- if (permissionId == 'camera') {
- msg = "相机";
- permissionId = "android.permission.CAMERA";
- }
- if (permissionId == 'storage') {
- msg = "存储";
- permissionId = "android.permission.READ_EXTERNAL_STORAGE";
- }
- if (permissionId == 'location') {
- msg = "定位";
- permissionId = "android.permission.ACCESS_FINE_LOCATION";
- }
- requestAndroidPermission(permissionId).then(res => {
- console.log("android permission resp:" + JSON.stringify(res))
- if (res == 1) {
- if (scallback) {
- scallback.apply();
- }
- } else {
- _this.askToPermission(msg, fcallback);
- }
- })
- }
- //#endif
- //#ifndef APP-PLUS
- if (scallback) {
- scallback.apply();
- }
- //#endif
- },
- askToPermission(msg, fcallback) {
- uni.showModal({
- content: "您未授予应用" + msg + "相关权限,是否前往APP设置?",
- success: ms => {
- if (ms.confirm) {
- try {
- gotoAppPermissionSetting();
- } catch (e) {
- console.error(e)
- }
- } else if (ms.cancel) {
- //do nothing
- if (fcallback) {
- fcallback.apply();
- }
- }
- }
- });
- },
- }
- };
- export {gm, msg};
|