This commit is contained in:
给我
2026-04-10 17:10:36 +08:00
parent 368ed7897b
commit ef83eeb5fe
767 changed files with 167713 additions and 0 deletions

View File

@ -0,0 +1,87 @@
function withData(param){
return param < 10 ? '0' + param : '' + param;
}
function getLoopArray(start,end){
var start = start || 0;
var end = end || 1;
var array = [];
for (var i = start; i <= end; i++) {
array.push(withData(i));
}
return array;
}
function getMonthDay(year,month){
var flag = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0), array = null;
switch (month) {
case '01':
case '03':
case '05':
case '07':
case '08':
case '10':
case '12':
array = getLoopArray(1, 31)
break;
case '04':
case '06':
case '09':
case '11':
array = getLoopArray(1, 30)
break;
case '02':
array = flag ? getLoopArray(1, 29) : getLoopArray(1, 28)
break;
default:
array = '月份格式不正确,请重新输入!'
}
return array;
}
function getNewDateArry(){
// 当前时间的处理 年月日时分秒
var newDate = new Date();
var year = withData(newDate.getFullYear()),
mont = withData(newDate.getMonth() + 1),
date = withData(newDate.getDate()),
hour = withData(newDate.getHours()),
minu = withData(newDate.getMinutes());
// seco = withData(newDate.getSeconds());
return [year, mont, date, hour, minu];
}
function dateTimePicker(startYear,endYear,date) {
// 返回默认显示的数组和联动数组的声明
var dateTime = [], dateTimeArray = [[],[],[],[],[]];
var start = startYear || 1978;
var end = endYear || 2100;
//处理传过来的字符串转化为数组
let dataArr = date.split(" ")[0].split('/')
let time = date.split(" ")[1].split(':')
// 默认开始显示数据 如果把自定义值传过来的话就使用自定义时间 否则用当前时间 ...dataArr数组解构
var defaultDate = date ? [...dataArr, ...time] : getNewDateArry();
// 处理联动列表数据
/*年月日 时分秒*/
dateTimeArray[0] = getLoopArray(start,end);
dateTimeArray[1] = getLoopArray(1, 12);
dateTimeArray[2] = getMonthDay(defaultDate[0], defaultDate[1]);
dateTimeArray[3] = getLoopArray(0, 23);
dateTimeArray[4] = getLoopArray(0, 59);
// dateTimeArray[5] = getLoopArray(0, 59);
//遍历dateTimeArray数组
dateTimeArray.forEach((current,index) =>
//匹配defaultDate[index]值在current数组中的位置
dateTime.push(current.indexOf(defaultDate[index]))
);
return {
dateTimeArray: dateTimeArray,
dateTime: dateTime
}
}
module.exports = {
dateTimePicker: dateTimePicker,
getMonthDay: getMonthDay
}

45
src/utils/dict.js Normal file
View File

@ -0,0 +1,45 @@
import { ref, toRefs } from "vue";
import { getDictListByCode } from "./../api/common";
/**
* 分局字典代码获取字典词条列表
* @param {字典代码} dict
*/
// export function getDictList(dict) {
// return new Promise((ok) => {
// getDictListByCode({ dictCode: dict }).then((res) => {
// ok(res.itemList);
// });
// });
// }
export function getDictList(...dict) {
const res = ref({})
return (()=>{
dict.forEach((d,index)=>{
res.value[d] = []
getDictListByCode({
dictCode: d
}).then(result=>{
res.value[d] = result.itemList.map(p=>({
text:p.zdmc,
value:p.dm,
...p
}));
})
})
return toRefs(res.value)
})()
}
// 列表字典翻译函数
export function setDict(dm,options){
var value = ''
options.forEach(v=>{
if(v.value == dm){
value = v.text
}
})
return value
}

5
src/utils/eventBus.js Normal file
View File

@ -0,0 +1,5 @@
import mitt from 'mitt'
const emitter = mitt();
export default emitter

130
src/utils/fpsc.js Normal file
View File

