Yizhan-app/common/util.js

953 lines
25 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {
hex_md5
} from './MD5.js'
import '@/common/aes.js'
import CryptoJS from '@/common/crypto-js.js'
var KEY = CryptoJS.enc.Utf8.parse("greenh5java12345")
var IV = CryptoJS.enc.Utf8.parse("greenh5java12345")
var md5s = "greenh5"
//设置本都存储
const SETSTORAGE = function(key, val) {
uni.setStorage({
key: key,
data: val,
success: _ => {
console.log('设置成功')
}
})
}
// console.log(Sm2Utils);
// 微信公众号授权
const WXAUTHORIZE = function() {
let link = window.location.href;
// let params = this._getUrlParams(link); // 地址解析
let params = ''; // 地址解析
// 已经授权登录过的就不用再授权了
//if (store.state.token) return;
// 如果拿到code调用授权接口没有拿到就跳转微信授权链接获取
if (params.code) {
api.wxAuth(params.code); // 调用后台接口,授权
} else {
let appid = 'wx7d707414e4623461'; //sj wx7d707414e4623461 华中 wx61ecc513905e876a
let uri = encodeURIComponent(link);
let authURL =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
window.location.href = authURL;
}
}
//获取本地存储
const GETSTORAGE = function(key) {
return uni.getStorageSync(key);
}
//清除本地存储
const CLEARSTORAGE = function(key) {
return uni.clearStorageSync()
}
const DEVENV = false; // 用于判断是否是开发环境 true 是开发环境
// const BASE = 'http://10.137.22.253:48080'; // 用清
const BASE = 'http://192.168.0.246:48080'; // 用清
const DOC_BASE = '/doc-api'; // 名流接口地址
// const BASE = 'http://220.248.250.227:49967'; // 测试服务器
// const BASE = 'http://192.168.0.99:48080'; // 用清
// const BASE = 'http://10.137.22.253:48080'; // 用清
// const BASE = 'http://192.168.231.237:48080'; //方淼
// const BASE = 'http://192.168.24.237:48080'; //方淼 连的郑兵的热点
// const BASE = 'http://10.137.205.186:48080'; // 张政
// const BASE = 'http://192.168.0.249:48080'; // 张政
// const BASE = 'http://127.0.0.1:48080'; // 后端打包自用
// const BASE = 'https://8984j70x85.zicp.fun'; //张政映射
// const BASE = 'http://10.137.2.164:48080'; // 正伟
// const BASE = 'http://192.168.39.230:48080'; // 正伟
// const BASE = 'http://10.27.17.201:19001'; // 黑龙江
const DOMAIN = BASE;
//'http://127.0.0.1:'+uni.getStorageSync("ZHHQ_HZ_PORT")+'/greenH5/greenH5modul/rest/mainInterface/approvalModule';
//发送请求
const VBPICTURE = function(a) {
WXSDK.previewImage({
current: a[0], // 当前显示图片的http链接
urls: a, // 需要预览的图片http链接列表
hidePreviewMenuList: [] // 要隐藏的菜单项,只能隐藏“传播类”和“保护类”按钮
});
}
const CALLPHONE = function(a) {
uni.makePhoneCall({
phoneNumber: a //仅为示例
});
}
const CALLBACK_REQUEST = function(data, method) {
// console.log('参数:', data)
data.checkTime = new Date().getTime();
if (!data.noLoading) {
uni.showLoading({
title: '加载中'
})
}
if (!data.userIdShow) {
data.userId = uni.getStorageSync("userId") ? uni.getStorageSync("userId") : '';
uni.setStorageSync("userId", data.userId)
}
let userInfos = uni.getStorageSync("userInfos")
data.tenantId = userInfos && userInfos.tenantId ? userInfos.tenantId : 1;
var KEY = CryptoJS.enc.Utf8.parse("greenh5java12345")
var IV = CryptoJS.enc.Utf8.parse("greenh5java12345")
var md5s = "greenh5"
var enparams = CryptoJS.AES.encrypt(JSON.stringify(data), KEY, {
iv: IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
}).toString()
var md5m = hex_md5(enparams + md5s).toLocaleUpperCase()
var checkTime = CryptoJS.AES.encrypt(JSON.stringify((new Date).getTime()), KEY, {
iv: IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
}).toString()
var method = CryptoJS.AES.encrypt(JSON.stringify(""), KEY, {
iv: IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
}).toString()
var params = {
body: enparams,
sign: md5m,
checkTime: checkTime,
method: method,
}
let Authorization = 'Bearer' + ' ' + data.userId
let userId = CryptoJS.AES.encrypt(Authorization, KEY, {
iv: IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
}).toString()
let url = "";
if (!DEVENV) {
// url = 'http://sgwpdm.ah.sgcc.com.cn';
url = 'http://10.138.55.104:48080';
} else {
url = DOMAIN;
}
return new Promise((resolve, reject) => {
uni.request({
url: url + data.method,
data: JSON.stringify(params),
method: 'POST',
dataType: 'json',
header: {
// 'tag': '',
'Authorization': userId,
'Tenant-Id': data.tenantId,
'content-type': 'application/json;charset=UTF-8', //自定义请求头信息
},
success: res => {
// let resdata = res.data
var md5m = hex_md5(res.body + md5s).toLocaleUpperCase()
// if (res.sign != md5m) {
// alert("数据异常")
// mui.hideLoading()
// return
// }
if (!data.noLoading) {
uni.hideLoading();
}
var decrypt = CryptoJS.AES.decrypt(res.data.body, KEY, {
iv: IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
})
var resdata = JSON.parse(decrypt.toString(CryptoJS.enc.Utf8))
console.log('接口入参' + data.method, data)
console.log('返回数据' + data.method, resdata)
// return param.cb(resdata)
resolve(resdata)
},
fail: err => {
if (!data.noLoading) {
uni.hideLoading();
}
console.log(err, "err");
reject(err);
if (!data.noLoading) {
uni.hideLoading();
}
ALERTTIP('数据加载失败')
},
// complete() {
// }
})
})
}
//图片上传公共方法
const chooseImg = () => {
return new Promise((resolve, reject) => {
let chec = 0;
let sty = []
uni.showActionSheet({
itemList: ['拍照', '相册'],
success: function(resp) {
chec = resp.tapIndex;
if (chec == 0) {
sty = ['camera']
} else {
sty = ['album']
}
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: sty,
quality: 1,
success: function(res) {
if (res.tempFiles[0].size > 1024 * 1024 * 5) {
uni.showToast({
title: '图片最大不能超过5M',
icon: 'none'
})
return
}
UPLOAD_IMG(res.tempFiles[0]).then(data => {
resolve(data)
})
.catch((errFiles) => {
reject(errFiles)
})
}
})
}
})
})
}
const UPLOAD_IMG = (imgUrl) => {
return new Promise((resolve, reject) => {
let url
let userId = ''
if (DEVENV) {
url = BASE + '/app-api/system/app/file/upload';
userId = 'cd43ce060ca0fe699de88297046f865c';
} else {
url = 'http://127.0.0.1:' + uni.getStorageSync("ZHHQ_HLJ_PORT") +
'/app-api/system/app/file/upload';
userId = uni.getStorageSync("userId") ? uni.getStorageSync("userId") : '';
}
let Bearer = 'Bearer' + ' ' + userId
let Authorization = CryptoJS.AES.encrypt(
Bearer,
KEY, {
iv: IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
}).toString()
uni.uploadFile({
url: url,
header: {
'Authorization': Authorization,
'tenant-id': 1,
},
file: imgUrl,
formData: {
domain: 'com',
code: '',
type: '',
},
success: resFiles => {
uni.showToast({
title: '上传成功',
icon: 'none'
})
let decrypt = CryptoJS.AES.decrypt(JSON
.parse(resFiles.data)
.body, KEY, {
iv: IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad
.ZeroPadding
})
let resdata = JSON.parse(decrypt
.toString(CryptoJS.enc.Utf8))
resolve(resdata.returnData)
},
fail: errFiles => {
reject(errFiles)
}
})
})
}
const CALLBACK_REQUEST_NOLOADING = function(data, method) {
data.checkTime = new Date().getTime();
data.clientId = uni.getStorageSync("clientId");
let url = "";
if (!DEVENV) {
url = 'http://127.0.0.1:' + uni.getStorageSync("ZHHQ_HZ_PORT") +
'/greenH5/greenH5modul/rest/mainInterface/approvalModule';
} else {
url = DOMAIN;
}
return new Promise((resolve, reject) => {
uni.request({
url: url,
data: JSON.stringify(data),
method: method || 'POST',
dataType: 'json',
header: {
'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
},
success: res => {
resolve(res)
},
fail: err => {
console.log(err, "err");
reject(err);
ALERTTIP('数据加载失败')
},
complete() {
// uni.hideLoading();
}
})
})
}
//发送无提示加载中的请求
const CALLBACK_REQUEST_NOTIP = function(url, data, method) {
data.checkTime = new Date().getTime();
if (!DEVENV) {
url = 'http://127.0.0.1:' + uni.getStorageSync("ZHHQ_HZ_PORT") +
'/greenH5/greenH5modul/rest/mainInterface/approvalModule';
} else {
url = DOMAIN;
}
return new Promise((resolve, reject) => {
uni.request({
url: url,
data: JSON.stringify(data),
method: method || 'POST',
dataType: 'json',
header: {
'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
},
success: res => {
resolve(res)
},
fail: err => {
console.log(err, "err");
reject(err);
uni.hideLoading();
ALERTTIP('数据加载失败')
},
complete() {
uni.hideLoading();
}
})
})
}
const REMOVEELEMENTOFARRAY = function(value, array) {
var index = -1;
for (var i = 0; i < array.length; i++) {
if (array[i] == value) {
index = i;
}
}
if (index >= 0) {
array.splice(index, 1);
}
return array;
}
//提示信息
const ALERTTIP = function(msg, icon, duration) {
uni.showToast({
title: msg,
icon: icon || 'none',
duration: duration || 2000
})
}
//需确认的提示信息
const SUREALERTTIP = function(title, content, showCancel) {
return new Promise((resolve, reject) => {
uni.showModal({
title: title || '',
content: content,
showCancel: showCancel,
success: res => {
if (res.confirm) {
resolve(200);
}
}
})
})
}
//时间格式化
const FORMATDATE = function(date, type) {
if (typeof date === 'string') {
date = date.replace(/-/g, '/');
}
let oldVal = new Date(date);
let newVal = '';
let year = oldVal.getFullYear();
let mount = oldVal.getMonth() + 1;
let day = oldVal.getDate();
let h = oldVal.getHours();
let m = oldVal.getMinutes();
let s = oldVal.getSeconds();
if (type == 'dateTime') {
newVal = year + '-' + format(mount) + '-' + format(day) + ' ' + format(h) + ':' + format(m) + ':' + format(
s);
} else if (type == 'm_Time') {
newVal = year + '-' + format(mount) + '-' + format(day) + ' ' + format(h) + ':' + format(m);
} else if (type == 'mTime') {
newVal = year + '/' + format(mount) + '/' + format(day) + ' ' + format(h) + ':' + format(m);
} else {
newVal = year + '-' + format(mount) + '-' + format(day);
}
function format(data) {
return data > 9 ? data : '0' + data
}
return newVal;
}
Date.prototype.format = function(fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var 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;
}
//获取近30天日期
const GETDATE = function() {
let time = new Date()
var a = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
let gday = 24 * 60 * 60 * 1000
let arr = [];
for (let i = 0; i < 30; i++) {
//         let tiems = new Date((time.getTime() + gday * i)).format('MM-dd');
let tiems = new Date((time.getTime() + gday * i));
tiems = FORMATDATE(tiems);
var day = new Date(tiems).getDay();
var week = a[day]
arr.push({
tiems: tiems,
week: week,
weekDay: day + "",
})
}
// var param ={
// "method": "greenCalendar/getCalendarList",
// "data": {
// date_name:arr[0].tiems,
// }
// };
// await getCalendar(param);
return arr;
}
const GETWEEK = function() {
var a = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
let arr = []
var now = new Date();
var year = now.getFullYear()
var day = now.getDay();
for (var i = 0; i < 7; i++) {
var firstDay = new Date(now - (now.getDay() - 1) * 86400000);
firstDay.setDate(firstDay.getDate() + i);
var mon = Number(firstDay.getMonth()) + 1 < 10 ? "0" + (Number(firstDay.getMonth()) + 1) : Number(firstDay
.getMonth()) + 1;
var day = firstDay.getDate() < 10 ? "0" + firstDay.getDate() : firstDay.getDate();
arr.push({
tiems: year + "-" + mon + "-" + day,
week: a[i],
weekDay: i,
})
}
return arr
}
const FORMATIMGURL = function(url) {
let oldUrl = url || "";
let imgName = oldUrl.split("webImageDir")[1];
if (imgName) {
let newUrl = 'http://127.0.0.1:' + uni.getStorageSync("ZHHQ_HZ_PORT") + '/webImageDir' + imgName;
return newUrl;
} else {
return "bucunzaideimg.jpg";
}
}
// 判断 json ,数组 等是否相等
const Compare = function Compare(objA, objB) {
if (!isObj(objA) || !isObj(objB)) return false; //判断类型是否正确
if (getLength(objA) != getLength(objB)) return false; //判断长度是否一致
return CompareObj(objA, objB, true); //默认为true
}
function isObj(object) {
return object && typeof(object) == 'object' && Object.prototype.toString.call(object).toLowerCase() ==
"[object object]";
}
function isArray(object) {
return object && typeof(object) == 'object' && object.constructor == Array;
}
function getLength(object) {
var count = 0;
for (var i in object) count++;
return count;
}
const CompareObj = function CompareObj(objA, objB, flag) {
for (var key in objA) {
if (!flag) //跳出整个循环
break;
if (!objB.hasOwnProperty(key)) {
flag = false;
break;
}
if (!isArray(objA[key])) { //子级不是数组时,比较属性值
if (objB[key] != objA[key]) {
flag = false;
break;
}
} else {
if (!isArray(objB[key])) {
flag = false;
break;
}
var oA = objA[key],
oB = objB[key];
if (oA.length != oB.length) {
flag = false;
break;
}
for (var k in oA) {
if (!flag) //这里跳出循环是为了不让递归继续
break;
flag = CompareObj(oA[k], oB[k], flag);
}
}
}
return flag;
}
// 获取今天起 指定天数的日期
const GETNUMDATE = function(num) {
let time = new Date()
var a = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
let gday = 24 * 60 * 60 * 1000
let arr = []
if (num <= 0) {
return arr
}
for (let i = 0; i < num; i++) {
//         let tiems = new Date((time.getTime() + gday * i)).format('MM-dd');
let tiems = new Date((time.getTime() + gday * i));
tiems = FORMATDATE(tiems);
var day = new Date(tiems).getDay();
var week = a[day]
arr.push({
tiems: tiems,
week: week,
weekDay: day + "",
})
}
return arr
}
//验证手机号
const REGPHONE = /^1[3|4|5|6|7|8|9]\d{9}$/;
//验证身份证号
const REGIDCARD =
/^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31|30)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/;
// 解决图片旋转问题 压缩
const resetOrientation = function(srcBase64, srcOrientation, callback) {
var img = new Image();
img.onload = function() {
var width = img.width,
height = img.height,
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
var maxWidth = 1024,
maxHeight = 1024;
if (width > maxWidth || height > maxHeight) {
if (width / height > maxWidth / maxHeight) {
maxHeight = Math.round(maxWidth * (height / width));
} else {
maxWidth = Math.round(maxHeight * (width / height));
}
} else {
maxWidth = width;
maxHeight = height;
}
if ([5, 6, 7, 8].indexOf(srcOrientation) > -1) {
canvas.width = maxHeight;
canvas.height = maxWidth;
} else {
canvas.width = maxWidth;
canvas.height = maxHeight;
}
switch (srcOrientation) {
case 2:
ctx.transform(-1, 0, 0, 1, maxWidth, 0);
break;
case 3:
ctx.transform(-1, 0, 0, -1, maxWidth, maxHeight);
break;
case 4:
ctx.transform(1, 0, 0, -1, 0, maxHeight);
break;
case 5:
ctx.transform(0, 1, 1, 0, 0, 0);
break;
case 6:
ctx.transform(0, 1, -1, 0, maxHeight, 0);
break;
case 7:
ctx.transform(0, -1, -1, 0, maxHeight, maxWidth);
break;
case 8:
ctx.transform(0, -1, 1, 0, 0, maxWidth);
break;
default:
ctx.transform(1, 0, 0, 1, 0, 0);
}
ctx.drawImage(img, 0, 0, maxWidth, maxHeight);
callback(canvas.toDataURL('image/jpeg'));
};
img.src = srcBase64;
}
const CONVERTIMGTOBASE64 = function(url, callback, outputFormat) {
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function() {
var _this = this,
wid = img.width,
hei = img.height,
maxWidth = 1024,
maxHeight = 1024;
if (wid > maxWidth || hei > maxHeight) {
if (wid / hei > maxWidth / maxHeight) {
maxHeight = Math.round(maxWidth * (hei / wid));
} else {
maxWidth = Math.round(maxHeight * (wid / hei));
}
} else {
maxWidth = wid;
maxHeight = hei;
}
canvas.width = maxWidth;
canvas.height = maxHeight;
ctx.drawImage(img, 0, 0, maxWidth, maxHeight);
let newUrl = canvas.toDataURL(outputFormat || 'image/jpeg');
callback.call(_this, newUrl);
canvas = null;
};
img.src = url;
}
// 定义转换函数
const TRANSFORMNUM2CHINESE = function(tranvalue) {
try {
var i = 1;
var dw2 = new Array("", "万", "亿"); //大单位
var dw1 = new Array("十", "百", "千"); //小单位
var dw = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九"); //整数部分用
//以下是小写转换成大写显示在合计大写的文本框中
//分离整数与小数
// var source = SPLITS(tranvalue);
var source = [tranvalue.toString(), ""];
var num = tranvalue;
var dig = "";
//转换整数部分
var k1 = 0; //计小单位
var k2 = 0; //计大单位
var sum = 0;
var str = "";
var len = source[0].length; //整数的长度
for (i = 1; i <= len; i++) {
var n = source[0].charAt(len - i); //取得某个位数上的数字
var bn = 0;
if (len - i - 1 >= 0) {
bn = source[0].charAt(len - i - 1); //取得某个位数前一位上的数字
}
sum = sum + Number(n);
if (sum != 0) {
str = dw[Number(n)].concat(str); //取得该数字对应的大写数字并插入到str字符串的前面
if (n == '0') sum = 0;
}
if (len - i - 1 >= 0) { //在数字范围内
if (k1 != 3) { //加小单位
if (bn != 0) {
str = dw1[k1].concat(str);
}
k1++;
} else { //不加小单位,加大单位
k1 = 0;
var temp = str.charAt(0);
if (temp == "万" || temp == "亿") //若大单位前没有数字则舍去大单位
str = str.substr(1, str.length - 1);
str = dw2[k2].concat(str);
sum = 0;
}
}
if (k1 == 3) //小单位到千则大单位进一
{
k2++;
}
}
//转换小数部分
var strdig = "";
if (dig != "") {
var n = dig.charAt(0);
if (n != 0) {
strdig += dw[Number(n)] + "角"; //加数字
}
var n = dig.charAt(1);
if (n != 0) {
strdig += dw[Number(n)] + "分"; //加数字
}
}
str += strdig;
} catch (e) {
return "";
}
return str;
}
//拆分整数与小数
const SPLITS = function(tranvalue) {
var value = new Array('', '');
temp = tranvalue.split(".");
for (var i = 0; i < temp.length; i++) {
value[i] = temp[i];
}
return value;
}
// if (/(Android)/i.test(navigator.userAgent)) {
// WXSDK = jWeixin;
// } else {
// WXSDK = wx;
// }
// if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
// WXSDK = wx;
// }
let WXSDK = "";
if (wx.config) {
WXSDK = wx;
} else {
WXSDK = jWeixin;
}
const searchTree = function(nodes, targetField, targetValue) {
for (let node of nodes) {
if (node[targetField] === targetValue) {
return true; // 找到了匹配的值
}
if (node.children) {
// 递归搜索子节点
if (searchTree(node.children, targetField, targetValue)) {
return true;
}
}
}
return false; // 没有找到匹配的值
}
const searchTreeMenu = function(nodes, targetField, targetValue) {
for (let node of nodes) {
// 检查当前节点是否匹配
if (node[targetField] === targetValue) {
return node.children || []; // 返回匹配节点的子节点
}
// 如果有子节点,递归搜索子节点
if (node.children) {
const result = searchTreeMenu(node.children, targetField, targetValue);
if (result.length > 0) { // 找到第一个匹配子节点后立即返回
return result;
}
}
}
return []; // 未找到匹配节点时返回空数组
};
const ML_CALLBACK_REQUEST = function(url, method, data) {
return new Promise((resolve, reject) => {
uni.showLoading({
title: '加载中',
mask: false
});
let ML_BASE = ''
if (!DEVENV) {
ML_BASE = 'https://api.mljk.com';
} else {
ML_BASE = DOC_BASE;
}
uni.request({
url: ML_BASE + url,
method: method,
data: data,
success: (res) => {
console.log(res);
uni.hideLoading()
if (res.statusCode == 200) {
if (res.data.code == '1') {
resolve(res)
} else {
uni.showToast({
title: res.data.message,
icon: 'none'
});
reject()
}
} else {
uni.showModal({
title: '提示',
content: `错误编码:${res.statusCode},错误信息:${res.data.Message || res.data}`
});
reject()
}
},
fail: (err) => {
uni.hideLoading()
console.log(err)
uni.showModal({
title: '提示',
content: JSON.stringify(err),
showCancel: false
});
reject(err)
}
})
})
}
/**
** 加法函数,用来得到精确的加法结果
** 说明javascript的加法结果会有误差在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
** 调用accAdd(arg1,arg2)
** 返回值arg1加上arg2的精确结果
**/
const accAdd = function(arg1, arg2) {
var r1, r2, m, c;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
c = Math.abs(r1 - r2);
m = Math.pow(10, Math.max(r1, r2));
if (c > 0) {
var cm = Math.pow(10, c);
if (r1 > r2) {
arg1 = Number(arg1.toString().replace(".", ""));
arg2 = Number(arg2.toString().replace(".", "")) * cm;
} else {
arg1 = Number(arg1.toString().replace(".", "")) * cm;
arg2 = Number(arg2.toString().replace(".", ""));
}
} else {
arg1 = Number(arg1.toString().replace(".", ""));
arg2 = Number(arg2.toString().replace(".", ""));
}
return (arg1 + arg2) / m;
}
/**
** 减法函数,用来得到精确的减法结果
** 说明javascript的减法结果会有误差在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。
** 调用accSub(arg1,arg2)
** 返回值arg1减去arg2的精确结果
**/
const accSub = function(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)); //last modify by deeka //动态控制精度长度
n = (r1 >= r2) ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
/**
** 乘法函数,用来得到精确的乘法结果
** 说明javascript的乘法结果会有误差在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
** 调用accMul(arg1,arg2)
** 返回值arg1乘以 arg2的精确结果
**/
const accMul = function(arg1, arg2) {
var m = 0,
s1 = arg1.toString(),
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);
}
module.exports = {
callPhone: CALLPHONE,
vbPicture: VBPICTURE,
alertTip: ALERTTIP,
setStorage: SETSTORAGE,
wxAuthorize: WXAUTHORIZE,
getStorage: GETSTORAGE,
clearStorage: CLEARSTORAGE,
callbackRequest: CALLBACK_REQUEST,
callbackRequestNoTip: CALLBACK_REQUEST_NOTIP,
callbackRequestNoLoading: CALLBACK_REQUEST_NOLOADING,
uploadImg: UPLOAD_IMG,
sureAlterTip: SUREALERTTIP,
formatDate: FORMATDATE,
getDate: GETDATE,
regPhone: REGPHONE,
convertImgToBase64: CONVERTIMGTOBASE64,
devEnv: DEVENV,
getNumDate: GETNUMDATE,
compare: Compare,
regIdCard: REGIDCARD,
resetOrientation: resetOrientation,
removeElementOfArray: REMOVEELEMENTOFARRAY,
transformNum2Chinese: TRANSFORMNUM2CHINESE,
getWeek: GETWEEK,
formatImgUrl: FORMATIMGURL,
wxSdk: WXSDK,
chooseImg: chooseImg,
base: BASE,
searchTree: searchTree,
searchTreeMenu: searchTreeMenu,
DOC_BASE,
ML_CALLBACK_REQUEST,
accAdd,
accSub,
accMul
}