Initial commit

This commit is contained in:
lnljyang
2025-12-30 09:44:46 +08:00
commit 82b8d21506
147 changed files with 39113 additions and 0 deletions

26
utils/auth.js Normal file
View File

@@ -0,0 +1,26 @@
import store from './storage';
export const getToken = () => store.get('token');
export const setToken = (token) => {
try {
store.set('token', token);
return true;
} catch (e) {
return false;
}
}
export const removeToken = () => {
store.remove("token")
}
export const setUser = (userInof) => {
try {
store.set("userInfo", userInof);
return true;
} catch (e) {
return false;
}
}
export const getUser = () => store.get('userInfo');
export const removeUser = () =>
store.remove("userInfo");

623
utils/fileManager.js Normal file
View File

@@ -0,0 +1,623 @@
/**
* 文件管理工具类
* 用于统一处理文件列表操作,包括添加、删除、解析等
*/
class FileManager {
constructor() {
// 文件类型配置映射
this.fileTypeConfig = {
// 仪表盘照片
1: {
dataKey: "dashboardPic",
dataKey2: "dashboard2Pic",
isArray: false,
hasMultiple: true,
isPathOnly: true,
},
// 正面照片
2: {
dataKey: "frontPic",
isArray: false,
isPathOnly: true,
},
// 左前方照片
3: {
dataKey: "leftFrontPic",
isArray: false,
isPathOnly: true,
},
// 右前方照片
4: {
dataKey: "rightFrontPic",
isArray: false,
isPathOnly: true,
},
// 左后方照片
5: {
dataKey: "leftRearPic",
isArray: false,
isPathOnly: true,
},
// 右后方照片
6: {
dataKey: "rightRearPic",
isArray: false,
isPathOnly: true,
},
// 瑕疵照片
7: {
dataKey: "blemish",
isArray: true,
isPathOnly: true,
},
// 轮胎照片
8: {
dataKey: "tirePic",
isArray: true,
isPathOnly: true,
},
// 其它
9: {
dataKey: "otherPic",
isArray: true,
isPathOnly: true,
},
// 司机证件
10: {
dataKey: "documents",
isArray: true,
isPathOnly: true,
},
// 电子文档
11: {
dataKey: "esignatureAttachment",
isArray: true,
isPathOnly: false,
},
// 培训文件签字照片
12: {
dataKey: "signAttachment",
isArray: true,
isPathOnly: false,
},
// 安全培训照片
13: {
dataKey: "safetyTrainingPicture",
isArray: true,
isPathOnly: false,
},
// 安全培训附件
14: {
dataKey: "safetyTrainingAttachment",
isArray: true,
isPathOnly: false,
},
// 轮胎照片 - 左前轮
15: {
dataKey: "leftFrontTirePic",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 左后轮(内)
16: {
dataKey: "leftRearTirePicIn",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 左后轮(外)
17: {
dataKey: "leftRearTirePicOut",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 右前轮
18: {
dataKey: "rightFrontTirePic",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 右后轮(内)
19: {
dataKey: "rightRearTirePicIn",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 右后轮(外)
20: {
dataKey: "rightRearTirePicOut",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 备胎
21: {
dataKey: "spareTirePic",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 左中内
22: {
dataKey: "leftMiddleTirePicIn",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 左中外
23: {
dataKey: "leftMiddleTirePicOut",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 左后内
24: {
dataKey: "leftRearMiddleTirePicIn",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 左后外
25: {
dataKey: "leftRearMiddleTirePicOut",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 右中内
26: {
dataKey: "rightMiddleTirePicIn",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 右中外
27: {
dataKey: "rightMiddleTirePicOut",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 右后内
28: {
dataKey: "rightRearMiddleTirePicIn",
isArray: false,
isPathOnly: true,
},
// 轮胎照片 - 右后外
29: {
dataKey: "rightRearMiddleTirePicOut",
isArray: false,
isPathOnly: true,
},
// 底盘照片 - 正前方底部照片
30: {
dataKey: "frontBottomPic",
isArray: false,
isPathOnly: true,
},
// 底盘照片 - 左侧前部底部照片
31: {
dataKey: "leftFrontBottomPic",
isArray: false,
isPathOnly: true,
},
// 底盘照片 - 左侧后方底部照片
32: {
dataKey: "leftRearBottomPic",
isArray: false,
isPathOnly: true,
},
// 底盘照片 - 右侧前方底部照片
33: {
dataKey: "rightFrontBottomPic",
isArray: false,
isPathOnly: true,
},
// 底盘照片 - 右侧后方底部照片
34: {
dataKey: "rightRearBottomPic",
isArray: false,
isPathOnly: true,
},
// 底盘照片 - 正后方底部照片
35: {
dataKey: "rearBottomPic",
isArray: false,
isPathOnly: true,
},
// 12轮胎车辆 - 左前外
36: {
dataKey: "leftFrontTirePicOut",
isArray: false,
isPathOnly: true,
},
// 12轮胎车辆 - 左前内
37: {
dataKey: "leftFrontTirePicIn",
isArray: false,
isPathOnly: true,
},
// 12轮胎车辆 - 右前外
38: {
dataKey: "rightFrontTirePicOut",
isArray: false,
isPathOnly: true,
},
// 12轮胎车辆 - 右前内
39: {
dataKey: "rightFrontTirePicIn",
isArray: false,
isPathOnly: true,
},
};
}
/**
* 添加文件到数据对象
* @param {Object} data - 数据对象
* @param {string} fileTypeId - 文件类型ID
* @param {string} imgUrl - 图片URL
* @param {Object} extraData - 额外数据(如文件名等)
*/
addFileToData(data, fileTypeId, imgUrl, extraData = {}) {
const config = this.fileTypeConfig[fileTypeId];
if (!config) return;
// 仪表盘照片特殊处理,有两个字段
if (fileTypeId === "1") {
if (!data.dashboardPic || data.dashboardPic === "") {
data.dashboardPic = imgUrl;
} else {
data.dashboard2Pic = imgUrl;
}
return;
}
// 数组类型处理
if (config.isArray) {
if (!data[config.dataKey]) {
data[config.dataKey] = [];
}
if (config.isPathOnly) {
// 只保存路径
data[config.dataKey].push(imgUrl);
} else {
// 保存对象
data[config.dataKey].push({
path: imgUrl,
fileName: extraData.fileName || "",
thumb: extraData.thumb || "",
});
}
} else {
// 单个字段处理
if (config.isPathOnly) {
data[config.dataKey] = imgUrl;
} else {
data[config.dataKey] = {
path: imgUrl,
fileName: extraData.fileName || "",
thumb: extraData.thumb || "",
};
}
}
}
/**
* 从数据对象中删除文件
* @param {Object} data - 数据对象
* @param {string} fileTypeId - 文件类型ID
* @param {number} index - 要删除的索引
* @param {Array} fileList - 当前的文件列表(用于仪表盘照片特殊处理)
*/
removeFileFromData(data, fileTypeId, index, fileList) {
const config = this.fileTypeConfig[fileTypeId];
if (!config) return;
// 仪表盘照片特殊处理
if (fileTypeId === "1") {
if (fileList && fileList.length === 0) {
data.dashboardPic = "";
data.dashboard2Pic = "";
} else {
if (index === 0) {
data.dashboardPic = data.dashboard2Pic || "";
data.dashboard2Pic = "";
} else {
data.dashboard2Pic = "";
}
}
return;
}
// 数组类型处理
if (config.isArray) {
if (data[config.dataKey] && data[config.dataKey].length > index) {
data[config.dataKey].splice(index, 1);
}
} else {
// 单个字段处理
data[config.dataKey] = "";
}
}
/**
* 从后端数据解析文件列表
* @param {Object} data - 数据对象
* @param {Object} compressPicMap - 压缩图片映射
*/
parseFileListFromData(data, compressPicMap) {
const result = {};
// 处理仪表盘照片
result.fileList1 = [];
if (data.dashboardPicData?.path) {
result.fileList1.push({
url: data.dashboardPicData.path,
thumb:
data.dashboardPicData.compressedImagePath ||
data.dashboardPicData.path,
});
compressPicMap.set(
data.dashboardPicData.path,
data.dashboardPicData.compressedImagePath || data.dashboardPicData.path
);
}
data.dashboardPic = data.dashboardPicData?.path ?? "";
// 仪表盘第二张照片
if (data.dashboard2PicData?.path) {
result.fileList1.push({
url: data.dashboard2PicData.path,
thumb:
data.dashboard2PicData.compressedImagePath ||
data.dashboard2PicData.path,
});
compressPicMap.set(
data.dashboard2PicData.path,
data.dashboard2PicData.compressedImagePath ||
data.dashboard2PicData.path
);
}
data.dashboard2Pic = data.dashboard2PicData?.path ?? "";
// 处理其他类型的文件
const singlePicTypes = [
{ id: "2", dataKey: "frontPic", dataKeyData: "frontPicData" },
{ id: "3", dataKey: "leftFrontPic", dataKeyData: "leftFrontPicData" },
{ id: "4", dataKey: "rightFrontPic", dataKeyData: "rightFrontPicData" },
{ id: "5", dataKey: "leftRearPic", dataKeyData: "leftRearPicData" },
{ id: "6", dataKey: "rightRearPic", dataKeyData: "rightRearPicData" },
];
singlePicTypes.forEach((type) => {
result[`fileList${type.id}`] = [];
if (data[`${type.dataKeyData}`]?.path) {
result[`fileList${type.id}`] = [
{
url: data[`${type.dataKeyData}`].path,
thumb:
data[`${type.dataKeyData}`].compressedImagePath ||
data[`${type.dataKeyData}`].path,
},
];
compressPicMap.set(
data[`${type.dataKeyData}`].path,
data[`${type.dataKeyData}`].compressedImagePath ||
data[`${type.dataKeyData}`].path
);
}
data[type.dataKey] = data[`${type.dataKeyData}`]?.path ?? "";
});
// 处理数组类型的文件
const arrayPicTypes = [
{ id: "7", dataKey: "blemish" },
{ id: "8", dataKey: "tirePic" },
{ id: "9", dataKey: "otherPic" },
{ id: "10", dataKey: "documents" },
];
arrayPicTypes.forEach((type) => {
result[`fileList${type.id}`] = data[type.dataKey].map((x) => ({
url: x.path,
thumb: x.compressedImagePath || x.path,
}));
data[type.dataKey].forEach((x) => {
compressPicMap.set(x.path, x.compressedImagePath || x.path);
});
data[type.dataKey] = data[type.dataKey].map((x) => x.path);
// 交车页面的"其它"文件是对象数组,需要保持原结构
// if (type.id === "9") {
// // 交车页面的otherPic是对象数组不需要转换 将错就错了 在交车save/submit的时候会处理 正常这里改了 那边就可以不处理了
// } else {
// data[type.dataKey] = data[type.dataKey].map((x) => x.path);
// }
});
// 处理电子文档
if (data.esignatureAttachment && data.esignatureAttachment.length >= 1) {
result.fileList11 = [
{
url: data.esignatureAttachment[0].path,
thumb: "/static/pdf.png",
},
];
}
// 处理培训文件签字照片
result.fileList12 = data.signAttachment.map((x) => ({
url: x.path,
thumb: x.compressedImagePath || x.path,
}));
data.signAttachment.forEach((x) => {
compressPicMap.set(x.path, x.compressedImagePath || x.path);
});
// 处理安全培训照片
result.fileList13 =
data?.safetyTrainingPicture?.map((x) => ({
url: x.path,
thumb: x.compressedImagePath || x.path,
})) || [];
data?.safetyTrainingPicture?.forEach((x) => {
compressPicMap.set(x.path, x.compressedImagePath || x.path);
});
data.safetyTrainingPicture =
data?.safetyTrainingPicture?.map((x) => ({
path: x.path,
})) || [];
// 处理安全培训附件
result.fileList14 =
data?.safetyTrainingAttachment?.map((x) => ({
url: x.path,
name: x.fileName,
type: x.fileName.substring(x.fileName.lastIndexOf(".") + 1) || "",
thumb: x.compressedImagePath || x.path,
})) || [];
data.safetyTrainingAttachment =
data?.safetyTrainingAttachment?.map((x) => ({
path: x.path,
fileName: x.fileName,
})) || [];
// 处理轮胎照片
const tireKeys1 = [
"leftFrontTirePic",
"leftRearTirePicIn",
"leftRearTirePicOut",
"rightFrontTirePic",
"rightRearTirePicIn",
"rightRearTirePicOut",
"spareTirePic",
];
let tireIndex = 15;
tireKeys1.forEach((key) => {
if (data[key]) {
const picData = data[key];
if (picData?.path) {
result[`fileList${tireIndex}`] = [
{
url: picData.path,
thumb: picData.compressedImagePath || picData.path,
},
];
compressPicMap.set(
picData.path,
picData.compressedImagePath || picData.path
);
}
data[key] = picData?.path ?? "";
}
tireIndex++;
});
// 处理49吨轮胎照片
const tireKeys2 = [
"leftMiddleTirePicIn",
"leftMiddleTirePicOut",
"leftRearMiddleTirePicIn",
"leftRearMiddleTirePicOut",
"rightMiddleTirePicIn",
"rightMiddleTirePicOut",
"rightRearMiddleTirePicIn",
"rightRearMiddleTirePicOut",
];
tireIndex = 22;
tireKeys2.forEach((key) => {
if (data[key]) {
const picData = data[key];
if (picData?.path) {
result[`fileList${tireIndex}`] = [
{
url: picData.path,
thumb: picData.compressedImagePath || picData.path,
},
];
compressPicMap.set(
picData.path,
picData.compressedImagePath || picData.path
);
}
data[key] = picData?.path ?? "";
}
tireIndex++;
});
// 处理底盘照片
const bottomKeys = [
"frontBottomPic",
"leftFrontBottomPic",
"leftRearBottomPic",
"rightFrontBottomPic",
"rightRearBottomPic",
"rearBottomPic",
];
let bottomIndex = 30;
bottomKeys.forEach((key) => {
if (data[key]) {
const picData = data[key];
if (picData?.path) {
// 对象格式 {path:"",compressedImagePath:""}
result[`fileList${bottomIndex}`] = [
{
url: picData.path,
thumb: picData.compressedImagePath || picData.path,
},
];
compressPicMap.set(
picData.path,
picData.compressedImagePath || picData.path
);
data[key] = picData.path; // 转换为字符串格式
} else if (typeof picData === "string") {
// 字符串格式
result[`fileList${bottomIndex}`] = [
{
url: picData,
thumb: picData,
},
];
compressPicMap.set(picData, picData);
}
}
bottomIndex++;
});
// 处理12轮胎车辆的新增轮胎字段
const twelveTireKeys = [
"leftFrontTirePicOut",
"leftFrontTirePicIn",
"rightFrontTirePicOut",
"rightFrontTirePicIn",
];
let twelveTireIndex = 36;
twelveTireKeys.forEach((key) => {
if (data[key]) {
const picData = data[key];
if (picData?.path) {
result[`fileList${twelveTireIndex}`] = [
{
url: picData.path,
thumb: picData.compressedImagePath || picData.path,
},
];
compressPicMap.set(
picData.path,
picData.compressedImagePath || picData.path
);
}
data[key] = picData?.path ?? "";
}
twelveTireIndex++;
});
return result;
}
}
export default FileManager;

50
utils/init.js Normal file
View File

@@ -0,0 +1,50 @@
import {
getToken
} from "./auth"
export default function initApp() {
/**
* 页面跳转拦截器
*/
let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
list.forEach(item => { //用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
uni.addInterceptor(item, {
invoke(e) { // 调用前拦截
//获取用户的token
const token = getToken();
const url = e.url.split('?')[0];
let notNeed = ["/pages/login/login"].includes(url)
// 如果在whiteList里面就不需要登录
if (notNeed) {
return e
} else {
//需要登录
if (token == undefined || token == '') {
uni.showToast({
title: '请先登录',
icon: 'none'
})
uni.reLaunch({
url: "/pages/login/login"
})
return false
} else {
return e
}
}
},
fail(err) { // 失败回调拦截
console.log(err);
// uni.showModal({
// content: JSON.stringify(err),
// showCancel: false
// });
}
})
})
}

26
utils/key.js Normal file
View File

@@ -0,0 +1,26 @@
import CryptoJS from "crypto-js";
export default {
//加密
encrypt(data, keyStr) {
keyStr = keyStr ? keyStr : "5a261be5eda9445099bef50a5f8df559";
var key = CryptoJS.enc.Utf8.parse(keyStr);
var ivs = CryptoJS.enc.Utf8.parse(keyStr);
var encrypted = CryptoJS.AES.encrypt(data, key, {
iv: ivs,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return CryptoJS.enc.Hex.stringify(encrypted.ciphertext);
},
//解密
decrypt(word, keyStr) {
keyStr = keyStr ? keyStr : "5a261be5eda9445099bef50a5f8df559";
var key = CryptoJS.enc.Utf8.parse(keyStr); //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
var decrypt = CryptoJS.AES.decrypt(word, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
},
};

74
utils/permission.js Normal file
View File

@@ -0,0 +1,74 @@
import store from "@/store";
/**
* @param {Array} value
* @returns {Boolean}
* @example see @/views/permission/directive.vue
*/
export const checkButtonPermission = (buttonCode, pageCode) => {
console.log(store);
let resources = store.state.resources;
//console.log(resources);
if (!resources) {
return false;
}
if (!pageCode) {
return false;
}
if (!buttonCode) {
return false;
}
let pages = resources.filter(
(item) => item.code == pageCode && item.type == 0
);
if (!pages) {
return false;
}
let buttons = [];
for (let key in pages) {
buttons = resources.filter(
(item) =>
item.type == 1 && item.code == buttonCode && item.pid == pages[key].id
);
if (buttons.length > 0) {
return true;
}
}
return false;
};
export const checkPagePermission = (pageCode) => {
let resources = store.state.resources;
//console.log(resources);
if (!Array.isArray(resources)) {
resources = [];
}
if (!pageCode) {
return false;
}
let pages = resources.filter(
(item) => item.code == pageCode && item.type == 0
);
if (pages.length < 1) {
return false;
}
if (
[
"truckOptBI",
"hydrogenBill",
"dailyHydrogenOrderBI",
"weappMileageBi",
"bi_ele_daily_summary",
].includes(pages[0].code)
) {
return pages[0].link;
}
return true;
};

580
utils/request.js Normal file
View File

@@ -0,0 +1,580 @@
/**
* @description 请求配置
*/
import axios from "axios";
import CryptoJS from "crypto-js";
import { Base64 } from "js-base64";
import { getToken, removeToken } from "./auth.js";
import JSONBig from "json-bigint";
import { v1 as uuidv1 } from "uuid";
// export const baseUrl = "https://lingniu-gateway.demo.chinawayltd.com/";
// export const baseUrl = "http://192.168.1.6:6902/";
const ENV = {
test: {
URL: "https://lingniu.test.chinawayltd.com/gateway/",
},
demo: {
URL: "https://lingniu-gateway.demo.chinawayltd.com/",
},
loce: {
URL: "http://192.168.130.136:6902/",
},
loce2: {
URL: "http://192.168.110.222:6902/",
},
loce3: {
URL: "http://192.168.110.23:6902/",
},
local: {
URL: "http://lingniu.huixintop.com/",
},
online: {
URL: "https://lnh2e.com/api/",
},
beta: {
URL: "https://beta.lnh2e.com/api/",
},
test2: {
URL: "http://115.230.138.233:6902/",
},
huixin: {
URL: "https://lingniu.huixintop.com/",
},
};
const vega = {
["lingniu-manager-v1"]: {
key: "lingniu_server",
secret: "TiDjIe7dEaNfzI7n2w9emXkXlCbLmPar",
},
["lingniu-export-v1"]: {
key: "lingniu_server",
secret: "TiDjIe7dEaNfzI7n2w9emXkXlCbLmPar",
},
};
const product = "lingniu-manager-v1";
const uploadProduct = "lingniu-export-v1";
const version = "v1";
const sin_key = "lingniu_server";
const sin_secret = "TiDjIe7dEaNfzI7n2w9emXkXlCbLmPar";
export const baseUrl = ENV.beta.URL;
console.log("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" + baseUrl);
class REQUEST {
static request(config) {
return new Promise((resolve, reject) => {
uni.request({
...config,
success: (res) => {
resolve(res.data.data);
},
fail: (e) => {
reject(e);
},
});
});
}
static get(url, data, config) {
return this.request({
url: url, //仅为示例,并非真实接口地址。
method: "get",
data: data,
...config,
});
}
static post(url, data, config = {}) {
return this.request({
url: url, //仅为示例,并非真实接口地址。
method: "post",
data: data,
...config,
});
}
static put(url, data, config = {}) {
return this.request({
url: url, //仅为示例,并非真实接口地址。
method: "put",
data: data,
...config,
});
}
static delete(url, data, config = {}) {
return this.request({
url: url, //仅为示例,并非真实接口地址。
method: "delete",
data: data,
...config,
});
}
static upload(url, config = {}) {
const _this = this;
return new Promise((resolve, reject) => {
uni.uploadFile({
url,
...config,
success: (res) => {
resolve(res.data);
},
fail: (e) => {
reject(e);
},
});
});
}
static download(url, fileName, cb) {
let config = {
responseType: "blob",
};
_requestAxios("get", {
url: url,
data: {},
config: config,
}).then((res) => {
if (cb) {
cb();
}
const blob = new Blob([res.data]);
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = fileName || _getFileName(res);
link.style.display = "none";
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(link.href);
document.body.removeChild(link);
function _getFileName(res) {
let headers = res.headers;
let contentDisposition = headers["content-disposition"];
let reg = /(filename=)(\S)*(;)?/g;
let fileNameArr = contentDisposition.match(reg);
if (fileNameArr.length < 1) {
return "template.txt";
}
let fileNameStr = fileNameArr[0].replace(";", "");
let fileName = fileNameStr.replace("filename=", "");
return decodeURI(fileName);
}
});
return false;
}
static getImageUrlParam(url, data, config = {}) {
config.params = data;
let reg = _regurl(url);
if (Array.isArray(reg) && reg.length >= 4) {
const [, product, version, path] = reg;
const key = vega[product].key;
const secret = vega[product].secret;
const timestamp = Date.now();
const stringToSign = `GET\n${timestamp}\n/${product}/${version}${path}`;
const sign = Base64.btoa(
CryptoJS.HmacSHA1(stringToSign, secret).toString()
);
return `g7liteSaasGatewayAppKey=${key}&g7liteSaasGatewayTimestamp=${timestamp}&g7liteSaasGatewaySign=${encodeURIComponent(
sign
)}&g7liteGToken=${encodeURIComponent(getToken())}`;
} else {
console.warn("vega配置存在问题请检查vega相关配置");
}
}
}
//BlobUrl转blob数据
function funobjectURLToBlob(blodurl, nmae) {
return new Promise((resolve, reject) => {
const fileManager = uni.getFileSystemManager();
fileManager.readFile({
filePath: `${blodurl}`,
position: 0,
success(res) {
// let files = new window.File([res.data], name, {
// type: 'image'
// });
// console.log(res.data)
resolve(res);
},
fail(res) {
console.error(res);
},
});
// var http = new XMLHttpRequest();
// http.open('GET', blodurl, true);
// http.responseType = 'blob';
// http.onload = function(e) {
// };
// http.send();
});
}
function _regurl(url) {
return url.match(/([^/]+)\/(v\d)(\/\S+)/);
}
function _requestAxios(type, { url, config = {}, data = {} }) {
console.log(/(http|https):\/\/([\w.]+\/?)\S*/.test(url));
const reqUrl = /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
? url
: baseUrl + url;
let sign = {};
const langMapping = {
zh: "zh_CN",
en: "en_US",
th: "th_TH",
tw: "zh_TW",
};
if (Array.isArray(reg) && reg.length >= 4) {
const [, product, version, path] = reg;
let pathArr = path.split("?");
let pathStr = pathArr[0];
sign = _makeApiSign({
reqType: type,
path: pathStr,
product,
version,
key: vega[product].key,
secret: vega[product].secret,
});
} else {
console.warn("vega配置存在问题请检查vega相关配置");
}
config.headers = Object.assign(
{
"Content-Type": "application/json",
from_type: 1,
},
{
"G7LITE-LANGUAGE": "zh_CN",
g7liteGToken: getToken(),
g7liteSaasGatewayAppKey: sign.key,
g7liteSaasGatewayTimestamp: sign.timestamp,
g7liteSaasGatewaySign: sign.sign,
},
config.headers
);
_formatRequestData(type, config, data);
let requestConfig = Object.assign(config, {
method: type.toLowerCase(),
url: reqUrl,
});
return axios(requestConfig)
.then((res) => _requestThen(config, res))
.catch((error) => _requestCatch(config, error));
function _requestThen(config, res) {
return new Promise((resolve, reject) => {
if (!config.responseType || config.responseType === "json") {
if (res.data.code === 0 && res.data.subCode === 0) {
resolve(res.data);
} else {
const vegaErrorCode = [
"330000011",
"330000012",
"330000013",
"330000014",
"330000015",
"330000016",
"330000017",
"330000018",
"330000019",
"331040003", // gtoken not allow empty
"331040007", // gtoken not existed
];
if (
vegaErrorCode.includes("" + res.data.subCode) ||
vegaErrorCode.includes("" + res.data.code)
) {
console.log("token失效");
removeToken();
uni.reLaunch({
url: "pages/index/index",
});
}
if (!config.hideErrorMsg) {
if (res.data.subCode === 331090010) {
uni.$u.toast("禁止访问");
} else {
let messageStr = "系统错误";
if (res.data.message) {
messageStr = res.data.message;
}
if (res.data.subMessage) {
messageStr = res.data.subMessage;
}
uni.$u.toast(messageStr);
}
}
reject(res);
}
} else {
if (res && res.data) {
resolve(res);
}
}
});
}
function _formatRequestData(type, config, data) {
const isBody = ["PUT", "put", "POST", "post", "PATCH", "patch"];
let resultData = {};
data.hash = Math.random() * 100000000000000;
if (isBody.includes(type)) {
resultData = _trimParams(data) || {};
if (
config.headers &&
config.headers["Content-Type"] &&
config.headers["Content-Type"].indexOf(
"application/x-www-form-urlencoded"
) > -1
) {
resultData = _formatParams(data);
}
config.data = resultData;
} else {
data = config.params || data;
config.params = _trimParams(data) || {};
resultData = config;
}
return resultData;
}
function _trimParams(data) {
if (data.constructor === Object) {
for (let i in data) {
if (typeof data[i] === "string") {
data[i] = data[i].trim();
}
}
}
return data;
}
function _formatParams(data) {
if (data.constructor === Object) {
const arr = [];
for (const i in data) {
arr.push(encodeURIComponent(i) + "=" + encodeURIComponent(data[i]));
}
data = arr.join("&");
}
return data;
}
function _requestCatch(config, error = {}) {
return new Promise((resolve, reject) => {
if (!error.isCancel) {
if (config.needReject) {
reject(error);
} else {
const res = (error || {}).data || {};
const messageText = res.code !== 0 ? res.message : res.subMessage;
this.$refs.uToast.show({
type: "error",
message: messageText || "请求失败",
complete() {
params.url &&
uni.navigateTo({
url: params.url,
});
},
});
reject(error);
}
}
});
}
function _makeApiSign(config) {
const { reqType, path, product = "", version, key, secret } = config;
const timestamp = Date.now();
const stringToSign = `${reqType.toUpperCase()}\n${timestamp}\n/${product}/${version}${path}`;
const sign = Base64.btoa(
CryptoJS.HmacSHA1(stringToSign, secret).toString()
);
return {
key,
sign,
timestamp,
};
}
}
function _makeApiSign(config) {
const { reqType, path, product = "", version, key, secret } = config;
const timestamp = Date.now();
const stringToSign = `${reqType.toUpperCase()}\n${timestamp}\n/${product}/${version}${path}`;
const sign = Base64.btoa(CryptoJS.HmacSHA1(stringToSign, secret).toString());
return {
key,
sign,
timestamp,
};
}
async function getFormDataParams() {
const date = new Date();
date.setHours(date.getHours() + 1);
const policyText = {
expiration: date.toISOString(), // 设置policy过期时间。
conditions: [
// 限制上传大小。
["content-length-range", 0, 1024 * 1024 * 1024],
],
};
const credentials = await axios.get("/getToken");
const policy = Base64.encode(JSON.stringify(policyText)); // policy必须为base64的string。
const signature = computeSignature(credentials.AccessKeySecret, policy);
const formData = {
OSSAccessKeyId: credentials.AccessKeyId,
signature,
policy,
"x-oss-security-token": credentials.SecurityToken,
};
return formData;
}
uni.addInterceptor("uploadFile", {
invoke(args) {
// request 触发前拼接 url
let pathArr = args.url.split("?");
const pathStr = pathArr[0];
args.url = baseUrl + uploadProduct + "/" + version + args.url;
// args.url = "http://127.0.0.1:6902/"+uploadProduct+"/"+version+ args.url
const sign = _makeApiSign({
reqType: "post",
path: pathStr,
uploadProduct,
version,
key: sin_key,
secret: sin_secret,
});
args.header = {
...args.header,
"G7lite-Language": "zh_CN",
g7liteSaasGatewayAppKey: sign.key,
g7liteSaasGatewayTimestamp: sign.timestamp,
g7liteSaasGatewaySign: sign.sign,
G7litegtoken: getToken(),
};
},
success(res) {},
});
uni.addInterceptor("request", {
invoke(args) {
// request 触发前拼接 url
let pathArr = args.url.split("?");
const pathStr = pathArr[0];
// 如果是附件上传接口,则使用 uploadProduct
if (pathStr == "/attachment/upload") {
args.url = baseUrl + uploadProduct + "/" + version + args.url;
} else if (pathStr.indexOf("/apis.map.qq.co") > -1) {
args.url = args.url;
} else {
args.url = baseUrl + product + "/" + version + args.url;
}
//地图API单独处理
const sign = _makeApiSign({
reqType: args.method,
path: pathStr,
product,
version,
key: sin_key,
secret: sin_secret,
});
args.header = {
...args.header,
"G7lite-Language": "zh_CN",
g7liteSaasGatewayAppKey: sign.key,
g7liteSaasGatewayTimestamp: sign.timestamp,
g7liteSaasGatewaySign: sign.sign,
G7litegtoken: getToken(),
};
},
success(res) {
res.data = res.data;
if (
(res.data.code === 0 && res.data.subCode === 0) ||
(res.statusCode === 200 && res.data.code === 200) || //获取地图markers接口
(res.statusCode === 200 && res.data.status === 0) //微信泛解析地址接口
) {
return res.data;
}
const vegaErrorCode = [
"330000011",
"330000012",
"330000013",
"330000014",
"330000015",
"330000016",
"330000017",
"330000018",
"330000019",
"331040003", // gtoken not allow empty
"331040007", // gtoken not existed
];
console.log("请求失败", res);
if (
vegaErrorCode.includes("" + res.data.subCode) ||
vegaErrorCode.includes("" + res.data.code)
) {
removeToken();
uni.reLaunch({
url: "pages/index/index",
});
}
if (res.data.subCode === 331090010) {
uni.$u.toast("禁止访问");
} else {
let messageStr = "系统错误";
if (res.data.message) {
messageStr = res.data.message;
}
if (res.data.subMessage) {
messageStr = res.data.subMessage;
}
if (res.data.code == 330000013) {
messageStr = "请登录";
}
uni.$u.toast(messageStr);
}
},
fail(err) {
console.log("interceptor-fail", err);
if (err.errno == "600001") {
uni.$u.toast("请求超时");
} else {
uni.$u.toast(err.errMsg);
}
},
});
export default REQUEST;

32
utils/storage.js Normal file
View File

@@ -0,0 +1,32 @@
import JSONBigint from 'json-bigint';
export default {
get(key) {
if (!key) console.error('key不能为空');
let result = uni.getStorageSync(key);
try {
result = JSONBigint.parse(result);
} catch (e) {}
return result;
},
set(key, value) {
if (!key) console.error('key不能为空');
typeof value === 'object' && (value = JSONBigint.stringify(value));
try {
uni.setStorageSync(key, value)
} catch (e) {
console.log("数据存储错误", e)
}
},
remove(key) {
uni.removeStorageSync(key);
},
clean() {
uni.clearStorage();
}
};

35
utils/time.js Normal file
View File

@@ -0,0 +1,35 @@
/* y 会被替换为年份M、d、h、H、m、s、q、S、a、A 分别表示月份、日期、小时12 小时制、小时24 小时制)、分钟、秒、季度、毫秒、上午/下午、AM/PM。
例如yyyy-MM-dd HH:mm:ss
*/
export function formatDateTime(date, format) {
if(date==undefined||date==''){
return ""
}
date=new Date(date);
const o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
'H+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds(), // 毫秒
a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(
RegExp.$1,
RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
);
}
}
return format;
}