@ -0,0 +1,130 @@
import {
upImage,
bigDataUpload
} from "../api/common.js";
const upVideo = {
file: null, //文件对象
size: 0, //分片大小 kb
progressBar: 0, //进度条 num%
underWayFn: null, //进度条改变触发函数
upOverFn: null, //上传完成触发函数
t: null, //定时器
// 初始化函数
init({
fileObj, //文件对象
size = 2, //分片大小 默认2 单位m
underWayFn = function () {}, //进度条改变触发函数
upOverFn = function () {}, //上传完成触发函数
}) {
this.file = fileObj;
this.size = size * 1024 * 1024;
this.underWayFn = underWayFn;
this.upOverFn = upOverFn;
// 判断是否是满足条件的视频对象 满足条件调用this.upbegin()处理
this.upbegin();
},
// 上传文件
async upbegin() {
let videoTime = await this.videoLong(); //视频播放时间
// 视频分片
let start = 0,
end = 0,
chunkArr = [],
size = this.size;
let file = this.file;
function chuli() {
end += size;
var blob = file.slice(start, end);
start += size;
if (blob.size) {
chunkArr.push(blob);
chuli(file);
} else {
return chunkArr
}
}
chuli();
//预请求接口 然后this.inTurnto(chunkArr); 分片请求
// 分片请求主体
this.inTurnto(chunkArr);
},
// 缓慢增长到目标进度条
changeProgressBar(num) {
clearInterval(this.t)
this.t = setInterval(() => {
if (this.progressBar == num) {
clearInterval(this.t)
//上传完成
if (this.progressBar === 100) {
this.upOverFn(); //通知上传完成
this.clearUpVideo(); //格式化重置
}
} else {
this.progressBar++;
this.underWayFn(this.progressBar); //改变进度条通知
}
}, 50);
},
// 多个视频一一请求
inTurnto(chunkArr) {
const chunkAllNum = chunkArr.length; //片段总数量
let count = 0; //完成个数
chunkArr.forEach((item, index) => {
// 模拟数据请求
setTimeout(() => {
count++; //增加当前进度
const filename = new Date().toISOString();
const data = new FormData();
const files = new File([item], filename + ".mp4");
data.append("file", files);
if (item.size != 2097152) {
data.append("isEnd", 1);
}
bigDataUpload(data).then((res) => {
if (res) {
}
});
this.changeProgressBar(parseInt(count / chunkAllNum * 100)); //改变进度
}, 1000);
})
},
// 获取视频总时长
videoLong() {
return new Promise((resolve) => {
var url = URL.createObjectURL(this.file);
var audioElement = new Audio(url);
audioElement.addEventListener("loadedmetadata", function () {
var hour = parseInt((audioElement.duration) / 3600);
if (hour < 10) {
hour = "0" + hour;
}
var minute = parseInt((audioElement.duration % 3600) / 60);
if (minute < 10) {
minute = "0" + minute;
}
var second = Math.ceil(audioElement.duration % 60);
if (second < 10) {
second = "0" + second;
}
resolve(hour + ":" + minute + ":" + second)
});
})
},
// 重置
clearUpVideo() {
this.file = null;
this.size = 0;
this.progressBar = 0;
this.underWayFn = null;
this.upOverFn = null;
this.t = null;
},
}
export default upVideo

View File

@ -0,0 +1,70 @@
const imgCompressUtil = {
/**
* 压缩图片
* @param {*} file
* @param {*} quailty
*/
compressImg(file, quailty) {
if (!file || !window.FileReader) return // 判断是否支持FileReader
if (/^image/.test(file.type)) {
let reader = new FileReader()
reader.readAsDataURL(file) // 转成 base64 格式
return new Promise((resolve, reject) => { // 读取成功后的回调
reader.onloadend = function () {
let img = new Image()
img.src = this.result
// 判断图片是否小于500K,是就直接上传,反之压缩图片
if (this.result.length <= 5 * 1024) {
resolve(this.result)
} else {
img.onload = function () {
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
let tCanvas = document.createElement('canvas')
let tctx = tCanvas.getContext('2d')
let width = img.width
let height = img.height
// 如果图片大于四百万像素计算压缩比并将大小压至400万以下
let ratio
if ((ratio = (width * height) / 4000000) > 1) {
ratio = Math.sqrt(ratio)
width /= ratio
height /= ratio
} else {
ratio = 1
}
canvas.width = width
canvas.height = height
ctx.fillStyle = '#fff' // 铺底色
ctx.fillRect(0, 0, canvas.width, canvas.height)
// 如果图片像素大于100万则使用瓦片绘制
let count
if ((count = (width * height) / 1000000) > 1) {
count = ~~(Math.sqrt(count) + 1) // 计算要分成多少块瓦片
// 计算每块瓦片的宽和高
let nw = ~~(width / count)
let nh = ~~(height / count)
tCanvas.width = nw
tCanvas.height = nh
for (let i = 0; i < count; i++) {
for (let j = 0; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh)
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
}
}
} else {
ctx.drawImage(img, 0, 0, width, height)
}
// 进行压缩(---------quailty越低 图片越小)
let newBase64 = canvas.toDataURL('image/jpeg', quailty)
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0
resolve(newBase64) // 返回压缩后的base64
}
}
}
})
}
}
}
export default imgCompressUtil

129
src/utils/index.js Normal file
View File

@ -0,0 +1,129 @@
/**
* Parse the time to string
* @param {(Object|string|number)} time
* @param {string} cFormat
* @returns {string}
*/
export function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
/**
* @param {number} time
* @param {string} option
* @returns {string}
*/
export function formatTime(time, option) {
if (('' + time).length === 10) {
time = parseInt(time) * 1000
} else {
time = +time
}
const d = new Date(time)
const now = Date.now()
const diff = (now - d) / 1000
if (diff < 30) {
return '刚刚'
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) {
return '1天前'
}
if (option) {
return parseTime(time, option)
} else {
return (
d.getMonth() +
1 +
'月' +
d.getDate() +
'日' +
d.getHours() +
'时' +
d.getMinutes() +
'分'
)
}
}
/**
* @param {string} url
* @returns {Object}
*/
export function param2Obj(url) {
const search = url.split('?')[1]
if (!search) {
return {}
}
return JSON.parse(
'{"' +
decodeURIComponent(search)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')
.replace(/\+/g, ' ') +
'"}'
)
}
export function timeFormat(time) { // 时间格式化 2019-09-08
let year = time.getFullYear();
let m = time.getMonth() + 1
let month = m < 10 ? '0' + m : m;
let d = time.getDate()
let day = d < 10 ? '0' + d : d
return year + '-' + month + '-' + day;
}
export function timeFormatall(time) { // 时间格式化 2019-09-08
let year = time.getFullYear();
let m = time.getMonth() + 1
let month = m < 10 ? '0' + m : m;
let d = time.getDate()
let h = time.getHours()
let minute = time.getMinutes()
let second = time.getSeconds()
let day = d < 10 ? '0' + d : d
return year + '-' + month + '-' + day + ' ' + h + ':'+minute+':'+second;
}

