| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466 |
- import CONSTANT from "@/constant";
- import { mobileReg } from "@/utils/tools/validate";
- import { getMiniAppUrl, isWxBrowser } from "@/utils/common";
- // 是否为空
- const isEmpty = val => {
- if (val instanceof Array) {
- if (val.length === 0){
- return true
- }
- } else if (val instanceof Object) {
- if (Object.keys(val).length == 0){
- return true
- }
- } else {
- if ( val === "null" || val === null || val === "undefined" || val === undefined || val === "" || JSON.stringify(val) == "[]"){
- return true
- }
- return false;
- }
- return false;
- };
- /**
- * 深拷贝对象
- * @param {要拷贝对象} obj
- */
- export const copyObject = obj => {
- let str,
- newobj = Array.isArray(obj) === true ? [] : {};
- if (typeof obj !== "object") {
- return;
- } else if (JSON) {
- (str = JSON.stringify(obj)), //系列化对象
- (newobj = JSON.parse(str)); //还原
- } else {
- for (let i in obj) {
- newobj[i] = typeof obj[i] === "object" ? copyObject(obj[i]) : obj[i];
- }
- }
- return newobj;
- };
- const numberFormat = (number, type) => {
- if (number > 10000) {
- let num = (number / 10000 + "").split(".");
- return `${num[0]}.${("" + num[1]).slice(0, 1)} 万`;
- } else {
- return number;
- }
- };
- // 截取图片上传字符串
- const imgSubstr = val => {
- if (isEmpty(val)) return [];
- if (isArray(val)) {
- return val.map(e => {
- if(e.indexOf("?") > -1){
- e = e.slice(0,e.indexOf("?"))
- }
- let index = e.indexOf("uploads/");
- e = e.substring(index);
- return e;
- });
- } else {
- if(e.indexOf("?") > -1){
- e = e.slice(0,e.indexOf("?"))
- }
- let index = val.indexOf("uploads/");
- return val.substring(index);
- }
- };
- // 是否为数组
- const isArray = arr => {
- return typeof arr == "object" && arr.constructor == Array;
- };
- // 是否为字符串
- const isString = str => {
- return typeof str == "string" && str.constructor == String;
- };
- // 是否为对象
- const isObject = obj => {
- return typeof obj == "object" && obj.constructor == Object;
- };
- // 是否为数字
- const isNumber = num => {
- return typeof num == "number" && num.constructor == Number;
- };
- // 是否为日期类型
- const isDate = date => {
- return typeof date == "object" && date.constructor == Date;
- };
- // 是否为函数
- const isFunction = obj => {
- return typeof obj == "object" && obj.constructor == Function;
- };
- const checkMobile = num => {
- return mobileReg.test(num);
- };
- const checkName = str => {
- return /^[\u4E00-\u9FA5A-Za-z\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$/.test(str);
- };
- //是否金额
- const isMoney = money =>{
- return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(money)
- }
- /** *
- * 检查登录
- * @parmas query 拼接得参数对象
- * @parmas isFrist 为true时开头为&
- */
- export async function getCheckLogin() {
- let status = false;
- let token = uni.getStorageSync("token");
- if (token) {
- status = true;
- } else {
- // #ifdef H5
- if (isWxBrowser()) {
- let option = JSON.parse(uni.getStorageSync("currentQuery")) || {};
- console.log("option", option);
- // console.log('option', getMiniAppUrl(option, true))
- // return false
- location.href = `${CONSTANT.hostUrl}/auth/prepare?url=${encodeURIComponent(
- getMiniAppUrl(option, true)
- )}`;
- } else {
- // uni.showToast({
- // title: '请用微信浏览器打开!',
- // icon: 'none',
- // mask: true
- // })
- }
- // #endif
- // #ifndef H5
- // #endif
- }
- return status;
- }
- export const floatFormat = (f, n) => {
- let m = Math.pow(10, n);
- return parseInt(f * m, 10) / m;
- };
- /** *
- * 对象参数转为url参数
- * @parmas query 拼接得参数对象
- * @parmas isFrist 为true时开头为&
- */
- export const parse = (query, isFrist = false) => {
- let str = Object.keys(query)
- .filter(key => !isEmpty(query[key]))
- .reduce((result, key) => {
- const value = query[key];
- // in查询特殊处理
- if (Array.isArray(value) && !isEmpty(value)) {
- return `${result}&${value.reduce(
- (val, cVal) => `${val ? `${val}&` : val}${key}=${cVal}`,
- ""
- )}`;
- }
- // between查询做特殊处理
- if (typeof value === "object" && !isEmpty(value)) {
- const [start, end] = value;
- return `${result}&${key}[]=${start}&${key}[]=${end}`;
- }
- return `${result}&${key}=${value}`;
- }, "");
- return isFrist ? str : str.replace(/^&/, "?");
- };
- /** *
- * 全局时间转换
- * @parmas num 时间戳默认为11位时间戳
- * @parmas fmt 默认转换的时间格式
- * @parmas all 为true时time为13位时间戳
- */
- export const $formatDate = (num, fmt = "YYYY-MM-DD HH:mm", all) => {
- num = all ? num : num * 1000;
- let date = new Date();
- date.setTime(num);
- let o = {
- "M+": date.getMonth() + 1,
- "D+": date.getDate(),
- "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
- "H+": date.getHours(),
- "m+": date.getMinutes(),
- "s+": date.getSeconds(),
- "q+": Math.floor((date.getMonth() + 3) / 3),
- S: date.getMilliseconds()
- };
- let week = {
- "0": "\u65e5",
- "1": "\u4e00",
- "2": "\u4e8c",
- "3": "\u4e09",
- "4": "\u56db",
- "5": "\u4e94",
- "6": "\u516d"
- };
- if (/(Y+)/.test(fmt)) {
- fmt = fmt.replace(
- RegExp.$1,
- (date.getFullYear() + "").substr(4 - RegExp.$1.length)
- );
- }
- if (/(E+)/.test(fmt)) {
- fmt = fmt.replace(
- RegExp.$1,
- (RegExp.$1.length > 1
- ? RegExp.$1.length > 2
- ? "\u661f\u671f"
- : "\u5468"
- : "") + week[date.getDay() + ""]
- );
- }
- for (let k in o) {
- if (new RegExp("(" + k + ")").test(fmt)) {
- fmt = fmt.replace(
- RegExp.$1,
- RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
- );
- }
- }
- return fmt;
- };
- /** *
- * 全局公共按钮跳转
- * @parmas item.funtion 为可执行函数
- * @parmas item.url 为跳转的路径
- * @parmas item.query 为跳转携带的参数
- * @parmas item.type 为跳转调用的函数 1为navigateTo, 2为redirectTo 关闭当前页,跳转到指定页, 3为reLaunch, 4为switchTab
- */
- export const pageTo = item => {
- if (isNumber(item)) {
- uni.navigateBack({
- delta: item
- });
- }
- if (isString(item)) {
- uni.navigateTo({
- url: item
- });
- return false;
- }
- if (item.funtion) {
- item.funtion();
- }
- if (item.url) {
- let query = item.query ? parse(item.query) : "";
- let allUrl = `${item.url}${query}`;
- if (item.type == 2) {
- uni.redirectTo({ url: allUrl })
- } else if (item.type == 3) {
- uni.reLaunch({ url: allUrl })
- } else if (item.type == 4) {
- uni.setStorageSync("switchTabQuery", item.query);
- uni.switchTab({ url: item.url })
- } else {
- uni.navigateTo({ url: allUrl })
- }
- }
- };
- /** *
- * 是否登录
- */
- export const isLogin = () => {
- let token = uni.getStorageSync("token");
- if (token) {
- return true;
- }
- return false;
- };
- /**
- * 去重
- * 姜枫 2021.05.05
- * **/
- export const unique = (arr) => {
- for(var i=0; i<arr.length; i++){
- for(var j=i+1; j<arr.length; j++){
- if(arr[i].classId==arr[j].classId){ //第一个等同于第二个,splice方法删除第二个
- arr.splice(j,1);
- j--;
- }
- }
- }
- return arr;
- };
- //#ifdef APP-PLUS
- const CLDialog=uni.requireNativePlugin("CL-Dialog")
- //#endif
- export const confirmModal = (item,okCallback=null,cancelCallback=null) => {
- let title = item.title || '提示'
- let content = item.content || '确认操作?'
- let okText = item.okText || '确认'
- let cancelText = item.cancelText || '取消'
- let cacelTextColor = '#999999'
- let okTextColor = '#38ADFF'
- let singer = item.singer || false
- //#ifdef APP-PLUS
- let options={
- title:title,//标题 (可选)
- con:content,//内容(可选)但是标题和内容至少选择一个
- okTitle:okText,//确认按钮文字(可选)
- cancleTitle:cancelText,//取消按钮文字(可选)
- okTextColor:"#38ADFF",//确认按钮颜色(可选)
- cancleTextColor:"#999999",//取消按钮颜色(可选)
- singer:singer,//是否只显示确认按钮,默认false(可选)
- textAlign:"center",//对齐方式 //left居左,center居中,right 居右 默认居中
- conColor:"",
- bgColor:"#FFFFFF",//自定义弹框颜色
- titleColor:"#3d3d3d"//自定义title颜色
- }
- CLDialog.show(options,()=>{
- if(okCallback!=null){
- okCallback()
- }
- },()=>{
- if(cancelCallback!=null){
- cancelCallback()
- }
- })
- //#endif
- // #ifdef MP-WEIXIN
- uni.showModal({
- title: title,
- content: content,
- showCancel: true,
- cancelText: cancelText,
- cancelColor: cacelTextColor,
- confirmText: okText,
- confirmColor: okTextColor,
- success: function (res) {
- if (res.confirm) {
- if(okCallback!=null){
- okCallback()
- }
- } else if (res.cancel) {
- if(cancelCallback!=null){
- cancelCallback()
- }
- }
- }
- })
- //#endif
- }
- //判断是否有扫码的条件
- export const isScanEnv = () =>{
- let isScanEnv = false
- //#ifdef APP-PLUS
- if(plus.device.vendor == 'SUNMI'){
- isScanEnv = true
- }
- if(plus.device.vendor == 'Newland'){
- isScanEnv = true
- }
- //#endif
- return isScanEnv
- }
- //加
- export const add = (arg1, arg2) => {
- var r1, r2, m, n;
- try {
- r1 = arg1.toString().split(".")[1].length
- } catch (e) {
- r1 = 0
- }
- try {
- r2 = arg2.toString().split(".")[1].length
- } catch (e) {
- r2 = 0
- }
- m = Math.pow(10, Math.max(r1, r2))
- n = (r1 >= r2) ? r1 : r2;
- return ((arg1 * m + arg2 * m) / m).toFixed(n);
- }
- //减
- export const sub = (arg1, arg2) => {
- var re1, re2, m, n;
- try {
- re1 = arg1.toString().split(".")[1].length;
- } catch (e) {
- re1 = 0;
- }
- try {
- re2 = arg2.toString().split(".")[1].length;
- } catch (e) {
- re2 = 0;
- }
- m = Math.pow(10, Math.max(re1, re2));
- n = (re1 >= re2) ? re1 : re2;
- return ((arg1 * m - arg2 * m) / m).toFixed(n);
- }
- //乘
- export const mul = (arg1, arg2) => {
- var m = 0;
- var s1 = arg1.toString();
- var s2 = arg2.toString();
- try {
- m += s1.split(".")[1].length;
- } catch (e) {}
- try {
- m += s2.split(".")[1].length;
- } catch (e) {}
-
- return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
- }
- // 除数,被除数, 保留的小数点后的位数
- export const div = (arg1,arg2,digit) =>{
- var t1=0,t2=0,r1,r2;
- try{t1=arg1.toString().split(".")[1].length}catch(e){}
- try{t2=arg2.toString().split(".")[1].length}catch(e){}
- r1=Number(arg1.toString().replace(".",""))
- r2=Number(arg2.toString().replace(".",""))
- //获取小数点后的计算值
- var result= ((r1/r2)*Math.pow(10,t2-t1)).toString()
- var result2=result.split(".")[1];
- result2=result2.substring(0,digit>result2.length?result2.length:digit);
-
- return Number(result.split(".")[0]+"."+result2);
- }
- export default {
- isEmpty,
- copyObject,
- imgSubstr,
- isArray,
- parse,
- checkMobile,
- checkName,
- $formatDate,
- floatFormat,
- pageTo,
- isLogin,
- getCheckLogin,
- numberFormat,
- isString,
- unique,
- isMoney,
- confirmModal,
- isScanEnv,
- add,
- sub,
- mul,
- div
- };
|