源文件

This commit is contained in:
gyq
2024-05-23 14:39:33 +08:00
commit a1128dd791
2997 changed files with 500069 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
/**
* @param {Function} fn 需要执行的方法因this指向问题建议不使用箭头函数
* @param {Number} delay 间隔时间默认值100
* @param {Boolean} promptly 是否立即执行默认false
* **/
export const debounce = (fn, delay = 100, promptly) => {
let timer = null
return function (...args) {
// 立即执行
if (promptly) {
// 当timer为null时执行
if (!timer) fn.apply(this, args)
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
timer = null
}, delay)
} else {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
}
/**
* @param {Function} fn 需要执行的方法因this指向问题建议不使用箭头函数
* @param {Number} delay 间隔时间默认值100
* **/
const throttle = (fn, delay = 100) => {
let valid = true
return function (...args) {
if (!valid) {
return
}
valid = false
fn.apply(this, args)
setTimeout(() => {
valid = true
}, delay)
}
}

View File

@@ -0,0 +1,72 @@
/**
* 加解密工具包
*
* @author terrfly
* @site https://www.jeepay.vip
* @date 2021/5/16 17:35
*/
import { SM4 } from 'gm-crypto'
import appConfig from '@/config/appConfig.js'
let HEX_KEY = null
// 字符串转16进制
function str2hex(str) {
var val = ''
for (var i = 0; i < str.length; i++) {
if (val == '')
val = str.charCodeAt(i).toString(16)
else
val += str.charCodeAt(i).toString(16)
}
val += ''
return val
}
// 获取hex秘钥
function getHexKey(){
if(!HEX_KEY){
HEX_KEY = str2hex(appConfig.encryptKey)
}
return HEX_KEY
}
// 解密 (http响应数据 做通用处理)
export function sm4DecryptByResData(data){
if(!data){
return data
}
let res = SM4.decrypt(data, getHexKey(), {
inputEncoding: 'base64',
outputEncoding: 'utf8'
})
if(!res){
return res
}
return JSON.parse(res)['originData']
}
// 加密 (http响应数据 做通用处理)
export function sm4EncryptByReqData(data){
if(!data){
return data
}
// 加密处理
let encryptData = SM4.encrypt(JSON.stringify(data), getHexKey(), {
inputEncoding: 'utf8',
outputEncoding: 'base64'
})
return {encryptData : encryptData}
}

View File

@@ -0,0 +1,93 @@
//rules.js
export default {
error:'',
check : function (data, rule){
for(var i = 0; i < rule.length; i++){
if (!rule[i].checkType){return true;}
if (!rule[i].name) {return true;}
if (!rule[i].errorMsg) {return true;}
if (!data[rule[i].name]) {this.error = rule[i].errorMsg; return false;}
switch (rule[i].checkType){
case 'string':
var reg = new RegExp('^.{' + rule[i].checkRule + '}$');
if(!reg.test(data[rule[i].name])) {this.error = rule[i].errorMsg; return false;}
break;
case 'int':
var reg = new RegExp('^(-[1-9]|[1-9])[0-9]{' + rule[i].checkRule + '}$');
if(!reg.test(data[rule[i].name])) {this.error = rule[i].errorMsg; return false;}
break;
break;
case 'between':
if (!this.isNumber(data[rule[i].name])){
this.error = rule[i].errorMsg;
return false;
}
var minMax = rule[i].checkRule.split(',');
minMax[0] = Number(minMax[0]);
minMax[1] = Number(minMax[1]);
if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'betweenD':
var reg = /^-?[1-9][0-9]?$/;
if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
var minMax = rule[i].checkRule.split(',');
minMax[0] = Number(minMax[0]);
minMax[1] = Number(minMax[1]);
if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'betweenF':
var reg = /^-?[0-9][0-9]?.+[0-9]+$/;
if (!reg.test(data[rule[i].name])){this.error = rule[i].errorMsg; return false;}
var minMax = rule[i].checkRule.split(',');
minMax[0] = Number(minMax[0]);
minMax[1] = Number(minMax[1]);
if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'same':
if (data[rule[i].name] != rule[i].checkRule) { this.error = rule[i].errorMsg; return false;}
break;
case 'notsame':
if (data[rule[i].name] == rule[i].checkRule) { this.error = rule[i].errorMsg; return false; }
break;
case 'email':
var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
break;
case 'phoneno':
var reg = /^1[0-9]{10,10}$/;
if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
break;
case 'zipcode':
var reg = /^[0-9]{6}$/;
if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
break;
case 'reg':
var reg = new RegExp(rule[i].checkRule);
if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
break;
case 'in':
if(rule[i].checkRule.indexOf(data[rule[i].name]) == -1){
this.error = rule[i].errorMsg; return false;
}
break;
case 'notnull':
if(data[rule[i].name] == null || data[rule[i].name].length < 1){this.error = rule[i].errorMsg; return false;}
break;
}
}
return true;
},
isNumber : function (checkVal){
var reg = /^-?[1-9][0-9]?.?[0-9]*$/;
return reg.test(checkVal);
}
}