357
src/utils/recorder.js Normal file
View File

@ -0,0 +1,357 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Recorder = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
module.exports = require("./recorder").Recorder;
},{"./recorder":2}],2:[function(require,module,exports){
'use strict';
var _createClass = (function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
})();
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Recorder = undefined;
var _inlineWorker = require('inline-worker');
var _inlineWorker2 = _interopRequireDefault(_inlineWorker);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Recorder = exports.Recorder = (function () {
function Recorder(source, cfg) {
var _this = this;
_classCallCheck(this, Recorder);
this.config = {
bufferLen: 4096,
numChannels: 2,
mimeType: 'audio/wav'
};
this.recording = false;
this.callbacks = {
getBuffer: [],
exportWAV: []
};
Object.assign(this.config, cfg);
this.context = source.context;
this.node = (this.context.createScriptProcessor || this.context.createJavaScriptNode).call(this.context, this.config.bufferLen, this.config.numChannels, this.config.numChannels);
this.node.onaudioprocess = function (e) {
if (!_this.recording) return;
var buffer = [];
for (var channel = 0; channel < _this.config.numChannels; channel++) {
buffer.push(e.inputBuffer.getChannelData(channel));
}
_this.worker.postMessage({
command: 'record',
buffer: buffer
});
};
source.connect(this.node);
this.node.connect(this.context.destination); //this should not be necessary
var self = {};
this.worker = new _inlineWorker2.default(function () {
var recLength = 0,
recBuffers = [],
sampleRate = undefined,
numChannels = undefined;
self.onmessage = function (e) {
switch (e.data.command) {
case 'init':
init(e.data.config);
break;
case 'record':
record(e.data.buffer);
break;
case 'exportWAV':
exportWAV(e.data.type);
break;
case 'getBuffer':
getBuffer();
break;
case 'clear':
clear();
break;
}
};
function init(config) {
sampleRate = config.sampleRate;
numChannels = config.numChannels;
initBuffers();
}
function record(inputBuffer) {
for (var channel = 0; channel < numChannels; channel++) {
recBuffers[channel].push(inputBuffer[channel]);
}
recLength += inputBuffer[0].length;
}
function exportWAV(type) {
var buffers = [];
for (var channel = 0; channel < numChannels; channel++) {
buffers.push(mergeBuffers(recBuffers[channel], recLength));
}
var interleaved = undefined;
if (numChannels === 2) {
interleaved = interleave(buffers[0], buffers[1]);
} else {
interleaved = buffers[0];
}
var dataview = encodeWAV(interleaved);
var audioBlob = new Blob([dataview], { type: type });
self.postMessage({ command: 'exportWAV', data: audioBlob });
}
function getBuffer() {
var buffers = [];
for (var channel = 0; channel < numChannels; channel++) {
buffers.push(mergeBuffers(recBuffers[channel], recLength));
}
self.postMessage({ command: 'getBuffer', data: buffers });
}
function clear() {
recLength = 0;
recBuffers = [];
initBuffers();
}
function initBuffers() {
for (var channel = 0; channel < numChannels; channel++) {
recBuffers[channel] = [];
}
}
function mergeBuffers(recBuffers, recLength) {
var result = new Float32Array(recLength);
var offset = 0;
for (var i = 0; i < recBuffers.length; i++) {
result.set(recBuffers[i], offset);
offset += recBuffers[i].length;
}
return result;
}
function interleave(inputL, inputR) {
var length = inputL.length + inputR.length;
var result = new Float32Array(length);
var index = 0,
inputIndex = 0;
while (index < length) {
result[index++] = inputL[inputIndex];
result[index++] = inputR[inputIndex];
inputIndex++;
}
return result;
}
function floatTo16BitPCM(output, offset, input) {
for (var i = 0; i < input.length; i++, offset += 2) {
var s = Math.max(-1, Math.min(1, input[i]));
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
}
}
function writeString(view, offset, string) {
for (var i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
function encodeWAV(samples) {
var buffer = new ArrayBuffer(44 + samples.length * 2);
var view = new DataView(buffer);
/* RIFF identifier */
writeString(view, 0, 'RIFF');
/* RIFF chunk length */
view.setUint32(4, 36 + samples.length * 2, true);
/* RIFF type */
writeString(view, 8, 'WAVE');
/* format chunk identifier */
writeString(view, 12, 'fmt ');
/* format chunk length */
view.setUint32(16, 16, true);
/* sample format (raw) */
view.setUint16(20, 1, true);
/* channel count */
view.setUint16(22, numChannels, true);
/* sample rate */
view.setUint32(24, sampleRate, true);
/* byte rate (sample rate * block align) */
view.setUint32(28, sampleRate * 4, true);
/* block align (channel count * bytes per sample) */
view.setUint16(32, numChannels * 2, true);
/* bits per sample */
view.setUint16(34, 16, true);
/* data chunk identifier */
writeString(view, 36, 'data');
/* data chunk length */
view.setUint32(40, samples.length * 2, true);
floatTo16BitPCM(view, 44, samples);
return view;
}
}, self);
this.worker.postMessage({
command: 'init',
config: {
sampleRate: this.context.sampleRate,
numChannels: this.config.numChannels
}
});
this.worker.onmessage = function (e) {
var cb = _this.callbacks[e.data.command].pop();
if (typeof cb == 'function') {
cb(e.data.data);
}
};
}
_createClass(Recorder, [{
key: 'record',
value: function record() {
this.recording = true;
}
}, {
key: 'stop',
value: function stop() {
this.recording = false;
}
}, {
key: 'clear',
value: function clear() {
this.worker.postMessage({ command: 'clear' });
}
}, {
key: 'getBuffer',
value: function getBuffer(cb) {
cb = cb || this.config.callback;
if (!cb) throw new Error('Callback not set');
this.callbacks.getBuffer.push(cb);
this.worker.postMessage({ command: 'getBuffer' });
}
}, {
key: 'exportWAV',
value: function exportWAV(cb, mimeType) {
mimeType = mimeType || this.config.mimeType;
cb = cb || this.config.callback;
if (!cb) throw new Error('Callback not set');
this.callbacks.exportWAV.push(cb);
this.worker.postMessage({
command: 'exportWAV',
type: mimeType
});
}
}], [{
key: 'forceDownload',
value: function forceDownload(blob, filename) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
var link = window.document.createElement('a');
link.href = url;
link.download = filename || 'output.wav';
var click = document.createEvent("Event");
click.initEvent("click", true, true);
link.dispatchEvent(click);
}
}]);
return Recorder;
})();
exports.default = Recorder;
},{"inline-worker":3}],3:[function(require,module,exports){
"use strict";
module.exports = require("./inline-worker");
},{"./inline-worker":4}],4:[function(require,module,exports){
(function (global){
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var WORKER_ENABLED = !!(global === global.window && global.URL && global.Blob && global.Worker);
var InlineWorker = (function () {
function InlineWorker(func, self) {
var _this = this;
_classCallCheck(this, InlineWorker);
if (WORKER_ENABLED) {
var functionBody = func.toString().trim().match(/^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$/)[1];
var url = global.URL.createObjectURL(new global.Blob([functionBody], { type: "text/javascript" }));
return new global.Worker(url);
}
this.self = self;
this.self.postMessage = function (data) {
setTimeout(function () {
_this.onmessage({ data: data });
}, 0);
};
setTimeout(function () {
func.call(self);
}, 0);
}
_createClass(InlineWorker, {
postMessage: {
value: function postMessage(data) {
var _this = this;
setTimeout(function () {
_this.self.onmessage({ data: data });
}, 0);
}
}
});
return InlineWorker;
})();
module.exports = InlineWorker;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1])(1)
});

