1.数组的多条件筛选:
multiFilter(array, filters) {
const filterKeys = Object.keys(filters)
return array.filter((item) => {
return filterKeys.every(key => {
if (!filters[key].length) return true
return !!~filters[key].indexOf(item[key])
})
})
},
//array需要过滤的源数据,格式为array
//filters可以是对象,也可意识string类型的值
{
key1:[val1,val2,val2....],
key2:value
....
}
2.判断对象、数组是否为空
isEmpty(object) {
if (object === null || object === undefined || object === '' || object === '[]' || object === '{}') {
return true;
} else if (Object.prototype.toString.call(object) === '[object Array]' && object.length === 0) {
return true;
} else if (Object.prototype.toString.call(object) === '[object Object]' && JSON.stringify(object) === '{}') {
return true;
} else if (typeof object === 'string' && object.trim() === '') {
return true;
} else {
return false;
}
},
3.Vue时间过滤器 (使用方法:在vue中的模板语法中使用:例:{{ time | cficateTime }})
//获取当前时间到结束时间的间隔
Vue.filter('cficateTime', function(end_ttime) {
var start_time = new Date().getTime();
if (start_time === undefined || start_time === null || start_time === '') {
start_time = 0;
}
if (end_ttime === undefined || end_ttime === null || end_ttime === '') {
end_ttime = 0;
}
return parseInt((Number(end_ttime) - Number(start_time)) / 1000 / 60 / 60 /24);
});
//格式化图片列表
Vue.filter('img', function(url) {
if(url==null){
return;
}
const pathList = url.split(',');
const urlList = []
for (let i = 0; i < pathList.length; i++) {
// let urls = 'http://119.23.55.220:8003' + pathList[i];
let urls = pathList[i];
urlList.push(urls) //push中的参数为 :src="item.img_url" 中的图片地址
}
return urlList;
});
//格式化时间戳
Vue.filter('formatDate_yyyyMMddhhmmss', function(time) {
if (time === undefined || time === null || time === '') {
return '';
}
if ((typeof time) === 'string') {
time = Number(time);
}
return vm.formatDate(new Date(time), 'yyyy-MM-dd hh:mm:ss');
});
Vue.filter('formatDate_MMddhhmm', function(time) {
if (time === undefined || time === null || time === '') {
return '';
}
if ((typeof time) === 'string') {
time = Number(time);
}
return vm.formatDate(new Date(time), 'MM-dd hh:mm');
});
Vue.filter('formatDate_yyyy', function(time) {
if (time === undefined || time === null || time === '') {
return '';
}
if ((typeof time) === 'string') {
time = Number(time);
}
return vm.formatDate(new Date(time), 'yyyy');
});
Vue.filter('formatDate_MM', function(time) {
if (time === undefined || time === null || time === '') {
return '';
}
if ((typeof time) === 'string') {
time = Number(time);
}
return vm.formatDate(new Date(time), 'MM');
});
Vue.filter('formatDate_yyyyMMdd', function(time) {
if (time === undefined || time === null || time === '') {
return '';
}
if ((typeof time) === 'string') {
let date = new Date(time).getTime();
time = Number(date);
}
return vm.formatDate(new Date(time), 'yyyy-MM-dd');
});
Vue.filter('formatDate_yyyyMM', function(time) {
if (time === undefined || time === null || time === '') {
return '';
}
if ((typeof time) === 'string') {
let date = new Date(time).getTime();
time = Number(date);
}
return vm.formatDate(new Date(time), 'yyyy-MM');
});
Vue.filter('formatDate_ddhhmm', function(time) {
if (time === undefined || time === null || time === '') {
return '';
}
if ((typeof time) === 'string') {
time = Number(time);
}
return vm.formatDate(new Date(time), 'dd hh:mm');
});
Vue.filter('formatDate_hhmmss', function(time) {
if (time === undefined || time === null || time === '') {
return '';
}
if ((typeof time) === 'string') {
time = Number(time);
}
return vm.formatDate(new Date(time), 'hh:mm:ss');
});
//获取开始时间到结束时间的时间间隔
Vue.filter('date_interval', function(start_time,end_ttime) {
if (start_time === undefined || start_time === null || start_time === '') {
start_time = 0;
}
if (end_ttime === undefined || end_ttime === null || end_ttime === '') {
end_ttime = 0;
}
return (Number(end_ttime) - Number(start_time)) / 1000 ;
});
4.数组转字符串,转换成1,2,3,4逗号间隔
/**
* 数组转字符串,转换成1,2,3,4逗号间隔
* @param array 数组
* @param keyName 数组列键名
* @param split 间隔符号
* */
export function arrayToStringSplit(array, keyName, split) {
if (array == null || array === '') {
return '';
}
let str = '';
for (let i = 0; i < array.length; i++) {
const val = array[i];
if (typeof val === 'object') {
str = str + val[keyName] + split;
} else {
str = str + val + split;
}
}
return str.substr(0, str.length - split.length);
}
5.获取数组某个字段的集合
/**
* 获取数组某个字段的集合
* @param array 数组
* @param field 字段名称
* */
export function arrayToFieldList(array, field, prefix = null) {
if (array === null || array === undefined) {
return [];
}
return array.map(function(v) {
if (prefix === null) {
return v[field];
} else {
return prefix + v[field];
}
});
}
6.格式化时间戳
/**
* 格式化日期
* @param date 日期对象
* @param fmt 格式化样式
* */
export function formatDate(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
if ((typeof date) === 'string') {
return date;
}
if ((typeof date) === 'number') {
date = new Date(date);
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
const o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
};
for (const k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
const str = o[k] + '';
fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : (('00' + str).substr(str.length)));
}
}
return fmt;
}
7.时间戳相关
//日期转时间戳
function getUnixTime(dateStr){
var newstr = dateStr.replace(/-/g,'/');
var date = new Date(newstr);
var time_str = date.getTime().toString();
return time_str.substr(0, 10);
}
//时间戳转日期,falg:true表示只要年月日,part: year month date
function toDate(number,flag,part) {
var n = number;
var date = new Date(parseInt(n) * 1000);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
var h = date.getHours();
h = h < 10 ? ('0' + h) : h;
var minute = date.getMinutes();
var second = date.getSeconds();
minute = minute < 10 ? ('0' + minute) : minute;
second = second < 10 ? ('0' + second) : second;
if(flag){
if(part == "year"){
return y;
}else if(part == "month"){
return m;
}else if(part == "date"){
return n;
}
return y + '-' + m + '-' + d;
}
return y + '-' + m + '-' + d + ' ' + h + ':' + minute+':' + second;
}
//判断两个日期时间戳相差多少天,参数为时间戳
function dateCompare(dateTimeStamp1,dateTimeStamp2){
var dayNum = 0;
if(dateTimeStamp1 > dateTimeStamp2){
dayNum = Math.floor((dateTimeStamp1 - dateTimeStamp2) / 86400);
}else{
dayNum = Math.floor((dateTimeStamp2 - dateTimeStamp1) / 86400);
}
return dayNum;
}
//判断过去某个时间点到当前时间是否达到多少天,可以用来定期清理缓存
function datePassDays(dateTimeStamp,days){
var now = getUnixTime(formatDateThis(new Date()));
var diffValue = now - dateTimeStamp;
var limitTime = days * 86400;
if(diffValue >= limitTime){
return true;
}
return false;
}
//当前日期加减天数,falg:true表示只要年月日
function mathChangeDate(date,method,days,flag){
//method:'+' || '-'
//ios不解析带'-'的日期格式,要转成'/',不然Nan,切记
var dateVal = date.replace(/-/g, '/');
var timestamp = Date.parse(dateVal);
if(method == '+'){
timestamp = timestamp / 1000 + 24 * 60 * 60 * days;
} else if (method == '-'){
timestamp = timestamp / 1000 - 24 * 60 * 60 * days;
}
return toDate(timestamp,flag);
}
//时间戳转换具体时间描述(传入数值型时间戳)
function getDateDiff(dateTimeStamp) {
var result = '';
var minute = 1 * 60;
var hour = minute * 60;
var day = hour * 24;
var halfamonth = day * 15;
var month = day * 30;
var now = getUnixTime(formatDateThis(new Date()));//有些特殊 不能使用 new Date()
var diffValue = now - dateTimeStamp;
if (diffValue < 0) { return; }
var monthC = diffValue / month;
var weekC = diffValue / (7 * day);
var dayC = diffValue / day;
var hourC = diffValue / hour;
var minC = diffValue / minute;
if (monthC >= 1) {
result = "" + parseInt(monthC) + "月前";
}
else if (weekC >= 1) {
result = "" + parseInt(weekC) + "周前";
}
else if (dayC >= 1) {
result = "" + parseInt(dayC) + "天前";
}
else if (hourC >= 1) {
result = "" + parseInt(hourC) + "小时前";
}
else if (minC >= 1) {
result = "" + parseInt(minC) + "分钟前";
} else
result = "刚刚";
return result;
};
//获取当前年份,月份, 例: getCurrentTime("year")
const getCurrentTime = (method,date=new Date()) => {
if(method == "year"){
return date.getFullYear();
}else if(method == "month"){
return date.getMonth() + 1;
}
return date;
}
//获取当前服务器时间,参数直接用 new Date() 就可以了
const formatDateThis = (date,lab='-') => {
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(lab) +' '+ [hour, minute, second].map(formatNumber).join(':');
}
const formatTime = (date,lab='-') => {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return [year, month, day].map(formatNumber).join(lab);
}
const formatTimes = time => {
const hour = time.getHours();
const minute = time.getMinutes();
const second = time.getSeconds();
return [hour, minute,second].map(formatNumber).join(':');
}
//补0
const formatNumber = n => {
n = n.toString();
return n[1] ? n : '0' + n;
}
//比较两个时间大小(格式参考yyyy-mm-dd hh:mm:ss)
function compareTime(startTime,endTime){
//结束时间大于开始时间就是true , 反之则为 false
var sn = getUnixTime(startTime) * 1;
var en = getUnixTime(endTime) * 1;
if(en > sn){
return true;
}
return false;
}
8.function.js
var lsFrame = {};
//export
window.stringContainsSplitComma = stringContainsSplitComma;
window.getNowTimeStamp = getNowTimeStamp;
window.objectEquals = objectEquals;
window.gotoUrl = gotoUrl;
window.gotoLoginUrl = gotoLoginUrl;//微商城跳转登录页面 兼容小程序
window.hasValue = hasValue;
window.showloading = showloading;
window.closeloading = closeloading;
window.uuid = uuid;
window.gotoUrlNoVersion = gotoUrlNoVersion;
window.getToken = getToken;
window.gotoUrlForce = gotoUrlForce;
window.__changeLocalStorageContent2Url = __changeLocalStorageContent2Url;
window.getCurrentClient = getCurrentClient;
window.vueBack = "noFunction";
window.appBack = appBack;
window.deviceType = 'html';//设备标志: html 普通html app:app环境 miniprogram:小程序环境
window.appType = ""; //app类型,默认为空,若app回调成功,则修改此值,: ios 、 android
window.deviceEnv = deviceEnv;
window.exeAppFunc = exeAppFunc;
window.lisheClearLoc = lisheClearLoc;
window.isIE_Env = isIE_Env;//判断是否IE浏览器
window.IEVersion = IEVersion;//判断IE浏览器版本
window.setAppBack = setAppBack;
window.resetAppBack = resetAppBack;
window.logout = logout;
window.switchIdentity = switchIdentity;//切换企业
window.deepCopy = deepCopy;
window.objectValueEqual = objectValueEqual;
window.lishe = lishe;
window.lsFrame = lsFrame;
window.removeParam = removeParam;
window.replaceParam = replaceParam;
window.addQuery = addQuery;
window.getFirstAvailableValue = getFirstAvailableValue;
window.GFV = getFirstAvailableValue;
window.ObjectValue = ObjectValue;
window.getLastHost = getLastHost;
window.replaceObjectValue2AnotherOne = replaceObjectValue2AnotherOne;
window.mergeObject = mergeObject;
window.resetVuePageData = resetVuePageData;
window.getPCDomainName = getPCDomainName;
/**
*
* @param o1 destination
* @param o2 source
*/
function replaceObjectValue2AnotherOne(o1, o2) {
if (!o2) {
return o1;
}
for (var o1Key in o1) {
if (typeof o1[o1Key] == "object" && typeof o2[o1Key] == "object") {
replaceObjectValue2AnotherOne(o1[o1Key], o2[o1Key]);
} else {
//replace
if (typeof o2[o1Key] != "undefined") {
o1[o1Key] = o2[o1Key];
}
}
}
return o1;
}
function resetVuePageData(that, ...expectKeys) {
if (!hasValue(expectKeys) || expectKeys.length < 1) {
expectKeys = [];
}
var skippedKeys = ["pageOnShow", "lockPrice", "enablePrice"];
var originData = that.$options.data();
for (var key in originData) {
if (skippedKeys.contains(key) || expectKeys.contains(key)) {
continue;
}
that.$data[key] = originData[key];
}
}
/**
* 合并
* @param o1
* @param o2
*/
function mergeObject(o1, o2) {
if (!o2) {
return o1;
}
for (var o2Key in o2) {
if (typeof o2[o2Key] == "object") {
if (typeof o1[o2Key] == "undefined") {
o1[o2Key] = {};
}
mergeObject(o1[o2Key], o2[o2Key]);
} else {
//replace
o1[o2Key] = o2[o2Key];
}
}
return o1;
}
/**
* 公共函数区,每个前端同学请务必熟悉此文件的方法
* @param param
* @returns {boolean}
*/
function getPCDomainName() {
return "www";
}
function hasValue(param) {
return param !== undefined && param != null && param !== "" && param !== "null" && param !== "undefined" && param !== "error";
}
String.prototype.zintrim = function (char, type) {
if (char) {
if (type === 'left') {
return this.replace(new RegExp('^\\' + char + '+', 'g'), '');
} else if (type === 'right') {
return this.replace(new RegExp('\\' + char + '+$', 'g'), '');
}
return this.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
}
return this.replace(/^\s+|\s+$/g, '');
};
function getLastHost() {
let host = window.location.host;
let name = host.split(".")[0];
let lastHost = "";
if (["192", "10"].contains(name)) {
//内网
lastHost = host;
} else {
let hosts = host.split(".");
hosts.shift();
lastHost = hosts.join(".");
}
return lastHost;
}
function arrayValueEqual(x, y, z) {
if (x === y) {
return true;
}
if (!(x instanceof Array) || !(y instanceof Array)) {
return objectValueEqual(x, y, z);
}
if (x.length !== y.length) {
return false;
}
for (var i = 0; i < x.length; i++) {
if (x[i] instanceof Array) {
if (!arrayValueEqual(x[i], y[i], z)) {
return false;
}
} else if (x[i] instanceof Object) {
if (!objectValueEqual(x[i], y[i], z)) {
return false;
}
} else {
if (x[i] !== y[i]) {
return false;
}
}
}
return true;
}
/**
* 比较2个对象值相等,忽略属性下滑线_
* @param x
* @param y
* @param z
* @returns {boolean}
*/
function objectValueEqual(x, y, z) {
// If both x and y are null or undefined and exactly the same
if (x === y) {
return true;
}
if (x instanceof Array && y instanceof Array) {
return arrayValueEqual(x, y, z);
}
// If they are not strictly equal, they both need to be Objects
if (!(x instanceof Object) || !(y instanceof Object)) {
return false;
}
//They must have the exact same prototype chain,the closest we can do is
//test the constructor.
if (x.constructor !== y.constructor) {
return false;
}
//insure z is array...
if (!(z instanceof Array)) {
z = [];
}
for (var p in x) {
if (z.contains(p) || p.substring(0, 1) === "_") {
continue;
}
//Inherited properties were tested using x.constructor === y.constructor
if (x.hasOwnProperty(p)) {
// Allows comparing x[ p ] and y[ p ] when set to undefined
if (!y.hasOwnProperty(p)) {
return false;
}
// If they have the same strict value or identity then they are equal
if (x[p] === y[p]) {
continue;
}
// Numbers, Strings, Functions, Booleans must be strictly equal
if (typeof (x[p]) !== "object") {
return false;
}
// Objects and Arrays must be tested recursively
if (!objectValueEqual(x[p], y[p])) {
return false;
}
}
}
for (p in y) {
if (z.contains(p) || p.substring(0, 1) === "_") {
continue;
}
// allows x[ p ] to be set to undefined
if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
return false;
}
}
return true;
}
// loading 打开
function showloading(str="",specialShow=false) {
debug("打开loading:" + str);
if(centerCfg && centerCfg.forceCloseLoading && !specialShow){
return;
}
var loadImgSrc = "/static/images/load/loading.gif";
if(hasValue(ObjectValue("globalCfg.loadingIcon.src"))){
loadImgSrc = window.globalCfg.loadingIcon.src;
}
// if (hasValue(localStorage.moduleLocation)) {
// loadImgSrc = localStorage.moduleLocation + "assets/images/loading.gif";
// } else if (hasValue(window.globalCfg) && hasValue(window.globalCfg.loadingIcon) && hasValue(window.globalCfg.loadingIcon.src)) {
// //更改loading图片
// loadImgSrc = window.globalCfg.loadingIcon.src;
// }
var loadingWidth = '1.1rem', loadingLeft = '-0.55rem', loadingTop = "0rem";
if (getCurrentClient() === "1") {
loadingWidth = '180px';
loadingLeft = '-90px';
}
var template = '<div style="position:fixed; left:0;top:0;width:100%;height:100%;z-index:9999;" class="lisheloding">' +
'<div style="position: fixed;z-index:9998;width: 100%;min-height: 100%;top: 0;left: 0;background: transparent;text-align: center;">' +
'<div style="position: absolute;width: ' + loadingWidth + ';height: auto;left: 50%;top: 50%;margin-left: ' + loadingLeft + ';margin-top: ' + loadingLeft + '">' +
'<img style="width: 100%;pointer-events: none;" src="' + loadImgSrc + '" alt="">' +
'</div></div></div>';
if ($('.lisheloding').length > 0) {
$('.lisheloding').css({"display": "block"});
} else {
$('body').append(template);
}
setTimeout(function () {
closeloading();
//8s后关闭loading
}, 3666)
}
// loading 关闭
function closeloading() {
$('.lisheloding').css({"display": "none"});
}
String.prototype.startWith = function (str) {
var reg = new RegExp("^" + str);
return reg.test(this);
}
String.prototype.endWith = function (str) {
var reg = new RegExp(str + "$");
return reg.test(this);
}
String.prototype.contains = function (str) {
return this.indexOf(str) != -1;
}
//判断字符串中是否包含另一个字符串,用逗号分隔的
//str : "Details,"
//distStr: "Details"
function stringContainsSplitComma(str, distStr) {
var pages = str.split(",");
for (var i = 0; i < pages.length; i++) {
if (pages[i] === distStr) {
return true;
}
}
return false;
}
function getNowTimeStamp() {
return Math.round(new Date().getTime() / 1000);
}
//删除URL中的参数
function removeParam(param, url) {
if (!hasValue(url)) {
url = location.href;
}
var reg = new RegExp('(\\?|&)' + param + '=[^&]*(&)?', 'g');
return url.replace(reg, function (p0, p1, p2) {
return p1 === '?' || p2 ? p1 : '';
})
}
//在URL中增加参数
function addQuery(key, value, url) {
if (!hasValue(url)) {
url = location.href;
}
if (!hasValue(key) || !hasValue(value)) {
return url;
}
if (url.indexOf("?") !== -1) {
url = url + "&" + key + "=" + value;
} else {
url = url + "?" + key + "=" + value;
}
return url;
}
//替换URL中的参数
function replaceParam(param, val, url) {
url = removeParam(param, url);
url = url + "&" + param + "=" + val;
return url;
}
/**
* 比较2个对象的全部值是否相等,忽略隐藏属性 即 _开头的属性
* @param a
* @param b
* @returns {boolean}
*/
function objectEquals(a, b) {
return objectValueEqual(a, b, []);
}
function gotoUrl(url) {
var urlRefer = localStorage.getItem("urlRefer");
if (hasValue(urlRefer) && urlRefer.length > 10) {
//至少有10个字符的urlRefer
localStorage.removeItem("urlRefer");
__goto(urlRefer);
} else {
__goto(url);
}
}
function gotoLoginUrl() {
// 微商城跳转登录页
var token = getToken();
if (!hasValue(token)) {
// if (deviceType === "miniprogram") {
// /* 小程序获取openid */
// wx.miniProgram.navigateTo({
// url: "/pages/authorize/authorizePage?backUrl=zinEncodekUrl" + getEncodeString(window.location.href)
// });
// } else {
// window.location.href = "#/loginCode?backUrl=zinEncodekUrl" + getEncodeString(window.location.href);
// }
window.location.href = "/#/loginCode?backUrl=zinEncodekUrl" + getEncodeString(window.location.href);
return true
}
return false
}
function uuid() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
}
function gotoUrlNoVersion(url) {
window.location.href = url;
}
//给数组增加contains方法
Array.prototype.contains = function (needle) {
for (var i in this) {
if (this[i] === needle) return true;
}
return false;
};
function getToken(urlAfterLogin, isToken) {
var token = localStorage.getItem("token");
if (!token || token.length < 2) {
if (urlAfterLogin && urlAfterLogin.length > 3) {
//url编码
localStorage.setItem("urlAfterLogin", encodeURIComponent(urlAfterLogin));
}
if (isToken !== 1) {
return "";
}
}
return token;
}
function toDecimal2(x) {
var f = parseFloat(x);
if (isNaN(f)) {
return false;
}
var f = Math.round(x * 100) / 100;
var s = f.toString();
var rs = s.indexOf('.');
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + 2) {
s += '0';
}
return s;
}
function __goto(url) {
if (url.indexOf('?') == -1) {
url += '?v=VERSION_HOLD'
} else {
url += '&v=VERSION_HOLD'
}
if (typeof debugMode !== "undefined" && debugMode) {
if (confirm("测试模式,即将离开页面跳转到新的页面:\r\n" + url)) {
window.location.href = url;
}
return;
}
window.location.href = url;
}
function gotoUrlForce(url) {
__goto(url);
}
/**
* 退出登录
* @param callback 退出后的操作
*/
function logout(callback) {
lisheClearLoc(callback);
}
/**
* 此函数不建议使用了 请使用logout
* @param callback
*/
function lisheClearLoc(callback) {
var deviceId = localStorage.deviceId;
var vs = localStorage.appVS;
var fendId = localStorage.fendId;//授权码(长沙移动活动)
var switchAccountList = localStorage.switchAccountList;//切换账号列表 微商城切换账号
var appElemScrll = localStorage.appElemScrll;
var openId = localStorage.openId;
localStorage.clear();
sessionStorage.clear();
localStorage.deviceId = deviceId;
localStorage.appElemScrll = appElemScrll;
localStorage.appVS = vs;
if (hasValue(fendId)) {
localStorage.fendId = fendId;
}
if (hasValue(switchAccountList)) {
localStorage.switchAccountList = switchAccountList;
}
// 删除服务端
if (hasValue(openId)) {
deleteTempData("lg_" + openId, callback);
} else {
if (typeof callback == "function") {
callback();
}
}
}
//把localStorage的内容转换成url参数形式
function __changeLocalStorageContent2Url() {
var paramsString = "";
var ignoreKey = ["debugText", "redisContent", "switchAccountList", "listJSON"];//忽略的值
for (var localStorageItem in localStorage) {
if (ignoreKey.contains(localStorageItem)) {
//跳过忽略
continue;
}
if (typeof (localStorage[localStorageItem]) === 'function') {
//跳过方法
continue;
}
paramsString += localStorageItem + "EQUAL" + localStorage[localStorageItem] + "ANDAND";
}
paramsString = "localStroageContent=" + paramsString;
logout(function () {
})
return paramsString;
}
/**
* 切换临时企业身份
* @type {string}
*/
function switchIdentity(comId, res, err, nowIdentity) {
var token = getToken();
if (hasValue(token) && localStorage.comId == comId) {
if (typeof nowIdentity == "function") {
nowIdentity();
}
} else {
zinJSON(API_GATEWAY + "mainshop.User.switchIdentity?callback=?", {targetComId: comId},
function (result) {
if (result.errcode == 0) {
saveUserInfoAfterLogin(
result.data.info.token,
result.data.info.comId,
result.data.info.firstLogin,
result.data.info.userName,
1,
result.data.info.wwwRemainScore,
result.data.info.userAddressInfo,
result.data.info.domain,
result.data.info.account,
result.data.info.temporaryId,
result.data.info.articleCheckPermission,
function () {
//设置APP电池栏颜色0xf12c2f
subscribeMsg("appDeviceId", function (result) {
if (deviceType === "app") {
let dataAppColor = {'color': ''};
setLogoInfo(function (data) {
if (data.theme_color) {
let color = data.theme_color.split(",")[0].replace(/#/, '0x');
dataAppColor.color = Number(color);
window.zinAppFunc.jsCallAppFunc_changeStatusBarColor(dataAppColor);
}
})
}
})
//登录成功 存储登录信息
var switchAccountList = localStorage.getItem('switchAccountList');
if (hasValue(switchAccountList)) {
//已经存在账号切换列表
switchAccountList = JSON.parse(switchAccountList);
} else {
//不存在账号列表
switchAccountList = new Object();
}
//赋值
switchAccountList[result.data.info.account] = result.data.info;
//存储
localStorage.setItem('switchAccountList', JSON.stringify(switchAccountList));
res(result);
}
);
} else {
if (typeof err == "function") {
err(result);
}
return false;
}
}
)
}
}
//判断手机端还是电脑端
var currentClient = '0';
function getCurrentClient() {
if (currentClient !== '0') {
return currentClient;
}
//判断 https://m.zinsoft.com http://www.test.shopapi.zinsoft.com/ 被pc的iframe嵌套时
if ((location.href.indexOf('https://m.zinsoft.com') != -1 || location.href.indexOf('http://www.test.shopapi.zinsoft.com/') != -1) && window.top != window) {
setUserAgent(window, 'Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1');
}
var mobileAgent = new Array("iphone", "ipod", "ipad", "android", "mobile", "blackberry", "webos", "incognito", "webmate", "bada", "nokia", "lg", "ucweb", "skyfire");
var browser = navigator.userAgent.toLowerCase();
var isMobile = false;
for (var i = 0; i < mobileAgent.length; i++) {
if (browser.indexOf(mobileAgent[i]) != -1) {
isMobile = true;
currentClient = "2";
return "2";
}
}
currentClient = "1";
return "1";
}
//设置navigator userAgent 标识
function setUserAgent(window, userAgent) {
if (window.navigator.userAgent != userAgent) {
var userAgentProp = {
get: function () {
return userAgent;
}
};
try {
Object.defineProperty(window.navigator, 'userAgent', userAgentProp);
} catch (e) {
window.navigator = Object.create(navigator, {
userAgent: userAgentProp
});
}
}
}
String.prototype.LisheAllReplace = function (f, e) {//吧f替换成e
var reg = new RegExp(f, "g"); //创建正则RegExp对象
return this.replace(reg, e);
}
//这个函数是以前写的,以后用LisheAllReplace
String.prototype.myReplace = function (f, e) {//吧f替换成e
var reg = new RegExp(f, "g"); //创建正则RegExp对象
return this.replace(reg, e);
}
// var vueBack = "noFunction";
function appBack(type) {
if (type == 'close' && window.frames.length != parent.frames.length) {
window.parent.postMessage('close', '*');
return;
}
debug(typeof vueBack);
if (typeof vueBack === "function") {
vueBack();
} else {
window.history.go(-1);
}
}
//重置appback
function resetAppBack() {
window.vueBack = window.vueGlobalBack;
}
//设置appBack
function setAppBack(func) {
setTimeout(function () {
window.vueBack = func;
}, 500);
}
// APP功能使用
function setupWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
return callback(WebViewJavascriptBridge);
}
if (window.WVJBCallbacks) {
return window.WVJBCallbacks.push(callback);
}
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function () {
document.documentElement.removeChild(WVJBIframe)
}, 0)
}
//判断是否是IE浏览器
function isIE_Env() {
var ieVersion = IEVersion();
return ieVersion !== -1;
}
/**
* @return {number}
*/
function IEVersion() {
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
if (isIE) {
var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(userAgent);
var fIEVersion = parseFloat(RegExp["$1"]);
if (fIEVersion === 7) {
return 7;
} else if (fIEVersion === 8) {
return 8;
} else if (fIEVersion === 9) {
return 9;
} else if (fIEVersion === 10) {
return 10;
} else {
return 6;//IE版本<=7
}
} else if (isEdge) {
return 13;//edge
} else if (isIE11) {
return 11; //IE11
} else {
return -1;//不是ie浏览器
}
}
///
if (isWeiXin()) {
sessionStorage.setItem("deviceType", "html");
}
if (!isIE_Env() && getCurrentClient() == 2 && !isWeiXin()) {
if (getRequest("deviceType") == "html" || sessionStorage.getItem("deviceType") == "html") {
//强制跳过app检测,因为有个问题会导致其他app报错,比如民生银行手机银行
sessionStorage.setItem("deviceType", "html");
} else {
//< !--native 调用JS-- >
setupWebViewJavascriptBridge(function (bridge) {
bridge.registerHandler('deviceEnv', function (data, responseCallback) {
if (data.deviceType === 'ios' || data.deviceType === 'android') {
deviceType = "app";
appType = data.deviceType;
localStorage.deviceId = data.sn;
publishMsg('appDeviceId', localStorage.deviceId);
}
responseCallback('jsRunOk...');
})
});
setupWebViewJavascriptBridge(function (bridge) {
bridge.registerHandler('appBack', function (response) {
appBack();
})
});
}
}
// <!-- native 调用js -->
function deviceEnv(params) {
// if (!window.debugMode) {
// localStorage.debugMode = true;
// window.debugMode = true;
// location.reload();
// }
if (typeof params === "string") {
params = JSON.parse(params);
}
//确保param是json对象
if (params.deviceType === 'android' || params.deviceType === 'ios') {
deviceType = "app";
appType = params.deviceType;
localStorage.deviceId = params.sn;
publishMsg('appDeviceId', localStorage.deviceId);
}
debug(localStorage.deviceId);
}
//获取第一个可用的值
function getFirstAvailableValue(...p) {
for (var i = 0; i < p.length; i++) {
try {
if (hasValue(p[i])) {
return p[i];
}
} catch (e) {
//ignore
// console.log(e);
}
}
return p[p.length - 1];
}
/**
* 返回一个任意对象,防止对象不存在的问题
* @param str
* @param obj
* @returns {*|null}
* @constructor
*/
function ObjectValue(str, obj) {
if (!obj) {
obj = window;
}
if (typeof str !== "string") {
return null;
}
var split = str.split(".");
var key = split[0] + "";
if (split.length === 1) {
if (hasValue(obj[key])) {
return obj[key];
} else {
return null;
}
} else {
if (hasValue(obj[key])) {
split.shift();
return ObjectValue(split.join("."), obj[key])
} else {
return null;
}
}
}
/**
* 调用APP方法
* @param funcName 函数名,String
* @param param 这是Object形式的
* @param callback 回调(Object)
*/
function exeAppFunc(funcName, param, callback) {
if (hasValue(window.WebViewJavascriptBridge)) {
//老版本APP
if (funcName === 'loginAppClick' || funcName === 'logoutAppClick') {
return;
}
WebViewJavascriptBridge.callHandler(funcName, param, function (response) {
if (typeof callback === "function") {
callback(response);
}
});
}
if (appType === "ios") {
var tempParam = JSON.stringify(param);
window.webkit.messageHandlers[funcName].postMessage(tempParam);
if (hasValue(iosFunctionMap[funcName])) {
// 根据映射表 动态生成方法,供app回调
// result是iOS 调用该方法是传过来的参数(jsonString)
window[iosFunctionMap[funcName]] = function (result) {
var obj = JSON.parse(result);
callback(obj);
}
}
}
if (appType === "android") {
if (typeof JSCallNative_Interface[funcName] === "function") {
// var androidFunction = JSCallNative_Interface[funcName];
var tempParam = JSON.stringify(param);
var response = {}
if (hasValue(tempParam)) {
response = JSCallNative_Interface[funcName](tempParam);
} else {
response = JSCallNative_Interface[funcName]();
}
// 需要异步回调
if (hasValue(androidFunctionMap[funcName])) {
// 根据映射表 动态生成方法,供app回调
// result是android 调用该方法是传过来的参数(jsonString)
window[androidFunctionMap[funcName]] = function (result) {
if (typeof result === "string") {
try {
result = JSON.parse(result);
} catch (e) {
debug("cannot paserJSON:" + result);
}
}
callback(result);
}
return;
}
// 直接返回回调数据
if (hasValue(response)) {
if (typeof response === "string") {
response = JSON.parse(response);
}
if (typeof callback === "function") {
callback(response);
}
}
}
}
}
function deepCopy(obj) {
if (typeof Array.isArray != "function") {
Array.isArray = function (obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
}
}
var result = Array.isArray(obj) ? [] : {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
result[key] = deepCopy(obj[key]); //递归复制
} else {
result[key] = obj[key];
}
}
}
return result;
}
//运营获取localStorage
function lishe() {
var local = deepCopy(window.localStorage);
delete local.redisContent;
delete local.switchAccountList;
delete local.debugText;
delete local.listJSON;
local = JSON.stringify(local)
var localCode = getEncodeString(local);
return localCode;
}
lsFrame.open = function (url, title, description) {
lsFrame.close();
var titleDivDisplay = hasValue(title);
var urldecode = decodeURIComponent(url);
var windowDiv = document.createElement("div");
windowDiv.id = "windowDivWithTitle";
windowDiv.style.cssText = "height: 100%;position: fixed;left: 0;top: 0;width: 100%;z-index: 110;box-sizing: border-box;min-height: 100vh;";
var windowDiv_navGroup = document.createElement("div");
if (titleDivDisplay) {
windowDiv_navGroup.style.cssText = "background: #fff;display: flex;align-items: center;justify-content: space-between;height: 0.9rem;padding: 0 0.32rem;color: #000;position: fixed;width: 100%;z-index: 112;box-sizing: border-box;";
} else {
windowDiv_navGroup.style.cssText = "background: #fff;display: none;align-items: center;justify-content: space-between;height: 0.9rem;padding: 0 0.32rem;color: #000;position: fixed;width: 100%;z-index: 112;box-sizing: border-box;";
}
windowDiv.appendChild(windowDiv_navGroup);
var windowDiv_title = document.createElement("div");
windowDiv_title.innerHTML = "<span style='font-size: 0.38rem;font-weight: bold;'>" + title + "</span><span style='padding-left: 0.16rem;font-size: 0.26rem;font-weight: 500;'>" + description + "</span>";
windowDiv_title.style.cssText = "display: flex;align-items: flex-end;justify-content: space-between;";
windowDiv_navGroup.appendChild(windowDiv_title);
var windowDiv_icon = document.createElement("div");
windowDiv_icon.style.cssText = "width: 1.68rem;height: 0.6rem;border: 1px solid #E0E0E0;border-radius: 0.3rem;display: flex;align-items: center;justify-content: center;";
var icon_Setting = document.createElement("img");
icon_Setting.src = "https://lishe-shop-images.oss-cn-shenzhen.aliyuncs.com/editHtmlImg/upfile/2020-10-15/1602702869_11612.png";
icon_Setting.style.cssText = "width: 0.38rem;";
windowDiv_icon.appendChild(icon_Setting);
var icon_p = document.createElement("p");
icon_p.style.cssText = "width: 1px;height: 0.34rem;background: #E0E0E0;margin: 0.2rem;";
windowDiv_icon.appendChild(icon_p);
var icon_Close = document.createElement("img");
icon_Close.src = "https://lishe-shop-images.oss-cn-shenzhen.aliyuncs.com/editHtmlImg/upfile/2020-10-15/1602702869_19357.png";
icon_Close.style.cssText = "width: 0.38rem;";
windowDiv_icon.appendChild(icon_Close);
windowDiv_icon.onclick = function () {
lsFrame.close();
};
windowDiv_navGroup.appendChild(windowDiv_icon);
var iframe = document.createElement("iframe");
if (titleDivDisplay) {
iframe.style.cssText = "height: 100%;position: fixed;left: 0;top: 0;width: 100%;z-index: 110;box-sizing: border-box;padding-top: 0.9rem;border:0;background-color: #FFF;";
} else {
iframe.style.cssText = "height: 100%;position: fixed;left: 0;top: 0;width: 100%;z-index: 110;box-sizing: border-box;padding-top: 0rem;border:0;background-color: #FFF;";
}
windowDiv.appendChild(iframe);
iframe.src = urldecode;
document.body.appendChild(windowDiv);
};
lsFrame.close = function () {
var windowDivWithTitle = document.getElementById("windowDivWithTitle");
if (windowDivWithTitle) {
document.body.removeChild(windowDivWithTitle);
}
};
/**
* 这里需要配置 调用app方法后对应的回调方法映射表
* @type {{logoutAppClick: string, aaa: string}}
*/
var iosFunctionMap = {
"initClick": "initClickCallBack",
"checkVersionClick": "checkVersionClickCallBack",
"checkNetworkClick": "checkNetworkClickCallBack",
"storageGetClick": "storageGetClickCallBack",
"pasteBoredGetClick": "pasteBoredGetClickCallBack",
"locationClick": "locationClickCallBack",
"scanClick": "scanClickCallBack",
"uploadClick": "uploadClickCallBack",
"calcuCacheClick": "calcuCacheClickCallBack",
"loginClick": "loginClickCallBack",
"payClick": "payClickCallBack",
"getStepsClick": "getStepsClickCallBack",
"getAddressBookListClick": "getAddressBookListClickCallBack",
"checkPhoneNumLoginAuthClick": "checkPhoneNumLoginAuthClickCallBack",
"getPhoneNumLoginClick": "getPhoneNumLoginClickCallBack",
"audioClick": "audioClickCallBack",
"readBluetoothPrinter": "readBluetoothPrinterCallBack",
"connectBluetooth": "connectBluetoothCallBack",
"getBluetoothStatus": "getBluetoothStatusCallBack",
"getWechatPayAppid": "getWechatPayAppidCallBack",
"shareClick":"shareClickCallBack"
};
/**
* 这里需要配置 调用android方法后对应的回调方法映射表
* @type {{logoutAppClick: string, aaa: string}}
*/
var androidFunctionMap = {
"locationClick": "locationClickCallBack",
"scanClick": "scanClickCallBack",
"uploadClick": "uploadClickCallBack",
"loginClick": "loginClickCallBack",
"payClick": "payClickCallBack",
"getStepsClick": "getStepsClickCallBack",
"getAddressBookListClick": "getAddressBookListClickCallBack",
"checkPhoneNumLoginAuthClick": "checkPhoneNumLoginAuthClickCallBack",
"getPhoneNumLoginClick": "getPhoneNumLoginClickCallBack",
"audioClick": "audioClickCallBack",
"readBluetoothPrinter": "readBluetoothPrinterCallBack",
"connectBluetooth": "connectBluetoothCallBack",
"getWechatPayAppid": "getWechatPayAppidCallBack",
"shareClick":"shareClickCallBack"
};