View File

@@ -0,0 +1,352 @@
/*
* HTML5 Parser By Sam Blowes
*
* Designed for HTML5 documents
*
* Original code by John Resig (ejohn.org)
* http://ejohn.org/blog/pure-javascript-html-parser/
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*
* ----------------------------------------------------------------------------
* License
* ----------------------------------------------------------------------------
*
* This code is triple licensed using Apache Software License 2.0,
* Mozilla Public License or GNU Public License
*
* ////////////////////////////////////////////////////////////////////////////
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* ////////////////////////////////////////////////////////////////////////////
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is Simple HTML Parser.
*
* The Initial Developer of the Original Code is Erik Arvidsson.
* Portions created by Erik Arvidssson are Copyright (C) 2004. All Rights
* Reserved.
*
* ////////////////////////////////////////////////////////////////////////////
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* ----------------------------------------------------------------------------
* Usage
* ----------------------------------------------------------------------------
*
* // Use like so:
* HTMLParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* // or to get an XML string:
* HTMLtoXML(htmlString);
*
* // or to get an XML DOM Document
* HTMLtoDOM(htmlString);
*
* // or to inject into an existing document/DOM node
* HTMLtoDOM(htmlString, document);
* HTMLtoDOM(htmlString, document.body);
*
*/
// Regular Expressions for parsing tags and attributes
var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; // Empty Elements - HTML 5
var empty = makeMap('area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr'); // Block Elements - HTML 5
// fixed by xxx 将 ins 标签从块级名单中移除
var block = makeMap('a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video'); // Inline Elements - HTML 5
var inline = makeMap('abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'); // Elements that you can, intentionally, leave open
// (and which close themselves)
var closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'); // Attributes that have their values filled in disabled="disabled"
var fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'); // Special Elements (can contain anything)
var special = makeMap('script,style');
function HTMLParser(html, handler) {
var index;
var chars;
var match;
var stack = [];
var last = html;
stack.last = function () {
return this[this.length - 1];
};
while (html) {
chars = true; // Make sure we're not in a script or style element
if (!stack.last() || !special[stack.last()]) {
// Comment
if (html.indexOf('<!--') == 0) {
index = html.indexOf('-->');
if (index >= 0) {
if (handler.comment) {
handler.comment(html.substring(4, index));
}
html = html.substring(index + 3);
chars = false;
} // end tag
} else if (html.indexOf('</') == 0) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars = false;
} // start tag
} else if (html.indexOf('<') == 0) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars = false;
}
}
if (chars) {
index = html.indexOf('<');
var text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? '' : html.substring(index);
if (handler.chars) {
handler.chars(text);
}
}
} else {
html = html.replace(new RegExp('([\\s\\S]*?)<\/' + stack.last() + '[^>]*>'), function (all, text) {
text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, '$1$2');
if (handler.chars) {
handler.chars(text);
}
return '';
});
parseEndTag('', stack.last());
}
if (html == last) {
throw 'Parse Error: ' + html;
}
last = html;
} // Clean up any remaining tags
parseEndTag();
function parseStartTag(tag, tagName, rest, unary) {
tagName = tagName.toLowerCase();
if (block[tagName]) {
while (stack.last() && inline[stack.last()]) {
parseEndTag('', stack.last());
}
}
if (closeSelf[tagName] && stack.last() == tagName) {
parseEndTag('', tagName);
}
unary = empty[tagName] || !!unary;
if (!unary) {
stack.push(tagName);
}
if (handler.start) {
var attrs = [];
rest.replace(attr, function (match, name) {
var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : '';
attrs.push({
name: name,
value: value,
escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') // "
});
});
if (handler.start) {
handler.start(tagName, attrs, unary);
}
}
}
function parseEndTag(tag, tagName) {
// If no tag name is provided, clean shop
if (!tagName) {
var pos = 0;
} // Find the closest opened tag of the same type
else {
for (var pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos] == tagName) {
break;
}
}
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if (handler.end) {
handler.end(stack[i]);
}
} // Remove the open elements from the stack
stack.length = pos;
}
}
}
function makeMap(str) {
var obj = {};
var items = str.split(',');
for (var i = 0; i < items.length; i++) {
obj[items[i]] = true;
}
return obj;
}
function removeDOCTYPE(html) {
return html.replace(/<\?xml.*\?>\n/, '').replace(/<!doctype.*>\n/, '').replace(/<!DOCTYPE.*>\n/, '');
}
function parseAttrs(attrs) {
return attrs.reduce(function (pre, attr) {
var value = attr.value;
var name = attr.name;
if (pre[name]) {
pre[name] = pre[name] + " " + value;
} else {
pre[name] = value;
}
return pre;
}, {});
}
function parseHtml(html) {
html = removeDOCTYPE(html);
var stacks = [];
var results = {
node: 'root',
children: []
};
HTMLParser(html, {
start: function start(tag, attrs, unary) {
var node = {
name: tag
};
if (attrs.length !== 0) {
node.attrs = parseAttrs(attrs);
}
if (unary) {
var parent = stacks[0] || results;
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
} else {
stacks.unshift(node);
}
},
end: function end(tag) {
var node = stacks.shift();
if (node.name !== tag) console.error('invalid state: mismatch end tag');
if (stacks.length === 0) {
results.children.push(node);
} else {
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
},
chars: function chars(text) {
var node = {
type: 'text',
text: text
};
if (stacks.length === 0) {
results.children.push(node);
} else {
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
},
comment: function comment(text) {
var node = {
node: 'comment',
text: text
};
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
});
return results.children;
}
export default parseHtml;

View File

@@ -0,0 +1,19 @@
export function intNum(num) {
const type = typeof(num)
if(type === 'string' && num!== ''){
num = Number(num) //转换为数字
if(Number.isInteger(num)){
let res = `${String(num)}.00`
return res
}else{
return num
}
}else{
if(Number.isInteger(num)){
let res = `${String(num)}.00`
return res
}else{
return num
}
}
}

View File

@@ -0,0 +1,22 @@
/**
* 一次性 var 的管理
*
* @author terrfly
* @site https://www.jeequan.com
* @date 2022/04/14 11:35
*/
const model = {
// 图片预览flag
imgViewFlag: false,
imgView: (val) => {
if(typeof(val) === 'boolean' ){
model.imgViewFlag = val
}
return model.imgViewFlag
}
}
export default model

View File

@@ -0,0 +1,6 @@
export default {
ps:'品生',
bsj:'博实结',
zgwl:'智谷联',
fe:'飞蛾'
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,38 @@
// 保存图片
export function saveHeadImgFile(base64, quality) {
const bitmap = new plus.nativeObj.Bitmap("test");
return new Promise((resolve, reject) => {
// 从本地加载Bitmap图片
bitmap.loadBase64Data(base64, function() {
const url = "_doc/" + getTimeStamps() + ".png"; // url为时间戳命名方式
bitmap.save(url, {
overwrite: true, // 是否覆盖
quality: quality // 图片清晰度
}, (i) => {
console.log(url)
uni.saveImageToPhotosAlbum({
filePath: url,
success: function() {
resolve({
code: 0,
msg: '保存成功',
filePath: url
});
},
fail:function(){
msg:'保存失败'
}
});
}, (e) => {
reject('保存图片失败:' + JSON.stringify(e));
});
}, (e) => {
reject('加载图片失败:' + JSON.stringify(e));
});
})
}
function getTimeStamps (){
return (new Date()).valueOf()
}

View File

@@ -0,0 +1,126 @@
/**
* 存储管理对象
* 目标:将现有系统的所有需要存储的数据,统一管理
*
* @author terrfly
* @site https://www.jeequan.com
* @date 2022/04/13 07:18
*/
import appConfig from '@/config/appConfig.js'
const model = {
// 获取和放置token
token: (val, isDelete = false) => {
if (isDelete) {
appConfig.tokenVal = ''
return uni.removeStorageSync(appConfig.tokenKey)
}
if (val) {
// 有值,为放置
appConfig.tokenVal = val
uni.setStorageSync(appConfig.tokenKey, val)
} else {
// 否则为获取
if (!appConfig.tokenVal) {
//缓存取不到,获取应用本地信息
appConfig.tokenVal = uni.getStorageSync(appConfig.tokenKey)
}
return appConfig.tokenVal
}
},
// 已经登录的用户记录
loggedInUser: (addUserName = null, removeUserName = null) => {
let key = 'loggedInUserList'
// 删除
if (removeUserName) {
let nameList = uni.getStorageSync(key) || []
if (nameList.length <= 0) {
//不存在数据
return false
}
let hasUserIndex = nameList.indexOf(removeUserName)
if (hasUserIndex >= 0) {
nameList.splice(hasUserIndex, 1) //删除
uni.setStorageSync(key, nameList)
}
return false
}
// 有新插入的记录
if (addUserName) {
let nameList = uni.getStorageSync(key) || []
let hasUser = false
for (let i = 0; i < nameList.length; i++) {
if (nameList[i] == addUserName) {
hasUser = true
}
}
// 包含记录
if (hasUser) {
return false
}
// 最多存储 5 个
if (nameList.length >= 5) {
nameList.splice(0, 1) //删除第一个
}
nameList.push(addUserName)
uni.setStorageSync(key, nameList)
//获取
} else {
return uni.getStorageSync(key) || [] //默认空数组
}
},
// 用户信息
userInfo: (currentUserInfo) => {
if (currentUserInfo) {
// 仅保存基础数据
let saveUser = {
sysUserId: currentUserInfo.userNo,
userType: currentUserInfo.userType,
isEpUuser: currentUserInfo.userType === 3, //是否拓展员
state: currentUserInfo.state,
inviteCode: currentUserInfo.inviteCode,
inviteCodeUrl: currentUserInfo.inviteCodeUrl,
agtInviteCodeUrl: currentUserInfo.agtInviteCodeUrl,
entIdList: currentUserInfo.entIdList,
}
uni.setStorageSync('currentUserInfo', saveUser) // 改变存储
}
return uni.getStorageSync('currentUserInfo')
},
// 项目环境变量:(测试、 生产的切换)
env: (envMode) => {
if (envMode) {
uni.setStorageSync('currentEnvEnum', envMode) // 改变存储
}
return uni.getStorageSync('currentEnvEnum')
},
// 工作工具样式
toolStyle: (style) => {
if (style) {
uni.setStorageSync('toolStyle', style) // 改变存储
}
return uni.getStorageSync('toolStyle')
},
uploadImgSize: (uploadImgSize) => {
if (uploadImgSize) {
uni.setStorageSync("uploadImgSize", uploadImgSize) // 存储 上传 图片大小限制
}
return uni.getStorageSync("uploadImgSize")
},
}
export default model

View File

@@ -0,0 +1,13 @@
export function getDay(num, str) {
//如果要获取昨天的日期num就是-1 前天的就是-2依次类推。str表示年月日间的分割方式。
const today = new Date()
const nowTime = today.getTime()
const ms = 24 * 3600 * 1000 * num
today.setTime(nowTime + ms)
const oYear = today.getFullYear()
let oMoth = (today.getMonth() + 1).toString()
if (oMoth.length <= 1) oMoth = "0" + oMoth
let oDay = today.getDate().toString()
if (oDay.length <= 1) oDay = "0" + oDay
return oYear + str + oMoth + str + oDay
}

View File

@@ -0,0 +1,233 @@
import qrcode from "@/util/qrcode.js"
/* 获取当前日期并格式化 */
function getNowTime() {
var nowtime = new Date()
var year = nowtime.getFullYear()
var month = nowtime.getMonth() + 1 < 10 ? "0" + (nowtime.getMonth() + 1) : nowtime.getMonth() + 1
var day = nowtime.getDate() < 10 ? "0" + nowtime.getDate() : nowtime.getDate()
var hour = nowtime.getHours() < 10 ? "0" + nowtime.getHours() : nowtime.getHours()
var minute = nowtime.getMinutes() < 10 ? "0" + nowtime.getMinutes() : nowtime.getMinutes()
return year + "-" + month + "-" + day + " " + hour + ":" + minute
}
// 格式化日期格式为 xxxx-xx-xx
function getFullDate(targetDate) {
var nowDate = new Date()
var fullYear = nowDate.getFullYear()
var month = nowDate.getMonth() + 1 // getMonth 方法返回 0-11代表1-12月
var D, y, m, d
if (targetDate) {
D = new Date(targetDate)
y = D.getFullYear()
m = D.getMonth() + 1
d = D.getDate()
} else {
// 不传参数 则获取今天的日期
y = fullYear
m = month
d = new Date()
d = d.getDate()
}
m = m > 9 ? m : "0" + m
d = d > 9 ? d : "0" + d
return y + "-" + m + "-" + d
}
/* 将时间戳格式化为yyyy-MM-dd hh:mm:ss格式其它格式可自行更改 */
function formatTimeMills(timeMills, sign) {
var date = new Date(timeMills)
var timeStr = date.getFullYear() + sign
if (date.getMonth() < 9) {
// 月份从0开始的
timeStr += "0"
}
timeStr += date.getMonth() + 1 + sign
timeStr += date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
timeStr += " "
timeStr += date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
timeStr += ":"
timeStr += date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()
/* timeStr += ':';
timeStr += date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds(); */
return timeStr
}
/* 获取今天的零点/最后一刻 */
function getTodayStartOrEnd(sign) {
let resultTime = ""
if (sign == "start") {
resultTime = new Date(new Date(new Date().toLocaleDateString()).getTime())
} else if (sign == "end") {
resultTime = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
}
return formatTimeMills(resultTime, "-")
}
let num = (a) => {
if (a != null && a.toString() != "") {
let r = /^-?(0|[1-9]+\d*|[1-9]+\d*\.\d+|0\.\d+)$/
if (r.test(a.toString())) {
return true
}
}
return false
}
/* 除法 */
function division(a, b) {
if (!num(a) || !num(b)) {
return null
}
let c, d, f, g
try {
c = a.toString().split(".")[1].length
} catch (e) {
c = 0
}
try {
d = b.toString().split(".")[1].length
} catch (e) {
d = 0
}
f = Number(a.toString().replace(".", ""))
g = Number(b.toString().replace(".", ""))
return parseFloat(((f / g) * Math.pow(10, d - c)).toFixed(2))
}
/* 金额格式化 */
function amountFormatting(amount, sign) {
let changeAmount = 0
let resultAmount = 0
if (sign == 0) {
changeAmount = division(amount, 100)
resultAmount = changeAmount.toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, "$&,")
} else if (sign == 1) {
resultAmount = amount.toFixed(0).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, "$&,")
}
return resultAmount
}
// 获取n天后的日期
function getNdaysLater(n) {
var nowDate = new Date()
let nDaysLaterDate = getFullDate(nowDate.getTime() + 24 * 60 * 60 * 1000 * n) //获取明天日期
return nDaysLaterDate
}
export const debounce = (fn, t) => {
let delay = t || 500
let timer
return function () {
let args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
timer = null
fn.apply(this, args)
}, delay)
}
}
// 将回显的地址码,转为文本供只读组件使用 ,第一个参数为地址码数组,第二,三个参数为省市区的JSON只有收付通会用到第三个参数
const addressBack = (list, address, addressTow) => {
if (!list || list.length == 0) return "" // 非空校验
let addressText = ""
// 绝大多数清空都没有第二个 地址JSON表
if (!addressTow) {
let first = address.find((val) => val.value == list[0])
addressText += first.text + "/"
let second = first.children.find((val) => val.value == list[1])
addressText += second.text + "/"
let third = second.children.find((val) => val.value == list[2])
addressText += third.text
} else {
// 收付通 选择 支行所在地址专属 (只能选择到市一级)
let first = addressTow.find((val) => val.value == list[0])
addressText += first.text + "/"
let second = first.children.find((val) => val.value == list[1])
addressText += second.text
}
return addressText
}
// 将回显的行业mcc码转为文本供只读组件使用 ,第一个参数为地址码数组第二参数为行业mcc的JSON, 第三个参数为取值方式,拼接的截取取值,数组的拿最后一个值
const mccBack = (mccCode, mccJson, type) => {
if (!mccCode) return "" // 非空校验
let mccText = ""
if (type == "splicing") {
let code
if (mccCode) code = mccCode.split("_")[1]
for (var i = 0; i < mccJson.length; i++) {
mccText = mccJson[i].children.find((val) => val.value == code)
if (mccText) break
}
mccText = mccText.text
} else if (type == "last") {
for (var i = 0; i < mccJson.length; i++) {
mccText = mccJson[i].children.find((val) => val.value == mccCode)
if (mccText) break
}
mccText = mccText.text
}
return mccText
}
// 制作图片
const drawQRcode = (url) => {
let params = url // 二维码参数
var imgData = qrcode.drawImg(params, {
typeNumber: 4, // 密度
errorCorrectLevel: "Q", // 纠错等级
size: 175, // 白色边框
})
return imgData
}
function addressCode(val, address) {
const data = []
address.forEach((v) => {
if (val.indexOf(v.text) != -1) {
data.push(v)
v.children.forEach((ite) => {
if (val.indexOf(ite.text) != -1) {
data.push(ite)
ite.children.forEach((value) => {
if (val.indexOf(value.text) != -1) {
data.push(value)
}
})
}
})
}
})
const obj = {
text: [],
code: [],
}
data.forEach((v, i) => {
obj.text.push(v.text)
obj.code.push(v.value)
})
obj.text = obj.text.join("/")
return obj
}
export default {
getNowTime,
amountFormatting,
getNdaysLater,
getTodayStartOrEnd,
addressBack,
mccBack,
drawQRcode,
addressCode,
}