83
src/utils/request.js Normal file
View File

@ -0,0 +1,83 @@
import axios from 'axios';
import { hintToast } from "./tools";
let baseUrl2 = ''; //二类区地址
let baseUrlZddwUrl = ''; //重点单位地址
let zyURL = '/mosty-api';
try {
let fwzxToken = bridge.getToken();
baseUrl2 = `http://118.122.165.45:35623`;
baseUrlZddwUrl = `http://118.122.165.45:35623`;
zyURL = `http://118.122.165.45:35623/mosty-api`;
// baseUrl2 = `http://172.20.19.221:8006`;
// baseUrlZddwUrl = `http://172.20.19.221:8006`;
// zyURL = `http://172.20.19.221:8006/mosty-api`;
} catch (error) {
}
const service = axios.create({
baseURL: zyURL,
timeout: 60000
});
// 1.请求拦截器
service.interceptors.request.use(
(config) => {
// 请求接口之前 做些什么
//1.统一注入token
let token = window.localStorage.getItem('token')
if (token) {
config.headers.Authorization = token;
}
//2.设置headers icode
// config.headers.code = '';
// 必须返回 config
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 2.响应拦截器
service.interceptors.response.use(
// 请求成功的处理
(response) => {
const {
success,
code,
msg,
message,
data,
status
} = response.data;
// 需要判断当前请求是否成功
if (success && code === 10000) {
return data; // 成功后返回解析后的数据
} else if (code === 200 || code == "00000") {
return data; // 成功后返回解析后的数据
} else if (code === 401) {
// store.dispatch('user/logout');
// ElMessage.error(message); // 提示错误信息
// hintToast(message)
} else {
// 失败(请求成功 ,业务失败) 弹出消息提示
// hintToast(message)
return Promise.reject(new Error(message));
}
},
// 请求失败处理
(error) => {
//token过期
// hintToast(error.message)
return Promise.reject(error);
}
);
export {
service,
baseUrl2,
baseUrlZddwUrl
};

64
src/utils/requestUrl.js Normal file
View File

@ -0,0 +1,64 @@
import axios from 'axios';
let baseUrl2 = ''; //二类区地址
let baseUrlZddwUrl = ''; //重点单位地址
let zyURL = '';
try {
let fwzxToken = bridge.getToken();
baseUrl2 = `http://118.122.165.45:35623`;
baseUrlZddwUrl = `http://118.122.165.45:35623`;
zyURL = `http://118.122.165.45:35623/mosty-api`;
// baseUrl2 = `http://172.20.19.221:8006`;
// baseUrlZddwUrl = `http://172.20.19.221:8006`;
// zyURL = `http://172.20.19.221:8006/mosty-api`;
} catch (error) {
}
const service = axios.create({
baseURL: baseUrl2,
timeout: 60000
});
// 1.请求拦截器
service.interceptors.request.use(
(config) => {
// 请求接口之前 做些什么
//1.统一注入token
let token = window.localStorage.getItem('token')
if (token) { config.headers.Authorization = token; }
//2.设置headers icode
// config.headers.code = '';
// 必须返回 config
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 2.响应拦截器
service.interceptors.response.use(
// 请求成功的处理
(response) => {
const { success, code, message, data, resultCode } = response.data;
// 需要判断当前请求是否成功
if (success && code === 10000) {
return data; // 成功后返回解析后的数据
} else if (code === 200 || code == "00000") {
return data; // 成功后返回解析后的数据
} else if (resultCode == 0) {
return data;
}else {
return Promise.reject(new Error(message));
}
},
// 请求失败处理
(error) => {
return Promise.reject(error);
}
);
export {
service,
baseUrl2,
baseUrlZddwUrl
};

71
src/utils/rules.js Normal file
View File

@ -0,0 +1,71 @@
// 身份证校验
export const IdCardValidator = (value,rule) =>{
if(!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(value)){
return '输入的身份证长度或格式错误'
}
//身份证城市
var aCity = {11: "北京",12: "天津",13: "河北",14: "山西",15: "内蒙古",21: "辽宁",22: "吉林",23: "黑龙江",31: "上海",32: "江苏",33: "浙江",34: "安徽",35: "福建",36: "江西",37: "山东",41: "河南",42: "湖北",43: "湖南",44: "广东",45: "广西",46: "海南",50: "重庆",51: "四川",52: "贵州",53: "云南",54: "西藏",61: "陕西",62: "甘肃",63: "青海",64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" };
let citydm = value ? value.substr(0, 2) : null
if(citydm){
if (!aCity[parseInt(citydm)]) return '身份证地区非法'
}
// 出生日期验证
var sBirthday = (value.substr(6, 4) +"-" + Number(value.substr(10, 2)) + "-" + Number(value.substr(12, 2))).replace(/-/g, "/"),d = new Date(sBirthday);
if ( sBirthday !== d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()) {
return '身份证上的出生日期非法'
}
// 身份证号码校验
var sum = 0,
weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
codes = "10X98765432";
for (var i = 0; i < value.length - 1; i++) {
sum += value[i] * weights[i];
}
var last = codes[sum % 11]; //计算出来的最后一位身份证号码
if (value[value.length - 1] !== last) {
return '输入的身份证号非法'
}
}
// 手机号校验
export const phoneValidator = (value,rule) =>{
if(!value){
return '手机号不能为空'
}else{
const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
if(!reg.test(value)){
return '请输入正确的手机号'
}
}
}
// 车牌号校验
export const hphmValidator = (value,rule) =>{
const ptreg = /^[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘桂琼川贵云渝藏陕甘青宁新粤]{1}[ABCDEFGHJKLMNOPQRSTUVWXY]{1}[0-9A-Z]{5}$/u;
const xnyreg = /^[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘桂琼川贵云渝藏陕甘青宁新粤]{1}[A-Z]{1}(([0-9]{5}[DABCEFGHJK]$)|([DABCEFGHJK][A-HJ-NP-Z0-9][0-9]{4}$))/; // 2021年新能源车牌不止有DF
if (!value) {
return '请选择车牌号'
} else {
if (value.length === 7) {
if (!ptreg.test(value)) return '请输入正确的普通车牌号'
} else if (value.length === 8) {
if (!xnyreg.test(value)) return '请输入正确的新能源车牌号'
} else {
return '车牌号错误'
}
}
}
// 邮箱校验
export const emailValidator = (value,rule) => {
const reg = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
if (!value) {
return '邮箱不能为空'
} else {
if (!reg.test(value)) return '请输入正确的邮箱地址'
}
};

71
src/utils/storage.js Normal file
View File

@ -0,0 +1,71 @@
/**
* 存储数据
* @param {*} key
* @param {*} value
*/
export const setItem = (key, value) => {
//value 的 两种请款 1基本数据类型 2复杂数据类型
value = JSON.stringify(value)
setStorage(key, value)
}
/**
* 获取数据
* @param {*} key
*/
export const getItem = (key) => {
const data = getStorage(key)
try {
return JSON.parse(data)
} catch (e) {
return data
}
}
/**
* 删除指定数据
* @param {*} key
*/
export const removeItem = (key) => {
window.localStorage.removeItem(key)
}
/**
* 删除所有数据
*/
export const removeAllItem = () => {
window.localStorage.clear()
}
/**
* 删除指定数据sessionStorage
* @param {*} key
*/
export const removeSItem = (key) => {
window.sessionStorage.removeItem(key)
}
/**
* 获取数据sessionStorage
* @param {*} key
*/
export const getSItem = (key) => {
const data = window.sessionStorage.getItem(key)
try {
return JSON.parse(data)
} catch (e) {
return data
}
}
/**
* 存储数据sessionStorage
* @param {*} key
* @param {*} value
*/
export const setSItem = (key, value) => {
//value 的 两种请款 1基本数据类型 2复杂数据类型
value = JSON.stringify(value)
window.sessionStorage.setItem(key, value)
}

574
src/utils/tools.js Normal file
View File

@ -0,0 +1,574 @@
import axios from 'axios';
import router from "../router";
import {
Toast
} from "vant";
import {
baseUrl2
} from './request';
// 转换时间格式
export function timeValidate(date, type) {
const time = date ? new Date(date) : new Date()
const yyyy = time.getFullYear()
const MM = (time.getMonth() + 1).toString().padStart(2, 0)
const dd = time.getDate().toString().padStart(2, '0')
const hh = time.getHours().toString().padStart(2, '0')
const mm = time.getMinutes().toString().padStart(2, '0')
const ss = time.getSeconds().toString().padStart(2, '0')
if (type == 'ymd') {
return `${yyyy}-${MM}-${dd}`;
}
if (type == 'md') {
return `${MM}.${dd}`
}
return `${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss}`
}
// 获取当前近多少天 7后7天 -7 前五天
export function getRecentDay(n, type) {
var currentDate = new Date();
var preDate = new Date(currentDate.getTime() + n * 24 * 3600 * 1000)
let year = preDate.getFullYear()
let mon = preDate.getMonth() + 1
let day = preDate.getDate()
let s = year + '-' + (mon < 10 ? ('0' + mon) : mon) + '-' + (day < 10 ? ('0' + day) : day)
if (type == 'ymd') {
return s
} else {
return s + ' 00:00:00'
}
}
// 获取n近7月 7后7 -7 前
export function getnRencebtMonth(n) {
let date = new Date();
date.setMonth(date.getMonth() - n)
date.toLocaleDateString()
let y = date.getFullYear()
let m = date.getMonth() + 1
m = m < 10 ? ('0' + m) : m + ''
return y + m
}
/**
* 数据去重 相同数据值累加
* @param {Object} array 数据
*/
export function setArray(array) {
let newArr = []
array.forEach(item => {
const res = newArr.findIndex(ol => {
//组织机构代码相同 并且报警类别相同
return item.ssbmdm == ol.ssbmdm && item.bjlb == ol.bjlb
})
if (res !== -1) {
newArr[res].sl = newArr[res].sl + item.sl
} else {
newArr.push(item)
}
})
return newArr
}
/**
* 合并数据
* @param {Object} array 数据
*/
export function hbArray(array, item1, item2, item3) {
let newArr = []
array.forEach(item => {
const res = newArr.findIndex(ol => {
//组织机构代码相同 并且报警类别相同
return item.product == ol.product
})
if (res !== -1) {
newArr[res][item1] = newArr[res][item1] + item[item1]
newArr[res][item2] = newArr[res][item2] + item[item2]
newArr[res][item3] = newArr[res][item3] + item[item3]
} else {
newArr.push(item)
}
})
return newArr
}
/**
* 时间格式
* @param {*} type
* @param {*} time
*/
export function dateFormat(type, time) {
let date
if (time) {
date = new Date(time);
} else {
date = new Date();
}
let year = date.getFullYear();
let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
if (type == 'all') {
//格式化日期时间
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
} else if (type == 'z') {
//前一天
let date1 = new Date(date.getTime() - 24 * 60 * 60 * 1000)
return setTimeTormat(date1);
} else if (type == 'z2') {
//前2天
let date1 = new Date(date.getTime() - 48 * 60 * 60 * 1000)
return setTimeTormat(date1);
} else if (type == 'h') {
//后一天
let date1 = new Date(date.getTime() + 24 * 60 * 60 * 1000)
return setTimeTormat(date1);
} else if (type == '3') {
//近三天
let date1 = new Date(date.getTime() - 72 * 60 * 60 * 1000)
return setTimeTormat(date1);
} else if (type == 'week') {
//近7天
let date1 = new Date(date.getTime() - 168 * 60 * 60 * 1000)
return setTimeTormat(date1);
} else if (type == 'month') {
//近一月
let date1 = new Date(date.getTime() - 720 * 60 * 60 * 1000)
return setTimeTormat(date1);
} else if (type == '3month') {
//近三月
let date1 = new Date(date.getTime() - 2160 * 60 * 60 * 1000)
return setTimeTormat(date1);
} else if (type == '6month') {
//近半年
let date1 = new Date(date.getTime() - 4320 * 60 * 60 * 1000)
return setTimeTormat(date1);
} else {
//当天日期
return `${year}-${month}-${day}`;
}
}
//设置时间
function setTimeTormat(date) {
let year1 = date.getFullYear();
let month1 =
date.getMonth() + 1 < 10 ?
"0" + (date.getMonth() + 1) :
date.getMonth() + 1;
let day1 = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return `${year1}-${month1}-${day1}`;
}
/**
* 获取类型名称
* @param {*} type
*/
export function getTypeName(type) {
let name
switch (type) {
case 'zjq':
name = '总数'
break
case 'zdjq':
name = '重大警情'
break
case 'wffz':
name = '违法犯罪'
break
case 'jmjq':
name = '街面警情'
break
}
return name
}
/**
* 警情数据去重
* @param {Object} array 数据
*/
export function setArrayQc(array) {
let newArr = []
array.forEach(item => {
const res = newArr.findIndex(ol => {
return item.type == ol.type
})
if (res !== -1) {
newArr[res] = item
} else {
newArr.push(item)
}
})
return newArr
}
//深珀方面警情相关请求
export function spPostRequest(url, data = {}, fun) {
axios.post(`${baseUrl2}/xz1Api${url}`, data, {}).then(res => {
fun(res.data)
})
}
//托尔斯走访记录相关请求
export function trsGetRequest(url, params = {}, token, fun) {
axios.get(`${baseUrl2}/trs2Api${url}`, {
params,
headers: {
"Authorization": `Bearer ${token}`,
"User-Agent": "trs",
"End-Mode": "app"
},
}).then(res => {
fun(res.data)
})
}
//托尔斯走访记录相关请求
export function trsPostRequest(url, data = {}, token, fun) {
axios.post(`${baseUrl2}/trs2Api${url}`, data, {
headers: {
"Authorization": `Bearer ${token}`,
"User-Agent": "trs",
"End-Mode": "app"
}
}).then(res => {
fun(res.data)
})
}
export function trs2PostRequest(url, data, token, fun) {
axios.post(`${baseUrl2}/trs2Api${url}?${data}`, {}, {
headers: {
"Authorization": `Bearer ${token}`,
"User-Agent": "trs",
"End-Mode": "app"
}
}).then(res => {
fun(res.data)
})
}
//获取托尔斯token
export function getTrsToken(params, fun) {
axios.get(`${baseUrl2}/mosty-api/mosty-base/trs/token/new/getToken`, {
params
}, {}).then(res => {
fun(res.data)
})
}
//源码实有人口任务相关请求
export function ymGetRequest(url, params = {}, token, fun) {
axios.get(`${baseUrl2}/ymApi/af-api/api${url}`, {
params,
headers: {
"Authorization": token,
},
}).then(res => {
fun(res.data)
})
}
//源码实有人口任务相关请求
export function ymPostRequest(url, data = {}, token, fun) {
axios.post(`${baseUrl2}/ymApi/af-api/api${url}`, data, {
headers: {
"Authorization": token,
}
}).then(res => {
fun(res.data)
})
}
//获取源码token
export function getYmToken(data, fun) {
axios.post(`${baseUrl2}/ymApi/af-api/login`, data, {}).then(res => {
fun(res.data)
}).catch((err) => {
hintToast("您没有权限,请联系管理员!")
});
}
//获取模板内容信息
export function getPzPlateList(bklx) {
if (bklx) {
let plateList = []
let module = JSON.parse(getStorage("defaultModule"))
//模板信息
if (module) {
let info = module.find(item => {
return bklx == item.bklx
})
//模板内容信息
if (info) plateList = info.plateList
}
return plateList
}
}
/**
* 计算两点之间距离
* @export
* @param {*} lat1
* @param {*} lng1
* @param {*} lat2
* @param {*} lng2
*/
export function getDistance(lat1, lng1, lat2, lng2) {
let redLat1 = lat1 * Math.PI / 180.0;
let redLat2 = lat2 * Math.PI / 180.0;
let a = redLat1 - redLat2;
let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(redLat1) * Math.cos(redLat2) * Math.pow(Math
.sin(b / 2), 2)));
s = s * 6378.137;
s = Math.round(s * 10000) / 10000
s = s * 1000
return s
}
/**
* @export 函数节流
* @param {*} fn 函数
* @param {number} [time=500] 延迟延迟执行毫秒数
* @param {number} [type=2] 1 时间戳 2 定时器
*/
export function throtter(fn, time = 500, type = 2) {
let previous, timeout
if (type == 1) previous = 0
return function () {
let context = this
let args = arguments
if (type == 1) {
let now = Date.now()
if (now - previous > time) {
fn.apply(context, args);
previous = now;
}
} else {
if (!timeout) {
timeout = setTimeout(() => {
timeout = null
fn.apply(context, args);
}, time)
}
}
}
}
/**
*对象数组排序
* @export
* @param {*} attr 排序的字段
* @param {*} rev true 升序 false 降序
*/
export function compare(attr, rev) {
if (rev == undefined) {
rev = 1
} else {
rev = rev ? 1 : -1
}
return (a, b) => {
a = a[attr]
b = b[attr]
if (a > b) {
return rev * -1
}
if (a < b) {
return rev * 1
}
return 0
}
}
/**
* 获取base64地址
* @param {*} fun 回调
* @param {*} url 地址
*/
export function getBase64(fun, url) {
if (fun && typeof fun === 'function') {
axios.get(`${baseUrl2}/mosty-api/mosty-base/image/base64`, {
params: {
url
}
}).then((res) => {
fun(`data:image/jpeg;base64,${res.data.data}`);
}).catch((err) => {
fun("");
});
} else {
// Promise模式
return new Promise((resolve, reject) => {
axios.get(`${baseUrl2}/mosty-api/mosty-base/image/base64`, {
params: { url }
}).then((res) => {
resolve(`data:image/jpeg;base64,${res.data.data}`);
}).catch((err) => {
console.error('获取base64失败:', err);
resolve("");
});
});
}
}
/**
* 文件是否是图片
* @param {*} val
*/
export function IS_PNG(val) {
return ['bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo',
'eps', 'ai', 'raw', 'wmf', 'webp', 'avif', 'apng'
].indexOf(val.toLowerCase()) !== -1
}
/**
* 文件是否是音频
* @param {*} val
*/
export function IS_MP3(val) {
return ['mp3', 'wav', 'wma', 'mp2', 'flac', 'midi', 'ra', 'ape', 'aac', 'cda', 'mov'].indexOf(val.toLowerCase()) !==
-1
}
/**
* 文件是否是视频
* @param {*} val
*/
export function IS_MP4(val) {
return ['avi', 'wmv', 'mpeg', 'mp4', 'm4v', 'mov', 'asf', 'fiv', 'f4v', 'mvb', 'rm', '3gp', 'vob'].indexOf(val
.toLowerCase()) !== -1
}
/**
* 数据去重
* @param {*} array 去重数据
* @param {*} val 去重字段
*/
export function dataQc(array, val) {
let newArr = []
array.forEach(item => {
const res = newArr.findIndex(ol => {
return item[val] == ol[val]
})
if (res !== -1) {
newArr[res] = item
} else {
newArr.push(item)
}
})
return newArr
}
//默认时间赛选条件
export function setTimeQuantum() {
return {
title: "按时间",
isCheckBox: false,
array: [{
name: "今日",
key: 1,
},
{
name: "近三日",
key: 2,
},
{
name: "近一周",
key: 3,
},
{
name: "近一月",
key: 4,
},
{
name: "近三月",
key: 5,
},
{
name: "近半年",
key: 6,
},
],
}
}
export function GetDateDiff(startTime, endTime, diffType) {
startTime = startTime.replace(/\-/g, "/");
endTime = endTime.replace(/\-/g, "/");
var sTime = new Date(startTime);
var eTime = new Date(endTime);
var timeType = 1
switch (diffType) {
case 's':
timeType = 1000;
break;
case 'm':
timeType = 1000 * 60;
break;
case 'h':
timeType = 1000 * 3600;
break;
case 'd':
timeType = 1000 * 3600 * 24;
break;
default:
break;
}
return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(timeType))
}
/**
* 跳转首页
* @param {*} value ID
*/
export function setUserHome(value) {
switch (value) {
case 6:
setStorage("homeUrl", "/newTwoHome");
router.replace("/newTwoHome");
break;
case 7:
setStorage("homeUrl", "/");
router.replace("/");
break;
}
}
//获取天气数据
export function getWeatherData(params, fun) {
axios.get(`${baseUrl2}/mosty-api/mosty-base/other/getWeather`, {
params
}, {}).then(res => {
fun(res.data.data)
})
}
/**
* 提示窗口
* @param {*} msg 消息
* @param {*} hintType 位置
*/
Toast.allowMultiple();
export function hintToast(msg, hintType = 'top') {
const toast1 = Toast({
message: msg,
position: hintType
})
}
export function getLocationJs() {
let jwd = {}
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
(pos) => {
if (pos.coords) {
jwd.lat = pos.coords.latitude;
jwd.lng = pos.coords.longitude;
}
},
(err) => {
console.log(err, "err");
}
);
} else {
console.log("Geolocation is not supported by this browser.");
}
return jwd;
};

