ReedawFoodApp/toolJs/tools.js

370 lines
9.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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 $store from '@/store'
import $tools from '@/toolJs/tools.js'
import $model from '@/toolJs/model.js'
export default {
msg,
toHex,
gethms,
str2hex,
hex2str,
ab2hex,
inArray,
getMonth,
getDate,
GetDateStr,
PrefixZero,
showModal,
NewsPtype,
getTime,
compareVersions,
validatePhoneEmail,
checkPrivacyAgreement,
mergeAndDeduplicate,
parseUnitMask,
handleUserList
}
function parseUnitMask(hexValue, UNIT_MAP) {
// 转换为数字
const mask = typeof hexValue === 'string' ? parseInt(hexValue, 16) : hexValue;
// 验证输入
if (isNaN(mask) || mask < 0 || mask > 0xFF) {
console.error('无效的位掩码值');
return [];
}
// 存储结果
const usedUnits = [];
// 遍历每一位
for (let i = 0; i < 8; i++) {
// 使用位运算检查第 i 位是否为 1
if (mask & (1 << i)) {
usedUnits.push(UNIT_MAP[i]);
}
}
return usedUnits;
}
function NewsPtype(con) {
if (con.type == "wechat") { //跳小程序
// #ifdef APP
uni.navigateTo({
url: "/body/webview/webview?id=" + con.id + '&url=' + con.jump_url
})
// #endif
// #ifdef MP-WEIXIN
uni.navigateToMiniProgram({ //小程序跳小程序
appId: con.appid,
path: con.path,
extraData: {},
})
// #endif
} else if (con.type != 'wechat') { //跳h5或文本
uni.navigateTo({
url: "/body/webview/webview?id=" + con.id + '&url=' + con.jump_url
})
}
}
function msg(str) {
uni.showToast({
title: str,
icon: 'none',
duration: 3000
})
}
function showModal(text) {
uni.showModal({
title: "提示",
content: text,
showCancel: false,
success: function(res) {
if (res.confirm) {
uni.switchTab({ //返回
url: "/pages/index/index"
})
}
}
})
}
// 版本对比
function compareVersions(version1, version2) {
console.log("版本对比", version1, version2)
// 将版本号拆分成数字数组
var arr1 = version1.split('.').map(Number);
var arr2 = version2.split('.').map(Number);
var platform = uni.getSystemInfoSync().platform
// 遍历数字数组进行逐段比较
for (var i = 0; i < Math.max(arr1.length, arr2.length); i++) {
var num1 = parseInt(arr1[i] || 0); // 如果数组长度不够则将缺失部分补0
var num2 = parseInt(arr2[i] || 0);
if (num1 < num2) {
// 版本1小于版本2
return uni.showModal({
title: '发现新版本',
content: '检查到新版本' + version2 + ',是否更新?',
success: (modalRes) => {
if (modalRes.confirm) { //确定更新
if (platform === 'android') { //安卓更新
uni.navigateTo({
url: "/body/my/about"
})
} else { //ios跳转
plus.runtime.launchApplication({
action: `itms-apps://itunes.apple.com/cn/app/id6654906497?mt=8`
})
}
} else {
that.$tools.msg("稍后可在'关于我们'内更新程序!")
}
}
});
}
}
}
// 2进制位数不足补0
function PrefixZero(num, n) {
return (Array(n).join(0) + num).slice(-n);
}
//转16进制位数不足补0
function toHex(num, length) {
return num.toString(16).padStart(length, '0');
}
function inArray(arr, key, val) {
if (!arr || !arr.length || typeof arr != 'object' || !Array.isArray(arr)) {
return -1
}
for (let i = 0; i < arr.length; i++) {
if (!key) {
if (arr[i] == val) {
return i
}
} else if (arr[i][key] === val) {
return i
}
}
return -1;
}
//邮箱、手机号验证
function validatePhoneEmail(input) {
const phoneRegex = /^(\+?\d{1,4})?[-\s.]?\(?(\d{3})\)?[-\s.]?(\d{3})[-\s.]?(\d{4})$/;
const emailRegex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
const isPhone = phoneRegex.test(input);
const isEmail = emailRegex.test(input);
return {
isPhone,
isEmail
};
}
function ab2hex(buffer, split) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join(split);
}
function hex2str(arr) {
let decoder = new TextDecoder('utf8')
let uint8 = new Uint8Array(arr)
let res = decoder.decode(uint8)
return res
}
function str2hex(str) {
let encoder = new TextEncoder('utf8')
return encoder.encode(str)
}
// 跳绳分秒时间选择
function gethms(type) {
var mindata = []
var secondData = []
let timeList = []
for (var i = 0; i <= 59; i++) {
i = i > 9 ? i : '0' + i
mindata.push(i + '分');
}
for (var i = 0; i <= 59; i++) {
i = i > 9 ? i : '0' + i
secondData.push(i + '秒');
}
timeList[0] = mindata
timeList[1] = secondData
return timeList
}
// 指定日期起始月
function getMonth(dates, months) {
var d = new Date(dates.substring(0, 10));
let year = d.getFullYear();
var month = d.getMonth() + 1;
if (Math.abs(months) > 12) {
months = months % 12;
};
if (months != 0) {
if (month + months > 12) {
year++;
month = (month + months) % 12;
} else if (month + months < 1) {
year--;
month = 12 + month + months;
} else {
month = month + months;
};
};
month = month < 10 ? "0" + month : month;
var date = d.getDate();
if (month == "01" || month == "03" || month == "05" || month == "07" || month == "08" || month == "10" ||
month == "12") {
return year + "-" + month + "-01" + "~" + year + "-" + month + "-31";
} else if (month == "02") {
if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
return year + '-' + month + "-01" + "~" + year + "-" + month + "-29";
} else {
return year + '-' + month + "-01" + "~" + year + "-" + month + "-28";
};
} else {
return year + '-' + month + "-01" + "~" + year + "-" + month + "-30";
};
};
function getDate(type) {
const date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
month = month > 9 ? month : '0' + month;
day = day > 9 ? day : '0' + day;
if (type === 'tow') {
year = year - 2;
return `${year}-${month}-${day}`;
}
if (type === 'start') {
year = year;
return `${year}-${month}-${day}`;
}
if (type === 'end') {
year = year + 60;
return `${year}-${month}-${day}`;
}
if (type === 'year') {
year = year;
return `${year}`;
}
if (type === 'month') {
year = year;
return `${year}-${month}`;
}
if (type == "m") {
if (month == "01" || month == "03" || month == "05" || month == "07" || month == "08" || month == "10" ||
month == "12") {
return year + "-" + month + "-01" + "~" + year + "-" + month + "-31";
} else if (month == "02") {
if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
return year + "-" + month + "-01" + "~" + year + "-" + month + "-29";
} else {
return year + "-" + month + "-01" + "~" + year + "-" + month + "-28";
};
} else {
return year + "-" + month + "-01" + "~" + year + "-" + month + "-30";
};
}
}
//获取AddDayCount天后的日期
function GetDateStr(AddDayCount) {
var dd = new Date();
dd.setDate(dd.getDate() + AddDayCount);
var y = dd.getFullYear();
var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1); //获取当前月份的日期不足10补0
var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate(); //获取当前几号不足10补0
return y + "-" + m + "-" + d;
}
//用于检查用户是否同意隐私协议
function checkPrivacyAgreement() {
// 这里应该是获取用户同意状态的逻辑,例如从本地存储或服务端获取
const isAgreed = uni.getStorageSync('isPrivacyAgreed');
return !!isAgreed;
}
// 合并数组并去重
function mergeAndDeduplicate(arr1, arr2, uniqueKey) {
let map = new Map();
let mergedArr = [...arr1, ...arr2];
for (let item of mergedArr) {
if (!map.has(item[uniqueKey])) {
map.set(item[uniqueKey], item);
}
}
return [...map.values()];
}
// 获取当前年、月、日、时、分、秒
function getTime() {
var date = new Date()
var y = date.getFullYear();
var m = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1); //获取当前月份的日期不足10补0
var d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
let H = date.getHours() > 9 ? date.getHours() : '0' + date.getHours()
let Min = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()
return y + '/' + m + '/' + d + " " + H + ':' + Min
}
// 未登录及取消更新
function handleUserList() {
$model.getUserList({
type: 2
}).then(res => {
if (res.code != 0) {
$tools.msg(res.msg)
return
}
$store.commit('changeFamilay', res.data.user_list)
if (res.data.user_list.length) {
let userid = ""
if (uni.getStorageSync('userid')) {
let found = res.data.user_list.find(e => e.id == uni.getStorageSync('userid'));
if (found !== undefined) {
userid = found.id
} else {
userid = res.data.user_list[0].id
uni.setStorageSync('userid', res.data.user_list[0].id)
}
} else {
userid = res.data.user_list[0].id
uni.setStorageSync('userid', res.data.user_list[0].id)
}
// 用户信息接口
$store.dispatch('getUserInfo', {
aud_id: userid
})
// 厨房秤接口
$store.dispatch("getCountFoodInfo", {
aud_id: userid,
time: $tools.getDate("start")
})
// 全部卡片
$store.dispatch("getCardAllList", {
aud_id: userid
})
//
$store.dispatch("getResult", {
aud_id: userid
})
$store.dispatch("getPublicRecord", {
aud_id: userid
})
$store.commit("changehomeCard", 0);
}
}).catch(err => {})
}