View File

@@ -0,0 +1,139 @@
/**
* 软件升级管理类
*
* @author terrfly
* @site https://www.jeequan.com
* @date 2022/04/13 15:18
*/
import { $versionDetection } from '@/http/apiManager.js';
import appConfig from '@/config/appConfig.js'
// app更新
function appPlusUpdate(value){
let isCheck = value //点击检查更新时是否检查
// 获取版本号
plus.runtime.getProperty(plus.runtime.appid, function(inf) {
// 调起接口查询
$versionDetection({versionNumber: inf.versionCode})
.then(({ bizData }) => {
//返回data为空
if (!bizData || Object.keys(bizData).length == 0 ||!bizData.versionSerialNumber || bizData.versionSerialNumber == inf.versionCode) {
if(isCheck){
uni.showToast({
icon:'none',
title:'已是最新版本'
})
}
return false;
}
// // 版本号一致
// if(){
// return false;
// }
// 是否强制更新
let isForceUpdate = bizData.forceUpdate == 1
uni.showModal({
title:'当前本V'+ inf.versionCode.split('').join('.') +';发现新版本:' + bizData.versionName,
showCancel: !isForceUpdate ,
content: bizData.versionDesc,
confirmText: '立即更新',
confirmColor: '#108EE9',
success: function(r) {
if (r.confirm) {
downLoad(bizData.downloadUrl);
}else{
// 强制更新也需要更新
if(isForceUpdate){
downLoad(bizData.downloadUrl);
}
}
}
});
});
});
}
//下载更新包
function downLoad(url) {
if (!url) {
uni.showToast({icon: 'none',title: '下载地址错误'});
return false;
}
// 下载文件
uni.showLoading({title: '更新中'});
uni.downloadFile({
url: url,
success: res => {
uni.hideLoading();
if (res.statusCode === 200) {
uni.showToast({title: '下载成功'});
plus.runtime.install(res.tempFilePath);
}
},
fail: res => {
uni.hideLoading();
}
});
}
// 获取当前版本 & 检查
export function getCurrentVersionPromise() {
let isApp = false
// #ifdef APP-PLUS
isApp = true
// #endif
if(!isApp){
return Promise.reject()
}
// 获取版本号
return new Promise((resolve, reject) => {
plus.runtime.getProperty(plus.runtime.appid, function(inf) {
resolve(inf)
})
})
}
// 获取当前版本 & 检查
export function checkCurrVersion(value) {
// #ifdef APP-PLUS
switch(uni.getSystemInfoSync().platform){
case 'android':
appPlusUpdate(value) //仅安卓更新
break;
case 'ios':
console.log('运行iOS上')
break;
default:
console.log('运行在开发者工具上')
break;
}
// #endif
}
//同步取出ext.json对象
export function getExtStoreId(){
try{
const extConfig = uni.getExtConfigSync()
if(extConfig.domain){
appConfig.env.JEEPAY_BASE_URL = extConfig.domain
}
// uni.showToast({title: JSON.stringify(extConfig),icon:"none",duration:3000});
console.log(extConfig,'extJson对象');
return extConfig;
}catch(err){
console.log(err,'getExtStoreId__error')
}
}