73
src/utils/watermark.js Normal file
View File

@ -0,0 +1,73 @@
let watermark = {}
let setWatermark = (str1, str2) => {
let id = '1.23452384164.123412415'
if (document.getElementById(id) !== null) {
document.body.removeChild(document.getElementById(id))
}
//创建一个画布
let can = document.createElement('canvas')
//设置画布的长宽
can.width = 400
can.height = 100
let cans = can.getContext('2d')
//旋转角度
cans.rotate(-10 * Math.PI / 180)
cans.font = '12px Vedana'
//设置填充绘画的颜色、渐变或者模式
//cans.fillStyle = 'rgba(200, 200, 200, 0.40)'
cans.fillStyle = '#000'
//设置文本内容的当前对齐方式
cans.textAlign = 'center'
//设置在绘制文本时使用的当前文本基线
cans.textBaseline = 'Middle'
//在画布上绘制填色的文本输出的文本开始绘制文本的x坐标位置开始绘制文本的Y坐标位置
cans.fillText(str1, can.width / 2, can.height)
cans.fillText(str2, can.width / 2, can.height + 22)
let div = document.createElement('div')
div.id = id
div.style.pointerEvents = 'none'
div.style.top = '0vw'
div.style.left = '-10%'
div.style.opacity = '0.15'
div.style.position = 'fixed'
div.style.zIndex = '100000'
div.style.width = document.documentElement.clientWidth + 'px'
div.style.height = document.documentElement.clientHeight + 'px'
div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
document.body.appendChild(div)
return id
}
//添加水印方法
watermark.set = (str1, str2) => {
let id = setWatermark(str1, str2)
setInterval(() => {
if (document.getElementById(id) === null) {
id = setWatermark(str1, str2)
}
}, 2000)
window.onresize = () => {
setWatermark(str)
}
}
//添加水印方法
watermark.set = (str1, str2) => {
let id = setWatermark(str1, str2)
if (document.getElementById(id) === null) {
id = setWatermark(str1, str2)
}
}
//添加水印方法
watermark.remove = () => {
let id = '1.23452384164.123412415'
if (document.getElementById(id) !== null) {
document.body.removeChild(document.getElementById(id))
// const div = document.getElementById(id)
// div.style.display = 'none'
}
}
export default watermark