初始化项目文件
8
.env.development
Normal file
@ -0,0 +1,8 @@
|
||||
# just a flag
|
||||
VITE_USER_NODE_ENV = development
|
||||
|
||||
# base api
|
||||
VITE_APP_BASE_API = 'http://192.168.11.56:6060/'
|
||||
|
||||
VITE_APP_IM_WS_URL=wss://your-im-server.com/ws
|
||||
VITE_APP_IM_API_URL=https://your-im-server.com/api
|
||||
8
.env.production
Normal file
@ -0,0 +1,8 @@
|
||||
# just a flag
|
||||
VITE_USER_NODE_ENV = production
|
||||
|
||||
# base api
|
||||
VITE_APP_BASE_API = 'http://qimen.wms.gztbyc.com/'
|
||||
|
||||
VITE_APP_IM_WS_URL=wss://your-im-server.com/ws
|
||||
VITE_APP_IM_API_URL=https://your-im-server.com/api
|
||||
5
.env.staging
Normal file
@ -0,0 +1,5 @@
|
||||
# just a flag
|
||||
VITE_USER_NODE_ENV = production
|
||||
|
||||
# base api
|
||||
VITE_APP_BASE_API = '/stage-api'
|
||||
39
.gitignore
vendored
Normal file
@ -0,0 +1,39 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
.eslintcache
|
||||
|
||||
# Cypress
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Vitest
|
||||
__screenshots__/
|
||||
|
||||
# Vite
|
||||
*.timestamp-*-*.mjs
|
||||
8
.vite/deps/_metadata.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"hash": "9d9ccd0b",
|
||||
"configHash": "cfc2dbc4",
|
||||
"lockfileHash": "dd8f2c82",
|
||||
"browserHash": "1f2545e6",
|
||||
"optimized": {},
|
||||
"chunks": {}
|
||||
}
|
||||
3
.vite/deps/package.json
Normal file
@ -0,0 +1,3 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
||||
3
.vscode/extensions.json
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["Vue.volar"]
|
||||
}
|
||||
42
README.md
Normal file
@ -0,0 +1,42 @@
|
||||
# newproject
|
||||
|
||||
This template should help get you started developing with Vue 3 in Vite.
|
||||
|
||||
## Recommended IDE Setup
|
||||
|
||||
[VS Code](https://code.visualstudio.com/) + [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
|
||||
|
||||
## Recommended Browser Setup
|
||||
|
||||
- Chromium-based browsers (Chrome, Edge, Brave, etc.):
|
||||
- [Vue.js devtools](https://chromewebstore.google.com/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd)
|
||||
- [Turn on Custom Object Formatter in Chrome DevTools](http://bit.ly/object-formatters)
|
||||
- Firefox:
|
||||
- [Vue.js devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/)
|
||||
- [Turn on Custom Object Formatter in Firefox DevTools](https://fxdx.dev/firefox-devtools-custom-object-formatters/)
|
||||
|
||||
## Type Support for `.vue` Imports in TS
|
||||
|
||||
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types.
|
||||
|
||||
## Customize configuration
|
||||
|
||||
See [Vite Configuration Reference](https://vite.dev/config/).
|
||||
|
||||
## Project Setup
|
||||
|
||||
```sh
|
||||
npm install
|
||||
```
|
||||
|
||||
### Compile and Hot-Reload for Development
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Type-Check, Compile and Minify for Production
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
12
env.d.ts
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
/// <reference types="vite/client" />
|
||||
declare module '@/utils/auth' {
|
||||
export function getToken(): string | undefined
|
||||
export function setToken(token: string): void
|
||||
export function removeToken(): void
|
||||
}
|
||||
declare module '@/api/user' {
|
||||
export function login(data: any): Promise<any>
|
||||
export function getInfo(data: any): Promise<any>
|
||||
export function changeRole(data: any): Promise<any>
|
||||
export function logout(data: any): Promise<any>
|
||||
}
|
||||
13
index.html
Normal file
@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Vite App</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
9602
package-lock.json
generated
Normal file
57
package.json
Normal file
@ -0,0 +1,57 @@
|
||||
{
|
||||
"name": "newproject",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "run-p type-check \"build-only {@}\" --",
|
||||
"preview": "vite preview",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"@types/nprogress": "^0.2.3",
|
||||
"@vueuse/core": "^14.2.1",
|
||||
"axios": "^1.13.6",
|
||||
"dayjs": "^1.11.19",
|
||||
"echarts": "^6.0.0",
|
||||
"element-plus": "^2.13.3",
|
||||
"js-cookie": "^3.0.5",
|
||||
"jsbarcode": "^3.12.3",
|
||||
"nprogress": "^0.2.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"path-to-regexp": "^8.3.0",
|
||||
"pinia": "^3.0.4",
|
||||
"qrcode": "^1.5.4",
|
||||
"spark-md5": "^3.0.2",
|
||||
"three": "^0.183.2",
|
||||
"uuid": "^13.0.0",
|
||||
"vue": "^3.5.29",
|
||||
"vue-draggable-plus": "^0.6.1",
|
||||
"vue-i18n": "^11.2.8",
|
||||
"vue-router": "^5.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node24": "^24.0.4",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/node": "^24.11.0",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/spark-md5": "^3.0.5",
|
||||
"@vitejs/plugin-vue": "^6.0.4",
|
||||
"@vue/tsconfig": "^0.8.1",
|
||||
"eslint-plugin-vue": "^10.8.0",
|
||||
"fast-glob": "^3.3.3",
|
||||
"npm-run-all2": "^8.0.4",
|
||||
"sass": "^1.97.3",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^7.3.1",
|
||||
"vite-plugin-svg-icons": "^2.0.1",
|
||||
"vite-plugin-vue-devtools": "^8.0.6",
|
||||
"vue-tsc": "^3.2.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
}
|
||||
BIN
public/favicon.ico
Normal file
|
After Width: | Height: | Size: 4.2 KiB |
BIN
public/logo/1.png
Normal file
|
After Width: | Height: | Size: 82 KiB |
25
src/App.vue
Normal file
@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import elementEnLocale from 'element-plus/es/locale/lang/en'
|
||||
import elementZhLocale from 'element-plus/es/locale/lang/zh-cn'
|
||||
|
||||
const { locale } = useI18n()
|
||||
|
||||
const currentLocale = computed(() => {
|
||||
if (locale.value === 'en') {
|
||||
return elementEnLocale
|
||||
}
|
||||
return elementZhLocale
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-config-provider :locale="currentLocale">
|
||||
<div id="app">
|
||||
<router-view />
|
||||
</div>
|
||||
</el-config-provider>
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
137
src/api/index.ts
Normal file
@ -0,0 +1,137 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
export function fastWhereTree(type:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.fastWhereTree',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {type},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
export function loadStores(type:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.loadStores',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {type},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
export function getCOSUploadConfig(data:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.getCOSUploadConfig',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {data},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
export function getImages(data:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.getImages',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function uploadSuccessNotify(data:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.uploadSuccessNotify',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function ReferenceFile(data:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.ReferenceFile',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getMessageDetail(data:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.getMessageDetail',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getI18nMessage(data:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.getI18nMessage',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function putI18nCollect(data:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.putI18nCollect',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getExpressList(){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.getExpressList',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
159
src/api/print/station.ts
Normal file
@ -0,0 +1,159 @@
|
||||
import request from '@/utils/request'
|
||||
const v = "1.0";
|
||||
|
||||
export function getList(data:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'print.getList',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
export function getItem(id: string) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'print.getItem',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { id }
|
||||
})
|
||||
}
|
||||
|
||||
export function add(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'print.add',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
export function hasName(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'print.hasName',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
export function updateItem(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'print.updateItem',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
// 删除单个打印台(兼容传入 id 或 { ids: [...] })
|
||||
export function delItem(idOrPayload: any) {
|
||||
let payload: any = idOrPayload
|
||||
if (typeof idOrPayload === 'string' || typeof idOrPayload === 'number') {
|
||||
payload = { ids: [String(idOrPayload)] }
|
||||
} else if (Array.isArray(idOrPayload)) {
|
||||
payload = { ids: idOrPayload }
|
||||
}
|
||||
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'print.del',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: payload
|
||||
})
|
||||
}
|
||||
|
||||
// 批量删除打印台,接受 id 字符串数组
|
||||
export function delItems(ids: string[]) {
|
||||
const payload = { ids: ids.map(String) }
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'print.del',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: payload
|
||||
})
|
||||
}
|
||||
|
||||
export function getComputer() {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'print.getComputer',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
|
||||
export function getExpressList() {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'index.getExpressList',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data:{},
|
||||
})
|
||||
}
|
||||
|
||||
export function getComputerPrinter(id: string) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'print.getComputerPrinter',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { id }
|
||||
})
|
||||
}
|
||||
|
||||
// 保存打印机与快递绑定关系
|
||||
export function savePrinters(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'print.savePrinters',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data
|
||||
})
|
||||
}
|
||||
196
src/api/printTemplate.ts
Normal file
@ -0,0 +1,196 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
// 模板列表(旧接口,保留兼容)
|
||||
export function listTemplates(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.list',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 新的模板列表请求,接受业务类型参数用于过滤
|
||||
export function listTemplatesByType(data:any) {
|
||||
// 内部映射仍使用同一方法,后端根据 data.businessType 处理
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.listTemplatesByType',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 获取模板详情
|
||||
export function getTemplateDetail(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.get',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 创建模板
|
||||
export function createTemplate(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.create',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 更新模板
|
||||
export function updateTemplate(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.update',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 删除模板
|
||||
export function deleteTemplate(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.delete',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 导出模板为 XML
|
||||
export function exportTemplateXml(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.exportXml',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 导入 XML 模板
|
||||
export function importTemplateXml(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.importXml',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 元素相关:新增元素
|
||||
export function addElement(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.addElement',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 更新元素
|
||||
export function updateElement(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.updateElement',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 删除元素
|
||||
export function deleteElement(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.deleteElement',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 复制元素
|
||||
export function duplicateElement(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.duplicateElement',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
export function saveTemplate (data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'setting.printTemplate.save',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
171
src/api/printer.ts
Normal file
@ -0,0 +1,171 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
// ---------------- 打印台 (Print Station) ----------------
|
||||
|
||||
// 打印台列表
|
||||
export function listPrintStations(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.station.list',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 创建打印台
|
||||
export function createPrintStation(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.station.create',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 更新打印台
|
||||
export function updatePrintStation(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.station.update',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 删除打印台
|
||||
export function deletePrintStation(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.station.delete',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
// ---------------- 打印电脑 (Print Computer) ----------------
|
||||
|
||||
// 打印电脑列表
|
||||
export function listPrintComputers(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.computer.list',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 创建打印电脑
|
||||
export function createPrintComputer(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.computer.create',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 更新打印电脑
|
||||
export function updatePrintComputer(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.computer.update',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 删除打印电脑
|
||||
export function deletePrintComputer(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.computer.delete',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// ---------------- 打印机绑定 (Printer Binding) ----------------
|
||||
|
||||
// 打印机列表 (获取电脑上的物理打印机)
|
||||
export function listPrinters(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.device.list',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 绑定打印机到打印台
|
||||
export function bindPrinterToStation(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.station.bind',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 解绑打印机
|
||||
export function unbindPrinterFromStation(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'printer.station.unbind',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
325
src/api/stock.ts
Normal file
@ -0,0 +1,325 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
const v = "1.0";
|
||||
|
||||
export function stockWarehouse(pagination: any, data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.stockWarehouse',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { pagination, where: data },
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getProhibitedType() {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.getProhibitedType',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getProhibitedList() {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.getProhibitedList',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getInfo(id: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.getInfo',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { id },
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function saveWarehouseStock(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.saveWarehouseStock',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getBarcodes(id: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.getBarcodes',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { id },
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function saveWarehouseStockBarcode(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.saveWarehouseStockBarcode',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getStoreStocks(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.getStoreStocks',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function bindItem(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.bindItem',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function unbindItem(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.unbindItem',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function queryStockLogs(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.queryStockLogs',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getStockUnits() {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.getStockUnits',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getUnitList() {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.getUnitList',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function createUnit(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.createUnit',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getBoxUnits() {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.getBoxUnits',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function checkItemCodeUnique(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.checkItemCodeUnique',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function createWarehouseStock(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.createWarehouseStock',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function handleBatchDelete(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.handleBatchDelete',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function handleBatchChange(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.handleBatchChange',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function deleteUnit(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.deleteUnit',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function createProhibited(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.createProhibited',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function deleteProhibited(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.deleteProhibited',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function backData(data: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'stock.backData',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
54
src/api/storage/receiving.ts
Normal file
@ -0,0 +1,54 @@
|
||||
import request from '@/utils/request'
|
||||
const v = "1.0"
|
||||
|
||||
export function getReceivingList(data: any): Promise<any> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'storage.receiving.getReceivingList',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
export function getReceivingDetail(data: any): Promise<any> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'storage.receiving.getReceivingDetail',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
export function batchCancelReceiving(data: any): Promise<any> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'storage.receiving.batchCancelReceiving',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
export function exportReceiving(data: any): Promise<any> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'storage.receiving.exportReceiving',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data
|
||||
})
|
||||
}
|
||||
85
src/api/store.ts
Normal file
@ -0,0 +1,85 @@
|
||||
import request from '@/utils/request'
|
||||
const v = "1.0";
|
||||
export function createStore(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'store.createStore',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function createWarehouse(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'store.createWarehouse',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function joinStore(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'store.joinStore',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function joinWarehouse(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'store.joinWarehouse',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function auditApply(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'store.auditApply',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getStoreRoles(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'store.getStoreRoles',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
66
src/api/system/config.ts
Normal file
@ -0,0 +1,66 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
// 查询参数列表
|
||||
export function listConfig(query: any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'config.list',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: query,
|
||||
isSystemApi:true,
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 查询参数详细
|
||||
export function getConfig(configId:any) {
|
||||
return request({
|
||||
url: '/system/config/getConfigValue/' + configId,
|
||||
method: 'get'
|
||||
})
|
||||
}
|
||||
|
||||
// 根据参数键名查询参数值
|
||||
export function getConfigKey(configKey:any) {
|
||||
return request({
|
||||
url: '/system/config/configKey/' + configKey,
|
||||
method: 'get'
|
||||
})
|
||||
}
|
||||
|
||||
// 新增参数配置
|
||||
export function addConfig(data:any) {
|
||||
return request({
|
||||
url: '/system/config',
|
||||
method: 'post',
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
// 修改参数配置
|
||||
export function updateConfig(data:any) {
|
||||
return request({
|
||||
url: '/system/config',
|
||||
method: 'put',
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
// 删除参数配置
|
||||
export function delConfig(configId:any) {
|
||||
return request({
|
||||
url: '/system/config/' + configId,
|
||||
method: 'delete'
|
||||
})
|
||||
}
|
||||
|
||||
// 刷新参数缓存
|
||||
export function refreshCache() {
|
||||
return request({
|
||||
url: '/system/config/refreshCache',
|
||||
method: 'delete'
|
||||
})
|
||||
}
|
||||
9
src/api/table.ts
Normal file
@ -0,0 +1,9 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
export function getList(params: any) {
|
||||
return request({
|
||||
url: '/vue-admin-template/table/list',
|
||||
method: 'get',
|
||||
params
|
||||
})
|
||||
}
|
||||
82
src/api/user.ts
Normal file
@ -0,0 +1,82 @@
|
||||
import request from '@/utils/request'
|
||||
import type { AxiosRequestConfig } from 'axios'
|
||||
|
||||
interface SystemApiRequestConfig<T = any> extends AxiosRequestConfig<T> {
|
||||
isSystemApi?: boolean;
|
||||
}
|
||||
|
||||
export interface UserLoginParams {
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export function login(data: UserLoginParams) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'user.login',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true
|
||||
} as SystemApiRequestConfig<UserLoginParams>);
|
||||
}
|
||||
|
||||
export function register (data:any):any {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'user.register',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true
|
||||
} as SystemApiRequestConfig<any>);
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function getInfo(data: Record<string, any>) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'user.info',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true
|
||||
} as SystemApiRequestConfig<Record<string, any>>);
|
||||
}
|
||||
|
||||
export function changeRole(data: Record<string, any>) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'user.changeRole',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true
|
||||
} as SystemApiRequestConfig<Record<string, any>>);
|
||||
}
|
||||
|
||||
export function logout(data?: Record<string, any>) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'user.logout',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {},
|
||||
isSystemApi: true
|
||||
} as SystemApiRequestConfig<Record<string, any>>);
|
||||
}
|
||||
212
src/api/warehouse.ts
Normal file
@ -0,0 +1,212 @@
|
||||
// src/api/warehouse.js
|
||||
|
||||
import request from '@/utils/request'
|
||||
|
||||
export function getWarehouseZones(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.getWarehouseZones',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data || {},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getWarehouseTree(warehouseId:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.getWarehouseTree',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { warehouseId },
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getChildren(zoneId:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.getChildren',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { zoneId },
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function create(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.create',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function update(data:any, id:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.update',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { id, ...data },
|
||||
isSystemApi: true
|
||||
} as any )
|
||||
}
|
||||
|
||||
export function deleteZone(id:any) { // 避免使用保留字
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.delete',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { id },
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function detail(id:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.detail',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { id },
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function toggleActive(id:any, isActive:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.toggleActive',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { id, isActive },
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getPath(id:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.getPath',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: { id },
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
// 检测连通性
|
||||
export function checkConnectivity(data:any) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.checkConnectivity',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getSpacesByRack(id:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.getSpacesByRack',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {id:id},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function createRackWithSpaces(id:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.createRackWithSpaces',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {id:id},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function getSpaceInfo(id:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.getSpaceInfo',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {id:id},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
export function checkBarcodeUnique(data:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.checkBarcodeUnique',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
export function updateSpaceInfo(data:any){
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'warehouse.updateSpaceInfo',
|
||||
v: '1.0',
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
BIN
src/assets/404_images/404.png
Normal file
|
After Width: | Height: | Size: 96 KiB |
BIN
src/assets/404_images/404_cloud.png
Normal file
|
After Width: | Height: | Size: 4.7 KiB |
86
src/components/Breadcrumb/index.vue
Normal file
@ -0,0 +1,86 @@
|
||||
<template>
|
||||
<el-breadcrumb class="app-breadcrumb" separator="/">
|
||||
<transition-group name="breadcrumb">
|
||||
<el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
|
||||
<span v-if="item.redirect === 'noRedirect' || index == levelList.length - 1" class="no-redirect">{{ generateTitle(item.meta.title, item.name) }}</span>
|
||||
<a v-else @click.prevent="handleLink(item)">{{ generateTitle(item.meta.title, item.name) }}</a>
|
||||
</el-breadcrumb-item>
|
||||
</transition-group>
|
||||
</el-breadcrumb>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, onMounted } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { compile } from 'path-to-regexp'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t, te } = useI18n()
|
||||
const levelList = ref<any[]>([])
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const generateTitle = (title: string, name: any) => {
|
||||
// Use name as key if available
|
||||
if (name && te('menu.' + name)) {
|
||||
return t('menu.' + name)
|
||||
}
|
||||
return title
|
||||
}
|
||||
|
||||
const getBreadcrumb = () => {
|
||||
let matched = route.matched.filter(item => item.meta && item.meta.title)
|
||||
const first = matched[0]
|
||||
|
||||
if (!isDashboard(first)) {
|
||||
matched = [{ path: '/dashboard', meta: { title: 'Dashboard' } } as any].concat(matched)
|
||||
}
|
||||
|
||||
levelList.value = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
|
||||
}
|
||||
|
||||
const isDashboard = (route: any) => {
|
||||
const name = route && route.name
|
||||
if (!name) {
|
||||
return false
|
||||
}
|
||||
return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
|
||||
}
|
||||
|
||||
const pathCompile = (path: string) => {
|
||||
const { params } = route
|
||||
const toPath = compile(path)
|
||||
return toPath(params)
|
||||
}
|
||||
|
||||
const handleLink = (item: any) => {
|
||||
const { redirect, path } = item
|
||||
if (redirect) {
|
||||
router.push(redirect)
|
||||
return
|
||||
}
|
||||
router.push(pathCompile(path))
|
||||
}
|
||||
|
||||
watch(route, () => {
|
||||
getBreadcrumb()
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
getBreadcrumb()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.app-breadcrumb.el-breadcrumb {
|
||||
display: inline-block;
|
||||
font-size: 14px;
|
||||
line-height: 50px;
|
||||
margin-left: 8px;
|
||||
|
||||
.no-redirect {
|
||||
color: #97a8be;
|
||||
cursor: text;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
578
src/components/ImagesUpload/index.vue
Normal file
@ -0,0 +1,578 @@
|
||||
<template>
|
||||
<div class="image-upload-container">
|
||||
<div class="image-wall-wrapper">
|
||||
<!-- Element Plus 图片墙上传组件 -->
|
||||
<el-upload
|
||||
ref="elUploadRef"
|
||||
action="#"
|
||||
v-model:file-list="fileList"
|
||||
list-type="picture-card"
|
||||
:auto-upload="false"
|
||||
:multiple="true"
|
||||
:limit="20"
|
||||
:on-change="handleChange"
|
||||
:on-preview="handlePictureCardPreview"
|
||||
:on-remove="handleRemove"
|
||||
:before-upload="beforeUpload"
|
||||
:on-exceed="handleExceed"
|
||||
:disabled="!hasPermission('index.ReferenceFile')"
|
||||
accept="image/*"
|
||||
>
|
||||
<el-icon><Plus /></el-icon>
|
||||
<template #tip>
|
||||
<div class="el-upload__tip">
|
||||
支持jpg/png格式,单张不超过10MB
|
||||
</div>
|
||||
</template>
|
||||
</el-upload>
|
||||
</div>
|
||||
|
||||
<div class="camera-section" v-if="hasPermission('index.ReferenceFile')">
|
||||
<div class="section-title">
|
||||
<el-icon><Camera /></el-icon>
|
||||
<span>摄像头拍照</span>
|
||||
</div>
|
||||
|
||||
<!-- 摄像头预览区域 -->
|
||||
<div class="camera-preview">
|
||||
<video
|
||||
ref="videoElement"
|
||||
v-show="isCameraActive && !capturedImage"
|
||||
class="camera-video"
|
||||
autoplay
|
||||
playsinline
|
||||
></video>
|
||||
|
||||
<!-- 拍照结果显示 -->
|
||||
<div v-if="capturedImage" class="captured-result">
|
||||
<img :src="capturedImage" alt="拍摄的照片" />
|
||||
<div class="capture-actions">
|
||||
<el-button
|
||||
type="success"
|
||||
size="small"
|
||||
@click="uploadCapturedImage"
|
||||
:loading="captureUploading"
|
||||
:disabled="!hasPermission('index.ReferenceFile')"
|
||||
>
|
||||
确认上传
|
||||
</el-button>
|
||||
<el-button
|
||||
type="info"
|
||||
size="small"
|
||||
@click="retakePhoto"
|
||||
>
|
||||
重新拍摄
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 摄像头未激活时的提示 -->
|
||||
<div v-else-if="!isCameraActive" class="camera-placeholder">
|
||||
<el-icon class="placeholder-icon"><CameraFilled /></el-icon>
|
||||
<p>点击下方按钮启动摄像头</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 摄像头控制按钮 -->
|
||||
<div class="camera-controls">
|
||||
<el-button
|
||||
type="primary"
|
||||
@click="toggleCamera"
|
||||
:loading="cameraLoading"
|
||||
:disabled="captureUploading"
|
||||
>
|
||||
{{ isCameraActive ? '关闭摄像头' : '启动摄像头' }}
|
||||
</el-button>
|
||||
|
||||
<el-button
|
||||
type="success"
|
||||
:disabled="!isCameraActive || capturedImage || captureUploading"
|
||||
@click="capturePhoto"
|
||||
>
|
||||
<el-icon><Camera /></el-icon>
|
||||
拍照
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 图片预览对话框 -->
|
||||
<el-dialog
|
||||
v-model="previewVisible"
|
||||
title="图片预览"
|
||||
width="80%"
|
||||
top="5vh"
|
||||
append-to-body
|
||||
>
|
||||
<img :src="dialogImageUrl" alt="预览" style="width: 100%; max-height: 70vh; object-fit: contain;" />
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, watch, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Plus, Camera, CameraFilled } from '@element-plus/icons-vue'
|
||||
import * as indexApi from '@/api/index'
|
||||
import SparkMD5 from 'spark-md5'
|
||||
import { useUserStore } from '@/stores/modules/user'
|
||||
|
||||
const props = defineProps<{
|
||||
type: string
|
||||
id: string | number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits(['refresh'])
|
||||
|
||||
const userStore = useUserStore()
|
||||
const hasPermission = (permission: string) => {
|
||||
return userStore.checkPermission(permission)
|
||||
}
|
||||
|
||||
// Element Upload组件数据
|
||||
const fileList = ref<any[]>([])
|
||||
const dialogImageUrl = ref('')
|
||||
const previewVisible = ref(false)
|
||||
const elUploadRef = ref()
|
||||
|
||||
// 摄像头相关
|
||||
const videoElement = ref<HTMLVideoElement | null>(null)
|
||||
const videoStream = ref<MediaStream | null>(null)
|
||||
const isCameraActive = ref(false)
|
||||
const cameraLoading = ref(false)
|
||||
const capturedImage = ref<string | null>(null)
|
||||
const captureUploading = ref(false)
|
||||
|
||||
// 缓存
|
||||
const cosConfigCache = new Map()
|
||||
const md5CalculationPool = new Map()
|
||||
const chunkSize = 2 * 1024 * 1024 // 2MB
|
||||
|
||||
// 加载图片
|
||||
const loadImages = async () => {
|
||||
if (!props.id) return
|
||||
try {
|
||||
const params = {
|
||||
type: props.type,
|
||||
id: props.id
|
||||
}
|
||||
const response = await indexApi.getImages(params)
|
||||
// 确保每个文件都有uid属性
|
||||
fileList.value = (response.data || []).map((img: any) => ({
|
||||
uid: img.file_id,
|
||||
name: img.file?.file_name || 'unknown',
|
||||
url: img.file?.file_url || '',
|
||||
status: 'success',
|
||||
response: img
|
||||
}))
|
||||
} catch (error) {
|
||||
console.error('加载图片失败:', error)
|
||||
ElMessage.error('加载图片失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 监听 ID 变化
|
||||
watch(() => props.id, (newVal) => {
|
||||
if (newVal) {
|
||||
loadImages()
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
onMounted(() => {
|
||||
loadImages()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopCamera()
|
||||
// 清理 URL
|
||||
fileList.value.forEach(file => {
|
||||
if (file.url && file.url.startsWith('blob:')) {
|
||||
URL.revokeObjectURL(file.url)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// 自动关联文件
|
||||
const referenceFile = async () => {
|
||||
const pendingFiles = fileList.value.filter(file => file.status === 'success' && file.uid)
|
||||
const images = pendingFiles.map(item => ({ file_id: item.uid }))
|
||||
|
||||
const params = {
|
||||
type: props.type,
|
||||
id: props.id,
|
||||
images: images
|
||||
}
|
||||
await indexApi.ReferenceFile(params)
|
||||
emit('refresh')
|
||||
}
|
||||
|
||||
// 预览图片
|
||||
const handlePictureCardPreview = (uploadFile: any) => {
|
||||
dialogImageUrl.value = uploadFile.url!
|
||||
previewVisible.value = true
|
||||
}
|
||||
|
||||
// 移除图片
|
||||
const handleRemove = async (uploadFile: any, uploadFiles: any[]) => {
|
||||
// 更新 fileList
|
||||
// fileList.value = uploadFiles // v-model 会自动更新
|
||||
await referenceFile()
|
||||
}
|
||||
|
||||
// 文件状态改变
|
||||
const handleChange = async (uploadFile: any, uploadFiles: any[]) => {
|
||||
// fileList.value = uploadFiles // v-model 会自动更新
|
||||
|
||||
if (uploadFile.raw) {
|
||||
if (!uploadFile.url) {
|
||||
uploadFile.url = URL.createObjectURL(uploadFile.raw)
|
||||
}
|
||||
// 计算 MD5
|
||||
calculateMd5ForFile(uploadFile).then(md5 => {
|
||||
uploadFile.md5 = md5
|
||||
console.log('文件MD5:', uploadFile.name, md5)
|
||||
}).catch(console.warn)
|
||||
}
|
||||
|
||||
// 如果是新添加的文件(status === 'ready'),执行上传
|
||||
if (uploadFile.status === 'ready') {
|
||||
await uploadAllFiles()
|
||||
await referenceFile()
|
||||
}
|
||||
}
|
||||
|
||||
// 上传逻辑
|
||||
const uploadAllFiles = async () => {
|
||||
const pendingFiles = fileList.value.filter(file => file.status === 'ready')
|
||||
if (pendingFiles.length === 0) return
|
||||
|
||||
for (const file of pendingFiles) {
|
||||
try {
|
||||
file.status = 'uploading'
|
||||
const result = await uploadFile(file)
|
||||
|
||||
file.url = result.fileUrl
|
||||
file.uid = result.fileId
|
||||
file.status = 'success'
|
||||
} catch (error: any) {
|
||||
file.status = 'fail'
|
||||
ElMessage.error(error.message || '上传失败')
|
||||
}
|
||||
}
|
||||
// 清理缓存
|
||||
cosConfigCache.clear()
|
||||
}
|
||||
|
||||
const uploadFile = async (file: any) => {
|
||||
const rawFile = file.raw || file
|
||||
const cosConfig = await getCOSUploadConfig(rawFile)
|
||||
|
||||
if (cosConfig.isNew === false) {
|
||||
return cosConfig
|
||||
}
|
||||
if (cosConfig.error) {
|
||||
throw new Error(cosConfig.msg)
|
||||
}
|
||||
|
||||
const formData = new FormData()
|
||||
if (cosConfig.data) {
|
||||
Object.keys(cosConfig.data).forEach(key => {
|
||||
formData.append(key, cosConfig.data[key])
|
||||
})
|
||||
}
|
||||
formData.append('file', rawFile)
|
||||
|
||||
const response = await fetch(cosConfig.uploadUrl, {
|
||||
method: 'POST',
|
||||
headers: cosConfig.headers || {},
|
||||
body: formData
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`上传失败: ${response.status}`)
|
||||
}
|
||||
|
||||
const { data } = await indexApi.uploadSuccessNotify(cosConfig.fileInfo || cosConfig) // 注意这里可能需要根据实际接口返回调整
|
||||
return data
|
||||
}
|
||||
|
||||
const getCOSUploadConfig = async (file: File) => {
|
||||
const cacheKey = `${file.name}_${file.size}`
|
||||
if (cosConfigCache.has(cacheKey)) {
|
||||
return cosConfigCache.get(cacheKey)
|
||||
}
|
||||
|
||||
let fileMd5 = ''
|
||||
try {
|
||||
if (file.size < 5 * 1024 * 1024) {
|
||||
fileMd5 = await calculateFileMd5Quick(file)
|
||||
} else {
|
||||
fileMd5 = await calculateFileMd5(file)
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('MD5 calculation failed', e)
|
||||
}
|
||||
|
||||
const response = await indexApi.getCOSUploadConfig({
|
||||
fileName: file.name,
|
||||
fileType: file.type,
|
||||
fileSize: file.size,
|
||||
md5: fileMd5,
|
||||
type: props.type,
|
||||
id: props.id
|
||||
})
|
||||
|
||||
const config = response.data
|
||||
cosConfigCache.set(cacheKey, config)
|
||||
return config
|
||||
}
|
||||
|
||||
// MD5 Calculations
|
||||
const calculateFileMd5 = (file: File): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const spark = new SparkMD5.ArrayBuffer()
|
||||
const reader = new FileReader()
|
||||
const fileSize = file.size
|
||||
const chunks = Math.ceil(fileSize / chunkSize)
|
||||
let currentChunk = 0
|
||||
|
||||
reader.onload = (e: any) => {
|
||||
spark.append(e.target.result)
|
||||
currentChunk++
|
||||
if (currentChunk < chunks) {
|
||||
loadNext()
|
||||
} else {
|
||||
resolve(spark.end())
|
||||
}
|
||||
}
|
||||
reader.onerror = () => reject(new Error('Read file failed'))
|
||||
|
||||
const loadNext = () => {
|
||||
const start = currentChunk * chunkSize
|
||||
const end = Math.min(start + chunkSize, fileSize)
|
||||
reader.readAsArrayBuffer(file.slice(start, end))
|
||||
}
|
||||
loadNext()
|
||||
})
|
||||
}
|
||||
|
||||
const calculateFileMd5Quick = (file: File): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
const spark = new SparkMD5.ArrayBuffer()
|
||||
reader.onload = (e: any) => {
|
||||
spark.append(e.target.result)
|
||||
resolve(spark.end())
|
||||
}
|
||||
reader.onerror = () => reject(new Error('Read file failed'))
|
||||
reader.readAsArrayBuffer(file)
|
||||
})
|
||||
}
|
||||
|
||||
const calculateMd5ForFile = async (file: any) => {
|
||||
const fileObj = file.raw || file
|
||||
if (fileObj.size < 5 * 1024 * 1024) {
|
||||
return await calculateFileMd5Quick(fileObj)
|
||||
} else {
|
||||
return await calculateFileMd5(fileObj)
|
||||
}
|
||||
}
|
||||
|
||||
const beforeUpload = (file: any) => {
|
||||
// 可以在这里做一些校验
|
||||
return true
|
||||
}
|
||||
|
||||
const handleExceed = () => {
|
||||
ElMessage.warning('超出文件数量限制')
|
||||
}
|
||||
|
||||
// 摄像头相关逻辑
|
||||
const toggleCamera = async () => {
|
||||
if (isCameraActive.value) {
|
||||
stopCamera()
|
||||
} else {
|
||||
await startCamera()
|
||||
}
|
||||
}
|
||||
|
||||
const startCamera = async () => {
|
||||
cameraLoading.value = true
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
video: { facingMode: 'environment' }
|
||||
})
|
||||
videoStream.value = stream
|
||||
if (videoElement.value) {
|
||||
videoElement.value.srcObject = stream
|
||||
videoElement.value.play()
|
||||
}
|
||||
isCameraActive.value = true
|
||||
capturedImage.value = null
|
||||
} catch (error) {
|
||||
console.error('无法启动摄像头:', error)
|
||||
ElMessage.error('无法启动摄像头,请检查权限')
|
||||
} finally {
|
||||
cameraLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const stopCamera = () => {
|
||||
if (videoStream.value) {
|
||||
videoStream.value.getTracks().forEach(track => track.stop())
|
||||
videoStream.value = null
|
||||
}
|
||||
if (videoElement.value) {
|
||||
videoElement.value.srcObject = null
|
||||
}
|
||||
isCameraActive.value = false
|
||||
}
|
||||
|
||||
const capturePhoto = () => {
|
||||
if (!videoElement.value) return
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = videoElement.value.videoWidth
|
||||
canvas.height = videoElement.value.videoHeight
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (ctx) {
|
||||
ctx.drawImage(videoElement.value, 0, 0)
|
||||
capturedImage.value = canvas.toDataURL('image/jpeg')
|
||||
// 停止视频流以节省资源? 或者保持开启?
|
||||
// 这里选择保持开启,因为可能需要重拍
|
||||
}
|
||||
}
|
||||
|
||||
const retakePhoto = () => {
|
||||
capturedImage.value = null
|
||||
}
|
||||
|
||||
const uploadCapturedImage = async () => {
|
||||
if (!capturedImage.value) return
|
||||
|
||||
captureUploading.value = true
|
||||
try {
|
||||
// 将 Base64 转换为 File 对象
|
||||
const arr = capturedImage.value.split(',')
|
||||
const mime = arr[0]?.match(/:(.*?);/)?.[1] || 'image/jpeg'
|
||||
const bstr = atob(arr[1] || '')
|
||||
let n = bstr.length
|
||||
const u8arr = new Uint8Array(n)
|
||||
while (n--) {
|
||||
u8arr[n] = bstr.charCodeAt(n)
|
||||
}
|
||||
const blob = new Blob([u8arr], { type: mime })
|
||||
const file = new File([blob], `camera_${Date.now()}.jpg`, { type: mime })
|
||||
|
||||
// 添加到 fileList 并上传
|
||||
const uploadFileObj = {
|
||||
uid: Date.now(),
|
||||
name: file.name,
|
||||
status: 'ready',
|
||||
raw: file,
|
||||
url: URL.createObjectURL(file)
|
||||
}
|
||||
fileList.value.push(uploadFileObj)
|
||||
|
||||
// 触发上传逻辑
|
||||
await uploadAllFiles()
|
||||
await referenceFile()
|
||||
|
||||
ElMessage.success('拍照上传成功')
|
||||
capturedImage.value = null
|
||||
} catch (error) {
|
||||
console.error('上传失败:', error)
|
||||
ElMessage.error('上传失败')
|
||||
} finally {
|
||||
captureUploading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.image-upload-container {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.image-wall-wrapper {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.camera-section {
|
||||
border: 1px solid #dcdfe6;
|
||||
border-radius: 4px;
|
||||
padding: 15px;
|
||||
background-color: #f5f7fa;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 15px;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
color: #606266;
|
||||
}
|
||||
|
||||
.camera-preview {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 640px;
|
||||
height: 480px;
|
||||
background-color: #000;
|
||||
margin: 0 auto 15px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.camera-video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.captured-result {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.captured-result img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.capture-actions {
|
||||
position: absolute;
|
||||
bottom: 20px;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 15px;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
padding: 10px 0;
|
||||
}
|
||||
|
||||
.camera-placeholder {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.placeholder-icon {
|
||||
font-size: 48px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.camera-controls {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 20px;
|
||||
}
|
||||
</style>
|
||||
57
src/components/LangSelect/index.vue
Normal file
@ -0,0 +1,57 @@
|
||||
<template>
|
||||
<el-dropdown trigger="click" @command="handleSetLanguage" class="lang-select">
|
||||
<div class="lang-wrapper">
|
||||
<svg-icon icon-class="language" class="lang-icon" />
|
||||
<span class="lang-text">{{ $t("common.language") }}</span>
|
||||
</div>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="zh-CN" :disabled="language === 'zh-CN'">
|
||||
中文
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item command="en" :disabled="language === 'en'">
|
||||
English
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAppStore } from '@/stores/modules/app'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
const { locale } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
|
||||
const language = computed(() => appStore.language)
|
||||
|
||||
const handleSetLanguage = (lang: string) => {
|
||||
locale.value = lang
|
||||
appStore.setLanguage(lang)
|
||||
ElMessage({
|
||||
message: 'Switch Language Success',
|
||||
type: 'success'
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.lang-select {
|
||||
cursor: pointer;
|
||||
}
|
||||
.lang-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 8px;
|
||||
}
|
||||
.lang-icon {
|
||||
font-size: 18px;
|
||||
margin-right: 4px;
|
||||
}
|
||||
.lang-text {
|
||||
font-size: 14px;
|
||||
}
|
||||
</style>
|
||||
365
src/components/RequestData/index.vue
Normal file
@ -0,0 +1,365 @@
|
||||
<template>
|
||||
<div class="api-message-viewer">
|
||||
<!-- 加载状态 -->
|
||||
<div v-if="loading" class="loading-container">
|
||||
<el-skeleton :rows="5" animated />
|
||||
</div>
|
||||
|
||||
<!-- 内容区域 -->
|
||||
<template v-else>
|
||||
<!-- 请求报文 -->
|
||||
<div class="message-section">
|
||||
<div class="section-title-bar">
|
||||
<h3 class="section-title">请求报文</h3>
|
||||
<div class="section-actions">
|
||||
<el-button
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="copyRequestBody"
|
||||
:disabled="!messageData || !messageData.body"
|
||||
>
|
||||
复制请求体
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="message-content-container">
|
||||
<el-tooltip content="格式化/压缩" placement="top">
|
||||
<el-button
|
||||
type="info"
|
||||
size="small"
|
||||
circle
|
||||
class="format-btn"
|
||||
@click="toggleFormat('requestBody')"
|
||||
>
|
||||
{{ formatState.requestBody ? '压缩' : '格式化' }}
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
<pre class="message-content">{{ formatContent(messageData && messageData.body, 'requestBody') }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 响应报文 -->
|
||||
<div class="message-section">
|
||||
<div class="section-title-bar">
|
||||
<h3 class="section-title">响应报文</h3>
|
||||
<div class="section-actions">
|
||||
<el-button
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="copyResponseBody"
|
||||
:disabled="!messageData || !messageData.result"
|
||||
>
|
||||
复制响应体
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="message-content-container">
|
||||
<el-tooltip content="格式化/压缩" placement="top">
|
||||
<el-button
|
||||
type="info"
|
||||
size="small"
|
||||
circle
|
||||
class="format-btn"
|
||||
@click="toggleFormat('responseBody')"
|
||||
>
|
||||
{{ formatState.responseBody ? '压缩' : '格式化' }}
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
<pre class="message-content">{{ formatContent(messageData && messageData.result, 'responseBody') }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 原始数据复制 -->
|
||||
<div class="raw-section" v-if="messageData">
|
||||
<el-button type="info" size="small" plain @click="copyRawData">
|
||||
复制原始JSON数据
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, watch, onMounted } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import * as indexApi from '@/api/index'
|
||||
|
||||
const props = defineProps<{
|
||||
id?: number
|
||||
type?: string
|
||||
}>()
|
||||
|
||||
const loading = ref(false)
|
||||
const messageData = ref<any>(null)
|
||||
const formatState = reactive({
|
||||
requestBody: true,
|
||||
responseBody: true
|
||||
})
|
||||
|
||||
watch(() => props.id, (newVal) => {
|
||||
if (newVal) {
|
||||
fetchMessageData()
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
if (props.id) {
|
||||
fetchMessageData()
|
||||
}
|
||||
})
|
||||
|
||||
// 获取报文数据
|
||||
async function fetchMessageData() {
|
||||
if (!props.id) return
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const params: any = {
|
||||
id: props.id,
|
||||
type: props.type
|
||||
}
|
||||
|
||||
const response: any = await indexApi.getMessageDetail(params)
|
||||
if (response && response.data) {
|
||||
messageData.value = response.data
|
||||
} else {
|
||||
messageData.value = null
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取报文数据失败:', error)
|
||||
ElMessage.error('获取报文数据失败')
|
||||
messageData.value = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 格式化内容
|
||||
function formatContent(data: any, type: 'requestBody' | 'responseBody') {
|
||||
if (!data) return '暂无数据'
|
||||
|
||||
const isFormatted = formatState[type]
|
||||
|
||||
// 如果是XML,尝试格式化
|
||||
if (typeof data === 'string' && data.trim().startsWith('<?xml')) {
|
||||
try {
|
||||
return formatXML(data, isFormatted)
|
||||
} catch (error) {
|
||||
return isFormatted ? data : data.replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
}
|
||||
|
||||
// 如果是JSON或普通文本
|
||||
try {
|
||||
// 尝试解析为JSON
|
||||
const parsed = typeof data === 'string' ? JSON.parse(data) : data
|
||||
return isFormatted ?
|
||||
JSON.stringify(parsed, null, 2) :
|
||||
JSON.stringify(parsed)
|
||||
} catch (error) {
|
||||
// 如果不是JSON,按原样显示
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
// 简单格式化XML
|
||||
function formatXML(xml: string, formatted: boolean) {
|
||||
if (!formatted || !xml) {
|
||||
return xml ? xml.replace(/\s+/g, ' ').trim() : ''
|
||||
}
|
||||
|
||||
try {
|
||||
// 使用正则表达式简单格式化XML
|
||||
let formattedXml = xml
|
||||
.replace(/>\s*</g, '>\n<')
|
||||
.replace(/<([^>]+)>/g, function(match, p1) {
|
||||
if (p1.startsWith('/')) {
|
||||
return match
|
||||
}
|
||||
return match
|
||||
})
|
||||
|
||||
// 添加缩进
|
||||
let indent = ''
|
||||
const tab = ' '
|
||||
const lines = formattedXml.split('\n')
|
||||
let result = []
|
||||
|
||||
for (let line of lines) {
|
||||
line = line.trim()
|
||||
if (!line) continue
|
||||
|
||||
if (line.match(/^<\/\w/)) {
|
||||
indent = indent.substring(tab.length)
|
||||
}
|
||||
|
||||
result.push(indent + line)
|
||||
|
||||
if (line.match(/^<\w[^>]*[^/]$/) && !line.match(/^<\?xml/)) {
|
||||
indent += tab
|
||||
}
|
||||
}
|
||||
|
||||
return result.join('\n')
|
||||
} catch (error) {
|
||||
return xml
|
||||
}
|
||||
}
|
||||
|
||||
// 切换格式化状态
|
||||
function toggleFormat(type: 'requestBody' | 'responseBody') {
|
||||
formatState[type] = !formatState[type]
|
||||
}
|
||||
|
||||
// 复制文本
|
||||
async function copyText(text: any, successMsg: string) {
|
||||
try {
|
||||
const content = typeof text === 'object' ? JSON.stringify(text, null, 2) : String(text)
|
||||
await navigator.clipboard.writeText(content)
|
||||
ElMessage.success(successMsg)
|
||||
return true
|
||||
} catch (error) {
|
||||
ElMessage.error('复制失败')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// 复制请求体
|
||||
function copyRequestBody() {
|
||||
const body = messageData.value && messageData.value.body
|
||||
copyText(body, '请求体复制成功')
|
||||
}
|
||||
|
||||
// 复制响应体
|
||||
function copyResponseBody() {
|
||||
const result = messageData.value && messageData.value.result
|
||||
copyText(result, '响应体复制成功')
|
||||
}
|
||||
|
||||
// 复制原始数据
|
||||
function copyRawData() {
|
||||
copyText(messageData.value, '原始JSON数据复制成功')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.api-message-viewer {
|
||||
height: 100%;
|
||||
padding: 20px;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.loading-container {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.message-section {
|
||||
margin-bottom: 30px;
|
||||
border: 1px solid #ebeef5;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.section-title-bar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
background: #f5f7fa;
|
||||
border-bottom: 1px solid #ebeef5;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.section-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.message-content-container {
|
||||
position: relative;
|
||||
padding: 16px;
|
||||
background: #fafafa;
|
||||
min-height: 200px;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.format-btn {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.message-content {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
overflow: auto;
|
||||
flex: 1;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.raw-section {
|
||||
text-align: center;
|
||||
margin-top: 20px;
|
||||
padding-top: 20px;
|
||||
border-top: 1px dashed #dcdfe6;
|
||||
}
|
||||
|
||||
/* 滚动条样式 */
|
||||
.message-content::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.message-content::-webkit-scrollbar-thumb {
|
||||
background: #c1c1c1;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.message-content::-webkit-scrollbar-thumb:hover {
|
||||
background: #a8a8a8;
|
||||
}
|
||||
|
||||
/* 响应式设计 */
|
||||
@media (max-width: 768px) {
|
||||
.section-title-bar {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.section-actions {
|
||||
width: 100%;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.message-content-container {
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.message-content {
|
||||
max-height: 300px;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
896
src/components/ScanBox/index.vue
Normal file
@ -0,0 +1,896 @@
|
||||
<template>
|
||||
<div class="scan-box-container" :style="{ width: width }">
|
||||
<!-- Tab 切换 -->
|
||||
<div class="scan-tabs">
|
||||
<el-tabs v-model="activeTab" stretch @tab-click="handleTabChange">
|
||||
<el-tab-pane label="筛选" name="custom">
|
||||
<template #label>
|
||||
<span class="tab-label">
|
||||
<el-icon><Operation /></el-icon>
|
||||
筛选
|
||||
</span>
|
||||
</template>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="过滤" name="preset">
|
||||
<template #label>
|
||||
<span class="tab-label">
|
||||
<el-icon><DataAnalysis /></el-icon>
|
||||
过滤
|
||||
</span>
|
||||
</template>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</div>
|
||||
|
||||
<!-- 内容区域 -->
|
||||
<div class="scan-content">
|
||||
<!-- 自定义筛选 -->
|
||||
<div v-show="activeTab === 'custom'" class="custom-filter">
|
||||
<div class="filter-scroll-area" ref="filterScroll">
|
||||
<!-- 所有字段配置的表单 -->
|
||||
<div class="field-forms">
|
||||
<template v-for="field in availableFields" :key="field.value">
|
||||
<!-- 文本类型 -->
|
||||
<div v-if="field.type === 'text'" class="field-form-item">
|
||||
<div class="field-label">
|
||||
<span>{{ field.label }}</span>
|
||||
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
|
||||
</div>
|
||||
<div class="field-control">
|
||||
<el-select
|
||||
v-model="customConditions[field.value].operator"
|
||||
placeholder="条件类型"
|
||||
size="small"
|
||||
style="width: 100%; margin-bottom: 8px;"
|
||||
@change="handleTextOperatorChange(field)"
|
||||
>
|
||||
<el-option
|
||||
v-for="op in getOperators(field)"
|
||||
:key="op.value"
|
||||
:label="op.label"
|
||||
:value="op.value"
|
||||
/>
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="customConditions[field.value].value"
|
||||
:placeholder="getTextPlaceholder(field)"
|
||||
size="small"
|
||||
clearable
|
||||
@change="handleCustomChange"
|
||||
@blur="normalizeTextValue(field)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 数字类型 -->
|
||||
<div v-else-if="field.type === 'number'" class="field-form-item">
|
||||
<div class="field-label">
|
||||
<span>{{ field.label }}</span>
|
||||
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
|
||||
</div>
|
||||
<div class="field-control">
|
||||
<el-select
|
||||
v-model="customConditions[field.value].operator"
|
||||
placeholder="请选择"
|
||||
size="small"
|
||||
style="width: 100%; margin-bottom: 8px;"
|
||||
>
|
||||
<el-option
|
||||
v-for="op in getOperators(field)"
|
||||
:key="op.value"
|
||||
:label="op.label"
|
||||
:value="op.value"
|
||||
/>
|
||||
</el-select>
|
||||
<el-input-number
|
||||
v-model="customConditions[field.value].value"
|
||||
:controls="false"
|
||||
size="small"
|
||||
:placeholder="field.placeholder || `请输入${field.label}`"
|
||||
style="width: 100%;"
|
||||
@change="handleCustomChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 日期类型 -->
|
||||
<div v-else-if="field.type === 'date'" class="field-form-item">
|
||||
<div class="field-label">
|
||||
<span>{{ field.label }}</span>
|
||||
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
|
||||
</div>
|
||||
<div class="field-control">
|
||||
<el-select
|
||||
v-model="customConditions[field.value].operator"
|
||||
placeholder="请选择"
|
||||
size="small"
|
||||
style="width: 100%; margin-bottom: 8px;"
|
||||
>
|
||||
<el-option
|
||||
v-for="op in getOperators(field)"
|
||||
:key="op.value"
|
||||
:label="op.label"
|
||||
:value="op.value"
|
||||
/>
|
||||
</el-select>
|
||||
<el-date-picker
|
||||
v-model="customConditions[field.value].value"
|
||||
type="date"
|
||||
:placeholder="field.placeholder || `请选择${field.label}`"
|
||||
size="small"
|
||||
style="width: 100%;"
|
||||
format="YYYY-MM-DD"
|
||||
value-format="YYYY-MM-DD"
|
||||
@change="handleCustomChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 日期范围类型 -->
|
||||
<div v-else-if="field.type === 'daterange'" class="field-form-item">
|
||||
<div class="field-label">
|
||||
<span>{{ field.label }}</span>
|
||||
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
|
||||
</div>
|
||||
<div class="field-control">
|
||||
<el-date-picker
|
||||
v-model="customConditions[field.value].value"
|
||||
type="daterange"
|
||||
range-separator="至"
|
||||
:start-placeholder="field.startPlaceholder || '开始日期'"
|
||||
:end-placeholder="field.endPlaceholder || '结束日期'"
|
||||
size="small"
|
||||
style="width: 100%;"
|
||||
format="YYYY-MM-DD"
|
||||
value-format="YYYY-MM-DD"
|
||||
@change="handleCustomChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 下拉选择类型 -->
|
||||
<div v-else-if="field.type === 'select'" class="field-form-item">
|
||||
<div class="field-label">
|
||||
<span>{{ field.label }}</span>
|
||||
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
|
||||
</div>
|
||||
<div class="field-control">
|
||||
<el-select
|
||||
v-model="customConditions[field.value].value"
|
||||
:placeholder="field.placeholder || `请选择${field.label}`"
|
||||
size="small"
|
||||
filterable
|
||||
clearable
|
||||
style="width: 100%;"
|
||||
@change="handleCustomChange"
|
||||
>
|
||||
<el-option
|
||||
v-for="option in field.options"
|
||||
:key="option.value"
|
||||
:label="option.label"
|
||||
:value="option.value"
|
||||
/>
|
||||
</el-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 多选类型 -->
|
||||
<div v-else-if="field.type === 'multiple'" class="field-form-item">
|
||||
<div class="field-label">
|
||||
<span>{{ field.label }}</span>
|
||||
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
|
||||
</div>
|
||||
<div class="field-control">
|
||||
<el-select
|
||||
v-model="customConditions[field.value].value"
|
||||
multiple
|
||||
:placeholder="field.placeholder || `请选择${field.label}`"
|
||||
size="small"
|
||||
:filterable = "field.filterable"
|
||||
style="width: 100%;"
|
||||
@change="handleCustomChange"
|
||||
>
|
||||
<el-option
|
||||
v-for="option in field.options"
|
||||
:key="option.value"
|
||||
:label="option.label"
|
||||
:value="option.value"
|
||||
/>
|
||||
</el-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 布尔类型 -->
|
||||
<div v-else-if="field.type === 'boolean'" class="field-form-item">
|
||||
<div class="field-label">
|
||||
<span>{{ field.label }}</span>
|
||||
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
|
||||
</div>
|
||||
<div class="field-control">
|
||||
<el-select
|
||||
v-model="customConditions[field.value].value"
|
||||
:placeholder="field.placeholder || `请选择${field.label}`"
|
||||
size="small"
|
||||
style="width: 100%;"
|
||||
@change="handleCustomChange"
|
||||
>
|
||||
<el-option label="是" :value="true" />
|
||||
<el-option label="否" :value="false" />
|
||||
<el-option label="全部" :value="null" />
|
||||
</el-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 自定义组件类型 -->
|
||||
<div v-else-if="field.type === 'custom'" class="field-form-item">
|
||||
<div class="field-label">
|
||||
<span>{{ field.label }}</span>
|
||||
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
|
||||
</div>
|
||||
<div class="field-control">
|
||||
<component
|
||||
:is="field.component"
|
||||
v-model="customConditions[field.value].value"
|
||||
v-bind="field.props || {}"
|
||||
@change="handleCustomChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 固定底部操作栏 -->
|
||||
<div class="fixed-bottom-actions" :class="{ 'has-scroll': hasScroll }">
|
||||
<div class="actions-content">
|
||||
<el-button
|
||||
size="small"
|
||||
@click="handleReset"
|
||||
class="reset-btn"
|
||||
>
|
||||
重置
|
||||
</el-button>
|
||||
<el-button
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="handleSubmit"
|
||||
:loading="submitting"
|
||||
>
|
||||
确定
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 预设过滤 -->
|
||||
<div v-show="activeTab === 'preset'" class="preset-filter">
|
||||
<div class="filter-scroll-area">
|
||||
<!-- 搜索框 -->
|
||||
<div class="preset-search" v-if="presetTree && presetTree.length > 0">
|
||||
<el-input
|
||||
v-model="presetSearchText"
|
||||
placeholder="搜索过滤条件"
|
||||
size="small"
|
||||
clearable
|
||||
@input="filterPresetTree"
|
||||
>
|
||||
<template #prefix>
|
||||
<el-icon><Search /></el-icon>
|
||||
</template>
|
||||
</el-input>
|
||||
</div>
|
||||
|
||||
<!-- 预设树 -->
|
||||
<div class="preset-tree" v-if="filteredPresetTree && filteredPresetTree.length > 0">
|
||||
<el-tree
|
||||
ref="presetTreeRef"
|
||||
:data="filteredPresetTree"
|
||||
:props="treeProps"
|
||||
node-key="id"
|
||||
accordion
|
||||
highlight-current
|
||||
:expand-on-click-node="false"
|
||||
:filter-node-method="filterNode"
|
||||
@node-click="handlePresetClick"
|
||||
>
|
||||
<template #default="{ node, data }">
|
||||
<span class="custom-tree-node">
|
||||
<span class="tree-node-content">
|
||||
<i v-if="data.icon" :class="data.icon" class="tree-icon"></i>
|
||||
<span class="node-label">{{ node.label }}</span>
|
||||
<span v-if="data.count" class="count-badge">{{ data.count }}</span>
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
</el-tree>
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div v-else class="empty-preset">
|
||||
<div class="empty-content">
|
||||
<el-icon size="40"><Files /></el-icon>
|
||||
<p>暂无预设过滤条件</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, watch, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
|
||||
import { Operation, DataAnalysis, Search, Files } from '@element-plus/icons-vue'
|
||||
|
||||
defineOptions({
|
||||
name: 'ScanBox'
|
||||
})
|
||||
|
||||
const props = defineProps({
|
||||
// 组件宽度
|
||||
width: {
|
||||
type: String,
|
||||
default: '300px'
|
||||
},
|
||||
|
||||
// 预设树状条件
|
||||
presetTree: {
|
||||
type: Array,
|
||||
default: () => []
|
||||
},
|
||||
|
||||
// 树形结构配置
|
||||
treeProps: {
|
||||
type: Object,
|
||||
default: () => ({
|
||||
children: 'children',
|
||||
label: 'label'
|
||||
})
|
||||
},
|
||||
|
||||
// 可用字段配置
|
||||
availableFields: {
|
||||
type: Array as any,
|
||||
default: () => []
|
||||
},
|
||||
|
||||
// 默认操作符配置
|
||||
defaultOperators: {
|
||||
type: Object,
|
||||
default: () => ({
|
||||
text: [
|
||||
{ value: 'eq', label: '等于' },
|
||||
{ value: 'ne', label: '不等于' },
|
||||
{ value: 'contains', label: '包含' },
|
||||
{ value: 'startswith', label: '开头为' },
|
||||
{ value: 'endswith', label: '结尾为' }
|
||||
],
|
||||
number: [
|
||||
{ value: 'eq', label: '等于' },
|
||||
{ value: 'ne', label: '不等于' },
|
||||
{ value: 'gt', label: '大于' },
|
||||
{ value: 'lt', label: '小于' },
|
||||
{ value: 'ge', label: '大于等于' },
|
||||
{ value: 'le', label: '小于等于' },
|
||||
{ value: 'between', label: '包含' }
|
||||
],
|
||||
date: [
|
||||
{ value: 'eq', label: '等于' },
|
||||
{ value: 'ne', label: '不等于' },
|
||||
{ value: 'gt', label: '晚于' },
|
||||
{ value: 'lt', label: '早于' }
|
||||
]
|
||||
})
|
||||
},
|
||||
|
||||
// 初始条件
|
||||
initialConditions: {
|
||||
type: Object,
|
||||
default: null
|
||||
},
|
||||
|
||||
// 是否自动提交
|
||||
autoSubmit: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
}
|
||||
})
|
||||
|
||||
const emit = defineEmits(['condition-change', 'reset', 'condition-clear'])
|
||||
|
||||
// Data
|
||||
const activeTab = ref('custom')
|
||||
const customConditions = reactive<any>({})
|
||||
const presetSearchText = ref('')
|
||||
const filteredPresetTree = ref<any[]>([])
|
||||
const activeCondition = ref<any>(null)
|
||||
const submitting = ref(false)
|
||||
const hasScroll = ref(false)
|
||||
const filterScroll = ref<HTMLElement | null>(null)
|
||||
const presetTreeRef = ref<any>(null)
|
||||
let debounceTimer: any = null
|
||||
|
||||
// Watchers
|
||||
watch(() => props.initialConditions, (val) => {
|
||||
if (val) {
|
||||
loadInitialConditions(val)
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
watch(() => props.presetTree, (val) => {
|
||||
if (val && Array.isArray(val)) {
|
||||
filteredPresetTree.value = JSON.parse(JSON.stringify(val))
|
||||
} else {
|
||||
filteredPresetTree.value = []
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
watch(() => props.availableFields, (fields) => {
|
||||
initCustomConditions(fields)
|
||||
}, { immediate: true })
|
||||
|
||||
// Computed
|
||||
const fieldValues = computed(() => {
|
||||
return props.availableFields.map((field: any) => field.value)
|
||||
})
|
||||
|
||||
// Lifecycle
|
||||
onMounted(() => {
|
||||
initCustomConditions(props.availableFields)
|
||||
if (filterScroll.value) {
|
||||
filterScroll.value.addEventListener('scroll', handleScroll)
|
||||
}
|
||||
checkScroll()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (filterScroll.value) {
|
||||
filterScroll.value.removeEventListener('scroll', handleScroll)
|
||||
}
|
||||
})
|
||||
|
||||
// Methods
|
||||
function getTextPlaceholder(field: any) {
|
||||
const operator = customConditions[field.value].operator
|
||||
const basePlaceholder = field.placeholder || `请输入${field.label}`
|
||||
|
||||
if (operator === 'contains') {
|
||||
return `${basePlaceholder}(多个值用逗号分隔)`
|
||||
}
|
||||
|
||||
return basePlaceholder
|
||||
}
|
||||
|
||||
function handleTextOperatorChange(field: any) {
|
||||
const operator = customConditions[field.value].operator
|
||||
if (operator !== 'contains') {
|
||||
const currentValue = customConditions[field.value].value
|
||||
if (Array.isArray(currentValue)) {
|
||||
customConditions[field.value].value = currentValue.join(', ')
|
||||
}
|
||||
}
|
||||
handleCustomChange()
|
||||
}
|
||||
|
||||
function normalizeTextValue(field: any) {
|
||||
const operator = customConditions[field.value].operator
|
||||
const value = customConditions[field.value].value
|
||||
|
||||
if (operator !== 'contains' || !value) {
|
||||
return
|
||||
}
|
||||
|
||||
let normalizedValue = value
|
||||
normalizedValue = normalizedValue
|
||||
.replace(/[,;;、]/g, ',')
|
||||
.replace(/\s+/g, '')
|
||||
.replace(/,+/g, ',')
|
||||
.replace(/^,|,$/g, '')
|
||||
|
||||
if (normalizedValue !== value) {
|
||||
customConditions[field.value].value = normalizedValue
|
||||
handleCustomChange()
|
||||
}
|
||||
}
|
||||
|
||||
function initCustomConditions(fields: any[]) {
|
||||
fields.forEach(field => {
|
||||
let defaultValue = undefined
|
||||
let defaultOperator = ''
|
||||
|
||||
switch (field.type) {
|
||||
case 'select':
|
||||
case 'multiple':
|
||||
defaultValue = field.multiple ? [] : undefined
|
||||
break
|
||||
case 'boolean':
|
||||
defaultValue = null
|
||||
break
|
||||
case 'daterange':
|
||||
defaultValue = []
|
||||
break
|
||||
default:
|
||||
defaultValue = undefined
|
||||
}
|
||||
|
||||
if (field.operators && Array.isArray(field.operators) && field.operators.length > 0) {
|
||||
defaultOperator = field.defaultOperator || field.operators[0]
|
||||
} else {
|
||||
const defaultOps = props.defaultOperators[field.type as keyof typeof props.defaultOperators]
|
||||
if (defaultOps && defaultOps.length > 0) {
|
||||
defaultOperator = field.defaultOperator || defaultOps[0].value || ''
|
||||
}
|
||||
}
|
||||
|
||||
// Assign to reactive object
|
||||
// Using Object.assign or direct assignment for existing properties to maintain reactivity if needed,
|
||||
// but here we are initializing/resetting so direct assignment is fine, but we need to ensure reactivity.
|
||||
// Since customConditions is reactive({}), adding new properties works.
|
||||
if (!customConditions[field.value]) {
|
||||
customConditions[field.value] = { value: defaultValue, operator: defaultOperator }
|
||||
} else {
|
||||
customConditions[field.value].value = defaultValue
|
||||
customConditions[field.value].operator = defaultOperator
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function loadInitialConditions(conditions: any) {
|
||||
if (conditions.type === 'preset') {
|
||||
activeCondition.value = conditions
|
||||
activeTab.value = 'preset'
|
||||
} else if (conditions.type === 'custom') {
|
||||
activeCondition.value = conditions
|
||||
activeTab.value = 'custom'
|
||||
|
||||
if (conditions.conditions) {
|
||||
Object.keys(conditions.conditions).forEach(field => {
|
||||
if (customConditions[field]) {
|
||||
Object.assign(customConditions[field], conditions.conditions[field])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function checkScroll() {
|
||||
if (!filterScroll.value) return
|
||||
hasScroll.value = filterScroll.value.scrollHeight > filterScroll.value.clientHeight
|
||||
}
|
||||
|
||||
function handleScroll() {
|
||||
checkScroll()
|
||||
}
|
||||
|
||||
function handleTabChange(pane: any) {
|
||||
// Element Plus tab-click returns pane context. pane.paneName is the name.
|
||||
// Vue 2 was tab component instance.
|
||||
if (pane.paneName === 'custom') {
|
||||
nextTick(() => {
|
||||
checkScroll()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function getOperators(field: any) {
|
||||
if (field.operators && field.operators.length > 0) {
|
||||
const operatorDefinitions = props.defaultOperators[field.type as keyof typeof props.defaultOperators] || []
|
||||
return operatorDefinitions.filter((op: any) => field.operators.includes(op.value))
|
||||
}
|
||||
return props.defaultOperators[field.type as keyof typeof props.defaultOperators] || (props.defaultOperators as any).text || []
|
||||
}
|
||||
|
||||
function handlePresetClick(data: any, node: any) {
|
||||
if (!node.isLeaf) return
|
||||
activeCondition.value = data.value
|
||||
emit('condition-change', activeCondition.value)
|
||||
}
|
||||
|
||||
function handleCustomChange() {
|
||||
if (props.autoSubmit) {
|
||||
clearTimeout(debounceTimer)
|
||||
debounceTimer = setTimeout(() => {
|
||||
buildAndEmitCustomCondition()
|
||||
}, 300)
|
||||
}
|
||||
}
|
||||
|
||||
function buildAndEmitCustomCondition() {
|
||||
const conditions: any = {}
|
||||
let hasCondition = false
|
||||
|
||||
props.availableFields.forEach((field: any) => {
|
||||
const condition = customConditions[field.value]
|
||||
let conditionValue = condition.value
|
||||
|
||||
if (field.type === 'text' && condition.operator === 'contains' && conditionValue) {
|
||||
const values = conditionValue.split(',').filter((v: string) => v.trim())
|
||||
if (values.length > 0) {
|
||||
conditionValue = values
|
||||
}
|
||||
}
|
||||
|
||||
if (conditionValue !== undefined &&
|
||||
conditionValue !== null &&
|
||||
conditionValue !== '' &&
|
||||
!(Array.isArray(conditionValue) && conditionValue.length === 0)) {
|
||||
|
||||
conditions[field.value] = {
|
||||
value: conditionValue,
|
||||
operator: condition.operator,
|
||||
field: field.value,
|
||||
type: field.type,
|
||||
isMultiple: Array.isArray(conditionValue)
|
||||
}
|
||||
hasCondition = true
|
||||
}
|
||||
})
|
||||
|
||||
if (hasCondition) {
|
||||
activeCondition.value = conditions
|
||||
emit('condition-change', activeCondition.value)
|
||||
} else if (activeCondition.value && activeCondition.value.type === 'custom') {
|
||||
clearActiveCondition()
|
||||
}
|
||||
}
|
||||
|
||||
function filterPresetTree(val: string) {
|
||||
if (presetTreeRef.value) {
|
||||
presetTreeRef.value.filter(val)
|
||||
}
|
||||
}
|
||||
|
||||
function filterNode(value: string, data: any) {
|
||||
if (!value) return true
|
||||
return data.label && data.label.toLowerCase().includes(value.toLowerCase())
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
initCustomConditions(props.availableFields)
|
||||
activeCondition.value = null
|
||||
presetSearchText.value = ''
|
||||
filterPresetTree('')
|
||||
emit('reset')
|
||||
if (props.autoSubmit) {
|
||||
buildAndEmitCustomCondition()
|
||||
}
|
||||
}
|
||||
|
||||
function handleSubmit() {
|
||||
submitting.value = true
|
||||
buildAndEmitCustomCondition()
|
||||
setTimeout(() => {
|
||||
submitting.value = false
|
||||
}, 300)
|
||||
}
|
||||
|
||||
function clearActiveCondition() {
|
||||
activeCondition.value = null
|
||||
emit('condition-clear')
|
||||
}
|
||||
|
||||
// 对外暴露的方法,供父组件调用
|
||||
function getConditions() {
|
||||
if (!activeCondition.value) return {}
|
||||
|
||||
if (typeof activeCondition.value === 'string' || typeof activeCondition.value === 'number') {
|
||||
return { preset: activeCondition.value }
|
||||
}
|
||||
|
||||
if (activeCondition.value && (activeCondition.value as any).conditions) {
|
||||
const where: any = {}
|
||||
Object.keys((activeCondition.value as any).conditions).forEach((k) => {
|
||||
const c = (activeCondition.value as any).conditions[k]
|
||||
where[k] = c && c.value !== undefined ? c.value : c
|
||||
})
|
||||
return where
|
||||
}
|
||||
|
||||
if (typeof activeCondition.value === 'object') {
|
||||
const where: any = {}
|
||||
Object.keys(activeCondition.value).forEach((k) => {
|
||||
const c = (activeCondition.value as any)[k]
|
||||
where[k] = c && c.value !== undefined ? c.value : c
|
||||
})
|
||||
return where
|
||||
}
|
||||
|
||||
return {}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
handleReset()
|
||||
}
|
||||
|
||||
function clear() {
|
||||
clearActiveCondition()
|
||||
}
|
||||
|
||||
defineExpose({ getConditions, reset, clear })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.scan-box-container {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #fff;
|
||||
border-right: 1px solid #e8e8e8;
|
||||
box-shadow: 1px 0 2px rgba(0, 0, 0, 0.05);
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.scan-tabs {
|
||||
flex-shrink: 0;
|
||||
border-bottom: 1px solid #e8e8e8;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
.scan-tabs :deep(.el-tabs__header) {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.scan-tabs :deep(.el-tabs__nav-wrap::after) {
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
.scan-tabs :deep(.el-tabs__item) {
|
||||
height: 40px;
|
||||
line-height: 40px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.tab-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.scan-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.custom-filter,
|
||||
.preset-filter {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.filter-scroll-area {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
/* 自定义筛选样式 */
|
||||
.field-forms {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.field-form-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.field-label .el-tag {
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.field-control {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
/* 预设筛选样式 */
|
||||
.preset-search {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.preset-tree {
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.custom-tree-node {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 13px;
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.tree-node-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.tree-icon {
|
||||
color: #409eff;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.node-label {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.count-badge {
|
||||
background: #f0f0f0;
|
||||
padding: 2px 6px;
|
||||
border-radius: 10px;
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.empty-preset {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.empty-content {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-content i {
|
||||
font-size: 40px;
|
||||
margin-bottom: 12px;
|
||||
color: #e0e0e0;
|
||||
}
|
||||
|
||||
.empty-content p {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* 底部固定操作栏 */
|
||||
.fixed-bottom-actions {
|
||||
flex-shrink: 0;
|
||||
padding: 12px 16px;
|
||||
background: #fff;
|
||||
border-top: 1px solid #e8e8e8;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
|
||||
z-index: 10;
|
||||
transition: all 0.3s;
|
||||
}
|
||||
|
||||
.fixed-bottom-actions.has-scroll {
|
||||
box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.actions-content {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.actions-content button {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.reset-btn {
|
||||
color: #666;
|
||||
}
|
||||
</style>
|
||||
54
src/components/SvgIcon/index.vue
Normal file
@ -0,0 +1,54 @@
|
||||
<template>
|
||||
<div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-bind="$attrs" />
|
||||
<svg v-else :class="svgClass" aria-hidden="true" v-bind="$attrs">
|
||||
<use :xlink:href="iconName" />
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { isExternal as isExternalFn } from '@/utils/validate'
|
||||
|
||||
const props = defineProps({
|
||||
iconClass: {
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
className: {
|
||||
type: String,
|
||||
default: ''
|
||||
}
|
||||
})
|
||||
|
||||
const isExternal = computed(() => isExternalFn(props.iconClass))
|
||||
const iconName = computed(() => `#icon-${props.iconClass}`)
|
||||
const svgClass = computed(() => {
|
||||
if (props.className) {
|
||||
return 'svg-icon ' + props.className
|
||||
} else {
|
||||
return 'svg-icon'
|
||||
}
|
||||
})
|
||||
const styleExternalIcon = computed(() => {
|
||||
return {
|
||||
mask: `url(${props.iconClass}) no-repeat 50% 50%`,
|
||||
'-webkit-mask': `url(${props.iconClass}) no-repeat 50% 50%`
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.svg-icon {
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
vertical-align: -0.15em;
|
||||
fill: currentColor;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.svg-external-icon {
|
||||
background-color: currentColor;
|
||||
mask-size: cover!important;
|
||||
display: inline-block;
|
||||
}
|
||||
</style>
|
||||
696
src/components/UpperTable/index.vue
Normal file
@ -0,0 +1,696 @@
|
||||
<template>
|
||||
<div class="upper-table-container" :class="tableSize">
|
||||
<!-- 表格区域 -->
|
||||
<div class="table-container" ref="tableContainer">
|
||||
<el-table
|
||||
v-loading="loading"
|
||||
ref="tableRef"
|
||||
:data="data"
|
||||
:highlight-current-row="highlightCurrentRow"
|
||||
:row-key="rowKey"
|
||||
:current-row-key="currentRowKey"
|
||||
@current-change="handleCurrentChange"
|
||||
@row-click="handleRowClick"
|
||||
@sort-change="handleSortChange"
|
||||
style="width: 100%"
|
||||
:size="tableSize"
|
||||
:border="border"
|
||||
:stripe="stripe"
|
||||
:show-header="showHeader"
|
||||
:empty-text="emptyText"
|
||||
:fit="fit"
|
||||
:tooltip-effect="tooltipEffect"
|
||||
height="100%"
|
||||
>
|
||||
<!-- 自定义选择列 -->
|
||||
<el-table-column v-if="showSelection" :width="selectionColumnWidth" fixed="left">
|
||||
<!-- 表头 -->
|
||||
<template #header>
|
||||
<div class="custom-selection-header" @click.stop="toggleAllSelection">
|
||||
<el-checkbox
|
||||
v-model="isAllSelectedInView"
|
||||
:indeterminate="isIndeterminate"
|
||||
@click.stop="toggleAllSelection"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 单元格 -->
|
||||
<template #default="scope">
|
||||
<div class="custom-selection-cell" @click.stop="toggleRowSelection(scope.row)">
|
||||
<el-checkbox
|
||||
:model-value="isRowSelected(scope.row)"
|
||||
:key="`checkbox-${getRowKey(scope.row)}-${checkboxUpdateKey}`"
|
||||
@click.stop="toggleRowSelection(scope.row)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<!-- 动态列 -->
|
||||
<template v-for="column in columns" :key="column.prop">
|
||||
<el-table-column
|
||||
v-if="column.prop"
|
||||
:prop="column.prop"
|
||||
:label="column.label"
|
||||
:width="column.width"
|
||||
:min-width="column.minWidth"
|
||||
:fixed="column.fixed"
|
||||
:sortable="column.sortable"
|
||||
:sort-by="column.sortBy"
|
||||
:sort-orders="column.sortOrders"
|
||||
:resizable="column.resizable"
|
||||
:show-overflow-tooltip="column.showOverflowTooltip !== false"
|
||||
:align="column.align || 'left'"
|
||||
:header-align="column.headerAlign || column.align || 'left'"
|
||||
:class-name="column.className"
|
||||
:label-class-name="column.labelClassName"
|
||||
:filters="column.filters"
|
||||
:filter-method="column.filterMethod"
|
||||
:filtered-value="column.filteredValue"
|
||||
:filter-multiple="column.filterMultiple"
|
||||
:filter-placement="column.filterPlacement"
|
||||
>
|
||||
<template #default="scope">
|
||||
<slot :name="`column-${column.prop}`" :row="scope.row" :index="scope.$index">
|
||||
<template v-if="column.formatter">
|
||||
<span v-html="column.formatter(scope.row, scope.column, scope.row[scope.column.property], scope.$index)"></span>
|
||||
</template>
|
||||
<template v-else-if="column.template">
|
||||
<component
|
||||
:is="column.template"
|
||||
:row="scope.row"
|
||||
:column="scope.column"
|
||||
:index="scope.$index"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="column.imgs">
|
||||
<el-image
|
||||
style="height: 23px; overflow: unset; margin: 0 3px"
|
||||
v-for="(img, idx) in column.imgs(scope.row, scope.column, scope.$index)"
|
||||
:key="idx"
|
||||
:src="img"
|
||||
:preview-src-list="column.imgs(scope.row, scope.column, scope.$index)"
|
||||
></el-image>
|
||||
</template>
|
||||
<span v-else>{{ scope.row[column.prop] }}</span>
|
||||
</slot>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</template>
|
||||
|
||||
<!-- 空状态插槽 -->
|
||||
<template #empty>
|
||||
<slot name="empty">
|
||||
<div class="empty-table">
|
||||
<el-icon size="48" color="#c0c4cc"><Box /></el-icon>
|
||||
<p>{{ emptyText }}</p>
|
||||
</div>
|
||||
</slot>
|
||||
</template>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<!-- 分页区域 -->
|
||||
<div class="pagination-container" v-if="showPagination">
|
||||
<div class="pagination-info">
|
||||
已选 {{ selectedCount }} 条,查询用时 {{ (queryTime / 1000).toFixed(2) }} 秒
|
||||
</div>
|
||||
<el-pagination
|
||||
:current-page="pagination.currentPage"
|
||||
:page-sizes="pageSizes"
|
||||
:page-size="pagination.pageSize"
|
||||
:total="total"
|
||||
:layout="paginationLayout"
|
||||
:background="paginationBackground"
|
||||
:small="tableSize === 'small'"
|
||||
@size-change="handlePageSizeChange"
|
||||
@current-change="handlePageChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
|
||||
import { Box } from '@element-plus/icons-vue'
|
||||
|
||||
defineOptions({
|
||||
name: 'UpperTable'
|
||||
})
|
||||
|
||||
const props = defineProps({
|
||||
loading: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
// 表格数据
|
||||
data: {
|
||||
type: Array as any,
|
||||
default: () => [],
|
||||
},
|
||||
// 表格列配置
|
||||
columns: {
|
||||
type: Array as any,
|
||||
default: () => [],
|
||||
},
|
||||
// 表格尺寸
|
||||
tableSize: {
|
||||
type: String,
|
||||
default: 'small',
|
||||
validator: (value: string) => ['large', 'default', 'small'].includes(value),
|
||||
},
|
||||
// 高亮当前行
|
||||
highlightCurrentRow: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
// 行唯一键
|
||||
rowKey: {
|
||||
type: [String, Function],
|
||||
default: 'id',
|
||||
},
|
||||
// 当前选中行的key
|
||||
currentRowKey: {
|
||||
type: [String, Number],
|
||||
default: '',
|
||||
},
|
||||
// 显示边框
|
||||
border: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
// 显示斑马纹
|
||||
stripe: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
// 显示表头
|
||||
showHeader: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
// 空数据文本
|
||||
emptyText: {
|
||||
type: String,
|
||||
default: '暂无数据',
|
||||
},
|
||||
queryTime: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
// 列的宽度是否自撑开
|
||||
fit: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
// tooltip effect
|
||||
tooltipEffect: {
|
||||
type: String,
|
||||
default: 'dark',
|
||||
},
|
||||
// 显示选择列
|
||||
showSelection: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
// 是否可勾选函数
|
||||
selectable: {
|
||||
type: Function,
|
||||
default: () => true,
|
||||
},
|
||||
// 外部传入的默认选中数据
|
||||
defaultSelected: {
|
||||
type: Array as any,
|
||||
default: () => [],
|
||||
},
|
||||
// 是否自动同步外部选中状态到表格
|
||||
autoSyncSelection: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
// 选择列宽度
|
||||
selectionColumnWidth: {
|
||||
type: [String, Number],
|
||||
default: 55,
|
||||
},
|
||||
// 选择列是否固定
|
||||
selectionColumnFixed: {
|
||||
type: [String, Boolean],
|
||||
default: true,
|
||||
},
|
||||
// 分页配置
|
||||
pagination: {
|
||||
type: Object,
|
||||
default: () => ({
|
||||
currentPage: 1,
|
||||
pageSize: 20,
|
||||
total: 0,
|
||||
}),
|
||||
},
|
||||
// 是否显示分页
|
||||
showPagination: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
// 分页每页显示个数选择器的选项设置
|
||||
pageSizes: {
|
||||
type: Array as any,
|
||||
default: () => [10, 20, 50, 100, 200, 500],
|
||||
},
|
||||
// 分页布局
|
||||
paginationLayout: {
|
||||
type: String,
|
||||
default: 'total, sizes, prev, pager, next, jumper',
|
||||
},
|
||||
// 分页背景色
|
||||
paginationBackground: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits([
|
||||
'current-change',
|
||||
'selection-change',
|
||||
'row-click',
|
||||
'sort-change',
|
||||
'page-size-change',
|
||||
'page-change',
|
||||
'refresh',
|
||||
'select-all-change',
|
||||
'row-selection-change',
|
||||
])
|
||||
|
||||
// Refs
|
||||
const tableRef = ref<any>(null)
|
||||
const scrollContainer = ref<HTMLElement | null>(null)
|
||||
|
||||
// State
|
||||
// const visibleData = ref<any[]>([]) // Removed
|
||||
// const rowHeight = ref(41) // Removed
|
||||
// const bufferSize = ref(8) // Removed
|
||||
// const offset = ref(0) // Removed
|
||||
// const containerHeight = ref(0) // Removed
|
||||
const selectedRows = ref<any[]>([])
|
||||
const selectedRowKeys = ref<Set<any>>(new Set())
|
||||
// const rowKeyMap = ref<Map<any, any>>(new Map()) // Removed
|
||||
// const lastScrollTop = ref(0) // Removed
|
||||
// let scrollTimer: any = null // Removed
|
||||
const checkboxUpdateKey = ref<number | null>(null)
|
||||
|
||||
// Computed
|
||||
const total = computed(() => {
|
||||
return props.pagination.total || props.data.length
|
||||
})
|
||||
|
||||
const selectableRows = computed(() => {
|
||||
return props.data.filter((row: any, index: number) => props.selectable(row, index))
|
||||
})
|
||||
|
||||
const isAllSelected = computed(() => {
|
||||
if (selectableRows.value.length === 0) return false
|
||||
return selectableRows.value.every((row: any) =>
|
||||
selectedRowKeys.value.has(getRowKey(row))
|
||||
)
|
||||
})
|
||||
|
||||
const isAllSelectedInView = computed({
|
||||
get() {
|
||||
return props.data.length > 0 && props.data.length === selectedRows.value.length
|
||||
},
|
||||
set(val) {
|
||||
toggleAllSelection()
|
||||
}
|
||||
})
|
||||
|
||||
const isIndeterminate = computed(() => {
|
||||
return props.data.length > selectedRows.value.length && selectedRows.value.length > 0
|
||||
})
|
||||
|
||||
const selectedCount = computed(() => {
|
||||
return selectedRows.value.length
|
||||
})
|
||||
|
||||
// Watchers
|
||||
watch(() => props.data, () => {
|
||||
clearSelection()
|
||||
}, { deep: true })
|
||||
|
||||
watch(() => props.defaultSelected, (newVal) => {
|
||||
if (props.autoSyncSelection) {
|
||||
setSelectionFromExternal(newVal)
|
||||
}
|
||||
}, { deep: true })
|
||||
|
||||
watch(selectedRows, (newVal) => {
|
||||
emit('selection-change', [...newVal])
|
||||
}, { deep: true })
|
||||
|
||||
// Lifecycle
|
||||
onMounted(() => {
|
||||
if (props.defaultSelected.length > 0) {
|
||||
setSelectionFromExternal(props.defaultSelected)
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
})
|
||||
|
||||
// Methods
|
||||
function getRowKey(row: any) {
|
||||
if (typeof props.rowKey === 'function') {
|
||||
return props.rowKey(row)
|
||||
}
|
||||
return row[props.rowKey]
|
||||
}
|
||||
|
||||
function isRowSelected(row: any) {
|
||||
const rowKey = getRowKey(row)
|
||||
return selectedRowKeys.value.has(rowKey)
|
||||
}
|
||||
|
||||
function toggleRowSelection(row: any, selected: boolean | null = null) {
|
||||
const rowKey = getRowKey(row)
|
||||
const currentlySelected = selectedRowKeys.value.has(rowKey)
|
||||
const shouldSelect = selected !== null ? selected : !currentlySelected
|
||||
|
||||
if (shouldSelect && !currentlySelected) {
|
||||
selectedRowKeys.value.add(rowKey)
|
||||
selectedRows.value.push(row)
|
||||
|
||||
emit('row-selection-change', {
|
||||
row,
|
||||
rowKey,
|
||||
selected: true,
|
||||
selectedRows: [...selectedRows.value],
|
||||
selectedKeys: [...selectedRowKeys.value]
|
||||
})
|
||||
} else if (!shouldSelect && currentlySelected) {
|
||||
selectedRowKeys.value.delete(rowKey)
|
||||
const index = selectedRows.value.findIndex((r: any) => getRowKey(r) === rowKey)
|
||||
if (index !== -1) {
|
||||
selectedRows.value.splice(index, 1)
|
||||
}
|
||||
|
||||
emit('row-selection-change', {
|
||||
row,
|
||||
rowKey,
|
||||
selected: false,
|
||||
selectedRows: [...selectedRows.value],
|
||||
selectedKeys: [...selectedRowKeys.value]
|
||||
})
|
||||
}
|
||||
|
||||
emit('select-all-change', {
|
||||
isSelectAll: isAllSelected.value,
|
||||
isAllSelectedInView: isAllSelectedInView.value,
|
||||
selectedRows: [...selectedRows.value],
|
||||
selectedKeys: [...selectedRowKeys.value],
|
||||
totalSelectableRows: selectableRows.value.length
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
checkboxUpdateKey.value = Date.now()
|
||||
}, 10)
|
||||
}
|
||||
|
||||
function toggleAllSelection() {
|
||||
if (props.data.length === selectedRows.value.length) {
|
||||
clearSelection()
|
||||
} else {
|
||||
const allSelectableRows = selectableRows.value
|
||||
selectedRows.value = [...allSelectableRows]
|
||||
selectedRowKeys.value.clear()
|
||||
allSelectableRows.forEach((row: any) => {
|
||||
selectedRowKeys.value.add(getRowKey(row))
|
||||
})
|
||||
|
||||
emit('select-all-change', {
|
||||
isSelectAll: true,
|
||||
isAllSelectedInView: isAllSelectedInView.value,
|
||||
selectedRows: [...selectedRows.value],
|
||||
selectedKeys: [...selectedRowKeys.value],
|
||||
totalSelectableRows: allSelectableRows.length
|
||||
})
|
||||
}
|
||||
setTimeout(() => {
|
||||
checkboxUpdateKey.value = Date.now()
|
||||
}, 10)
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
selectedRows.value = []
|
||||
selectedRowKeys.value.clear()
|
||||
|
||||
emit('selection-change', [])
|
||||
emit('select-all-change', {
|
||||
isSelectAll: false,
|
||||
isAllSelectedInView: false,
|
||||
selectedRows: [],
|
||||
selectedKeys: [],
|
||||
totalSelectableRows: selectableRows.value.length
|
||||
})
|
||||
}
|
||||
|
||||
function getSelection() {
|
||||
return [...selectedRows.value]
|
||||
}
|
||||
|
||||
function getSelectionKeys() {
|
||||
return [...selectedRowKeys.value]
|
||||
}
|
||||
|
||||
function isSelected(row: any) {
|
||||
const rowKey = getRowKey(row)
|
||||
return selectedRowKeys.value.has(rowKey)
|
||||
}
|
||||
|
||||
function setSelectionFromExternal(rows: any[]) {
|
||||
// Logic to sync external selection
|
||||
// This was missing in the original code snippet provided in Read tool for methods section
|
||||
// Assuming it sets selectedRows and selectedRowKeys
|
||||
selectedRows.value = [...rows]
|
||||
selectedRowKeys.value.clear()
|
||||
rows.forEach(row => {
|
||||
selectedRowKeys.value.add(getRowKey(row))
|
||||
})
|
||||
}
|
||||
|
||||
function handleCurrentChange(currentRow: any, oldCurrentRow: any) {
|
||||
emit('current-change', currentRow, oldCurrentRow)
|
||||
}
|
||||
|
||||
function handleRowClick(row: any, column: any, event: any) {
|
||||
const target = event.target
|
||||
const isCheckbox = target.classList.contains('el-checkbox') ||
|
||||
target.closest('.el-checkbox') ||
|
||||
target.classList.contains('custom-selection-cell') ||
|
||||
target.closest('.custom-selection-cell')
|
||||
|
||||
if (!isCheckbox) {
|
||||
emit('row-click', row, column, event)
|
||||
}
|
||||
}
|
||||
|
||||
function handleSortChange({ column, prop, order }: any) {
|
||||
emit('sort-change', { column, prop, order })
|
||||
}
|
||||
|
||||
function handlePageSizeChange(size: number) {
|
||||
emit('page-size-change', size)
|
||||
}
|
||||
|
||||
function handlePageChange(page: number) {
|
||||
emit('page-change', page)
|
||||
}
|
||||
|
||||
function handleRefresh() {
|
||||
emit('refresh')
|
||||
}
|
||||
|
||||
function getTableRef() {
|
||||
return tableRef.value
|
||||
}
|
||||
|
||||
function setCurrentRow(row: any) {
|
||||
if (tableRef.value) {
|
||||
tableRef.value.setCurrentRow(row)
|
||||
}
|
||||
}
|
||||
|
||||
function clearSort() {
|
||||
if (tableRef.value) {
|
||||
tableRef.value.clearSort()
|
||||
}
|
||||
}
|
||||
|
||||
function clearFilter(columnKey: string) {
|
||||
if (tableRef.value) {
|
||||
tableRef.value.clearFilter(columnKey)
|
||||
}
|
||||
}
|
||||
|
||||
function getSummaries(param: { columns: any, data: any }) {
|
||||
const { columns, data } = param
|
||||
const sums: string[] = []
|
||||
columns.forEach((column: any, index: number) => {
|
||||
if (index === 0) {
|
||||
sums[index] = '总计'
|
||||
return
|
||||
}
|
||||
const values = data.map((item: any) => Number(item[column.property]))
|
||||
if (!values.every((value: number) => isNaN(value))) {
|
||||
sums[index] = values.reduce((prev: number, curr: number) => {
|
||||
const value = Number(curr)
|
||||
if (!isNaN(value)) {
|
||||
return prev + curr
|
||||
} else {
|
||||
return prev
|
||||
}
|
||||
}, 0)
|
||||
sums[index] += ' 元'
|
||||
} else {
|
||||
sums[index] = 'N/A'
|
||||
}
|
||||
})
|
||||
|
||||
return sums
|
||||
}
|
||||
|
||||
// Expose methods
|
||||
defineExpose({
|
||||
getSelection,
|
||||
getSelectionKeys,
|
||||
toggleRowSelection,
|
||||
toggleAllSelection,
|
||||
clearSelection,
|
||||
getTableRef,
|
||||
setCurrentRow,
|
||||
clearSort,
|
||||
clearFilter,
|
||||
getSummaries
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 基础样式 */
|
||||
.upper-table-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #fff;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
flex-shrink: 0; /* Prevent vertical shrinking which might clip pagination */
|
||||
}
|
||||
|
||||
.table-container {
|
||||
height: 395px;
|
||||
overflow: auto;
|
||||
z-index: 9;
|
||||
}
|
||||
|
||||
.pagination-container {
|
||||
padding: 16px 20px;
|
||||
border-top: 1px solid #e8e8e8;
|
||||
background: #fff;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-wrap: wrap; /* Allow wrapping if needed */
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.pagination-info {
|
||||
font-size: 14px;
|
||||
color: #606266;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Ensure pagination elements don't disappear on small screens/containers */
|
||||
.pagination-container :deep(.el-pagination__sizes),
|
||||
.pagination-container :deep(.el-pagination__jump),
|
||||
.pagination-container :deep(.el-pagination__total) {
|
||||
display: inline-flex !important;
|
||||
}
|
||||
|
||||
.pagination-container :deep(.el-pagination) {
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.empty-table {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 200px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.empty-table p {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* 自定义选择列样式 */
|
||||
.custom-selection-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.custom-selection-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* 防止复选框点击事件冒泡 */
|
||||
.custom-selection-header :deep(.el-checkbox),
|
||||
.custom-selection-cell :deep(.el-checkbox) {
|
||||
margin: 0;
|
||||
pointer-events: none; /* 让父元素处理点击事件 */
|
||||
}
|
||||
|
||||
/* 表格尺寸样式 */
|
||||
.upper-table-container.small :deep(.el-table) {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.upper-table-container.small :deep(.el-table td),
|
||||
.upper-table-container.small :deep(.el-table th) {
|
||||
padding: 6px 0;
|
||||
}
|
||||
|
||||
.upper-table-container.large :deep(.el-table) {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.upper-table-container.large :deep(.el-table td),
|
||||
.upper-table-container.large :deep(.el-table th) {
|
||||
padding: 12px 0;
|
||||
}
|
||||
|
||||
/* 响应式调整 */
|
||||
@media (max-width: 768px) {
|
||||
.table-header {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.header-right {
|
||||
width: 100%;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
9
src/icons/index.js
Normal file
@ -0,0 +1,9 @@
|
||||
import Vue from 'vue'
|
||||
import SvgIcon from '@/components/SvgIcon'// svg component
|
||||
|
||||
// register globally
|
||||
Vue.component('svg-icon', SvgIcon)
|
||||
|
||||
const req = require.context('./svg', false, /\.svg$/)
|
||||
const requireAll = requireContext => requireContext.keys().map(requireContext)
|
||||
requireAll(req)
|
||||
1
src/icons/svg/dashboard.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="128" height="100" xmlns="http://www.w3.org/2000/svg"><path d="M27.429 63.638c0-2.508-.893-4.65-2.679-6.424-1.786-1.775-3.94-2.662-6.464-2.662-2.524 0-4.679.887-6.465 2.662-1.785 1.774-2.678 3.916-2.678 6.424 0 2.508.893 4.65 2.678 6.424 1.786 1.775 3.94 2.662 6.465 2.662 2.524 0 4.678-.887 6.464-2.662 1.786-1.775 2.679-3.916 2.679-6.424zm13.714-31.801c0-2.508-.893-4.65-2.679-6.424-1.785-1.775-3.94-2.662-6.464-2.662-2.524 0-4.679.887-6.464 2.662-1.786 1.774-2.679 3.916-2.679 6.424 0 2.508.893 4.65 2.679 6.424 1.785 1.774 3.94 2.662 6.464 2.662 2.524 0 4.679-.888 6.464-2.662 1.786-1.775 2.679-3.916 2.679-6.424zM71.714 65.98l7.215-27.116c.285-1.23.107-2.378-.536-3.443-.643-1.064-1.56-1.762-2.75-2.094-1.19-.33-2.333-.177-3.429.462-1.095.639-1.81 1.573-2.143 2.804l-7.214 27.116c-2.857.237-5.405 1.266-7.643 3.088-2.238 1.822-3.738 4.152-4.5 6.992-.952 3.644-.476 7.098 1.429 10.364 1.905 3.265 4.69 5.37 8.357 6.317 3.667.947 7.143.474 10.429-1.42 3.285-1.892 5.404-4.66 6.357-8.305.762-2.84.619-5.607-.429-8.305-1.047-2.697-2.762-4.85-5.143-6.46zm47.143-2.342c0-2.508-.893-4.65-2.678-6.424-1.786-1.775-3.94-2.662-6.465-2.662-2.524 0-4.678.887-6.464 2.662-1.786 1.774-2.679 3.916-2.679 6.424 0 2.508.893 4.65 2.679 6.424 1.786 1.775 3.94 2.662 6.464 2.662 2.524 0 4.679-.887 6.465-2.662 1.785-1.775 2.678-3.916 2.678-6.424zm-45.714-45.43c0-2.509-.893-4.65-2.679-6.425C68.68 10.01 66.524 9.122 64 9.122c-2.524 0-4.679.887-6.464 2.661-1.786 1.775-2.679 3.916-2.679 6.425 0 2.508.893 4.65 2.679 6.424 1.785 1.774 3.94 2.662 6.464 2.662 2.524 0 4.679-.888 6.464-2.662 1.786-1.775 2.679-3.916 2.679-6.424zm32 13.629c0-2.508-.893-4.65-2.679-6.424-1.785-1.775-3.94-2.662-6.464-2.662-2.524 0-4.679.887-6.464 2.662-1.786 1.774-2.679 3.916-2.679 6.424 0 2.508.893 4.65 2.679 6.424 1.785 1.774 3.94 2.662 6.464 2.662 2.524 0 4.679-.888 6.464-2.662 1.786-1.775 2.679-3.916 2.679-6.424zM128 63.638c0 12.351-3.357 23.78-10.071 34.286-.905 1.372-2.19 2.058-3.858 2.058H13.93c-1.667 0-2.953-.686-3.858-2.058C3.357 87.465 0 76.037 0 63.638c0-8.613 1.69-16.847 5.071-24.703C8.452 31.08 13 24.312 18.714 18.634c5.715-5.68 12.524-10.199 20.429-13.559C47.048 1.715 55.333.035 64 .035c8.667 0 16.952 1.68 24.857 5.04 7.905 3.36 14.714 7.88 20.429 13.559 5.714 5.678 10.262 12.446 13.643 20.301 3.38 7.856 5.071 16.09 5.071 24.703z"/></svg>
|
||||
|
After Width: | Height: | Size: 2.3 KiB |
1
src/icons/svg/example.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg"><path d="M96.258 57.462h31.421C124.794 27.323 100.426 2.956 70.287.07v31.422a32.856 32.856 0 0 1 25.971 25.97zm-38.796-25.97V.07C27.323 2.956 2.956 27.323.07 57.462h31.422a32.856 32.856 0 0 1 25.97-25.97zm12.825 64.766v31.421c30.46-2.885 54.507-27.253 57.713-57.712H96.579c-2.886 13.466-13.146 23.726-26.292 26.291zM31.492 70.287H.07c2.886 30.46 27.253 54.507 57.713 57.713V96.579c-13.466-2.886-23.726-13.146-26.291-26.292z"/></svg>
|
||||
|
After Width: | Height: | Size: 497 B |
1
src/icons/svg/eye-open.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg class="icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="128" height="128"><defs><style/></defs><path d="M512 128q69.675 0 135.51 21.163t115.498 54.997 93.483 74.837 73.685 82.006 51.67 74.837 32.17 54.827L1024 512q-2.347 4.992-6.315 13.483T998.87 560.17t-31.658 51.669-44.331 59.99-56.832 64.34-69.504 60.16-82.347 51.5-94.848 34.687T512 896q-69.675 0-135.51-21.163t-115.498-54.826-93.483-74.326-73.685-81.493-51.67-74.496-32.17-54.997L0 513.707q2.347-4.992 6.315-13.483t18.816-34.816 31.658-51.84 44.331-60.33 56.832-64.683 69.504-60.331 82.347-51.84 94.848-34.816T512 128.085zm0 85.333q-46.677 0-91.648 12.331t-81.152 31.83-70.656 47.146-59.648 54.485-48.853 57.686-37.675 52.821-26.325 43.99q12.33 21.674 26.325 43.52t37.675 52.351 48.853 57.003 59.648 53.845T339.2 767.02t81.152 31.488T512 810.667t91.648-12.331 81.152-31.659 70.656-46.848 59.648-54.186 48.853-57.344 37.675-52.651T927.957 512q-12.33-21.675-26.325-43.648t-37.675-52.65-48.853-57.345-59.648-54.186-70.656-46.848-81.152-31.659T512 213.334zm0 128q70.656 0 120.661 50.006T682.667 512 632.66 632.661 512 682.667 391.339 632.66 341.333 512t50.006-120.661T512 341.333zm0 85.334q-35.328 0-60.33 25.002T426.666 512t25.002 60.33T512 597.334t60.33-25.002T597.334 512t-25.002-60.33T512 426.666z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
1
src/icons/svg/eye.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="128" height="64" xmlns="http://www.w3.org/2000/svg"><path d="M127.072 7.994c1.37-2.208.914-5.152-.914-6.87-2.056-1.717-4.797-1.226-6.396.982-.229.245-25.586 32.382-55.74 32.382-29.24 0-55.74-32.382-55.968-32.627-1.6-1.963-4.57-2.208-6.397-.49C-.17 3.086-.399 6.275 1.2 8.238c.457.736 5.94 7.36 14.62 14.72L4.17 35.96c-1.828 1.963-1.6 5.152.228 6.87.457.98 1.6 1.471 2.742 1.471s2.284-.49 3.198-1.472l12.564-13.983c5.94 4.416 13.021 8.587 20.788 11.53l-4.797 17.418c-.685 2.699.686 5.397 3.198 6.133h1.37c2.057 0 3.884-1.472 4.341-3.68L52.6 42.83c3.655.736 7.538 1.227 11.422 1.227 3.883 0 7.767-.49 11.422-1.227l4.797 17.173c.457 2.208 2.513 3.68 4.34 3.68.457 0 .914 0 1.143-.246 2.513-.736 3.883-3.434 3.198-6.133l-4.797-17.172c7.767-2.944 14.848-7.114 20.788-11.53l12.336 13.738c.913.981 2.056 1.472 3.198 1.472s2.284-.49 3.198-1.472c1.828-1.963 1.828-4.906.228-6.87l-11.65-13.001c9.366-7.36 14.849-14.474 14.849-14.474z"/></svg>
|
||||
|
After Width: | Height: | Size: 944 B |
1
src/icons/svg/form.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg"><path d="M84.068 23.784c-1.02 0-1.877-.32-2.572-.96a8.588 8.588 0 0 1-1.738-2.237 11.524 11.524 0 0 1-1.042-2.621c-.232-.895-.348-1.641-.348-2.238V0h.278c.834 0 1.622.085 2.363.256.742.17 1.645.575 2.711 1.214 1.066.64 2.363 1.535 3.892 2.686 1.53 1.15 3.453 2.664 5.77 4.54 2.502 2.045 4.494 3.771 5.977 5.178 1.483 1.406 2.618 2.6 3.406 3.58.787.98 1.274 1.812 1.46 2.494.185.682.277 1.278.277 1.79v2.046H84.068zM127.3 84.01c.278.682.464 1.535.556 2.558.093 1.023-.37 2.003-1.39 2.94-.463.427-.88.832-1.25 1.215-.372.384-.696.704-.974.96a6.69 6.69 0 0 1-.973.767l-11.816-10.741a44.331 44.331 0 0 0 1.877-1.535 31.028 31.028 0 0 1 1.737-1.406c1.112-.938 2.317-1.343 3.615-1.215 1.297.128 2.363.405 3.197.83.927.427 1.923 1.173 2.989 2.239 1.065 1.065 1.876 2.195 2.432 3.388zM78.23 95.902c2.038 0 3.752-.511 5.143-1.534l-26.969 25.83H18.037c-1.761 0-3.684-.47-5.77-1.407a24.549 24.549 0 0 1-5.838-3.709 21.373 21.373 0 0 1-4.518-5.306c-1.204-2.003-1.807-4.07-1.807-6.202V16.495c0-1.79.44-3.665 1.32-5.626A18.41 18.41 0 0 1 5.04 5.562a21.798 21.798 0 0 1 5.213-3.964C12.198.533 14.237 0 16.37 0h53.24v15.984c0 1.62.278 3.367.834 5.242a16.704 16.704 0 0 0 2.572 5.179c1.159 1.577 2.665 2.898 4.518 3.964 1.853 1.066 4.078 1.598 6.673 1.598h20.295v42.325L85.458 92.45c1.02-1.364 1.529-2.856 1.529-4.476 0-2.216-.857-4.113-2.572-5.69-1.714-1.577-3.776-2.366-6.186-2.366H26.1c-2.409 0-4.448.789-6.116 2.366-1.668 1.577-2.502 3.474-2.502 5.69 0 2.217.834 4.092 2.502 5.626 1.668 1.535 3.707 2.302 6.117 2.302h52.13zM26.1 47.951c-2.41 0-4.449.789-6.117 2.366-1.668 1.577-2.502 3.473-2.502 5.69 0 2.216.834 4.092 2.502 5.626 1.668 1.534 3.707 2.302 6.117 2.302h52.13c2.409 0 4.47-.768 6.185-2.302 1.715-1.534 2.572-3.41 2.572-5.626 0-2.217-.857-4.113-2.572-5.69-1.714-1.577-3.776-2.366-6.186-2.366H26.1zm52.407 64.063l1.807-1.663 3.476-3.196a479.75 479.75 0 0 0 4.587-4.284 500.757 500.757 0 0 1 5.004-4.667c3.985-3.666 8.48-7.758 13.485-12.276l11.677 10.741-13.485 12.404-5.004 4.603-4.587 4.22a179.46 179.46 0 0 0-3.267 3.068c-.88.853-1.367 1.322-1.46 1.407-.463.341-.973.703-1.529 1.087-.556.383-1.112.703-1.668.959-.556.256-1.413.575-2.572.959a83.5 83.5 0 0 1-3.545 1.087 72.2 72.2 0 0 1-3.475.895c-1.112.256-1.946.426-2.502.511-1.112.17-1.854.043-2.224-.383-.371-.426-.464-1.151-.278-2.174.092-.511.278-1.279.556-2.302.278-1.023.602-2.067.973-3.132l1.042-3.005c.325-.938.58-1.577.765-1.918a10.157 10.157 0 0 1 2.224-2.941z"/></svg>
|
||||
|
After Width: | Height: | Size: 2.4 KiB |
1
src/icons/svg/link.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg"><path d="M115.625 127.937H.063V12.375h57.781v12.374H12.438v90.813h90.813V70.156h12.374z"/><path d="M116.426 2.821l8.753 8.753-56.734 56.734-8.753-8.745z"/><path d="M127.893 37.982h-12.375V12.375H88.706V0h39.187z"/></svg>
|
||||
|
After Width: | Height: | Size: 285 B |
1
src/icons/svg/nested.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg"><path d="M.002 9.2c0 5.044 3.58 9.133 7.998 9.133 4.417 0 7.997-4.089 7.997-9.133 0-5.043-3.58-9.132-7.997-9.132S.002 4.157.002 9.2zM31.997.066h95.981V18.33H31.997V.066zm0 45.669c0 5.044 3.58 9.132 7.998 9.132 4.417 0 7.997-4.088 7.997-9.132 0-3.263-1.524-6.278-3.998-7.91-2.475-1.63-5.524-1.63-7.998 0-2.475 1.632-4 4.647-4 7.91zM63.992 36.6h63.986v18.265H63.992V36.6zm-31.995 82.2c0 5.043 3.58 9.132 7.998 9.132 4.417 0 7.997-4.089 7.997-9.132 0-5.044-3.58-9.133-7.997-9.133s-7.998 4.089-7.998 9.133zm31.995-9.131h63.986v18.265H63.992V109.67zm0-27.404c0 5.044 3.58 9.133 7.998 9.133 4.417 0 7.997-4.089 7.997-9.133 0-3.263-1.524-6.277-3.998-7.909-2.475-1.631-5.524-1.631-7.998 0-2.475 1.632-4 4.646-4 7.91zm31.995-9.13h31.991V91.4H95.987V73.135z"/></svg>
|
||||
|
After Width: | Height: | Size: 821 B |
1
src/icons/svg/password.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg"><path d="M108.8 44.322H89.6v-5.36c0-9.04-3.308-24.163-25.6-24.163-23.145 0-25.6 16.881-25.6 24.162v5.361H19.2v-5.36C19.2 15.281 36.798 0 64 0c27.202 0 44.8 15.281 44.8 38.961v5.361zm-32 39.356c0-5.44-5.763-9.832-12.8-9.832-7.037 0-12.8 4.392-12.8 9.832 0 3.682 2.567 6.808 6.407 8.477v11.205c0 2.718 2.875 4.962 6.4 4.962 3.524 0 6.4-2.244 6.4-4.962V92.155c3.833-1.669 6.393-4.795 6.393-8.477zM128 64v49.201c0 8.158-8.645 14.799-19.2 14.799H19.2C8.651 128 0 121.359 0 113.201V64c0-8.153 8.645-14.799 19.2-14.799h89.6c10.555 0 19.2 6.646 19.2 14.799z"/></svg>
|
||||
|
After Width: | Height: | Size: 623 B |
1
src/icons/svg/table.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg"><path d="M.006.064h127.988v31.104H.006V.064zm0 38.016h38.396v41.472H.006V38.08zm0 48.384h38.396v41.472H.006V86.464zM44.802 38.08h38.396v41.472H44.802V38.08zm0 48.384h38.396v41.472H44.802V86.464zM89.598 38.08h38.396v41.472H89.598zm0 48.384h38.396v41.472H89.598z"/><path d="M.006.064h127.988v31.104H.006V.064zm0 38.016h38.396v41.472H.006V38.08zm0 48.384h38.396v41.472H.006V86.464zM44.802 38.08h38.396v41.472H44.802V38.08zm0 48.384h38.396v41.472H44.802V86.464zM89.598 38.08h38.396v41.472H89.598zm0 48.384h38.396v41.472H89.598z"/></svg>
|
||||
|
After Width: | Height: | Size: 597 B |
1
src/icons/svg/tree.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg"><path d="M126.713 90.023c.858.985 1.287 2.134 1.287 3.447v29.553c0 1.423-.429 2.6-1.287 3.53-.858.93-1.907 1.395-3.146 1.395H97.824c-1.145 0-2.146-.465-3.004-1.395-.858-.93-1.287-2.107-1.287-3.53V93.47c0-.875.19-1.696.572-2.462.382-.766.906-1.368 1.573-1.806a3.84 3.84 0 0 1 2.146-.657h9.725V69.007a3.84 3.84 0 0 0-.43-1.806 3.569 3.569 0 0 0-1.143-1.313 2.714 2.714 0 0 0-1.573-.492h-36.47v23.149h9.725c1.144 0 2.145.492 3.004 1.478.858.985 1.287 2.134 1.287 3.447v29.553c0 .876-.191 1.696-.573 2.463-.38.766-.905 1.368-1.573 1.806a3.84 3.84 0 0 1-2.145.656H51.915a3.84 3.84 0 0 1-2.145-.656c-.668-.438-1.216-1.04-1.645-1.806a4.96 4.96 0 0 1-.644-2.463V93.47c0-1.313.43-2.462 1.288-3.447.858-.986 1.907-1.478 3.146-1.478h9.582v-23.15h-37.9c-.953 0-1.74.356-2.359 1.068-.62.711-.93 1.56-.93 2.544v19.538h9.726c1.239 0 2.264.492 3.074 1.478.81.985 1.216 2.134 1.216 3.447v29.553c0 1.423-.405 2.6-1.216 3.53-.81.93-1.835 1.395-3.074 1.395H4.29c-.476 0-.93-.082-1.358-.246a4.1 4.1 0 0 1-1.144-.657 4.658 4.658 0 0 1-.93-1.067 5.186 5.186 0 0 1-.643-1.395 5.566 5.566 0 0 1-.215-1.56V93.47c0-.437.048-.875.143-1.313a3.95 3.95 0 0 1 .429-1.15c.19-.328.429-.656.715-.984.286-.329.572-.602.858-.821.286-.22.62-.383 1.001-.493.382-.11.763-.164 1.144-.164h9.726V61.619c0-.985.31-1.833.93-2.544.619-.712 1.358-1.068 2.216-1.068h44.335V39.62h-9.582c-1.24 0-2.288-.492-3.146-1.477a5.09 5.09 0 0 1-1.287-3.448V5.14c0-1.423.429-2.627 1.287-3.612.858-.985 1.907-1.477 3.146-1.477h25.743c.763 0 1.478.246 2.145.739a5.17 5.17 0 0 1 1.573 1.888c.382.766.573 1.587.573 2.462v29.553c0 1.313-.43 2.463-1.287 3.448-.859.985-1.86 1.477-3.004 1.477h-9.725v18.389h42.762c.954 0 1.74.355 2.36 1.067.62.711.93 1.56.93 2.545v26.925h9.582c1.239 0 2.288.492 3.146 1.478z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.8 KiB |
1
src/icons/svg/user.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="130" height="130" xmlns="http://www.w3.org/2000/svg"><path d="M63.444 64.996c20.633 0 37.359-14.308 37.359-31.953 0-17.649-16.726-31.952-37.359-31.952-20.631 0-37.36 14.303-37.358 31.952 0 17.645 16.727 31.953 37.359 31.953zM80.57 75.65H49.434c-26.652 0-48.26 18.477-48.26 41.27v2.664c0 9.316 21.608 9.325 48.26 9.325H80.57c26.649 0 48.256-.344 48.256-9.325v-2.663c0-22.794-21.605-41.271-48.256-41.271z" stroke="#979797"/></svg>
|
||||
|
After Width: | Height: | Size: 440 B |
22
src/icons/svgo.yml
Normal file
@ -0,0 +1,22 @@
|
||||
# replace default config
|
||||
|
||||
# multipass: true
|
||||
# full: true
|
||||
|
||||
plugins:
|
||||
|
||||
# - name
|
||||
#
|
||||
# or:
|
||||
# - name: false
|
||||
# - name: true
|
||||
#
|
||||
# or:
|
||||
# - name:
|
||||
# param1: 1
|
||||
# param2: 2
|
||||
|
||||
- removeAttrs:
|
||||
attrs:
|
||||
- 'fill'
|
||||
- 'fill-rule'
|
||||
147
src/lang/en-US.ts
Normal file
@ -0,0 +1,147 @@
|
||||
export default {
|
||||
"common": {
|
||||
"add": "Add",
|
||||
"edit": "Edit",
|
||||
"delete": "Delete",
|
||||
"search": "Search",
|
||||
"export": "Export",
|
||||
"language": "Language",
|
||||
"validity": "Validity",
|
||||
"days": "Days",
|
||||
"refresh": "Refresh",
|
||||
"Close": "Close",
|
||||
"Close Other": "Close Other",
|
||||
"Close All": "Close All"
|
||||
},
|
||||
"menu": {
|
||||
"Dashboard": "Dashboard",
|
||||
"Download": "Download",
|
||||
"orderManagement": "Order Management",
|
||||
"System": "System",
|
||||
"deliverOrder": "Deliver Order",
|
||||
"orderSetting": "Order Setting",
|
||||
"Stock Info": "Stock Info",
|
||||
"Store Stock": "Store Stock",
|
||||
"Combo Stock ": "Combo Stock",
|
||||
"Stock Storage": "Stock Storage",
|
||||
"receiving": "Receiving",
|
||||
"Entry Order": "Entry Order",
|
||||
"Stock out": "Stock Out",
|
||||
"inventory": "Inventory",
|
||||
"Log": "Log",
|
||||
"Exception": "Exception",
|
||||
"Material Info": "Material Info",
|
||||
"Storage": "Storage",
|
||||
"Bill": "Bill",
|
||||
"Daily": "Daily",
|
||||
"Account": "Account",
|
||||
"Statistics": "Statistics",
|
||||
"Valuation": "Valuation",
|
||||
"Receivable": "Receivable",
|
||||
"Encoding": "Encoding",
|
||||
"Open": "Open Platform",
|
||||
"basicManagement": "Basic Management",
|
||||
"Order": "Order",
|
||||
"Stock": "Stock",
|
||||
"Material": "Material",
|
||||
"Finance": "Finance",
|
||||
"Warehouse": "Warehouse",
|
||||
"Store": "Store",
|
||||
"Express": "Express",
|
||||
"Data": "Data",
|
||||
"Video": "Video",
|
||||
"Message": "Message",
|
||||
"Profile": "Profile",
|
||||
"printTemplate": "Print Template"
|
||||
},
|
||||
"login": {
|
||||
"title": "Login",
|
||||
"username": "Username",
|
||||
"password": "Password",
|
||||
"logIn": "Login",
|
||||
"loggingIn": "Logging in...",
|
||||
"show": "Show",
|
||||
"hide": "Hide",
|
||||
"usernamePlaceholder": "Please enter username",
|
||||
"passwordPlaceholder": "Please enter password",
|
||||
"correctUsernameTip": "Please enter correct username",
|
||||
"usernameLengthTip": "Please enter valid username",
|
||||
"passwordLengthTip": "Password at least 6 characters",
|
||||
"loginFailed": "Login failed",
|
||||
"logOut": "Logout",
|
||||
"register": "Register",
|
||||
"confirmPassword": "Confirm Password",
|
||||
"passwordMismatch": "Passwords do not match",
|
||||
"registerSuccess": "Registration successful",
|
||||
"toLogin": "Back to Login",
|
||||
"noAccount": "Don't have an account?",
|
||||
"hasAccount": "Already have an account?"
|
||||
},
|
||||
"dashboard": {
|
||||
"expressDistribution": "Express Distribution",
|
||||
"hotOrderRank": "Hot Order Rank (Top 10)",
|
||||
"rank": "Rank",
|
||||
"productName": "Product Name",
|
||||
"orderOutboundCount": "Order Outbound Count",
|
||||
"trend": "Trend",
|
||||
"viewAll": "View All",
|
||||
"orderTrend": "Order Trend",
|
||||
"today": "Today",
|
||||
"thisWeek": "This Week",
|
||||
"thisMonth": "This Month",
|
||||
"platformDistribution": "Platform Distribution",
|
||||
"todayOrders": "Today Orders",
|
||||
"vsYesterday": "vs Yesterday",
|
||||
"unassignedExpress": "Unassigned Express",
|
||||
"toBeAssigned": "To Be Assigned",
|
||||
"unprinted": "Unprinted",
|
||||
"toBePrinted": "To Be Printed",
|
||||
"unpicked": "Unpicked",
|
||||
"needTimelyProcessing": "Need Timely Processing",
|
||||
"pendingShipment": "Pending Shipment",
|
||||
"welcomeCardPlaceholder": "Welcome Card Placeholder",
|
||||
"warehouseStatistics": "Warehouse Statistics",
|
||||
"storeStatistics": "Store Statistics",
|
||||
"expressRatio": "Express Ratio",
|
||||
"orderVolume": "Order Volume",
|
||||
"shipmentVolume": "Shipment Volume",
|
||||
"shipmentRate": "Shipment Rate",
|
||||
"todayOutbound": "Today Outbound",
|
||||
"completionRate": "Completion Rate",
|
||||
"interceptedOrders": "Intercepted Orders",
|
||||
"exceptionOrders": "Exception Orders"
|
||||
},
|
||||
"inventory": {
|
||||
"sku": "SKU",
|
||||
"batch_no": "Batch No",
|
||||
"quantity": "Quantity",
|
||||
"locked_qty": "Locked Qty",
|
||||
"safety_stock": "Safety Stock"
|
||||
},
|
||||
"order": {
|
||||
"order_no": "Order No",
|
||||
"customer": "Customer",
|
||||
"status": "Status",
|
||||
"create_time": "Create Time",
|
||||
"total_amount": "Total Amount"
|
||||
},
|
||||
"shipment": {
|
||||
"ship_no": "Shipment No",
|
||||
"ship_type": "Type",
|
||||
"express_no": "Express No",
|
||||
"ship_time": "Time"
|
||||
},
|
||||
"user": {
|
||||
"username": "Username",
|
||||
"role": "Role",
|
||||
"permission": "Permission",
|
||||
"login_time": "Login Time"
|
||||
},
|
||||
"warehouse": {
|
||||
"name": "Name",
|
||||
"code": "Code",
|
||||
"type": "Type",
|
||||
"status": "Status",
|
||||
"address": "Address"
|
||||
}
|
||||
}
|
||||
250
src/lang/index.ts
Normal file
@ -0,0 +1,250 @@
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import Cookies from 'js-cookie'
|
||||
import elementEnLocale from 'element-plus/es/locale/lang/en'
|
||||
import elementZhLocale from 'element-plus/es/locale/lang/zh-cn'
|
||||
import localEnUS from './en-US.ts'
|
||||
import localZhCN from './zh-CN.ts'
|
||||
import * as indexApi from '@/api/index.ts'
|
||||
|
||||
// ==================== 配置 ====================
|
||||
const CONFIG = {
|
||||
API_BASE: import.meta.env.VITE_APP_BASE_API || '/api',
|
||||
PROJECT: import.meta.env.VITE_APP_PROJECT_NAME || 'vue-admin',
|
||||
AUTO_REPORT: true, // 是否自动上报新键值
|
||||
REPORT_DELAY: 3000, // 上报延迟(毫秒)
|
||||
CACHE_KEY: 'i18n_collected_keys' // 本地缓存键名
|
||||
}
|
||||
|
||||
// ==================== 状态管理 ====================
|
||||
const state = {
|
||||
serverMessages: {} as Record<string, any>, // 服务器加载的翻译
|
||||
collectedKeys: new Set<string>(), // 已采集的键值
|
||||
pendingKeys: new Map<string, any>(), // 待上报的键值
|
||||
isReporting: false, // 是否正在上报
|
||||
isLoaded: false // 服务器翻译是否已加载
|
||||
}
|
||||
|
||||
const messages = {
|
||||
'en': {
|
||||
...localEnUS,
|
||||
...elementEnLocale
|
||||
},
|
||||
'zh-CN': {
|
||||
...localZhCN,
|
||||
...elementZhLocale
|
||||
}
|
||||
}
|
||||
|
||||
export function getLanguage() {
|
||||
const chooseLanguage = Cookies.get('language')
|
||||
if (chooseLanguage) return chooseLanguage
|
||||
|
||||
const language = (navigator.language || (navigator.languages && navigator.languages[0]) || 'zh-CN').toLowerCase()
|
||||
const locales = Object.keys(messages)
|
||||
for (const locale of locales) {
|
||||
if (language.indexOf(locale.toLowerCase()) > -1) {
|
||||
return locale
|
||||
}
|
||||
}
|
||||
return 'zh-CN'
|
||||
}
|
||||
|
||||
// ==================== 核心函数 ====================
|
||||
|
||||
/**
|
||||
* 4. 加载本地缓存的键值
|
||||
*/
|
||||
function loadCollectedKeys() {
|
||||
try {
|
||||
const saved = localStorage.getItem(CONFIG.CACHE_KEY)
|
||||
if (saved) {
|
||||
state.collectedKeys = new Set(JSON.parse(saved))
|
||||
// console.log(`📦 加载 ${state.collectedKeys.size} 个已采集键值`)
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('加载缓存键值失败:', e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 5. 保存到本地缓存
|
||||
*/
|
||||
function saveCollectedKeys() {
|
||||
try {
|
||||
localStorage.setItem(
|
||||
CONFIG.CACHE_KEY,
|
||||
JSON.stringify(Array.from(state.collectedKeys))
|
||||
)
|
||||
} catch (e) {
|
||||
console.warn('保存缓存键值失败:', e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 7. 获取调用上下文(帮助定位键值位置)
|
||||
*/
|
||||
function getCallContext() {
|
||||
try {
|
||||
const stack = new Error().stack
|
||||
// @ts-ignore
|
||||
const lines = stack.split('\n').slice(3, 6) // 获取调用堆栈
|
||||
|
||||
return {
|
||||
stack: lines.join('\n'),
|
||||
url: window.location.href,
|
||||
userAgent: navigator.userAgent,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 9. 上报键值到服务器
|
||||
*/
|
||||
async function reportKeysToServer() {
|
||||
if (state.isReporting || state.pendingKeys.size === 0) return
|
||||
|
||||
state.isReporting = true
|
||||
const keysToReport = Array.from(state.pendingKeys.values())
|
||||
|
||||
try {
|
||||
console.log(`📤 上报 ${keysToReport.length} 个新键值到服务器...`)
|
||||
// @ts-ignore
|
||||
const response = await indexApi.putI18nCollect({
|
||||
project: 'wms',
|
||||
locale: i18n.global.locale.value,
|
||||
keys: keysToReport,
|
||||
source: 'frontend-auto-collect'
|
||||
});
|
||||
|
||||
if (response.data && response.data.success) {
|
||||
// 清空已上报的
|
||||
keysToReport.forEach(item => state.pendingKeys.delete(item.key))
|
||||
console.log(`✅ 上报成功,服务器已处理 ${response.data.processed} 个键值`)
|
||||
|
||||
// 重新加载服务器翻译(获取新生成的翻译)
|
||||
await loadServerMessages()
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 上报失败:', error)
|
||||
} finally {
|
||||
state.isReporting = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 8. 防抖上报
|
||||
*/
|
||||
let reportTimer: any = null
|
||||
function debounceReport() {
|
||||
clearTimeout(reportTimer)
|
||||
reportTimer = setTimeout(() => {
|
||||
if (state.pendingKeys.size > 0 && !state.isReporting) {
|
||||
reportKeysToServer()
|
||||
}
|
||||
}, CONFIG.REPORT_DELAY)
|
||||
}
|
||||
|
||||
/**
|
||||
* 6. 采集新键值
|
||||
*/
|
||||
function collectKey(key: string, value: string | null = null) {
|
||||
// 跳过已采集的
|
||||
if (state.collectedKeys.has(key)) return
|
||||
|
||||
// 获取调用上下文(用于定位)
|
||||
// const context = getCallContext()
|
||||
|
||||
state.collectedKeys.add(key)
|
||||
saveCollectedKeys()
|
||||
|
||||
// 添加到待上报队列
|
||||
state.pendingKeys.set(key, {
|
||||
key,
|
||||
value: value || key,
|
||||
timestamp: Date.now(),
|
||||
visitedCount: 1
|
||||
})
|
||||
|
||||
// 触发上报
|
||||
if (CONFIG.AUTO_REPORT) {
|
||||
debounceReport()
|
||||
}
|
||||
}
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false, // Use Composition API
|
||||
locale: getLanguage(),
|
||||
fallbackLocale: 'zh-CN',
|
||||
globalInjection: true,
|
||||
messages,
|
||||
missing: (locale, key) => {
|
||||
// 采集这个新键值
|
||||
if (CONFIG.AUTO_REPORT) {
|
||||
collectKey(key)
|
||||
}
|
||||
// Return key as fallback
|
||||
return key
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* 递归深度合并对象
|
||||
*/
|
||||
function deepMerge(target: any, source: any) {
|
||||
if (!source) return target
|
||||
|
||||
Object.keys(source).forEach(key => {
|
||||
if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
|
||||
if (!target[key] || typeof target[key] !== 'object') {
|
||||
target[key] = {}
|
||||
}
|
||||
deepMerge(target[key], source[key])
|
||||
} else {
|
||||
target[key] = source[key]
|
||||
}
|
||||
})
|
||||
return target
|
||||
}
|
||||
|
||||
/**
|
||||
* 从服务器加载翻译
|
||||
*/
|
||||
export async function loadServerMessages(language: string | null = null) {
|
||||
const targetLanguage = language || i18n.global.locale.value;
|
||||
|
||||
try {
|
||||
console.log(`🌐 从服务器加载国际化翻译 (${targetLanguage})...`)
|
||||
|
||||
const response = await indexApi.getI18nMessage({
|
||||
language: targetLanguage
|
||||
});
|
||||
|
||||
if (response.data) {
|
||||
const newMessages = response.data.messages || response.data;
|
||||
// @ts-ignore
|
||||
state.serverMessages[targetLanguage] = newMessages;
|
||||
state.isLoaded = true;
|
||||
|
||||
// 深度合并到 i18n 实例,确保本地新增的键值不被服务器返回的同名父级对象覆盖
|
||||
// @ts-ignore
|
||||
const currentMessages = JSON.parse(JSON.stringify(i18n.global.getLocaleMessage(targetLanguage)))
|
||||
const mergedMessages = deepMerge(currentMessages, newMessages)
|
||||
|
||||
// @ts-ignore
|
||||
i18n.global.setLocaleMessage(targetLanguage, mergedMessages)
|
||||
|
||||
console.log(`✅ 服务器翻译加载并深度合并成功 (${targetLanguage})`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`⚠️ 服务器翻译加载失败 (${targetLanguage}),使用本地翻译`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化加载
|
||||
loadCollectedKeys()
|
||||
|
||||
export default i18n
|
||||
147
src/lang/zh-CN.ts
Normal file
@ -0,0 +1,147 @@
|
||||
export default {
|
||||
"common": {
|
||||
"add": "新增",
|
||||
"edit": "编辑",
|
||||
"delete": "删除",
|
||||
"search": "搜索",
|
||||
"export": "导出",
|
||||
"language": "语言",
|
||||
"validity": "有效期",
|
||||
"days": "天",
|
||||
"refresh": "刷新",
|
||||
"Close": "关闭",
|
||||
"Close Other": "关闭其他",
|
||||
"Close All": "全部关闭"
|
||||
},
|
||||
"menu": {
|
||||
"Dashboard": "控制台",
|
||||
"Download": "下载",
|
||||
"orderManagement": "订单管理",
|
||||
"System": "系统",
|
||||
"deliverOrder": "配送订单",
|
||||
"orderSetting": "订单设置",
|
||||
"Stock Info": "商品明细",
|
||||
"Store Stock": "货主商品",
|
||||
"Combo Stock ": "组合商品",
|
||||
"Stock Storage": "商品库存",
|
||||
"receiving": "收货单",
|
||||
"Entry Order": "入库单",
|
||||
"Stock out": "出库单",
|
||||
"inventory": "库存",
|
||||
"Log": "日志",
|
||||
"Exception": "异常处理",
|
||||
"Material Info": "物料明细",
|
||||
"Storage": "库存",
|
||||
"Bill": "余额",
|
||||
"Daily": "流水",
|
||||
"Account": "账户",
|
||||
"Statistics": "统计",
|
||||
"Valuation": "定价",
|
||||
"Receivable": "应收",
|
||||
"Encoding": "编码",
|
||||
"Open": "开放平台",
|
||||
"basicManagement": "基础设置",
|
||||
"Order": "订单",
|
||||
"Stock": "商品",
|
||||
"Material": "耗材",
|
||||
"Finance": "财务",
|
||||
"Warehouse": "仓库",
|
||||
"Store": "货主",
|
||||
"Express": "快递",
|
||||
"Data": "数据",
|
||||
"Video": "录像",
|
||||
"Message": "消息",
|
||||
"Profile": "个人中心",
|
||||
"printTemplate": "打印模板"
|
||||
},
|
||||
"login": {
|
||||
"title": "登录",
|
||||
"username": "用户名",
|
||||
"password": "密码",
|
||||
"logIn": "登录",
|
||||
"loggingIn": "登录中...",
|
||||
"show": "显示",
|
||||
"hide": "隐藏",
|
||||
"usernamePlaceholder": "请输入用户名",
|
||||
"passwordPlaceholder": "请输入密码",
|
||||
"correctUsernameTip": "请输入用户名",
|
||||
"usernameLengthTip": "请输入有效的用户名",
|
||||
"passwordLengthTip": "密码至少 6 位",
|
||||
"loginFailed": "登录失败",
|
||||
"logOut": "登出",
|
||||
"register": "注册",
|
||||
"confirmPassword": "确认密码",
|
||||
"passwordMismatch": "两次输入的密码不一致",
|
||||
"registerSuccess": "注册成功",
|
||||
"toLogin": "返回登录",
|
||||
"noAccount": "还没有账号?",
|
||||
"hasAccount": "已有账号?"
|
||||
},
|
||||
"dashboard": {
|
||||
"expressDistribution": "快递分布",
|
||||
"hotOrderRank": "热销商品排行(Top10)",
|
||||
"rank": "排名",
|
||||
"productName": "商品名称",
|
||||
"orderOutboundCount": "订单出库数",
|
||||
"trend": "趋势",
|
||||
"viewAll": "查看全部",
|
||||
"orderTrend": "订单趋势",
|
||||
"today": "今日",
|
||||
"thisWeek": "本周",
|
||||
"thisMonth": "本月",
|
||||
"platformDistribution": "平台分布",
|
||||
"todayOrders": "今日订单",
|
||||
"vsYesterday": "较昨日",
|
||||
"unassignedExpress": "未分配快递号",
|
||||
"toBeAssigned": "待分配",
|
||||
"unprinted": "未打印",
|
||||
"toBePrinted": "待打印",
|
||||
"unpicked": "未拣货",
|
||||
"needTimelyProcessing": "需及时处理",
|
||||
"pendingShipment": "待发货",
|
||||
"welcomeCardPlaceholder": "欢迎卡片占位符",
|
||||
"warehouseStatistics": "仓库统计",
|
||||
"storeStatistics": "店铺统计",
|
||||
"expressRatio": "快递占比",
|
||||
"orderVolume": "订单量",
|
||||
"shipmentVolume": "发货量",
|
||||
"shipmentRate": "发货率",
|
||||
"todayOutbound": "今日出库",
|
||||
"completionRate": "完成率",
|
||||
"interceptedOrders": "拦截订单",
|
||||
"exceptionOrders": "异常订单"
|
||||
},
|
||||
"inventory": {
|
||||
"sku": "商品SKU",
|
||||
"batch_no": "批次号",
|
||||
"quantity": "库存数量",
|
||||
"locked_qty": "锁定数量",
|
||||
"safety_stock": "安全库存"
|
||||
},
|
||||
"order": {
|
||||
"order_no": "订单编号",
|
||||
"customer": "客户名称",
|
||||
"status": "订单状态",
|
||||
"create_time": "创建时间",
|
||||
"total_amount": "订单金额"
|
||||
},
|
||||
"shipment": {
|
||||
"ship_no": "出库单号",
|
||||
"ship_type": "出库类型",
|
||||
"express_no": "快递单号",
|
||||
"ship_time": "出库时间"
|
||||
},
|
||||
"user": {
|
||||
"username": "用户名",
|
||||
"role": "用户角色",
|
||||
"permission": "用户权限",
|
||||
"login_time": "登录时间"
|
||||
},
|
||||
"warehouse": {
|
||||
"name": "仓库名称",
|
||||
"code": "仓库编码",
|
||||
"type": "仓库类型",
|
||||
"status": "仓库状态",
|
||||
"address": "仓库地址"
|
||||
}
|
||||
}
|
||||
7
src/layout/AppMain.vue
Normal file
@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<div class=""></div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts"></script>
|
||||
|
||||
<style lang="css" scoped></style>
|
||||
467
src/layout/component/AiChat/index.vue
Normal file
@ -0,0 +1,467 @@
|
||||
<template>
|
||||
<div class="ai-chat-wrapper">
|
||||
<!-- Header -->
|
||||
<div class="ai-header">
|
||||
<div class="header-title">
|
||||
<span v-if="showHistory">Chat History</span>
|
||||
<el-dropdown v-else trigger="click" @command="handleIdentityChange">
|
||||
<span class="el-dropdown-link">
|
||||
{{ aiStore.currentIdentity?.name || '' }}
|
||||
<el-icon class="el-icon--right"><ArrowDown /></el-icon>
|
||||
</span>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
v-for="identity in AI_IDENTITIES"
|
||||
:key="identity.key"
|
||||
:command="identity.key"
|
||||
:disabled="identity.key === aiStore.currentIdentityKey"
|
||||
>
|
||||
<el-icon><component :is="getIconComponent(identity.icon)" /></el-icon>
|
||||
{{ identity.name }}
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<el-tooltip content="New Chat" placement="bottom">
|
||||
<el-button link @click="handleNewChat">
|
||||
<el-icon><Plus /></el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip :content="showHistory ? 'Back to Chat' : 'History'" placement="bottom">
|
||||
<el-button link @click="toggleHistory">
|
||||
<el-icon><component :is="showHistory ? ChatDotRound : Clock" /></el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
<el-button link @click="closeAi" class="close-btn">
|
||||
<el-icon><Close /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="ai-content">
|
||||
<div v-if="showHistory" class="history-list">
|
||||
<el-scrollbar>
|
||||
<div v-if="aiStore.sessions.length === 0" class="empty-history">
|
||||
No chat history for {{ aiStore.currentIdentity?.name || '' }}
|
||||
</div>
|
||||
<div
|
||||
v-for="session in aiStore.sessions"
|
||||
:key="session.id"
|
||||
class="history-item"
|
||||
:class="{ active: aiStore.currentSessionId === session.id }"
|
||||
@click="loadSession(session.id)"
|
||||
>
|
||||
<div class="history-title">{{ session.title }}</div>
|
||||
<div class="history-time">{{ formatTime(session.createdAt) }}</div>
|
||||
<el-button link class="delete-btn" @click.stop="deleteSession(session.id)">
|
||||
<el-icon><Delete /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
</el-scrollbar>
|
||||
</div>
|
||||
|
||||
<el-scrollbar v-else ref="scrollbarRef" always style="height: 100%">
|
||||
<div class="messages-list">
|
||||
<div v-if="aiStore.messages.length === 0" class="empty-chat">
|
||||
<div class="empty-icon">
|
||||
<el-icon :size="48"><component :is="getIconComponent(aiStore.currentIdentity?.icon || '')" /></el-icon>
|
||||
</div>
|
||||
<p>{{ aiStore.currentIdentity?.description || '' }}</p>
|
||||
<p>{{ aiStore.currentIdentity?.systemPrompt || 'How can I help you today?' }}</p>
|
||||
</div>
|
||||
<div v-for="(msg, index) in aiStore.messages" :key="index" class="message-row" :class="msg.role">
|
||||
<div class="avatar">
|
||||
<el-avatar :size="32" :icon="msg.role === 'user' ? UserFilled : getIconComponent(aiStore.currentIdentity?.icon || '')" :class="msg.role === 'user' ? 'user-avatar' : 'ai-avatar'" />
|
||||
</div>
|
||||
<div class="message-bubble">
|
||||
<div class="message-text">{{ msg.content }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-scrollbar>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div class="ai-footer" v-if="!showHistory">
|
||||
<div class="input-area">
|
||||
<el-input
|
||||
v-model="inputMessage"
|
||||
:placeholder="`Ask ${aiStore.currentIdentity?.name || ''} something...`"
|
||||
@keyup.enter="sendMessage"
|
||||
resize="none"
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 1, maxRows: 4 }"
|
||||
class="chat-input"
|
||||
>
|
||||
</el-input>
|
||||
<el-button type="primary" circle :icon="Position" @click="sendMessage" :disabled="!inputMessage.trim()" class="send-btn" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, nextTick, onMounted, watch } from 'vue'
|
||||
import { useAiStore, AI_IDENTITIES } from '@/stores/modules/ai'
|
||||
import { Plus, Clock, Close, UserFilled, Service, Position, ChatDotRound, Delete, ArrowDown } from '@element-plus/icons-vue'
|
||||
import type { ElScrollbar } from 'element-plus'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
const aiStore = useAiStore()
|
||||
const inputMessage = ref('')
|
||||
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>()
|
||||
const showHistory = ref(false)
|
||||
|
||||
const getIconComponent = (iconName: string) => {
|
||||
const icons: Record<string, any> = { Service }
|
||||
return icons[iconName] || Service
|
||||
}
|
||||
|
||||
const scrollToBottom = () => {
|
||||
nextTick(() => {
|
||||
if (scrollbarRef.value) {
|
||||
const wrap = scrollbarRef.value.wrapRef
|
||||
if (wrap) {
|
||||
wrap.scrollTop = wrap.scrollHeight
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const closeAi = () => {
|
||||
aiStore.isVisible = false
|
||||
}
|
||||
|
||||
const handleNewChat = () => {
|
||||
aiStore.startNewChat()
|
||||
showHistory.value = false
|
||||
inputMessage.value = ''
|
||||
// scrollToBottom is called but list is empty, so it's fine
|
||||
}
|
||||
|
||||
const toggleHistory = () => {
|
||||
showHistory.value = !showHistory.value
|
||||
}
|
||||
|
||||
const loadSession = (sessionId: string) => {
|
||||
aiStore.loadSession(sessionId)
|
||||
showHistory.value = false
|
||||
scrollToBottom()
|
||||
}
|
||||
|
||||
const deleteSession = (sessionId: string) => {
|
||||
aiStore.deleteSession(sessionId)
|
||||
}
|
||||
|
||||
const handleIdentityChange = (key: string) => {
|
||||
aiStore.setIdentity(key)
|
||||
showHistory.value = false
|
||||
scrollToBottom()
|
||||
}
|
||||
|
||||
const formatTime = (timestamp: number) => {
|
||||
return dayjs(timestamp).format('MM-DD HH:mm')
|
||||
}
|
||||
|
||||
const sendMessage = () => {
|
||||
if (!inputMessage.value.trim()) return
|
||||
|
||||
const content = inputMessage.value
|
||||
aiStore.addMessage('user', content)
|
||||
inputMessage.value = ''
|
||||
scrollToBottom()
|
||||
|
||||
// Simulate AI response
|
||||
setTimeout(() => {
|
||||
const identity = aiStore.currentIdentity
|
||||
aiStore.addMessage('ai', `[${identity?.name || ''}] I received: "${content}". \n\n${identity?.systemPrompt || 'This is a simulated response.'}`)
|
||||
scrollToBottom()
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
watch(() => aiStore.messages.length, () => {
|
||||
if (!showHistory.value) {
|
||||
scrollToBottom()
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
scrollToBottom()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@use "@/styles/variables.scss" as *;
|
||||
|
||||
.ai-chat-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
// flex: 1;
|
||||
width: 500px;
|
||||
height: 100%;
|
||||
background-color: #fff;
|
||||
overflow: hidden;
|
||||
|
||||
.ai-header {
|
||||
height: 50px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0 15px;
|
||||
background-color: #3b3b3b;
|
||||
box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
|
||||
color: #fff;
|
||||
z-index: 1;
|
||||
|
||||
.header-title {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
|
||||
.el-dropdown-link {
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
|
||||
:deep(.el-button) {
|
||||
color: #fff;
|
||||
font-size: 18px;
|
||||
padding: 8px;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(255,255,255,0.1);
|
||||
}
|
||||
|
||||
&.close-btn:hover {
|
||||
background-color: #f56c6c;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ai-content {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
position: relative;
|
||||
|
||||
.messages-list {
|
||||
padding: 20px;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.empty-chat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
color: #909399;
|
||||
margin-top: 50px;
|
||||
font-size: 14px;
|
||||
|
||||
.empty-icon {
|
||||
margin-bottom: 20px;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
padding: 20px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 5px 0;
|
||||
|
||||
&:first-of-type {
|
||||
font-weight: bold;
|
||||
font-size: 16px;
|
||||
color: #606266;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.history-list {
|
||||
padding: 15px;
|
||||
height: 100%;
|
||||
|
||||
.empty-history {
|
||||
text-align: center;
|
||||
color: #909399;
|
||||
margin-top: 50px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.history-item {
|
||||
padding: 12px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 8px;
|
||||
background-color: #f4f4f5;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
background-color: #e9e9eb;
|
||||
}
|
||||
|
||||
&.active {
|
||||
background-color: #ecf5ff;
|
||||
border: 1px solid #c6e2ff;
|
||||
}
|
||||
|
||||
.history-title {
|
||||
font-size: 14px;
|
||||
color: #303133;
|
||||
flex: 1;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
.history-time {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.delete-btn {
|
||||
color: #f56c6c;
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s;
|
||||
padding: 2px;
|
||||
font-size: 16px;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(245, 108, 108, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
&:hover .delete-btn {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.message-row {
|
||||
display: flex;
|
||||
margin-bottom: 20px;
|
||||
gap: 12px;
|
||||
|
||||
&.user {
|
||||
flex-direction: row-reverse;
|
||||
|
||||
.message-bubble {
|
||||
background-color: #653eb3;
|
||||
color: #fff;
|
||||
border-radius: 12px 0 12px 12px;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.user-avatar {
|
||||
background-color: #653eb3;
|
||||
}
|
||||
}
|
||||
|
||||
&.ai {
|
||||
.message-bubble {
|
||||
background-color: #f4f4f5;
|
||||
color: #303133;
|
||||
border-radius: 0 12px 12px 12px;
|
||||
border: 1px solid #e9e9eb;
|
||||
}
|
||||
|
||||
.ai-avatar {
|
||||
background-color: #909399;
|
||||
}
|
||||
}
|
||||
|
||||
.avatar {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.message-bubble {
|
||||
padding: 12px 16px;
|
||||
max-width: 85%;
|
||||
word-break: break-word;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,0.05);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ai-footer {
|
||||
width: 100%;
|
||||
min-height: 80px;
|
||||
// justify-content: flex-end;
|
||||
flex-shrink: 0;
|
||||
padding: 15px;
|
||||
border-top: 1px solid #eee;
|
||||
background-color: #fff;
|
||||
z-index: 1;
|
||||
|
||||
.input-area {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 10px;
|
||||
|
||||
.chat-input {
|
||||
flex: 1;
|
||||
|
||||
:deep(.el-textarea__inner) {
|
||||
border-radius: 8px;
|
||||
padding: 8px 12px;
|
||||
resize: none;
|
||||
box-shadow: none;
|
||||
background-color: #f4f4f5;
|
||||
border: 1px solid transparent;
|
||||
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
&:focus {
|
||||
background-color: #fff;
|
||||
box-shadow: 0 0 0 1px #653eb3 inset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.send-btn {
|
||||
margin-bottom: 2px;
|
||||
background-color: #653eb3;
|
||||
border-color: #653eb3;
|
||||
color: white;
|
||||
|
||||
&:hover {
|
||||
background-color: #7a5ac9;
|
||||
border-color: #7a5ac9;
|
||||
}
|
||||
|
||||
&.is-disabled {
|
||||
background-color: #a0cfff;
|
||||
border-color: #a0cfff;
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
43
src/layout/component/AppMain.vue
Normal file
@ -0,0 +1,43 @@
|
||||
<template>
|
||||
<section class="app-main">
|
||||
<router-view v-slot="{ Component, route }">
|
||||
<transition name="fade-transform">
|
||||
<keep-alive :include="cachedViews">
|
||||
<component :is="Component" :key="route.fullPath" />
|
||||
</keep-alive>
|
||||
</transition>
|
||||
</router-view>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useTagsViewStore } from '@/stores/modules/tagsView'
|
||||
|
||||
const tagsViewStore = useTagsViewStore()
|
||||
const cachedViews = computed(() => tagsViewStore.cachedViews)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.app-main {
|
||||
/* 90 = navbar + tags-view = 50 + 40 */
|
||||
min-height: calc(100vh - 90px);
|
||||
width: 100%;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.fixed-header+.app-main {
|
||||
padding-top: 90px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="scss">
|
||||
// Global fix for el-popup-parent--hidden
|
||||
.el-popup-parent--hidden {
|
||||
.fixed-header {
|
||||
padding-right: 15px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
374
src/layout/component/Navbar.vue
Normal file
@ -0,0 +1,374 @@
|
||||
<template>
|
||||
<div class="navbar">
|
||||
<img src="/logo/1.png" alt="logo" class="logo">
|
||||
<breadcrumb v-if="layoutMode !== 'top-bottom'" class="breadcrumb-container" />
|
||||
|
||||
<div v-if="layoutMode === 'top-bottom'" class="top-menu-wrapper">
|
||||
<top-menu />
|
||||
</div>
|
||||
|
||||
<div class="right-menu">
|
||||
<template v-if="device !== 'mobile'">
|
||||
<!-- Validity indicator -->
|
||||
<el-tooltip
|
||||
v-if="userStore.checkPermission('dashboard.auth') && activeWarehouse"
|
||||
class="item"
|
||||
effect="dark"
|
||||
:content="validityTooltip"
|
||||
placement="bottom"
|
||||
>
|
||||
<div class="right-menu-item validity-item" :class="validityClass" @click="handleValidityClick">
|
||||
<svg-icon icon-class="time" class="validity-icon" />
|
||||
<span class="validity-text">{{ $t('common.validity') === 'common.validity' ? '有效期' : $t('common.validity') }}</span>
|
||||
<span class="remaining-days" :class="daysClass">{{ remainingDays }}</span>
|
||||
<span class="day-text">{{ $t('common.days') === 'common.days' ? '天' : $t('common.days') }}</span>
|
||||
</div>
|
||||
</el-tooltip>
|
||||
|
||||
<!-- Full Screen -->
|
||||
<div class="right-menu-item" @click="toggle">
|
||||
<svg-icon :icon-class="isFullscreen ? 'exit-fullscreen' : 'fullscreen'" />
|
||||
</div>
|
||||
|
||||
<!-- Message -->
|
||||
<router-link to="/message" class="right-menu-item">
|
||||
<div class="menu-item-content">
|
||||
<svg-icon icon-class="message" />
|
||||
<span class="menu-text">{{ $t('menu.Message') }}</span>
|
||||
</div>
|
||||
</router-link>
|
||||
|
||||
<!-- Download -->
|
||||
<router-link to="/download" class="right-menu-item">
|
||||
<div class="menu-item-content">
|
||||
<svg-icon icon-class="download" />
|
||||
<span class="menu-text">{{ $t('menu.Download') }}</span>
|
||||
</div>
|
||||
</router-link>
|
||||
|
||||
<!-- Language Select -->
|
||||
<lang-select class="right-menu-item" />
|
||||
</template>
|
||||
|
||||
<el-dropdown class="avatar-container right-menu-item" trigger="click">
|
||||
<div class="avatar-wrapper">
|
||||
<span class="user-name">{{ user.employees_name || user.username }}</span>
|
||||
<img :src="avatar || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'" class="user-avatar">
|
||||
<svg-icon icon-class="eye" style="font-size: 10px; margin-left: 5px;" />
|
||||
</div>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu class="user-dropdown">
|
||||
<!-- Role Switching -->
|
||||
<template v-if="user.employees && user.employees.length > 1">
|
||||
<el-dropdown-item
|
||||
v-for="role in user.employees"
|
||||
:key="role.id"
|
||||
:class="role.is_primary == 1 ? 'on' : ''"
|
||||
@click="changeRole(role.id)"
|
||||
>
|
||||
{{ role.store_name }} | {{ role.real_name }}
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item divided />
|
||||
</template>
|
||||
|
||||
<router-link to="/profile">
|
||||
<el-dropdown-item>
|
||||
{{ $t('menu.Profile') }}
|
||||
</el-dropdown-item>
|
||||
</router-link>
|
||||
|
||||
<el-dropdown-item divided @click="logout">
|
||||
<span style="display:block;">{{ $t('login.logOut') || 'Log Out' }}</span>
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<div class="view-btn">
|
||||
<div class="view-change" @click="toggleLayout">
|
||||
<svg-icon :icon-class="layoutMode === 'sidebar' ? 'tree' : 'table'" style="font-size: 20px; color: white;" />
|
||||
</div>
|
||||
<div class="ai-btn" @click="toggleAi">
|
||||
<img class="ai-img" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useAppStore } from '@/stores/modules/app'
|
||||
import { useUserStore } from '@/stores/modules/user'
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
import { useAiStore } from '@/stores/modules/ai'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import Breadcrumb from '@/components/Breadcrumb/index.vue'
|
||||
import LangSelect from '@/components/LangSelect/index.vue'
|
||||
import TopMenu from './TopMenu.vue'
|
||||
import dayjs from 'dayjs'
|
||||
import { useFullscreen } from '@vueuse/core'
|
||||
|
||||
const { isFullscreen, toggle } = useFullscreen()
|
||||
|
||||
const appStore = useAppStore()
|
||||
const userStore = useUserStore()
|
||||
const settingsStore = useSettingsStore()
|
||||
const aiStore = useAiStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const sidebar = computed(() => appStore.sidebar)
|
||||
const user = computed(() => userStore.user)
|
||||
const avatar = computed(() => userStore.avatar)
|
||||
const device = computed(() => appStore.device)
|
||||
const layoutMode = computed(() => settingsStore.layoutMode)
|
||||
|
||||
const remainingDays = ref(0)
|
||||
const isExpired = ref(false)
|
||||
|
||||
const activeWarehouse = computed(() => {
|
||||
const employees = user.value.employees
|
||||
if (!employees || !Array.isArray(employees)) return null
|
||||
const primaryRole = employees.find((role: any) => role.is_primary == 1)
|
||||
return primaryRole ? {
|
||||
store_id: primaryRole.store_id,
|
||||
auth_end: primaryRole.auth_end
|
||||
} : null
|
||||
})
|
||||
|
||||
const validityTooltip = computed(() => {
|
||||
if (isExpired.value) {
|
||||
return '已过期,只保留数据查询导出能力,点击跳转续费'
|
||||
}
|
||||
if (remainingDays.value <= 0) {
|
||||
return '今天到期,点击跳转续费'
|
||||
} else if (remainingDays.value <= 3) {
|
||||
return `即将过期(剩余${remainingDays.value}天),点击跳转续费`
|
||||
} else if (remainingDays.value <= 7) {
|
||||
return `剩余${remainingDays.value}天,建议提前续费`
|
||||
} else {
|
||||
return `剩余${remainingDays.value}天有效期`
|
||||
}
|
||||
})
|
||||
|
||||
const validityClass = computed(() => {
|
||||
if (isExpired.value) return 'is-expired'
|
||||
if (remainingDays.value <= 7) return 'is-warning'
|
||||
return ''
|
||||
})
|
||||
|
||||
const daysClass = computed(() => {
|
||||
if (remainingDays.value <= 3) return 'text-danger'
|
||||
if (remainingDays.value <= 7) return 'text-warning'
|
||||
return 'text-success'
|
||||
})
|
||||
|
||||
const calculateDays = () => {
|
||||
if (activeWarehouse.value && activeWarehouse.value.auth_end) {
|
||||
const end = dayjs(activeWarehouse.value.auth_end)
|
||||
const now = dayjs()
|
||||
const diff = end.diff(now, 'day')
|
||||
remainingDays.value = diff
|
||||
isExpired.value = diff < 0
|
||||
}
|
||||
}
|
||||
|
||||
const toggleAi = () => {
|
||||
aiStore.toggleAiContainer()
|
||||
}
|
||||
|
||||
const toggleLayout = () => {
|
||||
const newMode = layoutMode.value === 'sidebar' ? 'top-bottom' : 'sidebar'
|
||||
settingsStore.changeSetting({ key: 'layoutMode', value: newMode })
|
||||
}
|
||||
|
||||
const changeRole = async (roleId: number) => {
|
||||
await userStore.changeRole(roleId)
|
||||
location.reload()
|
||||
}
|
||||
|
||||
const handleValidityClick = () => {
|
||||
// Logic to redirect to renewal page if needed
|
||||
router.push('/auth/approve')
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
await userStore.logout()
|
||||
router.push(`/login?redirect=${route.fullPath}`)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
calculateDays()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.navbar {
|
||||
height: 45px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
background-color: #cab1f8;
|
||||
//box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
|
||||
|
||||
.logo {
|
||||
float: left;
|
||||
margin-left: 25px;
|
||||
margin-right: 10px;
|
||||
width: 120px;
|
||||
height: 45px;
|
||||
}
|
||||
|
||||
.hamburger-container {
|
||||
height: 45px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
float: left;
|
||||
cursor: pointer;
|
||||
transition: background .3s;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 0, 0, .025)
|
||||
}
|
||||
}
|
||||
|
||||
.breadcrumb-container {
|
||||
float: left;
|
||||
height: 45px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.top-menu-wrapper {
|
||||
float: left;
|
||||
height: 45px;
|
||||
margin-left: 10px;
|
||||
|
||||
:deep(.top-menu-container) {
|
||||
background-color: transparent !important;
|
||||
border-bottom: none !important;
|
||||
|
||||
.top-menu {
|
||||
height: 45px !important;
|
||||
background-color: transparent !important;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.right-menu {
|
||||
float: right;
|
||||
height: 45px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-right: 20px;
|
||||
&:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.right-menu-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0 12px;
|
||||
height: 45px;
|
||||
font-size: 14px;
|
||||
color: #5a5e66;
|
||||
vertical-align: text-bottom;
|
||||
cursor: pointer;
|
||||
transition: background .3s;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 0, 0, .025)
|
||||
}
|
||||
|
||||
&.validity-item {
|
||||
font-size: 12px;
|
||||
.validity-icon {
|
||||
margin-right: 4px;
|
||||
}
|
||||
.remaining-days {
|
||||
font-weight: bold;
|
||||
margin: 0 2px;
|
||||
font-size: 14px;
|
||||
}
|
||||
&.is-warning {
|
||||
color: #e6a23c;
|
||||
}
|
||||
&.is-expired {
|
||||
color: #f56c6c;
|
||||
}
|
||||
}
|
||||
|
||||
.menu-item-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
.menu-text {
|
||||
margin-left: 4px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.avatar-container {
|
||||
.avatar-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
position: relative;
|
||||
|
||||
.user-name {
|
||||
margin-right: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.user-avatar {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.el-icon-caret-bottom {
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
right: -16px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.text-danger { color: #f56c6c; }
|
||||
.text-warning { color: #e6a23c; }
|
||||
.text-success { color: #67c23a; }
|
||||
.user-dropdown {
|
||||
.on {
|
||||
background-color: #ecf5ff;
|
||||
color: #409EFF;
|
||||
font-weight: bold;
|
||||
}
|
||||
}
|
||||
|
||||
.view-btn {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.view-change,
|
||||
.ai-btn ,
|
||||
.ai-img {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
background-color: #409EFF;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
|
||||
73
src/layout/component/Sidebar/Item.vue
Normal file
@ -0,0 +1,73 @@
|
||||
<template>
|
||||
<div class="vertical-menu-item" :class="{ 'horizontal-item': settingsStore.layoutMode === 'top-bottom' }">
|
||||
<div class="menu-icon-wrapper">
|
||||
</div>
|
||||
<span v-if="title" class="menu-title">{{ $t("menu." + title) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
|
||||
const settingsStore = useSettingsStore()
|
||||
|
||||
defineProps({
|
||||
icon: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
default: ''
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.vertical-menu-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.horizontal-item {
|
||||
padding: 10px;
|
||||
|
||||
.menu-icon-wrapper {
|
||||
margin-bottom: 0;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.menu-title {
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
.menu-icon-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.menu-icon {
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.menu-title {
|
||||
font-size: 12px;
|
||||
line-height: 1.2;
|
||||
text-align: center;
|
||||
word-break: break-all;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
max-width: 100%;
|
||||
}
|
||||
</style>
|
||||
38
src/layout/component/Sidebar/Link.vue
Normal file
@ -0,0 +1,38 @@
|
||||
<template>
|
||||
<component :is="type" v-bind="linkProps(to)">
|
||||
<slot />
|
||||
</component>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { isExternal as isExternalFn } from '@/utils/validate'
|
||||
|
||||
const props = defineProps({
|
||||
to: {
|
||||
type: String,
|
||||
required: true
|
||||
}
|
||||
})
|
||||
|
||||
const isExternal = computed(() => isExternalFn(props.to))
|
||||
const type = computed(() => {
|
||||
if (isExternal.value) {
|
||||
return 'a'
|
||||
}
|
||||
return 'router-link'
|
||||
})
|
||||
|
||||
const linkProps = (to: string) => {
|
||||
if (isExternal.value) {
|
||||
return {
|
||||
href: to,
|
||||
target: '_blank',
|
||||
rel: 'noopener'
|
||||
}
|
||||
}
|
||||
return {
|
||||
to: to
|
||||
}
|
||||
}
|
||||
</script>
|
||||
136
src/layout/component/Sidebar/SidebarItem.vue
Normal file
@ -0,0 +1,136 @@
|
||||
<template>
|
||||
<div v-if="!item.hidden && !(item.meta && item.meta.hidden)">
|
||||
<template v-if="hasOneShowingChild(item.children, item) && (!onlyOneChild.children || onlyOneChild.noShowingChildren) && !item.alwaysShow">
|
||||
<app-link v-if="onlyOneChild.meta" :to="resolvePath(onlyOneChild.path)">
|
||||
<el-menu-item :index="resolvePath(onlyOneChild.path)" :class="{'submenu-title-noDropdown': !isNest}">
|
||||
<component
|
||||
:is="isNest ? SubItem : Item"
|
||||
:icon="onlyOneChild.meta.icon || (item.meta && item.meta.icon)"
|
||||
:title="onlyOneChild.name?.replace(/_Child$/, '')"
|
||||
:path="resolvePath(onlyOneChild.path)"
|
||||
/>
|
||||
</el-menu-item>
|
||||
</app-link>
|
||||
</template>
|
||||
|
||||
<el-sub-menu v-else ref="subMenu" :index="resolvePath(item.path)" popper-append-to-body>
|
||||
<template #title>
|
||||
<component
|
||||
:is="isNest ? SubItem : Item"
|
||||
v-if="item.meta"
|
||||
:icon="item.meta.icon"
|
||||
:title="item.name?.replace(/_Child$/, '')"
|
||||
:path="resolvePath(item.path)"
|
||||
/>
|
||||
</template>
|
||||
<sidebar-item
|
||||
v-for="child in item.children"
|
||||
:key="child.path"
|
||||
:is-nest="true"
|
||||
:item="child"
|
||||
:base-path="resolvePath(child.path)"
|
||||
:is-horizontal="isHorizontal"
|
||||
class="nest-menu"
|
||||
/>
|
||||
</el-sub-menu>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import path from 'path-browserify'
|
||||
import { isExternal } from '@/utils/validate'
|
||||
import Item from './Item.vue'
|
||||
import SubItem from './SubItem.vue'
|
||||
import AppLink from './Link.vue'
|
||||
|
||||
defineOptions({
|
||||
name: 'SidebarItem'
|
||||
})
|
||||
|
||||
const props = defineProps({
|
||||
item: {
|
||||
type: Object,
|
||||
required: true
|
||||
},
|
||||
isNest: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
},
|
||||
basePath: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
isHorizontal: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
}
|
||||
})
|
||||
|
||||
const onlyOneChild = ref<any>(null)
|
||||
|
||||
const hasOneShowingChild = (children: any[] = [], parent: any) => {
|
||||
const showingChildren = children.filter(item => {
|
||||
if (item.hidden || (item.meta && item.meta.hidden)) {
|
||||
return false
|
||||
} else {
|
||||
onlyOneChild.value = item
|
||||
return true
|
||||
}
|
||||
})
|
||||
|
||||
if (showingChildren.length === 1) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (showingChildren.length === 0) {
|
||||
onlyOneChild.value = { ...parent, path: '', noShowingChildren: true, name: parent.name }
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const resolvePath = (routePath: string) => {
|
||||
if (isExternal(routePath)) {
|
||||
return routePath
|
||||
}
|
||||
if (isExternal(props.basePath)) {
|
||||
return props.basePath
|
||||
}
|
||||
return path.resolve(props.basePath, routePath)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
/* Element Plus Menu Item Styles Override */
|
||||
:deep(.el-sub-menu__title),
|
||||
:deep(.el-menu-item) {
|
||||
height: auto !important;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
padding: 8px 10px !important;
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
/* Horizontal Mode Adjustment */
|
||||
:deep(.el-menu--horizontal) {
|
||||
.el-menu-item, .el-sub-menu__title {
|
||||
flex-direction: row !important;
|
||||
height: 50px !important;
|
||||
padding: 0 20px !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Nested menu indentation */
|
||||
.nest-menu {
|
||||
:deep(.el-menu-item),
|
||||
:deep(.el-sub-menu__title) {
|
||||
padding-left: 20px !important;
|
||||
flex-direction: row !important;
|
||||
height: 40px !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
103
src/layout/component/Sidebar/SubItem.vue
Normal file
@ -0,0 +1,103 @@
|
||||
<template>
|
||||
<div class="vertical-menu-item-sub">
|
||||
<div class="menu-info">
|
||||
<div class="menu-icon-wrapper">
|
||||
<svg-icon v-if="icon" :icon-class="icon" class="menu-icon" />
|
||||
</div>
|
||||
<span v-if="title" class="menu-title">{{ $t("menu." + title) }}</span>
|
||||
</div>
|
||||
<div class="shortcut-toggle" @click.stop.prevent="toggleShortcut">
|
||||
<el-icon :class="{ 'is-active': isShortcut }">
|
||||
<Star v-if="!isShortcut" />
|
||||
<StarFilled v-else />
|
||||
</el-icon>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { Star, StarFilled } from '@element-plus/icons-vue'
|
||||
import { useShortcutsStore } from '@/stores/modules/shortcuts'
|
||||
|
||||
const props = defineProps({
|
||||
icon: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
path: {
|
||||
type: String,
|
||||
default: ''
|
||||
}
|
||||
})
|
||||
|
||||
const shortcutsStore = useShortcutsStore()
|
||||
|
||||
const isShortcut = computed(() => {
|
||||
return shortcutsStore.isShortcut(props.path)
|
||||
})
|
||||
|
||||
const toggleShortcut = () => {
|
||||
shortcutsStore.toggleShortcut({
|
||||
title: props.title,
|
||||
path: props.path,
|
||||
icon: props.icon
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.vertical-menu-item-sub {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.menu-info {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.menu-icon-wrapper {
|
||||
width: 24px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-right: 12px;
|
||||
}
|
||||
|
||||
.menu-icon {
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.menu-title {
|
||||
font-size: 14px;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.shortcut-toggle {
|
||||
padding: 4px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
color: #909399;
|
||||
transition: color 0.3s;
|
||||
}
|
||||
|
||||
.shortcut-toggle:hover {
|
||||
color: #f7ba2a;
|
||||
}
|
||||
|
||||
.shortcut-toggle .is-active {
|
||||
color: #f7ba2a;
|
||||
}
|
||||
</style>
|
||||
67
src/layout/component/Sidebar/index.vue
Normal file
@ -0,0 +1,67 @@
|
||||
<template>
|
||||
<div :class="{'has-logo': showLogo}" @mouseleave="handleMouseLeave">
|
||||
<!-- Logo component if needed, skipping for now as not in file list explicitly but mentioned in settings -->
|
||||
<el-scrollbar wrap-class="scrollbar-wrapper">
|
||||
<el-menu
|
||||
:default-active="activeMenu"
|
||||
:collapse="isCollapse"
|
||||
:background-color="variables.menuBg"
|
||||
:text-color="variables.menuText"
|
||||
:unique-opened="false"
|
||||
:active-text-color="variables.menuActiveText"
|
||||
:collapse-transition="false"
|
||||
mode="vertical"
|
||||
class="vertical-layout-menu2"
|
||||
@click="handleMenuClick"
|
||||
>
|
||||
<sidebar-item v-for="route in permission_routes" :key="route.path" :item="route" :base-path="route.path" />
|
||||
</el-menu>
|
||||
</el-scrollbar>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useAppStore } from '@/stores/modules/app'
|
||||
import { usePermissionStore } from '@/stores/modules/permission'
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
import SidebarItem from './SidebarItem.vue'
|
||||
import variables from '@/styles/variables.module.scss'
|
||||
|
||||
const route = useRoute()
|
||||
const appStore = useAppStore()
|
||||
const permissionStore = usePermissionStore()
|
||||
const settingsStore = useSettingsStore()
|
||||
|
||||
const sidebar = computed(() => appStore.sidebar)
|
||||
const permission_routes = computed(() => permissionStore.routes)
|
||||
const showLogo = computed(() => settingsStore.sidebarLogo)
|
||||
const isCollapse = computed(() => !sidebar.value.opened)
|
||||
|
||||
const handleMenuClick = () => {
|
||||
if (isCollapse.value) {
|
||||
appStore.toggleSideBar()
|
||||
}
|
||||
}
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
if (appStore.sidebar.opened) {
|
||||
appStore.closeSideBar(false)
|
||||
}
|
||||
}
|
||||
|
||||
const activeMenu = computed(() => {
|
||||
const { meta, path } = route
|
||||
if (meta.activeMenu) {
|
||||
return meta.activeMenu as string
|
||||
}
|
||||
return path
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Reuse Vue 2 styles via global import or here */
|
||||
.sidebar-container {
|
||||
}
|
||||
</style>
|
||||
55
src/layout/component/TaskView/ScrollPane.vue
Normal file
@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<el-scrollbar ref="scrollContainer" :vertical="false" class="scroll-container" @wheel.prevent="handleScroll">
|
||||
<slot />
|
||||
</el-scrollbar>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { ElScrollbar } from 'element-plus'
|
||||
|
||||
const scrollContainer = ref<InstanceType<typeof ElScrollbar>>()
|
||||
|
||||
const emit = defineEmits(['scroll'])
|
||||
|
||||
const handleScroll = (e: WheelEvent) => {
|
||||
const eventDelta = (e as any).wheelDelta || -e.deltaY * 40
|
||||
const $scrollWrapper = scrollContainer.value?.$refs.wrapRef as HTMLElement
|
||||
$scrollWrapper.scrollLeft = $scrollWrapper.scrollLeft + eventDelta / 4
|
||||
}
|
||||
|
||||
const moveToTarget = (currentTag: HTMLElement) => {
|
||||
const $container = scrollContainer.value?.$el as HTMLElement
|
||||
const $containerWidth = $container.offsetWidth
|
||||
const $scrollWrapper = scrollContainer.value?.$refs.wrapRef as HTMLElement
|
||||
const $targetLeft = currentTag.offsetLeft
|
||||
const $targetWidth = currentTag.offsetWidth
|
||||
|
||||
if ($targetLeft < $scrollWrapper.scrollLeft) {
|
||||
// tag in the left
|
||||
$scrollWrapper.scrollLeft = $targetLeft
|
||||
} else if ($targetLeft + $targetWidth > $scrollWrapper.scrollLeft + $containerWidth) {
|
||||
// tag in the right
|
||||
$scrollWrapper.scrollLeft = $targetLeft + $targetWidth - $containerWidth
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
moveToTarget
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.scroll-container {
|
||||
white-space: nowrap;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
:deep(.el-scrollbar__bar) {
|
||||
bottom: 0px;
|
||||
}
|
||||
:deep(.el-scrollbar__wrap) {
|
||||
height: 55px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
411
src/layout/component/TaskView/index.vue
Normal file
@ -0,0 +1,411 @@
|
||||
<template>
|
||||
<div class="tags-view-container">
|
||||
<div class="navbar-wrapper">
|
||||
<navbar />
|
||||
</div>
|
||||
<div class="shortcut-key" v-show="shortcutExpanded">
|
||||
<component
|
||||
:is="isExternal(shortcut.path) ? 'a' : 'router-link'"
|
||||
v-for="shortcut in shortcuts"
|
||||
:key="shortcut.path"
|
||||
v-bind="isExternal(shortcut.path) ? { href: shortcut.path, target: '_blank' } : { to: shortcut.path }"
|
||||
class="shortcut-item"
|
||||
>
|
||||
<el-tooltip :content="$t('menu.' + shortcut.title)" placement="bottom" :show-after="500">
|
||||
<svg-icon v-if="shortcut.icon" :icon-class="shortcut.icon" />
|
||||
<span :style="{ marginLeft: shortcut.icon ? '5px' : '0' }">{{ $t('menu.' + shortcut.title) }}</span>
|
||||
</el-tooltip>
|
||||
</component>
|
||||
</div>
|
||||
<div class="shortcut-toggle" @click="toggleShortcut">
|
||||
<el-icon><ArrowUp v-if="shortcutExpanded" /><ArrowDown v-else /></el-icon>
|
||||
</div>
|
||||
<scroll-pane ref="scrollPane" class="tags-view-wrapper">
|
||||
<router-link
|
||||
v-for="tag in visitedViews"
|
||||
ref="tagsRef"
|
||||
:key="tag.path"
|
||||
:class="isActive(tag) ? 'active' : ''"
|
||||
:to="{ path: tag.path, query: tag.query }"
|
||||
class="tags-view-item"
|
||||
@click.middle="!isAffix(tag) && closeSelectedTag(tag)"
|
||||
@contextmenu.prevent="openMenu(tag, $event)"
|
||||
>
|
||||
{{ generateTitle(tag.name || tag.meta?.title) }}
|
||||
<span
|
||||
v-if="!isAffix(tag)"
|
||||
class="close-icon"
|
||||
@click.prevent.stop="closeSelectedTag(tag)"
|
||||
>x</span>
|
||||
</router-link>
|
||||
</scroll-pane>
|
||||
<ul v-show="visible" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
|
||||
<li @click="refreshSelectedTag(selectedTag)">{{ $t('common.refresh') || '刷新' }}</li>
|
||||
<li v-if="!isAffix(selectedTag)" @click="closeSelectedTag(selectedTag)">{{ $t('common.Close') || '关闭' }}</li>
|
||||
<li @click="closeOthersTags">{{ $t('common.Close Other') || '关闭其他' }}</li>
|
||||
<li @click="closeAllTags(selectedTag)">{{ $t('common.Close All') || '全部关闭' }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted, nextTick, onBeforeUpdate } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useTagsViewStore } from '@/stores/modules/tagsView'
|
||||
import { usePermissionStore } from '@/stores/modules/permission'
|
||||
import { useShortcutsStore } from '@/stores/modules/shortcuts'
|
||||
import ScrollPane from './ScrollPane.vue'
|
||||
import Navbar from '../Navbar.vue'
|
||||
import path from 'path-browserify'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { isExternal } from '@/utils/validate'
|
||||
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
|
||||
const { t, te } = useI18n()
|
||||
|
||||
const visible = ref(false)
|
||||
const top = ref(0)
|
||||
const left = ref(0)
|
||||
const selectedTag = ref<any>({})
|
||||
const affixTags = ref<any[]>([])
|
||||
const tagsRef = ref<any[]>([])
|
||||
|
||||
const tagsViewStore = useTagsViewStore()
|
||||
const permissionStore = usePermissionStore()
|
||||
const shortcutsStore = useShortcutsStore()
|
||||
const settingsStore = useSettingsStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const scrollPane = ref()
|
||||
|
||||
const visitedViews = computed(() => tagsViewStore.visitedViews)
|
||||
const routes = computed(() => permissionStore.routes)
|
||||
const shortcuts = computed(() => shortcutsStore.shortcuts)
|
||||
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
|
||||
|
||||
const toggleShortcut = () => {
|
||||
settingsStore.changeSetting({ key: 'shortcutExpanded', value: !shortcutExpanded.value })
|
||||
}
|
||||
|
||||
onBeforeUpdate(() => {
|
||||
tagsRef.value = []
|
||||
})
|
||||
|
||||
const isActive = (tag: any) => {
|
||||
return tag.path === route.path
|
||||
}
|
||||
|
||||
const isAffix = (tag: any) => {
|
||||
return tag.meta && tag.meta.affix
|
||||
}
|
||||
|
||||
const generateTitle = (title: any) => {
|
||||
const hasKey = te('menu.' + title)
|
||||
if (hasKey) {
|
||||
const translatedTitle = t('menu.' + title)
|
||||
return translatedTitle
|
||||
}
|
||||
return title || 'no-name'
|
||||
}
|
||||
|
||||
const filterAffixTags = (routes: any[], basePath = '/') => {
|
||||
let tags: any[] = []
|
||||
routes.forEach(route => {
|
||||
if (route.meta && route.meta.affix) {
|
||||
// Simple path resolve
|
||||
const tagPath = path.resolve(basePath, route.path)
|
||||
tags.push({
|
||||
fullPath: tagPath,
|
||||
path: tagPath,
|
||||
name: route.name,
|
||||
meta: { ...route.meta }
|
||||
})
|
||||
}
|
||||
if (route.children) {
|
||||
const tempTags = filterAffixTags(route.children, route.path)
|
||||
if (tempTags.length >= 1) {
|
||||
tags = [...tags, ...tempTags]
|
||||
}
|
||||
}
|
||||
})
|
||||
return tags
|
||||
}
|
||||
|
||||
const initTags = () => {
|
||||
const affixTagsArr = affixTags.value = filterAffixTags(routes.value)
|
||||
for (const tag of affixTagsArr) {
|
||||
if (tag.name) {
|
||||
tagsViewStore.addVisitedView(tag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const addTags = () => {
|
||||
const { name } = route
|
||||
if (name) {
|
||||
tagsViewStore.addView(route)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const moveToCurrentTag = () => {
|
||||
nextTick(() => {
|
||||
for (const [i, tag] of visitedViews.value.entries()) {
|
||||
if (tag.path === route.path) {
|
||||
const tagRef = tagsRef.value[i]
|
||||
if (tagRef) {
|
||||
// When using router-link with scoped slot or component, ref might be component instance
|
||||
// router-link renders an 'a' tag by default, but in Vue 3 it's a component.
|
||||
// Accessing $el gives the DOM element.
|
||||
scrollPane.value?.moveToTarget(tagRef.$el)
|
||||
}
|
||||
|
||||
if (tag.fullPath !== route.fullPath) {
|
||||
tagsViewStore.updateVisitedView(route)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const refreshSelectedTag = (view: any) => {
|
||||
tagsViewStore.delCachedView(view).then(() => {
|
||||
const { fullPath } = view
|
||||
nextTick(() => {
|
||||
router.replace({
|
||||
path: '/redirect' + fullPath
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const closeSelectedTag = (view: any) => {
|
||||
tagsViewStore.delView(view).then(({ visitedViews }: any) => {
|
||||
if (isActive(view)) {
|
||||
toLastView(visitedViews, view)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const closeOthersTags = () => {
|
||||
router.push(selectedTag.value)
|
||||
tagsViewStore.delOthersViews(selectedTag.value).then(() => {
|
||||
moveToCurrentTag()
|
||||
})
|
||||
}
|
||||
|
||||
const closeAllTags = (view: any) => {
|
||||
tagsViewStore.delAllViews().then(({ visitedViews }: any) => {
|
||||
if (affixTags.value.some(tag => tag.path === view.path)) {
|
||||
return
|
||||
}
|
||||
toLastView(visitedViews, view)
|
||||
})
|
||||
}
|
||||
|
||||
const toLastView = (visitedViews: any[], view: any) => {
|
||||
const latestView = visitedViews.slice(-1)[0]
|
||||
if (latestView) {
|
||||
router.push(latestView.fullPath)
|
||||
} else {
|
||||
if (view.name === 'Dashboard') {
|
||||
router.replace({ path: '/redirect' + view.fullPath })
|
||||
} else {
|
||||
router.push('/')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const openMenu = (tag: any, e: MouseEvent) => {
|
||||
const menuMinWidth = 105
|
||||
const offsetLeft = scrollPane.value?.$el.getBoundingClientRect().left // container margin left
|
||||
const offsetWidth = scrollPane.value?.$el.offsetWidth // container width
|
||||
const maxLeft = offsetWidth - menuMinWidth // left boundary
|
||||
const leftPos = e.clientX - offsetLeft + 15 // 15: margin right
|
||||
|
||||
if (leftPos > maxLeft) {
|
||||
left.value = maxLeft
|
||||
} else {
|
||||
left.value = leftPos
|
||||
}
|
||||
top.value = e.clientY
|
||||
visible.value = true
|
||||
selectedTag.value = tag
|
||||
}
|
||||
|
||||
const closeMenu = () => {
|
||||
visible.value = false
|
||||
}
|
||||
|
||||
watch(route, () => {
|
||||
addTags()
|
||||
moveToCurrentTag()
|
||||
})
|
||||
|
||||
watch(visible, (value) => {
|
||||
if (value) {
|
||||
document.body.addEventListener('click', closeMenu)
|
||||
} else {
|
||||
document.body.removeEventListener('click', closeMenu)
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
initTags()
|
||||
addTags()
|
||||
moveToCurrentTag() // Initial scroll to current tag
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.tags-view-container {
|
||||
height: auto;
|
||||
width: 100%;
|
||||
background: #fff;
|
||||
// border-bottom: 1px solid #d8dce5;
|
||||
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .12), 0 0 3px 0 rgba(0, 0, 0, .04);
|
||||
|
||||
.shortcut-toggle {
|
||||
height: 7px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
// background: #fafafa;
|
||||
// border-top: 1px solid #eee;
|
||||
border-bottom: 1px solid #eee;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
color: #000000;
|
||||
|
||||
&:hover {
|
||||
// background: #f0f2f5;
|
||||
// color: #409EFF;
|
||||
}
|
||||
}
|
||||
|
||||
.tags-view-wrapper {
|
||||
height: 40px;
|
||||
// border-bottom: 1px solid #d8dce5;
|
||||
// background-color: #e0dbdb;
|
||||
.tags-view-item {
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
height: 32px;
|
||||
line-height: 32px;
|
||||
// border: 1px solid #d8dce5;
|
||||
color: #495060;
|
||||
background: #b8b5b5;
|
||||
padding: 0 15px;
|
||||
font-size: 14px;
|
||||
margin-left: 5px;
|
||||
margin-top: 4px;
|
||||
text-decoration: none;
|
||||
&:first-of-type {
|
||||
margin-left: 15px;
|
||||
}
|
||||
&:last-of-type {
|
||||
margin-right: 15px;
|
||||
}
|
||||
&.active {
|
||||
background-color: #42b983;
|
||||
color: #fff;
|
||||
// border-color: #42b983;
|
||||
&::before {
|
||||
content: '';
|
||||
background: #fff;
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
position: relative;
|
||||
margin-right: 2px;
|
||||
}
|
||||
}
|
||||
.close-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
vertical-align: 2px;
|
||||
border-radius: 50%;
|
||||
text-align: center;
|
||||
transition: all .3s cubic-bezier(.645, .045, .355, 1);
|
||||
transform-origin: 100% 50%;
|
||||
margin-left: 5px;
|
||||
&:before {
|
||||
transform: scale(.6);
|
||||
display: inline-block;
|
||||
vertical-align: -3px;
|
||||
}
|
||||
&:hover {
|
||||
background-color: #b4bccc;
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.navbar-wrapper {
|
||||
height: 45px;
|
||||
}
|
||||
|
||||
|
||||
|
||||
.contextmenu {
|
||||
margin: 0;
|
||||
background: #fff;
|
||||
z-index: 3000;
|
||||
position: absolute;
|
||||
list-style-type: none;
|
||||
padding: 5px 0;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
color: #333;
|
||||
box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, .3);
|
||||
li {
|
||||
margin: 0;
|
||||
padding: 7px 16px;
|
||||
cursor: pointer;
|
||||
&:hover {
|
||||
background: #eee;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.shortcut-key {
|
||||
height: 30px;
|
||||
margin: 0 15px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
// padding-top: 7px;
|
||||
gap: 8px;
|
||||
background-color: #ffffff;
|
||||
|
||||
.shortcut-item {
|
||||
min-width: 70px;
|
||||
padding: 0px 10px;
|
||||
height: 24px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 4px;
|
||||
background-color: #dbdada;
|
||||
color: #606266;
|
||||
font-size: 13px;
|
||||
transition: all 0.3s;
|
||||
|
||||
&:hover {
|
||||
background-color: #e6e8eb;
|
||||
color: #409EFF;
|
||||
}
|
||||
|
||||
&.router-link-active {
|
||||
color: #409EFF;
|
||||
background-color: #ecf5ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
</style>
|
||||
88
src/layout/component/TopMenu.vue
Normal file
@ -0,0 +1,88 @@
|
||||
<template>
|
||||
<div class="top-menu-container">
|
||||
<el-menu
|
||||
:default-active="activeMenu"
|
||||
mode="horizontal"
|
||||
:background-color="variables.menuBg"
|
||||
:text-color="variables.menuText"
|
||||
:active-text-color="variables.menuActiveText"
|
||||
:ellipsis="false"
|
||||
class="top-menu"
|
||||
>
|
||||
<sidebar-item
|
||||
v-for="route in permission_routes"
|
||||
:key="route.path"
|
||||
:item="route"
|
||||
:base-path="route.path"
|
||||
:is-horizontal="true"
|
||||
/>
|
||||
</el-menu>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { usePermissionStore } from '@/stores/modules/permission'
|
||||
import SidebarItem from './Sidebar/SidebarItem.vue'
|
||||
import variables from '@/styles/variables.module.scss'
|
||||
|
||||
const route = useRoute()
|
||||
const permissionStore = usePermissionStore()
|
||||
|
||||
const permission_routes = computed(() => {
|
||||
// Filter out hidden routes
|
||||
return permissionStore.routes.filter((route: any) => !(route as any).hidden)
|
||||
})
|
||||
|
||||
const activeMenu = computed(() => {
|
||||
const { meta, path } = route
|
||||
if (meta.activeMenu) {
|
||||
return meta.activeMenu as string
|
||||
}
|
||||
return path
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.top-menu-container {
|
||||
width: 100%;
|
||||
height: 45px;
|
||||
background-color: v-bind('variables.menuBg');
|
||||
border-bottom: 1px solid #d8dce5;
|
||||
|
||||
.top-menu {
|
||||
border-bottom: none;
|
||||
height: 45px;
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
padding-left: 20px;
|
||||
/* Prevent menu items from wrapping and allow horizontal scroll when overflow */
|
||||
flex-wrap: nowrap;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
white-space: nowrap;
|
||||
/* Let the menu grow to its content so inner scroll works */
|
||||
min-width: max-content;
|
||||
|
||||
:deep(.el-menu-item), :deep(.el-sub-menu__title) {
|
||||
height: 40px !important;
|
||||
line-height: 40px !important;
|
||||
margin: 0px 4px;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
padding: 0 15px !important;
|
||||
display: inline-flex;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(0, 0, 0, 0.05) !important;
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.el-sub-menu__icon-arrow) {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
179
src/layout/index.vue
Normal file
@ -0,0 +1,179 @@
|
||||
<template>
|
||||
<div :class="classObj" class="app-wrapper">
|
||||
<div v-if="(device === 'mobile' || layoutMode === 'top-bottom') && sidebar.opened" class="drawer-bg"
|
||||
@click="handleClickOutside" />
|
||||
|
||||
<sidebar v-if="layoutMode !== 'top-bottom'" class="sidebar-container" />
|
||||
|
||||
<div class="main-container" :class="{ 'no-sidebar': layoutMode === 'top-bottom' }">
|
||||
<div :class="{ 'fixed-header': fixedHeader, 'fixed-header-top': layoutMode === 'top-bottom' }" :style="{ height: shortcutExpanded ? '134px' : '97px' }">
|
||||
<task-view />
|
||||
</div>
|
||||
<div v-if="fixedHeader" :style="{ height: shortcutExpanded ? '134px' : '97px' }"></div>
|
||||
<div class="main-box">
|
||||
<app-main />
|
||||
<transition name="ai-slide">
|
||||
<div class="ai-container" v-show="aiStore.isVisible" :style="{ top: shortcutExpanded ? '134px' : '97px', height: `calc(100vh - ${shortcutExpanded ? 134 : 97}px)` }">
|
||||
<ai-chat />
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, watch, onBeforeMount, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { useAppStore } from '@/stores/modules/app'
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
import { useAiStore } from '@/stores/modules/ai'
|
||||
import Sidebar from './component/Sidebar/index.vue'
|
||||
import TaskView from './component/TaskView/index.vue'
|
||||
import AppMain from './component/AppMain.vue'
|
||||
import AiChat from './component/AiChat/index.vue'
|
||||
import { useWindowSize } from '@vueuse/core'
|
||||
|
||||
const { width } = useWindowSize()
|
||||
const WIDTH = 992 // refer to Bootstrap's responsive design
|
||||
|
||||
const appStore = useAppStore()
|
||||
const settingsStore = useSettingsStore()
|
||||
const aiStore = useAiStore()
|
||||
|
||||
const sidebar = computed(() => appStore.sidebar)
|
||||
const device = computed(() => appStore.device)
|
||||
const fixedHeader = computed(() => settingsStore.fixedHeader)
|
||||
const layoutMode = computed(() => settingsStore.layoutMode)
|
||||
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
|
||||
|
||||
const classObj = computed(() => {
|
||||
return {
|
||||
hideSidebar: !sidebar.value.opened,
|
||||
openSidebar: sidebar.value.opened,
|
||||
withoutAnimation: sidebar.value.withoutAnimation,
|
||||
mobile: device.value === 'mobile',
|
||||
'layout-top-bottom': layoutMode.value === 'top-bottom'
|
||||
}
|
||||
})
|
||||
|
||||
watch(width, (val) => {
|
||||
if (val - 1 < WIDTH) {
|
||||
appStore.toggleDevice('mobile')
|
||||
appStore.closeSideBar(true)
|
||||
} else {
|
||||
appStore.toggleDevice('desktop')
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
const handleClickOutside = () => {
|
||||
appStore.closeSideBar(false)
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@use "@/styles/mixin.scss" as *;
|
||||
@use "@/styles/variables.scss" as *;
|
||||
|
||||
.app-main {
|
||||
padding: 0 !important;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.app-wrapper {
|
||||
@include clearfix;
|
||||
position: relative;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
|
||||
&.mobile.openSidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.drawer-bg {
|
||||
background: #000;
|
||||
opacity: 0.3;
|
||||
width: 100%;
|
||||
top: 0;
|
||||
height: 100%;
|
||||
position: absolute;
|
||||
z-index: 999;
|
||||
}
|
||||
|
||||
|
||||
|
||||
.fixed-header {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
z-index: 9;
|
||||
width: calc(100% - #{$sideBarWidth});
|
||||
transition: width 0.28s;
|
||||
min-height: 97px;
|
||||
max-height: 134px;
|
||||
|
||||
&.fixed-header-top {
|
||||
width: 100% !important;
|
||||
top: 0; // Menu is now inside Navbar
|
||||
}
|
||||
}
|
||||
|
||||
.hideSidebar .fixed-header {
|
||||
width: calc(100% - #{$sideBarCollapsedWidth})
|
||||
}
|
||||
|
||||
.hideSidebar .fixed-header-top {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
.mobile .fixed-header {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.main-container {
|
||||
min-height: 100%;
|
||||
transition: margin-left 0.28s;
|
||||
margin-left: #{$sideBarWidth};
|
||||
position: relative;
|
||||
|
||||
&.no-sidebar {
|
||||
margin-left: 0 !important;
|
||||
}
|
||||
}
|
||||
|
||||
.main-box {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
width: 100%;
|
||||
|
||||
:deep(.app-main) {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ai-container {
|
||||
width: 500px;
|
||||
height: auto;
|
||||
flex-shrink: 0;
|
||||
background-color: #fff;
|
||||
// border-left: 1px solid #e6e6e6;
|
||||
overflow: hidden;
|
||||
box-shadow: -2px 0 8px rgba(0,0,0,0.15);
|
||||
position: sticky;
|
||||
z-index: 10;
|
||||
}
|
||||
}
|
||||
|
||||
.ai-slide-enter-active,
|
||||
.ai-slide-leave-active {
|
||||
transition: width 0.3s ease-in-out, opacity 0.3s ease-in-out;
|
||||
}
|
||||
|
||||
.ai-slide-enter-from,
|
||||
.ai-slide-leave-to {
|
||||
width: 0;
|
||||
opacity: 0;
|
||||
}
|
||||
</style>
|
||||
26
src/main.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import 'virtual:svg-icons-register'
|
||||
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import './permission' // permission control
|
||||
import SvgIcon from '@/components/SvgIcon/index.vue'
|
||||
import i18n, { loadServerMessages } from '@/lang/index'
|
||||
|
||||
import '@/styles/index.scss' // global css
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
app.component('svg-icon', SvgIcon)
|
||||
app.use(createPinia())
|
||||
app.use(router)
|
||||
app.use(i18n)
|
||||
app.use(ElementPlus)
|
||||
|
||||
// 加载服务器国际化翻译
|
||||
loadServerMessages()
|
||||
|
||||
app.mount('#app')
|
||||
72
src/permission.ts
Normal file
@ -0,0 +1,72 @@
|
||||
import router from './router'
|
||||
import { useUserStore } from '@/stores/modules/user'
|
||||
import { usePermissionStore } from '@/stores/modules/permission'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import NProgress from 'nprogress'
|
||||
import 'nprogress/nprogress.css'
|
||||
import { getToken } from '@/utils/auth'
|
||||
import getPageTitle from '@/utils/get-page-title'
|
||||
|
||||
NProgress.configure({ showSpinner: false })
|
||||
|
||||
const whiteList = ['/login','/redirect']
|
||||
|
||||
router.beforeEach(async (to, from) => {
|
||||
NProgress.start()
|
||||
// console.log("路由表",router.getRoutes());
|
||||
document.title = getPageTitle(to.meta.title as string)
|
||||
|
||||
const hasToken = getToken()
|
||||
|
||||
if (hasToken) {
|
||||
if (to.path === '/login') {
|
||||
NProgress.done()
|
||||
return { path: '/' }
|
||||
} else {
|
||||
const userStore = useUserStore()
|
||||
const hasGetUserInfo = userStore.user && userStore.user.employees_name
|
||||
|
||||
if (hasGetUserInfo) {
|
||||
return true
|
||||
} else {
|
||||
try {
|
||||
// get user info
|
||||
const user = await userStore.getInfo()
|
||||
|
||||
const permissionStore = usePermissionStore()
|
||||
// generate accessible routes based on menus
|
||||
const accessRoutes = await permissionStore.generateRoutes(user.menus || [])
|
||||
// console.log("生成的路由表",accessRoutes);
|
||||
// dynamically add accessible routes
|
||||
accessRoutes.forEach(route => {
|
||||
router.addRoute(route)
|
||||
})
|
||||
|
||||
// hack method to ensure that addRoutes is complete
|
||||
// set the replace: true, so the navigation will not leave a history record
|
||||
return { ...to, replace: true }
|
||||
} catch (error) {
|
||||
// remove token and go to login page to re-login
|
||||
await userStore.resetToken()
|
||||
ElMessage.error((error as any).message || 'Has Error')
|
||||
NProgress.done()
|
||||
return `/login?redirect=${to.path}`
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
/* has no token*/
|
||||
if (whiteList.indexOf(to.path) !== -1) {
|
||||
// in the free login whitelist, go directly
|
||||
return true
|
||||
} else {
|
||||
// other pages that do not have permission to access are redirected to the login page.
|
||||
NProgress.done()
|
||||
return `/login?redirect=${to.path}`
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
router.afterEach(() => {
|
||||
NProgress.done()
|
||||
})
|
||||
221
src/router/index.ts
Normal file
@ -0,0 +1,221 @@
|
||||
import { createRouter, createWebHistory, RouterView } from 'vue-router'
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
import { getToken } from '@/utils/auth'
|
||||
import Layout from '@/layout/index.vue'
|
||||
import { usePermissionStore } from '@/stores/modules/permission'
|
||||
import { h } from 'vue'
|
||||
import { componentMap } from './map'
|
||||
|
||||
/**
|
||||
* 空白父级路由组件
|
||||
*/
|
||||
const ParentView = {
|
||||
name: 'ParentView',
|
||||
render: () => h(RouterView)
|
||||
}
|
||||
|
||||
/**
|
||||
* 基础路由 - 固定不变的路由
|
||||
*/
|
||||
export const constantRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/redirect',
|
||||
component: Layout,
|
||||
meta: { hidden: true },
|
||||
children: [
|
||||
{
|
||||
path: '/redirect/:path(.*)',
|
||||
component: () => import('@/views/redirect/index.vue')
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/login',
|
||||
name: 'Login',
|
||||
component: () => import('@/views/login/index.vue'),
|
||||
meta: { title: '登录', hidden: true }
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
component: Layout,
|
||||
redirect: '/dashboard',
|
||||
children: [
|
||||
{
|
||||
path: 'dashboard',
|
||||
name: 'Dashboard',
|
||||
component: () => import('@/views/dashboard/index.vue'),
|
||||
meta: {
|
||||
title: 'Dashboard',
|
||||
icon: 'dashboard',
|
||||
affix: true
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/message',
|
||||
component: Layout,
|
||||
meta: { hidden: true },
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
name: 'Message',
|
||||
component: () => import('@/views/message/index.vue'),
|
||||
meta: {
|
||||
title: '消息中心',
|
||||
icon: 'example',
|
||||
affix: false
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/profile',
|
||||
component: Layout,
|
||||
meta: { hidden: true },
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
name: 'Profile',
|
||||
component: () => import('@/views/profile/index.vue'),
|
||||
meta: {
|
||||
title: '个人中心',
|
||||
icon: 'user',
|
||||
affix: false
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/download',
|
||||
component: Layout,
|
||||
meta: { hidden: true },
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
name: 'Download',
|
||||
component: () => import('@/views/download/index.vue'),
|
||||
meta: {
|
||||
title: '下载中心',
|
||||
icon: 'link',
|
||||
affix: false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
/**
|
||||
* 404路由配置
|
||||
*/
|
||||
export const notFoundRoute: RouteRecordRaw = {
|
||||
path: '/:pathMatch(.*)*',
|
||||
redirect: '/404',
|
||||
meta: { hidden: true }
|
||||
}
|
||||
|
||||
export const notFoundPage: RouteRecordRaw = {
|
||||
path: '/404',
|
||||
name: 'Page404',
|
||||
component: () => import('@/views/404.vue'),
|
||||
meta: { hidden: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析组件路径
|
||||
*/
|
||||
function resolveComponent(componentPath: string) {
|
||||
if (componentMap[componentPath]) {
|
||||
return componentMap[componentPath]
|
||||
}
|
||||
|
||||
console.warn(`Component ${componentPath} not found in componentMap, using dynamic import`)
|
||||
|
||||
// 处理常见的目录结构,例如 'warehouse' -> 'warehouse/index.vue'
|
||||
if (!componentPath.includes('/')) {
|
||||
return () => import(`@/views/${componentPath}/index.vue`).catch(() => import(`@/views/${componentPath}.vue`))
|
||||
}
|
||||
|
||||
return () => import(`@/views/${componentPath}.vue`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将菜单数据转换为路由格式
|
||||
*/
|
||||
export const transformMenusToRoutes = (menus: any[]) => {
|
||||
if (!menus || !Array.isArray(menus)) {
|
||||
return []
|
||||
}
|
||||
|
||||
const transformRoute = (menu: any, parentName?: string): RouteRecordRaw => {
|
||||
let routeName = menu.name
|
||||
// 检查名称冲突:如果子路由名称与父路由名称相同,Vue Router 4 会报错
|
||||
if (routeName && parentName && routeName === parentName) {
|
||||
routeName = `${routeName}_Child`
|
||||
console.warn(`Route name conflict detected: ${parentName}. Child name changed to ${routeName}`)
|
||||
}
|
||||
|
||||
let routePath = menu.path
|
||||
const isExternal = /^(https?:|mailto:|tel:)/.test(routePath || '')
|
||||
// Vue Router 4 要求顶层路由路径必须以 / 开头
|
||||
if (!parentName && routePath && !routePath.startsWith('/') && !isExternal) {
|
||||
routePath = `/${routePath}`
|
||||
}
|
||||
|
||||
const route: any = {
|
||||
path: routePath,
|
||||
name: routeName,
|
||||
hidden: !!menu.hidden,
|
||||
alwaysShow: !!menu.alwaysShow,
|
||||
meta: {
|
||||
title: menu.meta?.title || menu.name || '',
|
||||
icon: menu.meta?.icon || '',
|
||||
noCache: !!menu.meta?.noCache,
|
||||
affix: !!menu.meta?.affix,
|
||||
breadcrumb: menu.meta?.breadcrumb !== false,
|
||||
activeMenu: menu.meta?.activeMenu,
|
||||
roles: menu.meta?.roles
|
||||
}
|
||||
}
|
||||
|
||||
if (menu.redirect) {
|
||||
route.redirect = menu.redirect
|
||||
}
|
||||
|
||||
if (menu.component) {
|
||||
if (menu.component === 'Layout') {
|
||||
route.component = Layout
|
||||
} else if (menu.component.startsWith('@/views/')) {
|
||||
const componentPath = menu.component.replace('@/views/', '')
|
||||
route.component = resolveComponent(componentPath)
|
||||
} else if (menu.component.startsWith('@/')) {
|
||||
const componentPath = menu.component.replace('@/', '')
|
||||
route.component = () => import(`@/${componentPath}.vue`)
|
||||
} else {
|
||||
route.component = () => import(`@/views/${menu.component}.vue`)
|
||||
}
|
||||
} else {
|
||||
if (!menu.children || menu.children.length === 0) {
|
||||
route.component = ParentView
|
||||
} else {
|
||||
route.component = Layout
|
||||
}
|
||||
}
|
||||
|
||||
if (menu.children && menu.children.length > 0) {
|
||||
route.children = menu.children.map((child: any) => transformRoute(child, routeName))
|
||||
}
|
||||
|
||||
return route as RouteRecordRaw
|
||||
}
|
||||
|
||||
return menus.map(menu => transformRoute(menu))
|
||||
}
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory('/'),
|
||||
routes: constantRoutes,
|
||||
scrollBehavior: () => ({ top: 0 })
|
||||
})
|
||||
|
||||
export default router
|
||||
19
src/router/map.ts
Normal file
@ -0,0 +1,19 @@
|
||||
export const componentMap: Record<string, any> = {
|
||||
'dashboard/index': () => import('@/views/dashboard/index.vue'),
|
||||
'login/index': () => import('@/views/login/index.vue'),
|
||||
'permission/index': () => import('@/views/permission/index.vue'),
|
||||
// 'system/setting/index': () => import('@/views/system/setting/index.vue'),
|
||||
'order/index': () => import('@/views/order/index.vue'),
|
||||
'auth/approve': () => import('@/views/auth/approve.vue'),
|
||||
'account/index': () => import('@/views/account/index.vue'),
|
||||
'warehouse/index': () => import('@/views/warehouse/index.vue'),
|
||||
'stock/index': () => import('@/views/stock/index.vue'),
|
||||
'stock/storestock/index': () => import('@/views/stock/storestock/index.vue'),
|
||||
'stock/combo_stock/index': () => import('@/views/stock/combo_stock/index.vue'),
|
||||
'storage/receiving': () => import('@/views/storage/receiving/index.vue'),
|
||||
'system/setting/printTemplate/index': () => import('@/views/system/setting/printTemplate/index.vue'),
|
||||
// 'system/setting/printStation/index': () => import('@/views/system/setting/printStation/index.vue'),
|
||||
'system/print/station': () => import('@/views/system/setting/printStation/index.vue'),
|
||||
// 'system/StoreManagement/station2': () => import('@/views/system/setting/printStation/index2.vue'),
|
||||
// 'system/setting/printStation': () => import('@/views/system/setting/printStation/index.vue'),
|
||||
};
|
||||
33
src/settings.ts
Normal file
@ -0,0 +1,33 @@
|
||||
export default {
|
||||
title: 'Vue Admin Template',
|
||||
|
||||
/**
|
||||
* @type {boolean} true | false
|
||||
* @description Whether show the settings right-panel
|
||||
*/
|
||||
showSettings: true,
|
||||
|
||||
/**
|
||||
* @type {boolean} true | false
|
||||
* @description Whether need tagsView
|
||||
*/
|
||||
tagsView: true,
|
||||
|
||||
/**
|
||||
* @type {boolean} true | false
|
||||
* @description Whether fix the header
|
||||
*/
|
||||
fixedHeader: true,
|
||||
|
||||
/**
|
||||
* @type {boolean} true | false
|
||||
* @description Whether show the logo in sidebar
|
||||
*/
|
||||
sidebarLogo: true,
|
||||
|
||||
/**
|
||||
* @type {boolean} true | false
|
||||
* @description Whether expand the shortcut key area
|
||||
*/
|
||||
shortcutExpanded: true
|
||||
}
|
||||
12
src/stores/counter.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { ref, computed } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useCounterStore = defineStore('counter', () => {
|
||||
const count = ref(0)
|
||||
const doubleCount = computed(() => count.value * 2)
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
|
||||
return { count, doubleCount, increment }
|
||||
})
|
||||
191
src/stores/modules/ai.ts
Normal file
@ -0,0 +1,191 @@
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export interface Message {
|
||||
role: 'user' | 'ai'
|
||||
content: string
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export interface ChatSession {
|
||||
id: string
|
||||
title: string
|
||||
messages: Message[]
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
export interface AiIdentity {
|
||||
key: string
|
||||
name: string
|
||||
icon: string
|
||||
description: string
|
||||
systemPrompt?: string
|
||||
}
|
||||
|
||||
export const AI_IDENTITIES: AiIdentity[] = [
|
||||
{
|
||||
key: 'assistant',
|
||||
name: 'General Assistant',
|
||||
icon: 'Service',
|
||||
description: 'Helpful general assistant',
|
||||
systemPrompt: 'You are a helpful general assistant.'
|
||||
}
|
||||
]
|
||||
|
||||
interface AiState {
|
||||
isVisible: boolean
|
||||
messages: Message[]
|
||||
sessions: ChatSession[]
|
||||
currentSessionId: string | null
|
||||
currentIdentityKey: string
|
||||
}
|
||||
|
||||
const getStorageKey = (identityKey: string) => `ai-chat-history-${identityKey}`
|
||||
|
||||
export const useAiStore = defineStore('ai', {
|
||||
state: (): AiState => {
|
||||
// Default to first identity
|
||||
const defaultIdentity = AI_IDENTITIES[0]?.key ?? 'assistant'
|
||||
let savedSessions: ChatSession[] = []
|
||||
|
||||
try {
|
||||
const stored = localStorage.getItem(getStorageKey(defaultIdentity))
|
||||
if (stored) {
|
||||
savedSessions = JSON.parse(stored)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load chat history', e)
|
||||
}
|
||||
|
||||
return {
|
||||
isVisible: false,
|
||||
messages: [],
|
||||
sessions: savedSessions,
|
||||
currentSessionId: null,
|
||||
currentIdentityKey: defaultIdentity
|
||||
}
|
||||
},
|
||||
getters: {
|
||||
currentIdentity: (state) => AI_IDENTITIES.find(i => i.key === state.currentIdentityKey) || AI_IDENTITIES[0]
|
||||
},
|
||||
actions: {
|
||||
toggleAiContainer() {
|
||||
this.isVisible = !this.isVisible
|
||||
},
|
||||
openAiContainer() {
|
||||
this.isVisible = true
|
||||
},
|
||||
closeAiContainer() {
|
||||
this.isVisible = false
|
||||
},
|
||||
setIdentity(identityKey: string) {
|
||||
if (this.currentIdentityKey === identityKey) return
|
||||
|
||||
// Save current session before switching if needed
|
||||
if (this.currentSessionId) {
|
||||
this.saveCurrentSession()
|
||||
}
|
||||
|
||||
this.currentIdentityKey = identityKey
|
||||
this.messages = []
|
||||
this.currentSessionId = null
|
||||
this.sessions = []
|
||||
|
||||
// Load sessions for new identity
|
||||
this.loadSessionsForIdentity()
|
||||
},
|
||||
loadSessionsForIdentity() {
|
||||
try {
|
||||
const stored = localStorage.getItem(getStorageKey(this.currentIdentityKey))
|
||||
if (stored) {
|
||||
this.sessions = JSON.parse(stored)
|
||||
} else {
|
||||
this.sessions = []
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load chat history for identity ' + this.currentIdentityKey, e)
|
||||
this.sessions = []
|
||||
}
|
||||
},
|
||||
addMessage(role: 'user' | 'ai', content: string) {
|
||||
this.messages.push({
|
||||
role,
|
||||
content,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
if (this.currentSessionId) {
|
||||
this.saveCurrentSession()
|
||||
}
|
||||
},
|
||||
startNewChat() {
|
||||
if (this.messages.length > 0 && !this.currentSessionId) {
|
||||
this.saveCurrentSession()
|
||||
}
|
||||
this.messages = []
|
||||
this.currentSessionId = null
|
||||
},
|
||||
saveCurrentSession() {
|
||||
if (this.messages.length === 0) return
|
||||
|
||||
const firstUserMsg = this.messages.find(m => m.role === 'user')
|
||||
const title = firstUserMsg ? firstUserMsg.content.slice(0, 20) : 'New Chat'
|
||||
|
||||
let session: ChatSession
|
||||
|
||||
if (this.currentSessionId) {
|
||||
const index = this.sessions.findIndex(s => s.id === this.currentSessionId)
|
||||
if (index !== -1) {
|
||||
const target = this.sessions[index]
|
||||
if (target) {
|
||||
target.messages = [...this.messages]
|
||||
}
|
||||
this._persist()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Create new session
|
||||
const newId = Date.now().toString()
|
||||
session = {
|
||||
id: newId,
|
||||
title,
|
||||
messages: [...this.messages],
|
||||
createdAt: Date.now()
|
||||
}
|
||||
this.sessions.unshift(session)
|
||||
this.currentSessionId = newId
|
||||
this._persist()
|
||||
},
|
||||
loadSession(sessionId: string) {
|
||||
const session = this.sessions.find(s => s.id === sessionId)
|
||||
if (session) {
|
||||
if (this.messages.length > 0 && this.currentSessionId !== sessionId) {
|
||||
this.saveCurrentSession()
|
||||
} else if (this.messages.length > 0 && !this.currentSessionId) {
|
||||
this.saveCurrentSession()
|
||||
}
|
||||
|
||||
this.messages = [...session.messages]
|
||||
this.currentSessionId = sessionId
|
||||
}
|
||||
},
|
||||
deleteSession(sessionId: string) {
|
||||
this.sessions = this.sessions.filter(s => s.id !== sessionId)
|
||||
if (this.currentSessionId === sessionId) {
|
||||
this.messages = []
|
||||
this.currentSessionId = null
|
||||
}
|
||||
this._persist()
|
||||
},
|
||||
clearHistory() {
|
||||
this.sessions = []
|
||||
this._persist()
|
||||
},
|
||||
_persist() {
|
||||
try {
|
||||
localStorage.setItem(getStorageKey(this.currentIdentityKey), JSON.stringify(this.sessions))
|
||||
} catch (e) {
|
||||
console.error('Failed to save chat history', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
46
src/stores/modules/app.ts
Normal file
@ -0,0 +1,46 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import Cookies from 'js-cookie'
|
||||
import { getLanguage } from '@/lang'
|
||||
|
||||
interface AppState {
|
||||
sidebar: {
|
||||
opened: boolean
|
||||
withoutAnimation: boolean
|
||||
}
|
||||
device: string
|
||||
language: string
|
||||
}
|
||||
|
||||
export const useAppStore = defineStore('app', {
|
||||
state: (): AppState => ({
|
||||
sidebar: {
|
||||
opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus')! : true,
|
||||
withoutAnimation: false
|
||||
},
|
||||
device: 'desktop',
|
||||
language: getLanguage()
|
||||
}),
|
||||
actions: {
|
||||
toggleSideBar() {
|
||||
this.sidebar.opened = !this.sidebar.opened
|
||||
this.sidebar.withoutAnimation = false
|
||||
if (this.sidebar.opened) {
|
||||
Cookies.set('sidebarStatus', '1')
|
||||
} else {
|
||||
Cookies.set('sidebarStatus', '0')
|
||||
}
|
||||
},
|
||||
closeSideBar(withoutAnimation: boolean) {
|
||||
Cookies.set('sidebarStatus', '0')
|
||||
this.sidebar.opened = false
|
||||
this.sidebar.withoutAnimation = withoutAnimation
|
||||
},
|
||||
toggleDevice(device: string) {
|
||||
this.device = device
|
||||
},
|
||||
setLanguage(language: string) {
|
||||
this.language = language
|
||||
Cookies.set('language', language)
|
||||
}
|
||||
}
|
||||
})
|
||||
39
src/stores/modules/permission.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { constantRoutes, transformMenusToRoutes, notFoundPage, notFoundRoute } from '@/router'
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
|
||||
interface PermissionState {
|
||||
routes: RouteRecordRaw[]
|
||||
addRoutes: RouteRecordRaw[]
|
||||
hasAddRoutes: boolean
|
||||
}
|
||||
|
||||
export const usePermissionStore = defineStore('permission', {
|
||||
state: (): PermissionState => ({
|
||||
routes: [],
|
||||
addRoutes: [],
|
||||
hasAddRoutes: false
|
||||
}),
|
||||
actions: {
|
||||
setRoutes(routes: RouteRecordRaw[]) {
|
||||
this.addRoutes = routes
|
||||
this.routes = constantRoutes.concat(routes)
|
||||
this.hasAddRoutes = true
|
||||
},
|
||||
generateRoutes(menus: any[]) {
|
||||
return new Promise<RouteRecordRaw[]>((resolve) => {
|
||||
let accessedRoutes: RouteRecordRaw[] = []
|
||||
// 如果有菜单数据,转换菜单为路由
|
||||
if (menus && menus.length > 0) {
|
||||
accessedRoutes = transformMenusToRoutes(menus) as RouteRecordRaw[]
|
||||
}
|
||||
|
||||
// 最后添加 404 路由,确保它在最后匹配
|
||||
const finalRoutes = [...accessedRoutes, notFoundPage, notFoundRoute]
|
||||
|
||||
this.setRoutes(finalRoutes)
|
||||
resolve(finalRoutes)
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
331
src/stores/modules/printTemplate.ts
Normal file
@ -0,0 +1,331 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
|
||||
interface TemplateInfo {
|
||||
template_name?: string
|
||||
width?: number
|
||||
height?: number
|
||||
dpi?: number
|
||||
createdAt?: string
|
||||
updatedAt?: string
|
||||
editable?: boolean
|
||||
businessType?: any
|
||||
id?: any
|
||||
}
|
||||
|
||||
interface History {
|
||||
past: any[]
|
||||
future: any[]
|
||||
maxSteps: number
|
||||
}
|
||||
|
||||
export const usePrintTemplateStore = defineStore('printTemplate', {
|
||||
state: () => ({
|
||||
// 模板对象树(平铺结构)
|
||||
templateObjects: [] as any[],
|
||||
// 模板信息
|
||||
templateInfo: {} as TemplateInfo,
|
||||
// 历史记录(用于撤销/重做)
|
||||
history: {
|
||||
past: [],
|
||||
future: [],
|
||||
maxSteps: 50
|
||||
} as History,
|
||||
|
||||
// 初始快照(用于完整重置)
|
||||
initialSnapshot: null as null | { info: TemplateInfo; objects: any[] },
|
||||
selectedElement: null as any,
|
||||
isSelectTable: false,
|
||||
editable: true
|
||||
}),
|
||||
|
||||
getters: {
|
||||
// 验证模板是否有效
|
||||
isValidTemplate: (state) => {
|
||||
try {
|
||||
const page = state.templateInfo.width
|
||||
return page !== undefined
|
||||
} catch (error) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
actions: {
|
||||
// 创建新模板
|
||||
createTemplate({ width, height, template_name }: { width?: number; height?: number; template_name?: string }) {
|
||||
this.templateObjects = []
|
||||
this.editable = true
|
||||
// 更新模板信息
|
||||
this.templateInfo = {
|
||||
template_name: template_name || '未命名模板',
|
||||
width: width || 75,
|
||||
height: height || 129,
|
||||
dpi: 203,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString()
|
||||
}
|
||||
// 清空历史
|
||||
this.history.past = []
|
||||
this.history.future = []
|
||||
},
|
||||
|
||||
// 删除元素
|
||||
deleteElement(id: string) {
|
||||
const element = this.templateObjects.find(el => el.id === id)
|
||||
if (!element) return
|
||||
|
||||
this.saveHistory() // 删除前保存
|
||||
|
||||
// 删除元素及其所有子元素
|
||||
const deleteRecursive = (elementId: string) => {
|
||||
// 删除所有子元素
|
||||
const children = this.templateObjects.filter(el => el.pid === elementId)
|
||||
children.forEach(child => deleteRecursive(child.id))
|
||||
|
||||
// 删除元素本身
|
||||
const index = this.templateObjects.findIndex(el => el.id === elementId)
|
||||
if (index !== -1) {
|
||||
this.templateObjects.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
deleteRecursive(id)
|
||||
|
||||
// 如果删除的是选中的元素,清空选中状态
|
||||
if (this.selectedElement?.id === id) {
|
||||
this.selectedElement = null
|
||||
}
|
||||
|
||||
this.templateInfo.updatedAt = new Date().toISOString()
|
||||
},
|
||||
|
||||
// 选择元素
|
||||
selectElement(selector: { id: string | null; tableCellId?: string; isSelectTable?: boolean }) {
|
||||
const { id, tableCellId, isSelectTable = false } = selector
|
||||
|
||||
if (id === null) {
|
||||
this.selectedElement = null
|
||||
return
|
||||
}
|
||||
|
||||
if (tableCellId) {
|
||||
const tableElement = this.templateObjects.find(el => el.id === id)
|
||||
if (!tableElement) return
|
||||
const cellElement = tableElement.rows.find((c: any) => c.id === tableCellId)
|
||||
if (!cellElement) return
|
||||
this.selectedElement = cellElement
|
||||
this.isSelectTable = true
|
||||
return
|
||||
}
|
||||
|
||||
this.isSelectTable = isSelectTable
|
||||
this.selectedElement = this.templateObjects.find(el => el.id === id)
|
||||
},
|
||||
|
||||
// 清空选中状态
|
||||
clearSelection() {
|
||||
this.selectedElement = null
|
||||
},
|
||||
|
||||
// 复制元素
|
||||
duplicateElement(id: string) {
|
||||
const sourceElement = this.templateObjects.find(el => el.id === id)
|
||||
if (!sourceElement) return
|
||||
|
||||
this.saveHistory() // 复制前保存
|
||||
|
||||
const newElement = {
|
||||
...sourceElement,
|
||||
id: uuidv4(),
|
||||
left: (sourceElement.left || 0) + 10, // 稍微偏移
|
||||
top: (sourceElement.top || 0) + 10
|
||||
}
|
||||
|
||||
this.templateObjects.push(newElement)
|
||||
this.selectedElement = newElement
|
||||
this.templateInfo.updatedAt = new Date().toISOString()
|
||||
},
|
||||
|
||||
// 记录历史快照
|
||||
saveHistory() {
|
||||
// 限制历史记录步数
|
||||
if (this.history.past.length >= this.history.maxSteps) {
|
||||
this.history.past.shift()
|
||||
}
|
||||
|
||||
this.history.past.push({
|
||||
objects: JSON.parse(JSON.stringify(this.templateObjects)),
|
||||
info: JSON.parse(JSON.stringify(this.templateInfo))
|
||||
})
|
||||
// 每次新的操作产生,清空“未来”历史(重做历史)
|
||||
this.history.future = []
|
||||
},
|
||||
|
||||
// 撤销
|
||||
undo() {
|
||||
if (this.history.past.length === 0) return
|
||||
|
||||
// 将当前状态存入 future 以支持 redo (虽然目前没 UI 触发 redo)
|
||||
this.history.future.push({
|
||||
objects: JSON.parse(JSON.stringify(this.templateObjects)),
|
||||
info: JSON.parse(JSON.stringify(this.templateInfo))
|
||||
})
|
||||
|
||||
const prevState = this.history.past.pop()
|
||||
this.templateObjects = prevState.objects
|
||||
this.templateInfo = prevState.info
|
||||
|
||||
this.selectedElement = null // 撤销后清除选中,避免指向已不存在的对象
|
||||
this.isSelectTable = false
|
||||
this.templateInfo.updatedAt = new Date().toISOString()
|
||||
},
|
||||
|
||||
// 载入模板数据
|
||||
loadFromData(data: any[]) {
|
||||
this.templateObjects = data || []
|
||||
},
|
||||
|
||||
loadInfo(info: TemplateInfo) {
|
||||
this.templateInfo = {
|
||||
...this.templateInfo,
|
||||
...info
|
||||
}
|
||||
if (info.editable !== undefined) {
|
||||
this.editable = info.editable
|
||||
}
|
||||
},
|
||||
|
||||
addElement(elements: any) {
|
||||
this.saveHistory() // 添加前保存历史
|
||||
const createTime = new Date().toISOString()
|
||||
const newElement = {
|
||||
name: elements.name,
|
||||
left: 0,
|
||||
top: 0,
|
||||
createdAt: createTime,
|
||||
updatedAt: createTime,
|
||||
id: uuidv4(),
|
||||
...elements
|
||||
}
|
||||
this.templateObjects.push(newElement)
|
||||
this.selectedElement = this.templateObjects.find(el => el.id === newElement.id)
|
||||
},
|
||||
|
||||
updateElementAction({ id, attributes, noHistory }: { id: string; attributes: any; noHistory?: boolean }) {
|
||||
const index = this.templateObjects.findIndex(el => el.id === id)
|
||||
if (index !== -1 && !noHistory) {
|
||||
this.saveHistory() // 更新前保存历史(除非明确指定不保存,如拖动中)
|
||||
}
|
||||
if (this.isSelectTable) {
|
||||
const tableIndex = this.templateObjects.findIndex(el => el.type === 'table')
|
||||
if (tableIndex !== -1 && this.selectedElement) {
|
||||
const cellIndex = this.templateObjects[tableIndex].rows.findIndex((c: any) => c.id === this.selectedElement.id)
|
||||
if (cellIndex !== -1) {
|
||||
Object.assign(this.templateObjects[tableIndex].rows[cellIndex], attributes)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if (index !== -1) {
|
||||
Object.assign(this.templateObjects[index], attributes)
|
||||
}
|
||||
},
|
||||
|
||||
async addTableObject(data: any) {
|
||||
data.id = uuidv4()
|
||||
let tableElement = this.templateObjects.find(el => el.type === 'table')
|
||||
|
||||
if (!tableElement) {
|
||||
this.addElement({
|
||||
name: 'table',
|
||||
type: 'table',
|
||||
headerHeight: 4,
|
||||
rowHeight: 4,
|
||||
rows: [data],
|
||||
width: 100,
|
||||
height: 20
|
||||
})
|
||||
} else {
|
||||
this.saveHistory() // 追加表格行前保存
|
||||
tableElement.rows.push(data)
|
||||
this.updateElementAction({ id: tableElement.id, attributes: { rows: tableElement.rows }, noHistory: true })
|
||||
}
|
||||
},
|
||||
|
||||
async addTemplateObject(data: any) {
|
||||
this.addElement(data)
|
||||
},
|
||||
|
||||
async updateTemplateObject({ id, attributes }: { id: string; attributes: any }) {
|
||||
this.updateElementAction({ id, attributes })
|
||||
},
|
||||
|
||||
async updateTemplateInfo(info: TemplateInfo) {
|
||||
this.loadInfo(info)
|
||||
},
|
||||
|
||||
async loadTemplate(data: any) {
|
||||
const info = {
|
||||
template_name: data.template_name || '未命名模板',
|
||||
width: data.page_width || 75,
|
||||
height: data.page_height || 129,
|
||||
businessType: data.business_type || null,
|
||||
id: data.id || null,
|
||||
editable: data.editable !== undefined ? data.editable : true
|
||||
}
|
||||
this.loadFromData(data.template_content)
|
||||
this.loadInfo(info)
|
||||
this.clearSelection()
|
||||
// 保存初始快照,用于 "重置为最初状态"
|
||||
try {
|
||||
this.initialSnapshot = {
|
||||
info: JSON.parse(JSON.stringify(this.templateInfo)),
|
||||
objects: JSON.parse(JSON.stringify(this.templateObjects))
|
||||
}
|
||||
} catch (e) {
|
||||
this.initialSnapshot = { info: { ...this.templateInfo }, objects: (this.templateObjects || []).slice() }
|
||||
}
|
||||
// 清空历史(加载新模板时,重置历史)
|
||||
this.history.past = []
|
||||
this.history.future = []
|
||||
},
|
||||
|
||||
// 完整重置为初始载入状态(撤销所有操作)
|
||||
resetTemplate() {
|
||||
if (!this.initialSnapshot) return
|
||||
try {
|
||||
this.templateInfo = JSON.parse(JSON.stringify(this.initialSnapshot.info))
|
||||
this.templateObjects = JSON.parse(JSON.stringify(this.initialSnapshot.objects))
|
||||
} catch (e) {
|
||||
this.templateInfo = { ...this.initialSnapshot.info }
|
||||
this.templateObjects = (this.initialSnapshot.objects || []).slice()
|
||||
}
|
||||
// 清空历史并清除选中
|
||||
this.history.past = []
|
||||
this.history.future = []
|
||||
this.selectedElement = null
|
||||
this.isSelectTable = false
|
||||
this.templateInfo.updatedAt = new Date().toISOString()
|
||||
},
|
||||
|
||||
// 更新初始快照(在保存成功后调用,使后续重置能恢复到此保存点)
|
||||
updateInitialSnapshot() {
|
||||
try {
|
||||
this.initialSnapshot = {
|
||||
info: JSON.parse(JSON.stringify(this.templateInfo)),
|
||||
objects: JSON.parse(JSON.stringify(this.templateObjects))
|
||||
}
|
||||
// 更新快照后,按理说也应该清空历史,因为现在这成了新的“最开始的模样”
|
||||
this.history.past = []
|
||||
this.history.future = []
|
||||
} catch (e) {
|
||||
this.initialSnapshot = { info: { ...this.templateInfo }, objects: (this.templateObjects || []).slice() }
|
||||
}
|
||||
},
|
||||
|
||||
removeTemplateObject(id: string) {
|
||||
this.deleteElement(id)
|
||||
}
|
||||
}
|
||||
})
|
||||
126
src/stores/modules/settings.ts
Normal file
@ -0,0 +1,126 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import defaultSettings from '@/settings'
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { useUserStore } from './user'
|
||||
|
||||
const { showSettings, tagsView, fixedHeader, sidebarLogo, shortcutExpanded } = defaultSettings
|
||||
|
||||
export const useSettingsStore = defineStore('settings', () => {
|
||||
const userStore = useUserStore()
|
||||
|
||||
const theme = ref('#1890ff')
|
||||
const showSettingsRef = ref(showSettings)
|
||||
const tagsViewRef = ref(tagsView)
|
||||
const fixedHeaderRef = ref(fixedHeader)
|
||||
const sidebarLogoRef = ref(sidebarLogo)
|
||||
const layoutMode = ref<'sidebar' | 'top-bottom'>('top-bottom')
|
||||
const shortcutExpandedRef = ref<boolean>(shortcutExpanded)
|
||||
|
||||
const storageKey = computed(() => {
|
||||
if (!userStore.user?.username && !userStore.user?.id) return null
|
||||
const userId = userStore.user.username || userStore.user.id || 'unknown'
|
||||
return `settings_${userId}_${userStore.roleId || 'default'}`
|
||||
})
|
||||
|
||||
const loadSettings = () => {
|
||||
if (!storageKey.value) return
|
||||
const saved = localStorage.getItem(storageKey.value)
|
||||
if (saved) {
|
||||
try {
|
||||
const parsed = JSON.parse(saved)
|
||||
if (typeof parsed.showSettings === 'boolean') showSettingsRef.value = parsed.showSettings
|
||||
if (typeof parsed.tagsView === 'boolean') tagsViewRef.value = parsed.tagsView
|
||||
if (typeof parsed.fixedHeader === 'boolean') fixedHeaderRef.value = parsed.fixedHeader
|
||||
if (typeof parsed.sidebarLogo === 'boolean') sidebarLogoRef.value = parsed.sidebarLogo
|
||||
if (typeof parsed.layoutMode === 'string') layoutMode.value = parsed.layoutMode
|
||||
if (typeof parsed.shortcutExpanded === 'boolean') shortcutExpandedRef.value = parsed.shortcutExpanded
|
||||
} catch (e) {
|
||||
console.error('Failed to parse settings from storage', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const saveSettings = () => {
|
||||
if (!storageKey.value) return
|
||||
const payload = {
|
||||
showSettings: showSettingsRef.value,
|
||||
tagsView: tagsViewRef.value,
|
||||
fixedHeader: fixedHeaderRef.value,
|
||||
sidebarLogo: sidebarLogoRef.value,
|
||||
layoutMode: layoutMode.value,
|
||||
shortcutExpanded: shortcutExpandedRef.value
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(storageKey.value, JSON.stringify(payload))
|
||||
} catch (e) {
|
||||
console.error('Failed to save settings to storage', e)
|
||||
}
|
||||
}
|
||||
|
||||
// When user changes (login/logout/role change), reload settings for that user
|
||||
watch(storageKey, (newKey) => {
|
||||
if (newKey) {
|
||||
loadSettings()
|
||||
} else {
|
||||
// reset to defaults when there's no user
|
||||
showSettingsRef.value = showSettings
|
||||
tagsViewRef.value = tagsView
|
||||
fixedHeaderRef.value = fixedHeader
|
||||
sidebarLogoRef.value = sidebarLogo
|
||||
layoutMode.value = 'top-bottom'
|
||||
shortcutExpandedRef.value = shortcutExpanded
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
const changeSetting = ({ key, value }: { key: string; value: any }) => {
|
||||
if (!Object.prototype.hasOwnProperty.call({
|
||||
theme: 1,
|
||||
showSettings: 1,
|
||||
tagsView: 1,
|
||||
fixedHeader: 1,
|
||||
sidebarLogo: 1,
|
||||
layoutMode: 1,
|
||||
shortcutExpanded: 1
|
||||
}, key)) return
|
||||
|
||||
switch (key) {
|
||||
case 'theme':
|
||||
theme.value = value
|
||||
break
|
||||
case 'showSettings':
|
||||
showSettingsRef.value = value
|
||||
break
|
||||
case 'tagsView':
|
||||
tagsViewRef.value = value
|
||||
break
|
||||
case 'fixedHeader':
|
||||
fixedHeaderRef.value = value
|
||||
break
|
||||
case 'sidebarLogo':
|
||||
sidebarLogoRef.value = value
|
||||
break
|
||||
case 'layoutMode':
|
||||
layoutMode.value = value
|
||||
break
|
||||
case 'shortcutExpanded':
|
||||
shortcutExpandedRef.value = value
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
// persist user settings
|
||||
saveSettings()
|
||||
}
|
||||
|
||||
return {
|
||||
theme,
|
||||
showSettings: showSettingsRef,
|
||||
tagsView: tagsViewRef,
|
||||
fixedHeader: fixedHeaderRef,
|
||||
sidebarLogo: sidebarLogoRef,
|
||||
layoutMode,
|
||||
shortcutExpanded: shortcutExpandedRef,
|
||||
changeSetting
|
||||
}
|
||||
})
|
||||
139
src/stores/modules/shortcuts.ts
Normal file
@ -0,0 +1,139 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, watch, computed } from 'vue'
|
||||
import { useUserStore } from './user'
|
||||
import { usePermissionStore } from './permission'
|
||||
import router from '@/router'
|
||||
|
||||
export interface Shortcut {
|
||||
title: string
|
||||
path: string
|
||||
icon?: string
|
||||
}
|
||||
|
||||
export const useShortcutsStore = defineStore('shortcuts', () => {
|
||||
const userStore = useUserStore()
|
||||
const permissionStore = usePermissionStore()
|
||||
const shortcuts = ref<Shortcut[]>([])
|
||||
|
||||
// Create a unique key for storage based on user and role
|
||||
const storageKey = computed(() => {
|
||||
// Wait for user info to be available
|
||||
if (!userStore.user?.username && !userStore.user?.id) return null
|
||||
// Use a combination of username (or id) and roleId to ensure uniqueness per identity
|
||||
const userId = userStore.user.username || userStore.user.id || 'unknown'
|
||||
return `shortcuts_${userId}_${userStore.roleId || 'default'}`
|
||||
})
|
||||
|
||||
// Load from localStorage
|
||||
const loadShortcuts = () => {
|
||||
if (!storageKey.value) {
|
||||
shortcuts.value = []
|
||||
return
|
||||
}
|
||||
|
||||
const saved = localStorage.getItem(storageKey.value)
|
||||
if (saved) {
|
||||
try {
|
||||
const loaded: Shortcut[] = JSON.parse(saved)
|
||||
|
||||
// Filter out invalid routes based on current router configuration
|
||||
// This ensures users only see shortcuts for pages they currently have access to
|
||||
if (permissionStore.hasAddRoutes) {
|
||||
shortcuts.value = loaded.filter(s => {
|
||||
const resolved = router.resolve(s.path)
|
||||
// Check if route exists and is not a 404 page
|
||||
if (!resolved || resolved.matched.length === 0) return false
|
||||
// Check if it's the catch-all or 404 page
|
||||
const is404 = resolved.matched.some(r => r.name === 'Page404' || r.path === '/:pathMatch(.*)*' || r.redirect === '/404')
|
||||
if (is404) return false
|
||||
|
||||
// Update title/icon from current route meta if available to keep it fresh
|
||||
if (resolved.meta?.title) {
|
||||
s.title = resolved.meta.title as string
|
||||
}
|
||||
if (resolved.meta?.icon) {
|
||||
s.icon = resolved.meta.icon as string
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
} else {
|
||||
// If dynamic routes are not loaded yet, we can't fully validate.
|
||||
// However, we should still load the data so it's ready when routes arrive.
|
||||
// The validation will happen when hasAddRoutes becomes true (via watcher).
|
||||
shortcuts.value = loaded
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to parse shortcuts', e)
|
||||
shortcuts.value = []
|
||||
}
|
||||
} else {
|
||||
shortcuts.value = []
|
||||
}
|
||||
}
|
||||
|
||||
const saveShortcuts = () => {
|
||||
if (storageKey.value) {
|
||||
localStorage.setItem(storageKey.value, JSON.stringify(shortcuts.value))
|
||||
}
|
||||
}
|
||||
|
||||
const addShortcut = (shortcut: Shortcut) => {
|
||||
// Validate that the route exists in current permission routes
|
||||
const resolved = router.resolve(shortcut.path)
|
||||
let isValid = resolved && resolved.matched.length > 0
|
||||
if (isValid) {
|
||||
const is404 = resolved.matched.some(r => r.name === 'Page404' || r.path === '/:pathMatch(.*)*' || r.redirect === '/404')
|
||||
if (is404) isValid = false
|
||||
}
|
||||
|
||||
if (isValid && !shortcuts.value.find(s => s.path === shortcut.path)) {
|
||||
shortcuts.value.push(shortcut)
|
||||
saveShortcuts()
|
||||
}
|
||||
}
|
||||
|
||||
const removeShortcut = (path: string) => {
|
||||
const index = shortcuts.value.findIndex(s => s.path === path)
|
||||
if (index > -1) {
|
||||
shortcuts.value.splice(index, 1)
|
||||
saveShortcuts()
|
||||
}
|
||||
}
|
||||
|
||||
const toggleShortcut = (shortcut: Shortcut) => {
|
||||
if (isShortcut(shortcut.path)) {
|
||||
removeShortcut(shortcut.path)
|
||||
} else {
|
||||
addShortcut(shortcut)
|
||||
}
|
||||
}
|
||||
|
||||
const isShortcut = (path: string) => {
|
||||
return shortcuts.value.some(s => s.path === path)
|
||||
}
|
||||
|
||||
// Watch for storage key changes (user/role change)
|
||||
watch(storageKey, (newKey) => {
|
||||
if (newKey) {
|
||||
loadShortcuts()
|
||||
} else {
|
||||
shortcuts.value = []
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
// Watch for permission routes loaded to re-validate shortcuts
|
||||
watch(() => permissionStore.hasAddRoutes, (hasRoutes) => {
|
||||
if (hasRoutes && storageKey.value) {
|
||||
loadShortcuts()
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
shortcuts,
|
||||
addShortcut,
|
||||
removeShortcut,
|
||||
toggleShortcut,
|
||||
isShortcut
|
||||
}
|
||||
})
|
||||
131
src/stores/modules/tagsView.ts
Normal file
@ -0,0 +1,131 @@
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export interface TagView extends Partial<import('vue-router').RouteLocationNormalized> {
|
||||
title?: string
|
||||
}
|
||||
|
||||
interface TagsViewState {
|
||||
visitedViews: TagView[]
|
||||
cachedViews: string[]
|
||||
}
|
||||
|
||||
export const useTagsViewStore = defineStore('tagsView', {
|
||||
state: (): TagsViewState => ({
|
||||
visitedViews: [],
|
||||
cachedViews: []
|
||||
}),
|
||||
actions: {
|
||||
addView(view: TagView) {
|
||||
this.addVisitedView(view)
|
||||
this.addCachedView(view)
|
||||
},
|
||||
addVisitedView(view: TagView) {
|
||||
if (this.visitedViews.some(v => v.path === view.path)) return
|
||||
this.visitedViews.push(
|
||||
Object.assign({}, view, {
|
||||
title: view.meta?.title || 'no-name'
|
||||
})
|
||||
)
|
||||
},
|
||||
addCachedView(view: TagView) {
|
||||
if (this.cachedViews.includes(view.name as string)) return
|
||||
if (!view.meta?.noCache) {
|
||||
this.cachedViews.push(view.name as string)
|
||||
}
|
||||
},
|
||||
|
||||
delView(view: TagView) {
|
||||
return new Promise(resolve => {
|
||||
this.delVisitedView(view)
|
||||
this.delCachedView(view)
|
||||
resolve({
|
||||
visitedViews: [...this.visitedViews],
|
||||
cachedViews: [...this.cachedViews]
|
||||
})
|
||||
})
|
||||
},
|
||||
delVisitedView(view: TagView) {
|
||||
return new Promise(resolve => {
|
||||
for (const [i, v] of this.visitedViews.entries()) {
|
||||
if (v.path === view.path) {
|
||||
this.visitedViews.splice(i, 1)
|
||||
break
|
||||
}
|
||||
}
|
||||
resolve([...this.visitedViews])
|
||||
})
|
||||
},
|
||||
delCachedView(view: TagView) {
|
||||
return new Promise(resolve => {
|
||||
const index = this.cachedViews.indexOf(view.name as string)
|
||||
index > -1 && this.cachedViews.splice(index, 1)
|
||||
resolve([...this.cachedViews])
|
||||
})
|
||||
},
|
||||
|
||||
delOthersViews(view: TagView) {
|
||||
return new Promise(resolve => {
|
||||
this.delOthersVisitedViews(view)
|
||||
this.delOthersCachedViews(view)
|
||||
resolve({
|
||||
visitedViews: [...this.visitedViews],
|
||||
cachedViews: [...this.cachedViews]
|
||||
})
|
||||
})
|
||||
},
|
||||
delOthersVisitedViews(view: TagView) {
|
||||
return new Promise(resolve => {
|
||||
this.visitedViews = this.visitedViews.filter(v => {
|
||||
return v.meta?.affix || v.path === view.path
|
||||
})
|
||||
resolve([...this.visitedViews])
|
||||
})
|
||||
},
|
||||
delOthersCachedViews(view: TagView) {
|
||||
return new Promise(resolve => {
|
||||
const index = this.cachedViews.indexOf(view.name as string)
|
||||
if (index > -1) {
|
||||
this.cachedViews = this.cachedViews.slice(index, index + 1)
|
||||
} else {
|
||||
// if index < 0, there is no cached view
|
||||
this.cachedViews = []
|
||||
}
|
||||
resolve([...this.cachedViews])
|
||||
})
|
||||
},
|
||||
|
||||
delAllViews(view?: TagView) {
|
||||
return new Promise(resolve => {
|
||||
this.delAllVisitedViews()
|
||||
this.delAllCachedViews()
|
||||
resolve({
|
||||
visitedViews: [...this.visitedViews],
|
||||
cachedViews: [...this.cachedViews]
|
||||
})
|
||||
})
|
||||
},
|
||||
delAllVisitedViews() {
|
||||
return new Promise(resolve => {
|
||||
// keep affix tags
|
||||
const affixTags = this.visitedViews.filter(tag => tag.meta?.affix)
|
||||
this.visitedViews = affixTags
|
||||
resolve([...this.visitedViews])
|
||||
})
|
||||
},
|
||||
delAllCachedViews() {
|
||||
return new Promise(resolve => {
|
||||
this.cachedViews = []
|
||||
resolve([...this.cachedViews])
|
||||
})
|
||||
},
|
||||
|
||||
updateVisitedView(view: TagView) {
|
||||
for (let v of this.visitedViews) {
|
||||
if (v.path === view.path) {
|
||||
v = Object.assign(v, view)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
110
src/stores/modules/user.ts
Normal file
@ -0,0 +1,110 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { getToken, setToken, removeToken } from '@/utils/auth'
|
||||
import {
|
||||
login as apiLogin,
|
||||
getInfo as apiGetInfo,
|
||||
changeRole as apiChangeRole,
|
||||
logout as apiLogout
|
||||
} from '@/api/user'
|
||||
import { useAppStore } from './app'
|
||||
import { useTagsViewStore } from './tagsView'
|
||||
|
||||
interface UserInfo {
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
interface State {
|
||||
token: string | undefined
|
||||
user: UserInfo
|
||||
avatar: string
|
||||
roleId: number
|
||||
permissions: string[]
|
||||
}
|
||||
|
||||
const getDefaultState = (): State => ({
|
||||
token: getToken(),
|
||||
user: {},
|
||||
avatar: '',
|
||||
roleId: 0,
|
||||
permissions: []
|
||||
})
|
||||
|
||||
export const useUserStore = defineStore('user', {
|
||||
state: (): State => getDefaultState(),
|
||||
|
||||
actions: {
|
||||
async login(payload: { username: string; password: string }) {
|
||||
const { username, password } = payload
|
||||
const appStore = useAppStore()
|
||||
const resp = await apiLogin({
|
||||
username: username.trim(),
|
||||
password,
|
||||
device: appStore.device
|
||||
})
|
||||
const data = resp.data
|
||||
this.token = data.token
|
||||
setToken(data.token)
|
||||
return true
|
||||
},
|
||||
|
||||
async register(payload: any) {
|
||||
// Dynamically import the API module and call register if available to avoid static import error
|
||||
const apiModule: any = await import('@/api/user')
|
||||
if (typeof apiModule.register !== 'function') {
|
||||
throw new Error('register API is not available')
|
||||
}
|
||||
const resp = await apiModule.register(payload)
|
||||
return resp
|
||||
},
|
||||
|
||||
async getInfo() {
|
||||
const appStore = useAppStore()
|
||||
const resp = await apiGetInfo({ device: appStore.device })
|
||||
const data = resp.data
|
||||
if (!data) throw new Error('Verification failed, please Login again.')
|
||||
const user = data
|
||||
this.permissions = user.permissions || []
|
||||
this.user = user
|
||||
this.roleId = user.employees_id || 0
|
||||
return user
|
||||
},
|
||||
|
||||
async changeRole(roleId: number) {
|
||||
const appStore = useAppStore()
|
||||
const tagsViewStore = useTagsViewStore()
|
||||
const resp = await apiChangeRole({ roleId, device: appStore.device })
|
||||
const data = resp.data
|
||||
const user = data.user
|
||||
setToken(data.token)
|
||||
this.token = data.token
|
||||
this.user = user
|
||||
this.permissions = user.permissions || []
|
||||
this.roleId = user.employees_id || 0
|
||||
|
||||
// Reset tags view after role change
|
||||
await tagsViewStore.delAllViews()
|
||||
|
||||
return resp
|
||||
},
|
||||
|
||||
async logout() {
|
||||
await apiLogout({})
|
||||
removeToken()
|
||||
this.$reset()
|
||||
},
|
||||
|
||||
async resetToken() {
|
||||
removeToken()
|
||||
this.$reset()
|
||||
},
|
||||
|
||||
updateToken(token: string) {
|
||||
setToken(token)
|
||||
this.token = token
|
||||
},
|
||||
|
||||
checkPermission(key: string) {
|
||||
return this.permissions.includes(key)
|
||||
}
|
||||
}
|
||||
})
|
||||
49
src/styles/element-ui.scss
Normal file
@ -0,0 +1,49 @@
|
||||
// cover some element-ui styles
|
||||
|
||||
.el-breadcrumb__inner,
|
||||
.el-breadcrumb__inner a {
|
||||
font-weight: 400 !important;
|
||||
}
|
||||
|
||||
.el-upload {
|
||||
input[type="file"] {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
.el-upload__input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
|
||||
// to fixed https://github.com/ElemeFE/element/issues/2461
|
||||
.el-dialog {
|
||||
transform: none;
|
||||
left: 0;
|
||||
position: relative;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
// refine element ui upload
|
||||
.upload-container {
|
||||
.el-upload {
|
||||
width: 100%;
|
||||
|
||||
.el-upload-dragger {
|
||||
width: 100%;
|
||||
height: 200px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dropdown
|
||||
.el-dropdown-menu {
|
||||
a {
|
||||
display: block
|
||||
}
|
||||
}
|
||||
|
||||
// to fix el-date-picker css style
|
||||
.el-range-separator {
|
||||
box-sizing: content-box;
|
||||
}
|
||||
68
src/styles/index.scss
Normal file
@ -0,0 +1,68 @@
|
||||
@use './variables.scss' as *;
|
||||
@use './mixin.scss' as *;
|
||||
@use './transition.scss' as *;
|
||||
@use './element-ui.scss' as *;
|
||||
@use './sidebar.scss' as *;
|
||||
|
||||
body {
|
||||
height: 100%;
|
||||
margin:0;
|
||||
overflow: hidden;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
text-rendering: optimizeLegibility;
|
||||
font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
|
||||
}
|
||||
|
||||
label {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
html {
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
#app {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
*,
|
||||
*:before,
|
||||
*:after {
|
||||
box-sizing: inherit;
|
||||
}
|
||||
|
||||
a:focus,
|
||||
a:active {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
a,
|
||||
a:focus,
|
||||
a:hover {
|
||||
cursor: pointer;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
div:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.clearfix {
|
||||
&:after {
|
||||
visibility: hidden;
|
||||
display: block;
|
||||
font-size: 0;
|
||||
content: " ";
|
||||
clear: both;
|
||||
height: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// main-container global css
|
||||
.app-container {
|
||||
padding: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
28
src/styles/mixin.scss
Normal file
@ -0,0 +1,28 @@
|
||||
@mixin clearfix {
|
||||
&:after {
|
||||
content: "";
|
||||
display: table;
|
||||
clear: both;
|
||||
}
|
||||
}
|
||||
|
||||
@mixin scrollBar {
|
||||
&::-webkit-scrollbar-track-piece {
|
||||
background: #d3dce6;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: #99a9bf;
|
||||
border-radius: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
@mixin relative {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
263
src/styles/sidebar.scss
Normal file
@ -0,0 +1,263 @@
|
||||
@use './variables.scss' as *;
|
||||
#app {
|
||||
|
||||
.main-container {
|
||||
height: 100%;
|
||||
transition: margin-left .28s;
|
||||
margin-left: $sideBarWidth;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.sidebar-container {
|
||||
transition: width 0.28s;
|
||||
width: $sideBarWidth !important;
|
||||
border-right: 1px solid #dcdfe6;
|
||||
background-color: $menuBg;
|
||||
height: 100%;
|
||||
position: fixed;
|
||||
font-size: 0px;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 1001;
|
||||
overflow: hidden;
|
||||
|
||||
// reset element-ui css
|
||||
.horizontal-collapse-transition {
|
||||
transition: 0s width ease-in-out, 0s padding-left ease-in-out, 0s padding-right ease-in-out;
|
||||
}
|
||||
|
||||
.scrollbar-wrapper {
|
||||
overflow-x: hidden !important;
|
||||
}
|
||||
|
||||
.el-scrollbar__bar.is-vertical {
|
||||
right: 0px;
|
||||
}
|
||||
|
||||
.el-scrollbar {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
&.has-logo {
|
||||
.el-scrollbar {
|
||||
height: calc(100% - 50px);
|
||||
}
|
||||
}
|
||||
|
||||
.is-horizontal {
|
||||
display: none;
|
||||
}
|
||||
|
||||
a {
|
||||
display: inline-block;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.svg-icon {
|
||||
margin-right: 16px;
|
||||
}
|
||||
|
||||
.sub-el-icon {
|
||||
margin-right: 12px;
|
||||
margin-left: -2px;
|
||||
}
|
||||
|
||||
.el-menu {
|
||||
border: none;
|
||||
height: 100%;
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
// Increase menu item size
|
||||
.el-menu-item, .el-sub-menu__title {
|
||||
height: 60px !important;
|
||||
line-height: 60px !important;
|
||||
font-size: 16px !important;
|
||||
}
|
||||
|
||||
// menu hover
|
||||
.submenu-title-noDropdown,
|
||||
.el-sub-menu__title {
|
||||
&:hover {
|
||||
background-color: #99a9bf;
|
||||
// background-color: $menuHover !important;
|
||||
}
|
||||
}
|
||||
|
||||
.is-active>.el-sub-menu__title {
|
||||
i{
|
||||
color: $subMenuActiveText !important;
|
||||
}
|
||||
color: $subMenuActiveText !important;
|
||||
}
|
||||
|
||||
& .nest-menu .el-sub-menu>.el-sub-menu__title,
|
||||
& .el-sub-menu .el-menu-item {
|
||||
min-width: $sideBarWidth !important;
|
||||
background-color: #f4f4f5 !important;
|
||||
|
||||
&:hover {
|
||||
background-color: #e9e9eb !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.hideSidebar {
|
||||
.sidebar-container {
|
||||
width: $sideBarCollapsedWidth !important;
|
||||
}
|
||||
|
||||
.main-container {
|
||||
margin-left: $sideBarCollapsedWidth;
|
||||
}
|
||||
|
||||
.submenu-title-noDropdown {
|
||||
padding: 0 !important;
|
||||
position: relative;
|
||||
|
||||
.el-tooltip {
|
||||
padding: 0 !important;
|
||||
|
||||
.svg-icon {
|
||||
margin-left: 20px;
|
||||
}
|
||||
|
||||
.sub-el-icon {
|
||||
margin-left: 19px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.el-sub-menu {
|
||||
overflow: hidden;
|
||||
|
||||
&>.el-sub-menu__title {
|
||||
padding: 0 !important;
|
||||
|
||||
.svg-icon {
|
||||
margin-left: 20px;
|
||||
}
|
||||
|
||||
.sub-el-icon {
|
||||
margin-left: 19px;
|
||||
}
|
||||
|
||||
.el-sub-menu__icon-arrow {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.el-menu--collapse {
|
||||
.el-sub-menu {
|
||||
&>.el-sub-menu__title {
|
||||
&>span {
|
||||
height: 0;
|
||||
width: 0;
|
||||
overflow: hidden;
|
||||
visibility: hidden;
|
||||
display: inline-block;
|
||||
}
|
||||
/* Ensure arrow is hidden */
|
||||
.el-sub-menu__icon-arrow {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.el-menu--collapse .el-menu .el-sub-menu {
|
||||
min-width: $sideBarWidth !important;
|
||||
}
|
||||
|
||||
// mobile responsive
|
||||
.mobile {
|
||||
.main-container {
|
||||
margin-left: 0px;
|
||||
}
|
||||
|
||||
.sidebar-container {
|
||||
transition: transform .28s;
|
||||
width: $sideBarWidth !important;
|
||||
}
|
||||
|
||||
&.hideSidebar {
|
||||
.sidebar-container {
|
||||
pointer-events: none;
|
||||
transition-duration: 0.3s;
|
||||
transform: translate3d(-$sideBarWidth, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.withoutAnimation {
|
||||
|
||||
.main-container,
|
||||
.sidebar-container {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
// Layout Switch Styles (Top-Bottom)
|
||||
.layout-top-bottom {
|
||||
.main-container {
|
||||
margin-left: 0 !important;
|
||||
}
|
||||
|
||||
.sidebar-container {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.fixed-header {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
/* Ensure drawer background is hidden as sidebar is gone */
|
||||
.drawer-bg {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// when menu collapsed
|
||||
.el-menu--vertical {
|
||||
&>.el-menu {
|
||||
.svg-icon {
|
||||
margin-right: 16px;
|
||||
}
|
||||
.sub-el-icon {
|
||||
margin-right: 12px;
|
||||
margin-left: -2px;
|
||||
}
|
||||
}
|
||||
|
||||
.nest-menu .el-sub-menu>.el-sub-menu__title,
|
||||
.el-menu-item {
|
||||
&:hover {
|
||||
// you can use $subMenuHover
|
||||
background-color: $menuHover !important;
|
||||
}
|
||||
}
|
||||
|
||||
// the scroll bar appears when the subMenu is too long
|
||||
>.el-menu--popup {
|
||||
max-height: 100vh;
|
||||
overflow-y: auto;
|
||||
|
||||
&::-webkit-scrollbar-track-piece {
|
||||
background: #d3dce6;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: #99a9bf;
|
||||
border-radius: 20px;
|
||||
}
|
||||
}
|
||||
}
|
||||
53
src/styles/transition.scss
Normal file
@ -0,0 +1,53 @@
|
||||
// global transition css
|
||||
|
||||
/* fade */
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.28s;
|
||||
}
|
||||
|
||||
.fade-enter-from,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
/* fade-transform */
|
||||
.fade-transform-leave-active,
|
||||
.fade-transform-enter-active {
|
||||
transition: all .5s;
|
||||
}
|
||||
|
||||
.fade-transform-leave-active {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.fade-transform-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateX(-30px);
|
||||
}
|
||||
|
||||
.fade-transform-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateX(30px);
|
||||
}
|
||||
|
||||
/* breadcrumb transition */
|
||||
.breadcrumb-enter-active,
|
||||
.breadcrumb-leave-active {
|
||||
transition: all .5s;
|
||||
}
|
||||
|
||||
.breadcrumb-enter-from,
|
||||
.breadcrumb-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateX(20px);
|
||||
}
|
||||
|
||||
.breadcrumb-move {
|
||||
transition: all .5s;
|
||||
}
|
||||
|
||||
.breadcrumb-leave-active {
|
||||
position: absolute;
|
||||
}
|
||||
14
src/styles/variables.module.scss
Normal file
@ -0,0 +1,14 @@
|
||||
@use "./variables.scss" as *;
|
||||
|
||||
// the :export directive is the magic sauce for webpack
|
||||
// https://www.bluematador.com/blog/how-to-share-variables-between-js-and-sass
|
||||
:export {
|
||||
menuText: $menuText;
|
||||
menuActiveText: $menuActiveText;
|
||||
subMenuActiveText: $subMenuActiveText;
|
||||
menuBg: $menuBg;
|
||||
menuHover: $menuHover;
|
||||
subMenuBg: $subMenuBg;
|
||||
subMenuHover: $subMenuHover;
|
||||
sideBarWidth: $sideBarWidth;
|
||||
}
|
||||
13
src/styles/variables.scss
Normal file
@ -0,0 +1,13 @@
|
||||
// sidebar
|
||||
$menuText:rgba(0,0,0,.65);
|
||||
$menuActiveText:#653eb3;
|
||||
$subMenuActiveText:#653eb3; //https://github.com/ElemeFE/element/issues/12951
|
||||
|
||||
$menuBg:#FFF;
|
||||
$menuHover:#efeaf4;
|
||||
|
||||
$subMenuBg:#1f2d3d;
|
||||
$subMenuHover:#001528;
|
||||
|
||||
$sideBarWidth: 210px;
|
||||
$sideBarCollapsedWidth: 70px;
|
||||
978
src/utils/CanvasRenderer.js
Normal file
@ -0,0 +1,978 @@
|
||||
import { watch } from 'vue'
|
||||
|
||||
/**
|
||||
* Canvas 渲染工具类
|
||||
* 自动监听模板数据变化,渲染到 Canvas,支持元素选中和拖拽
|
||||
*/
|
||||
class CanvasRenderer {
|
||||
constructor(options = {}) {
|
||||
// 配置
|
||||
this.config = {
|
||||
dpi: 203,
|
||||
scale: 1,
|
||||
backgroundColor: '#ffffff',
|
||||
gridColor: '#e0e0e0',
|
||||
gridSize: 5, // mm
|
||||
showGrid: true,
|
||||
...options
|
||||
}
|
||||
|
||||
// Canvas 相关
|
||||
this.canvas = null
|
||||
this.ctx = null
|
||||
this.container = null
|
||||
|
||||
// 渲染状态
|
||||
this.isRendering = false
|
||||
this.needsRender = false
|
||||
this.lastRenderTime = 0
|
||||
this.renderDebounce = 16 // 约 60fps
|
||||
|
||||
// 模板数据
|
||||
this.templateData = null
|
||||
this.templateTree = null
|
||||
|
||||
// 交互状态
|
||||
this.selectedElementId = null
|
||||
this.hoveredElementId = null
|
||||
this.draggingElement = null
|
||||
this.dragStartPos = { x: 0, y: 0 }
|
||||
this.dragElementStartPos = { x: 0, y: 0 }
|
||||
|
||||
// 转换缓存
|
||||
this.mmToPixelCache = {}
|
||||
this.elementsCache = new Map()
|
||||
|
||||
// 事件监听器
|
||||
this.eventListeners = {
|
||||
select: [],
|
||||
update: [],
|
||||
render: []
|
||||
}
|
||||
|
||||
// 边界检查
|
||||
this.bounds = {
|
||||
minX: 0,
|
||||
minY: 0,
|
||||
maxX: 0,
|
||||
maxY: 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化 Canvas 渲染器
|
||||
* @param {HTMLCanvasElement} canvas - Canvas 元素
|
||||
* @param {HTMLElement} container - 容器元素(用于事件)
|
||||
*/
|
||||
initialize(canvas, container) {
|
||||
if (!canvas || !container) {
|
||||
throw new Error('Canvas 和容器元素不能为空')
|
||||
}
|
||||
|
||||
this.canvas = canvas
|
||||
this.container = container
|
||||
this.ctx = canvas.getContext('2d')
|
||||
|
||||
// 设置 Canvas 尺寸
|
||||
this.updateCanvasSize()
|
||||
|
||||
// 初始化事件监听
|
||||
this.initEventListeners()
|
||||
|
||||
// 初始化渲染循环
|
||||
this.initRenderLoop()
|
||||
|
||||
console.log('CanvasRenderer 初始化完成')
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置模板数据并开始监听
|
||||
* @param {Object} templateStore - 模板 Store(响应式对象)
|
||||
*/
|
||||
setTemplateData(templateStore) {
|
||||
try {
|
||||
|
||||
|
||||
if (!templateStore || !templateStore.templateObjects) {
|
||||
console.error('无效的模板数据')
|
||||
return
|
||||
}
|
||||
|
||||
this.templateData = templateStore
|
||||
|
||||
// 初始渲染
|
||||
this.scheduleRender()
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新 Canvas 尺寸
|
||||
*/
|
||||
updateCanvasSize() {
|
||||
if (!this.canvas || !this.container) return
|
||||
|
||||
const containerRect = this.container.getBoundingClientRect()
|
||||
const width = containerRect.width
|
||||
const height = containerRect.height
|
||||
|
||||
// 设置 Canvas 物理像素
|
||||
const dpr = window.devicePixelRatio || 1
|
||||
this.canvas.width = width * dpr
|
||||
this.canvas.height = height * dpr
|
||||
this.canvas.style.width = `${width}px`
|
||||
this.canvas.style.height = `${height}px`
|
||||
|
||||
// 缩放 Canvas 上下文
|
||||
this.ctx.scale(dpr, dpr)
|
||||
|
||||
this.scheduleRender()
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化事件监听
|
||||
*/
|
||||
initEventListeners() {
|
||||
if (!this.canvas || !this.container) return
|
||||
|
||||
// 点击事件 - 选择元素
|
||||
this.canvas.addEventListener('click', this.handleCanvasClick.bind(this))
|
||||
|
||||
// 鼠标移动事件 - 悬停效果
|
||||
this.canvas.addEventListener('mousemove', this.handleMouseMove.bind(this))
|
||||
|
||||
// 鼠标按下事件 - 开始拖拽
|
||||
this.canvas.addEventListener('mousedown', this.handleMouseDown.bind(this))
|
||||
|
||||
// 鼠标松开事件 - 结束拖拽
|
||||
document.addEventListener('mouseup', this.handleMouseUp.bind(this))
|
||||
|
||||
// 鼠标离开事件
|
||||
this.canvas.addEventListener('mouseleave', this.handleMouseLeave.bind(this))
|
||||
|
||||
// 键盘事件 - 删除选中的元素
|
||||
document.addEventListener('keydown', this.handleKeyDown.bind(this))
|
||||
|
||||
// 窗口大小变化
|
||||
window.addEventListener('resize', this.handleResize.bind(this))
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除事件监听
|
||||
*/
|
||||
removeEventListeners() {
|
||||
if (!this.canvas) return
|
||||
|
||||
this.canvas.removeEventListener('click', this.handleCanvasClick)
|
||||
this.canvas.removeEventListener('mousemove', this.handleMouseMove)
|
||||
this.canvas.removeEventListener('mousedown', this.handleMouseDown)
|
||||
document.removeEventListener('mouseup', this.handleMouseUp)
|
||||
this.canvas.removeEventListener('mouseleave', this.handleMouseLeave)
|
||||
document.removeEventListener('keydown', this.handleKeyDown)
|
||||
window.removeEventListener('resize', this.handleResize)
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化渲染循环
|
||||
*/
|
||||
initRenderLoop() {
|
||||
const renderFrame = () => {
|
||||
if (this.needsRender) {
|
||||
this.render()
|
||||
this.needsRender = false
|
||||
}
|
||||
requestAnimationFrame(renderFrame)
|
||||
}
|
||||
requestAnimationFrame(renderFrame)
|
||||
}
|
||||
|
||||
/**
|
||||
* 安排渲染
|
||||
*/
|
||||
scheduleRender() {
|
||||
this.needsRender = true
|
||||
}
|
||||
|
||||
/**
|
||||
* 主渲染方法
|
||||
*/
|
||||
render() {
|
||||
if (!this.canvas || !this.ctx || !this.templateData) return
|
||||
|
||||
const startTime = performance.now()
|
||||
|
||||
// 清除画布
|
||||
this.clearCanvas()
|
||||
|
||||
// 绘制背景
|
||||
this.drawBackground()
|
||||
|
||||
// 绘制网格(如果启用)
|
||||
if (this.config.showGrid) {
|
||||
this.drawGrid()
|
||||
}
|
||||
|
||||
// 绘制模板
|
||||
this.drawTemplate()
|
||||
|
||||
// 绘制选中状态
|
||||
this.drawSelection()
|
||||
|
||||
// 绘制悬停状态
|
||||
this.drawHover()
|
||||
|
||||
// 绘制边界
|
||||
this.drawBounds()
|
||||
|
||||
this.lastRenderTime = performance.now() - startTime
|
||||
|
||||
// 触发渲染完成事件
|
||||
this.emit('render', {
|
||||
time: this.lastRenderTime,
|
||||
elements: this.templateData?.templateObjects?.length || 0
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除画布
|
||||
*/
|
||||
clearCanvas() {
|
||||
const width = this.canvas.width / (window.devicePixelRatio || 1)
|
||||
const height = this.canvas.height / (window.devicePixelRatio || 1)
|
||||
|
||||
this.ctx.save()
|
||||
this.ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||||
this.ctx.clearRect(0, 0, width, height)
|
||||
this.ctx.restore()
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制背景
|
||||
*/
|
||||
drawBackground() {
|
||||
const width = this.canvas.width / (window.devicePixelRatio || 1)
|
||||
const height = this.canvas.height / (window.devicePixelRatio || 1)
|
||||
|
||||
this.ctx.fillStyle = this.config.backgroundColor
|
||||
this.ctx.fillRect(0, 0, width, height)
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制网格
|
||||
*/
|
||||
drawGrid() {
|
||||
const width = this.canvas.width / (window.devicePixelRatio || 1)
|
||||
const height = this.canvas.height / (window.devicePixelRatio || 1)
|
||||
const gridSizePx = this.mmToPixel(this.config.gridSize)
|
||||
|
||||
this.ctx.strokeStyle = this.config.gridColor
|
||||
this.ctx.lineWidth = 0.5
|
||||
|
||||
// 绘制垂直线
|
||||
for (let x = 0; x <= width; x += gridSizePx) {
|
||||
this.ctx.beginPath()
|
||||
this.ctx.moveTo(x, 0)
|
||||
this.ctx.lineTo(x, height)
|
||||
this.ctx.stroke()
|
||||
}
|
||||
|
||||
// 绘制水平线
|
||||
for (let y = 0; y <= height; y += gridSizePx) {
|
||||
this.ctx.beginPath()
|
||||
this.ctx.moveTo(0, y)
|
||||
this.ctx.lineTo(width, y)
|
||||
this.ctx.stroke()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制模板
|
||||
*/
|
||||
drawTemplate() {
|
||||
if (!this.templateData?.templateObjects) return
|
||||
|
||||
// 获取页面元素
|
||||
const page = this.templateData.templateObjects.find(el => el.name === 'page')
|
||||
if (!page) return
|
||||
|
||||
// 计算偏移量(居中显示)
|
||||
const containerWidth = this.canvas.width / (window.devicePixelRatio || 1)
|
||||
const containerHeight = this.canvas.height / (window.devicePixelRatio || 1)
|
||||
const pageWidth = this.mmToPixel(page.width)
|
||||
const pageHeight = this.mmToPixel(page.height)
|
||||
|
||||
this.offsetX = (containerWidth - pageWidth) / 2
|
||||
this.offsetY = (containerHeight - pageHeight) / 2
|
||||
|
||||
// 保存上下文
|
||||
this.ctx.save()
|
||||
|
||||
// 应用偏移
|
||||
this.ctx.translate(this.offsetX, this.offsetY)
|
||||
|
||||
// 绘制页面背景
|
||||
this.ctx.fillStyle = '#ffffff'
|
||||
this.ctx.fillRect(0, 0, pageWidth, pageHeight)
|
||||
this.ctx.strokeStyle = '#cccccc'
|
||||
this.ctx.lineWidth = 1
|
||||
this.ctx.strokeRect(0, 0, pageWidth, pageHeight)
|
||||
|
||||
// 绘制所有元素
|
||||
this.templateData.templateObjects.forEach(element => {
|
||||
if (element.name !== 'page') {
|
||||
this.drawElement(element)
|
||||
}
|
||||
})
|
||||
|
||||
// 恢复上下文
|
||||
this.ctx.restore()
|
||||
|
||||
// 更新边界
|
||||
this.bounds = {
|
||||
minX: this.offsetX,
|
||||
minY: this.offsetY,
|
||||
maxX: this.offsetX + pageWidth,
|
||||
maxY: this.offsetY + pageHeight
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制单个元素
|
||||
* @param {Object} element - 元素对象
|
||||
*/
|
||||
drawElement(element) {
|
||||
const style = this.parseStyle(element.style)
|
||||
|
||||
// 应用样式
|
||||
this.ctx.save()
|
||||
|
||||
// 设置透明度
|
||||
this.ctx.globalAlpha = style.opacity || 1
|
||||
|
||||
// 绘制不同类型元素
|
||||
switch (element.name) {
|
||||
case 'text':
|
||||
this.drawTextElement(element, style)
|
||||
break
|
||||
case 'barcode':
|
||||
this.drawBarcodeElement(element, style)
|
||||
break
|
||||
case 'image':
|
||||
this.drawImageElement(element, style)
|
||||
break
|
||||
case 'line':
|
||||
this.drawLineElement(element, style)
|
||||
break
|
||||
case 'layout':
|
||||
this.drawLayoutElement(element, style)
|
||||
break
|
||||
default:
|
||||
console.warn(`未知元素类型: ${element.name}`)
|
||||
}
|
||||
|
||||
// 绘制元素边框(调试用)
|
||||
if (this.config.showDebugInfo) {
|
||||
this.drawElementDebugInfo(element)
|
||||
}
|
||||
|
||||
this.ctx.restore()
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制文本元素
|
||||
*/
|
||||
drawTextElement(element, style) {
|
||||
const x = this.mmToPixel(element.left || 0)
|
||||
const y = this.mmToPixel(element.top || 0)
|
||||
const width = this.mmToPixel(element.width || 50)
|
||||
const height = this.mmToPixel(element.height || 10)
|
||||
|
||||
// 设置文本样式
|
||||
this.ctx.fillStyle = style.color || element.color || '#000000'
|
||||
this.ctx.font = `${style.fontWeight || 'normal'} ${this.mmToPixel(style.fontSize || element.fontSize || 12)}px ${style.fontFamily || element.fontFamily || 'Arial'}`
|
||||
this.ctx.textAlign = style.align || element.align || 'left'
|
||||
this.ctx.textBaseline = 'top'
|
||||
|
||||
// 绘制文本
|
||||
const lines = (element.content || '').split('\n')
|
||||
const lineHeight = this.mmToPixel(style.lineHeight || element.lineHeight || element.fontSize || 12)
|
||||
|
||||
lines.forEach((line, index) => {
|
||||
const lineY = y + (lineHeight * index)
|
||||
|
||||
// 文本溢出处理
|
||||
if (style.overflow === 'ellipsis') {
|
||||
const metrics = this.ctx.measureText(line)
|
||||
if (metrics.width > width) {
|
||||
line = this.truncateText(line, width)
|
||||
}
|
||||
}
|
||||
|
||||
this.ctx.fillText(line, x, lineY)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制条码元素(简化版,实际应使用条码库)
|
||||
*/
|
||||
drawBarcodeElement(element, style) {
|
||||
const x = this.mmToPixel(element.left || 0)
|
||||
const y = this.mmToPixel(element.top || 0)
|
||||
const width = this.mmToPixel(element.width || 50)
|
||||
const height = this.mmToPixel(element.height || 20)
|
||||
|
||||
// 绘制条码背景
|
||||
this.ctx.fillStyle = '#ffffff'
|
||||
this.ctx.fillRect(x, y, width, height)
|
||||
this.ctx.strokeStyle = '#cccccc'
|
||||
this.ctx.strokeRect(x, y, width, height)
|
||||
|
||||
// 绘制模拟条码(实际项目应集成条码库)
|
||||
this.ctx.fillStyle = '#000000'
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const barWidth = width / 20
|
||||
const barHeight = Math.random() * height * 0.8
|
||||
const barX = x + i * barWidth
|
||||
const barY = y + (height - barHeight) / 2
|
||||
|
||||
if (Math.random() > 0.3) {
|
||||
this.ctx.fillRect(barX, barY, barWidth * 0.8, barHeight)
|
||||
}
|
||||
}
|
||||
|
||||
// 绘制条码文本
|
||||
if (!element.hideText) {
|
||||
this.ctx.fillStyle = '#000000'
|
||||
this.ctx.font = `${this.mmToPixel(8)}px Arial`
|
||||
this.ctx.textAlign = 'center'
|
||||
this.ctx.textBaseline = 'bottom'
|
||||
this.ctx.fillText(element.content || 'BARCODE', x + width / 2, y + height - 2)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制图片元素
|
||||
*/
|
||||
drawImageElement(element, style) {
|
||||
// 简化实现,实际项目需要加载图片
|
||||
const x = this.mmToPixel(element.left || 0)
|
||||
const y = this.mmToPixel(element.top || 0)
|
||||
const width = this.mmToPixel(element.width || 50)
|
||||
const height = this.mmToPixel(element.height || 50)
|
||||
|
||||
// 绘制图片占位
|
||||
this.ctx.fillStyle = '#f0f0f0'
|
||||
this.ctx.fillRect(x, y, width, height)
|
||||
this.ctx.strokeStyle = '#cccccc'
|
||||
this.ctx.strokeRect(x, y, width, height)
|
||||
|
||||
// 绘制图片图标
|
||||
this.ctx.fillStyle = '#999999'
|
||||
this.ctx.font = `${this.mmToPixel(10)}px Arial`
|
||||
this.ctx.textAlign = 'center'
|
||||
this.ctx.textBaseline = 'middle'
|
||||
this.ctx.fillText('📷', x + width / 2, y + height / 2)
|
||||
|
||||
// 绘制图片名称
|
||||
this.ctx.fillStyle = '#666666'
|
||||
this.ctx.font = `${this.mmToPixel(6)}px Arial`
|
||||
this.ctx.fillText(element.src ? element.src.split('/').pop() : '图片', x + width / 2, y + height + 5)
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制线条元素
|
||||
*/
|
||||
drawLineElement(element, style) {
|
||||
const startX = this.mmToPixel(element.startX || 0)
|
||||
const startY = this.mmToPixel(element.startY || 0)
|
||||
const endX = this.mmToPixel(element.endX || 50)
|
||||
const endY = this.mmToPixel(element.endY || 50)
|
||||
|
||||
// 设置线条样式
|
||||
this.ctx.strokeStyle = style.lineColor || element.lineColor || '#000000'
|
||||
this.ctx.lineWidth = this.mmToPixel(style.lineWidth || element.lineWidth || 1)
|
||||
|
||||
// 设置线条类型
|
||||
if (style.lineType === 'dashed') {
|
||||
this.ctx.setLineDash([5, 5])
|
||||
} else {
|
||||
this.ctx.setLineDash([])
|
||||
}
|
||||
|
||||
// 绘制线条
|
||||
this.ctx.beginPath()
|
||||
this.ctx.moveTo(startX, startY)
|
||||
this.ctx.lineTo(endX, endY)
|
||||
this.ctx.stroke()
|
||||
this.ctx.setLineDash([]) // 重置虚线
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制布局容器
|
||||
*/
|
||||
drawLayoutElement(element, style) {
|
||||
const x = this.mmToPixel(element.left || 0)
|
||||
const y = this.mmToPixel(element.top || 0)
|
||||
const width = this.mmToPixel(element.width || 100)
|
||||
const height = this.mmToPixel(element.height || 100)
|
||||
|
||||
// 绘制布局背景
|
||||
this.ctx.fillStyle = style.backgroundColor || 'rgba(200, 200, 255, 0.1)'
|
||||
this.ctx.fillRect(x, y, width, height)
|
||||
|
||||
// 绘制布局边框
|
||||
this.ctx.strokeStyle = style.borderColor || '#cccccc'
|
||||
this.ctx.lineWidth = 1
|
||||
this.ctx.strokeRect(x, y, width, height)
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制元素调试信息
|
||||
*/
|
||||
drawElementDebugInfo(element) {
|
||||
const x = this.mmToPixel(element.left || 0)
|
||||
const y = this.mmToPixel(element.top || 0)
|
||||
const width = this.mmToPixel(element.width || 0)
|
||||
const height = this.mmToPixel(element.height || 0)
|
||||
|
||||
this.ctx.strokeStyle = '#ff0000'
|
||||
this.ctx.lineWidth = 0.5
|
||||
this.ctx.strokeRect(x, y, width, height)
|
||||
|
||||
// 显示元素ID
|
||||
this.ctx.fillStyle = '#ff0000'
|
||||
this.ctx.font = '8px Arial'
|
||||
this.ctx.fillText(element.id.slice(0, 8), x, y - 5)
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制选中状态
|
||||
*/
|
||||
drawSelection() {
|
||||
if (!this.selectedElementId || !this.templateData) return
|
||||
|
||||
const element = this.templateData.templateObjects.find(el => el.id === this.selectedElementId)
|
||||
if (!element) return
|
||||
|
||||
this.drawElementHighlight(element, '#409eff', 2)
|
||||
|
||||
// 绘制控制点
|
||||
this.drawControlHandles(element)
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制悬停状态
|
||||
*/
|
||||
drawHover() {
|
||||
if (!this.hoveredElementId || !this.templateData || this.draggingElement) return
|
||||
|
||||
const element = this.templateData.templateObjects.find(el => el.id === this.hoveredElementId)
|
||||
if (!element) return
|
||||
|
||||
this.drawElementHighlight(element, '#67c23a', 1)
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制元素高亮
|
||||
*/
|
||||
drawElementHighlight(element, color, lineWidth) {
|
||||
const x = this.mmToPixel(element.left || 0)
|
||||
const y = this.mmToPixel(element.top || 0)
|
||||
const width = this.mmToPixel(element.width || 0)
|
||||
const height = this.mmToPixel(element.height || 0)
|
||||
|
||||
this.ctx.save()
|
||||
this.ctx.strokeStyle = color
|
||||
this.ctx.lineWidth = lineWidth
|
||||
this.ctx.setLineDash([5, 5])
|
||||
this.ctx.strokeRect(x, y, width, height)
|
||||
this.ctx.restore()
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制控制手柄
|
||||
*/
|
||||
drawControlHandles(element) {
|
||||
const x = this.mmToPixel(element.left || 0)
|
||||
const y = this.mmToPixel(element.top || 0)
|
||||
const width = this.mmToPixel(element.width || 0)
|
||||
const height = this.mmToPixel(element.height || 0)
|
||||
const handleSize = 6
|
||||
|
||||
// 定义控制点位置
|
||||
const handles = [
|
||||
{ x: x - handleSize/2, y: y - handleSize/2, type: 'nw' }, // 左上
|
||||
{ x: x + width/2 - handleSize/2, y: y - handleSize/2, type: 'n' }, // 上中
|
||||
{ x: x + width - handleSize/2, y: y - handleSize/2, type: 'ne' }, // 右上
|
||||
{ x: x - handleSize/2, y: y + height/2 - handleSize/2, type: 'w' }, // 左中
|
||||
{ x: x + width - handleSize/2, y: y + height/2 - handleSize/2, type: 'e' }, // 右中
|
||||
{ x: x - handleSize/2, y: y + height - handleSize/2, type: 'sw' }, // 左下
|
||||
{ x: x + width/2 - handleSize/2, y: y + height - handleSize/2, type: 's' }, // 下中
|
||||
{ x: x + width - handleSize/2, y: y + height - handleSize/2, type: 'se' } // 右下
|
||||
]
|
||||
|
||||
// 绘制控制点
|
||||
handles.forEach(handle => {
|
||||
this.ctx.fillStyle = '#ffffff'
|
||||
this.ctx.fillRect(handle.x + this.offsetX, handle.y + this.offsetY, handleSize, handleSize)
|
||||
this.ctx.strokeStyle = '#409eff'
|
||||
this.ctx.lineWidth = 1
|
||||
this.ctx.strokeRect(handle.x + this.offsetX, handle.y + this.offsetY, handleSize, handleSize)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制边界
|
||||
*/
|
||||
drawBounds() {
|
||||
this.ctx.save()
|
||||
this.ctx.strokeStyle = '#e0e0e0'
|
||||
this.ctx.lineWidth = 1
|
||||
this.ctx.setLineDash([2, 2])
|
||||
this.ctx.strokeRect(
|
||||
this.bounds.minX,
|
||||
this.bounds.minY,
|
||||
this.bounds.maxX - this.bounds.minX,
|
||||
this.bounds.maxY - this.bounds.minY
|
||||
)
|
||||
this.ctx.restore()
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件处理:画布点击
|
||||
*/
|
||||
handleCanvasClick(event) {
|
||||
if (!this.templateData) return
|
||||
|
||||
const rect = this.canvas.getBoundingClientRect()
|
||||
const x = event.clientX - rect.left - this.offsetX
|
||||
const y = event.clientY - rect.top - this.offsetY
|
||||
|
||||
// 查找点击的元素
|
||||
const clickedElement = this.findElementAtPoint(x, y)
|
||||
|
||||
if (clickedElement) {
|
||||
// 选择元素
|
||||
this.selectedElementId = clickedElement.id
|
||||
|
||||
// 更新 Store
|
||||
if (this.templateData.SELECT_ELEMENT) {
|
||||
this.templateData.SELECT_ELEMENT(clickedElement.id)
|
||||
}
|
||||
|
||||
// 触发选择事件
|
||||
this.emit('select', clickedElement)
|
||||
} else {
|
||||
// 点击空白处,清除选择
|
||||
this.selectedElementId = null
|
||||
if (this.templateData.CLEAR_SELECTION) {
|
||||
this.templateData.CLEAR_SELECTION()
|
||||
}
|
||||
}
|
||||
|
||||
this.scheduleRender()
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件处理:鼠标移动
|
||||
*/
|
||||
handleMouseMove(event) {
|
||||
if (!this.templateData) return
|
||||
|
||||
const rect = this.canvas.getBoundingClientRect()
|
||||
const x = event.clientX - rect.left - this.offsetX
|
||||
const y = event.clientY - rect.top - this.offsetY
|
||||
|
||||
// 拖拽处理
|
||||
if (this.draggingElement) {
|
||||
this.handleDragMove(x, y)
|
||||
return
|
||||
}
|
||||
|
||||
// 悬停处理
|
||||
const hoveredElement = this.findElementAtPoint(x, y)
|
||||
if (hoveredElement && hoveredElement.id !== this.hoveredElementId) {
|
||||
this.hoveredElementId = hoveredElement.id
|
||||
this.canvas.style.cursor = 'move'
|
||||
this.scheduleRender()
|
||||
} else if (!hoveredElement && this.hoveredElementId) {
|
||||
this.hoveredElementId = null
|
||||
this.canvas.style.cursor = 'default'
|
||||
this.scheduleRender()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件处理:鼠标按下
|
||||
*/
|
||||
handleMouseDown(event) {
|
||||
if (!this.templateData || !this.selectedElementId) return
|
||||
|
||||
const rect = this.canvas.getBoundingClientRect()
|
||||
const x = event.clientX - rect.left - this.offsetX
|
||||
const y = event.clientY - rect.top - this.offsetY
|
||||
|
||||
// 检查是否点击了选中的元素
|
||||
const element = this.templateData.templateObjects.find(el => el.id === this.selectedElementId)
|
||||
if (!element) return
|
||||
|
||||
const elementX = this.mmToPixel(element.left || 0)
|
||||
const elementY = this.mmToPixel(element.top || 0)
|
||||
const elementWidth = this.mmToPixel(element.width || 0)
|
||||
const elementHeight = this.mmToPixel(element.height || 0)
|
||||
|
||||
// 判断是否点击在元素范围内
|
||||
if (x >= elementX && x <= elementX + elementWidth &&
|
||||
y >= elementY && y <= elementY + elementHeight) {
|
||||
this.startDragging(element, x, y)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始拖拽
|
||||
*/
|
||||
startDragging(element, startX, startY) {
|
||||
this.draggingElement = element
|
||||
this.dragStartPos = { x: startX, y: startY }
|
||||
this.dragElementStartPos = {
|
||||
x: element.left || 0,
|
||||
y: element.top || 0
|
||||
}
|
||||
|
||||
this.canvas.style.cursor = 'grabbing'
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理拖拽移动
|
||||
*/
|
||||
handleDragMove(x, y) {
|
||||
if (!this.draggingElement || !this.templateData) return
|
||||
|
||||
// 计算移动距离(毫米)
|
||||
const deltaX = this.pixelToMm(x - this.dragStartPos.x)
|
||||
const deltaY = this.pixelToMm(y - this.dragStartPos.y)
|
||||
|
||||
// 计算新位置(对齐到网格)
|
||||
const gridSize = this.config.gridSize
|
||||
let newLeft = Math.round((this.dragElementStartPos.x + deltaX) / gridSize) * gridSize
|
||||
let newTop = Math.round((this.dragElementStartPos.y + deltaY) / gridSize) * gridSize
|
||||
|
||||
// 边界检查
|
||||
const page = this.templateData.templateObjects.find(el => el.name === 'page')
|
||||
if (page) {
|
||||
const maxX = page.width - (this.draggingElement.width || 0)
|
||||
const maxY = page.height - (this.draggingElement.height || 0)
|
||||
newLeft = Math.max(0, Math.min(newLeft, maxX))
|
||||
newTop = Math.max(0, Math.min(newTop, maxY))
|
||||
}
|
||||
|
||||
// 更新元素位置
|
||||
if (this.templateData.UPDATE_ELEMENT) {
|
||||
this.templateData.UPDATE_ELEMENT({
|
||||
id: this.draggingElement.id,
|
||||
attributes: { left: newLeft, top: newTop }
|
||||
})
|
||||
}
|
||||
|
||||
this.scheduleRender()
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件处理:鼠标松开
|
||||
*/
|
||||
handleMouseUp() {
|
||||
if (this.draggingElement) {
|
||||
this.draggingElement = null
|
||||
this.canvas.style.cursor = 'move'
|
||||
|
||||
// 触发更新事件
|
||||
this.emit('update', { type: 'dragEnd' })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件处理:鼠标离开
|
||||
*/
|
||||
handleMouseLeave() {
|
||||
if (this.hoveredElementId) {
|
||||
this.hoveredElementId = null
|
||||
this.scheduleRender()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件处理:键盘按下
|
||||
*/
|
||||
handleKeyDown(event) {
|
||||
if (!this.selectedElementId || !this.templateData) return
|
||||
|
||||
// 删除键
|
||||
if (event.key === 'Delete' || event.key === 'Backspace') {
|
||||
event.preventDefault()
|
||||
|
||||
if (this.templateData.DELETE_ELEMENT) {
|
||||
this.templateData.DELETE_ELEMENT(this.selectedElementId)
|
||||
this.selectedElementId = null
|
||||
this.scheduleRender()
|
||||
}
|
||||
}
|
||||
|
||||
// 方向键移动
|
||||
const moveStep = 1 // 1mm
|
||||
let deltaX = 0, deltaY = 0
|
||||
|
||||
switch (event.key) {
|
||||
case 'ArrowUp':
|
||||
deltaY = -moveStep
|
||||
break
|
||||
case 'ArrowDown':
|
||||
deltaY = moveStep
|
||||
break
|
||||
case 'ArrowLeft':
|
||||
deltaX = -moveStep
|
||||
break
|
||||
case 'ArrowRight':
|
||||
deltaX = moveStep
|
||||
break
|
||||
}
|
||||
|
||||
if (deltaX !== 0 || deltaY !== 0) {
|
||||
event.preventDefault()
|
||||
|
||||
const element = this.templateData.templateObjects.find(el => el.id === this.selectedElementId)
|
||||
if (element && this.templateData.UPDATE_ELEMENT) {
|
||||
const newLeft = (element.left || 0) + deltaX
|
||||
const newTop = (element.top || 0) + deltaY
|
||||
|
||||
this.templateData.UPDATE_ELEMENT({
|
||||
id: element.id,
|
||||
attributes: { left: newLeft, top: newTop }
|
||||
})
|
||||
|
||||
this.scheduleRender()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件处理:窗口大小变化
|
||||
*/
|
||||
handleResize() {
|
||||
this.updateCanvasSize()
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找指定坐标下的元素
|
||||
*/
|
||||
findElementAtPoint(x, y) {
|
||||
if (!this.templateData?.templateObjects) return null
|
||||
|
||||
// 反向遍历(后绘制的元素在上层)
|
||||
const elements = [...this.templateData.templateObjects].reverse()
|
||||
|
||||
for (const element of elements) {
|
||||
if (element.name === 'page') continue
|
||||
|
||||
const elementX = this.mmToPixel(element.left || 0)
|
||||
const elementY = this.mmToPixel(element.top || 0)
|
||||
const elementWidth = this.mmToPixel(element.width || 0)
|
||||
const elementHeight = this.mmToPixel(element.height || 0)
|
||||
|
||||
if (x >= elementX && x <= elementX + elementWidth &&
|
||||
y >= elementY && y <= elementY + elementHeight) {
|
||||
return element
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 毫米转像素
|
||||
*/
|
||||
mmToPixel(mm) {
|
||||
if (this.mmToPixelCache[mm] !== undefined) {
|
||||
return this.mmToPixelCache[mm]
|
||||
}
|
||||
|
||||
const pixels = (mm * this.config.dpi) / 25.4 * this.config.scale
|
||||
this.mmToPixelCache[mm] = pixels
|
||||
return pixels
|
||||
}
|
||||
|
||||
/**
|
||||
* 像素转毫米
|
||||
*/
|
||||
pixelToMm(pixel) {
|
||||
return (pixel * 25.4) / (this.config.dpi * this.config.scale)
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析样式字符串
|
||||
*/
|
||||
parseStyle(styleString) {
|
||||
if (!styleString) return {}
|
||||
|
||||
const style = {}
|
||||
const pairs = styleString.split(';').filter(Boolean)
|
||||
|
||||
pairs.forEach(pair => {
|
||||
const [key, value] = pair.split(':').map(s => s.trim())
|
||||
if (key && value) {
|
||||
style[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
return style
|
||||
}
|
||||
|
||||
/**
|
||||
* 截断文本
|
||||
*/
|
||||
truncateText(text, maxWidth) {
|
||||
let truncated = text
|
||||
const ellipsis = '...'
|
||||
|
||||
while (this.ctx.measureText(truncated + ellipsis).width > maxWidth && truncated.length > 1) {
|
||||
truncated = truncated.slice(0, -1)
|
||||
}
|
||||
|
||||
return truncated + ellipsis
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件发射
|
||||
*/
|
||||
on(event, callback) {
|
||||
if (!this.eventListeners[event]) {
|
||||
this.eventListeners[event] = []
|
||||
}
|
||||
this.eventListeners[event].push(callback)
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件触发
|
||||
*/
|
||||
emit(event, data) {
|
||||
if (this.eventListeners[event]) {
|
||||
this.eventListeners[event].forEach(callback => {
|
||||
callback(data)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 销毁
|
||||
*/
|
||||
destroy() {
|
||||
this.removeEventListeners()
|
||||
this.templateData = null
|
||||
this.canvas = null
|
||||
this.ctx = null
|
||||
this.container = null
|
||||
console.log('CanvasRenderer 已销毁')
|
||||
}
|
||||
}
|
||||
|
||||
export default CanvasRenderer
|
||||
1039
src/utils/CanvasRenderer.ts
Normal file
15
src/utils/auth.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import Cookies from 'js-cookie';
|
||||
|
||||
const TokenKey = 'token';
|
||||
|
||||
export function getToken(): string | undefined {
|
||||
return Cookies.get(TokenKey);
|
||||
}
|
||||
|
||||
export function setToken(token: string): void {
|
||||
Cookies.set(TokenKey, token);
|
||||
}
|
||||
|
||||
export function removeToken(): void {
|
||||
Cookies.remove(TokenKey);
|
||||
}
|
||||
10
src/utils/get-page-title.js
Normal file
@ -0,0 +1,10 @@
|
||||
import defaultSettings from '@/settings'
|
||||
|
||||
const title = defaultSettings.title || 'Vue Admin Template'
|
||||
|
||||
export default function getPageTitle(pageTitle) {
|
||||
if (pageTitle) {
|
||||
return `${pageTitle} - ${title}`
|
||||
}
|
||||
return `${title}`
|
||||
}
|
||||
10
src/utils/get-page-title.ts
Normal file
@ -0,0 +1,10 @@
|
||||
import defaultSettings from '@/settings'
|
||||
|
||||
const title = defaultSettings.title || 'Vue Admin Template'
|
||||
|
||||
export default function getPageTitle(pageTitle:any) {
|
||||
if (pageTitle) {
|
||||
return `${pageTitle} - ${title}`
|
||||
}
|
||||
return `${title}`
|
||||
}
|
||||
118
src/utils/index.js
Normal file
@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Created by PanJiaChen on 16/11/18.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Parse the time to string
|
||||
* @param {(Object|string|number)} time
|
||||
* @param {string} cFormat
|
||||
* @returns {string | null}
|
||||
*/
|
||||
export function parseTime(time, cFormat) {
|
||||
if (arguments.length === 0 || !time) {
|
||||
return null
|
||||
}
|
||||
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
|
||||
let date
|
||||
if (typeof time === 'object') {
|
||||
date = time
|
||||
} else {
|
||||
if ((typeof time === 'string')) {
|
||||
if ((/^[0-9]+$/.test(time))) {
|
||||
// support "1548221490638"
|
||||
time = parseInt(time)
|
||||
} else {
|
||||
// support safari
|
||||
// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
|
||||
time = time.replace(new RegExp(/-/gm), '/')
|
||||
}
|
||||
}
|
||||
|
||||
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(/{([ymdhisa])+}/g, (result, key) => {
|
||||
const value = formatObj[key]
|
||||
// Note: getDay() returns 0 on Sunday
|
||||
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
|
||||
return value.toString().padStart(2, '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 = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
|
||||
if (!search) {
|
||||
return {}
|
||||
}
|
||||
const obj = {}
|
||||
const searchArr = search.split('&')
|
||||
searchArr.forEach(v => {
|
||||
const index = v.indexOf('=')
|
||||
if (index !== -1) {
|
||||
const name = v.substring(0, index)
|
||||
const val = v.substring(index + 1, v.length)
|
||||
obj[name] = val
|
||||
}
|
||||
})
|
||||
return obj
|
||||
}
|
||||
|
||||
118
src/utils/index.ts
Normal file
@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Created by PanJiaChen on 16/11/18.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Parse the time to string
|
||||
* @param {(Object|string|number)} time
|
||||
* @param {string} cFormat
|
||||
* @returns {string | null}
|
||||
*/
|
||||
export function parseTime(time:any, cFormat:any) {
|
||||
if (arguments.length === 0 || !time) {
|
||||
return null
|
||||
}
|
||||
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
|
||||
let date
|
||||
if (typeof time === 'object') {
|
||||
date = time
|
||||
} else {
|
||||
if ((typeof time === 'string')) {
|
||||
if ((/^[0-9]+$/.test(time))) {
|
||||
// support "1548221490638"
|
||||
time = parseInt(time)
|
||||
} else {
|
||||
// support safari
|
||||
// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
|
||||
time = time.replace(new RegExp(/-/gm), '/')
|
||||
}
|
||||
}
|
||||
|
||||
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(/{([ymdhisa])+}/g, (result:any, key:any ) => {
|
||||
const value = formatObj[key as keyof typeof formatObj]
|
||||
// Note: getDay() returns 0 on Sunday
|
||||
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
|
||||
return value.toString().padStart(2, '0')
|
||||
})
|
||||
return time_str
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} time
|
||||
* @param {string} option
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatTime(time:any, option:any) {
|
||||
if (('' + time).length === 10) {
|
||||
time = parseInt(time) * 1000
|
||||
} else {
|
||||
time = +time
|
||||
}
|
||||
const d = new Date(time)
|
||||
const now = Date.now()
|
||||
|
||||
const diff = (now - d.getTime()) / 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:any) {
|
||||
const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
|
||||
if (!search) {
|
||||
return {}
|
||||
}
|
||||
const obj: Record<string, any> = {}
|
||||
const searchArr = search.split('&')
|
||||
searchArr.forEach(v => {
|
||||
const index = v.indexOf('=')
|
||||
if (index !== -1) {
|
||||
const name = v.substring(0, index)
|
||||
const val = v.substring(index + 1, v.length)
|
||||
obj[name] = val
|
||||
}
|
||||
})
|
||||
return obj
|
||||
}
|
||||
|
||||
371
src/utils/overlookControls.js
Normal file
@ -0,0 +1,371 @@
|
||||
//src/utils/overlookControls.js
|
||||
|
||||
import * as THREE from 'three'
|
||||
|
||||
// 辅助函数:厘米转Three.js单位(1单位=1cm)
|
||||
const cm = (value) => value // Three.js中直接使用厘米为单位
|
||||
|
||||
export class OverlookControls {
|
||||
constructor(camera, domElement, scene, config = {}) {
|
||||
this.camera = camera
|
||||
this.domElement = domElement
|
||||
this.scene = scene
|
||||
this.enabled = true
|
||||
|
||||
// 2.5D视角固定参数
|
||||
this.cameraAngle = Math.PI / 4 // 45度固定角度
|
||||
this.cameraPitch = 70 // 70度俯仰角(LOL风格)
|
||||
this.targetHeight = cm(0) // 目标在地面
|
||||
|
||||
// 相机高度(缩放)
|
||||
this.cameraHeight = cm(8000) // 初始高度80米
|
||||
this.minHeight = cm(4000) // 最小高度40米
|
||||
this.maxHeight = cm(20000) // 最大高度200米
|
||||
|
||||
// 目标位置(镜头中心点)
|
||||
this.target = new THREE.Vector3(0, 0, 0)
|
||||
|
||||
// 视野边界参数(类似LOL地图边界)
|
||||
this.boundaryMinX = config.boundaryMinX || cm(-30000)
|
||||
this.boundaryMaxX = config.boundaryMaxX || cm(30000)
|
||||
this.boundaryMinZ = config.boundaryMinZ || cm(-30000)
|
||||
this.boundaryMaxZ = config.boundaryMaxZ || cm(30000)
|
||||
|
||||
// 移动速度(厘米/秒)- 键盘速度加速2倍
|
||||
this.moveSpeed = {
|
||||
keyboard: cm(1600), // 键盘移动速度(原800 * 2)
|
||||
drag: cm(0.5) // 拖拽灵敏度系数
|
||||
}
|
||||
|
||||
// 鼠标拖拽控制
|
||||
this.isDragging = false
|
||||
this.dragStart = new THREE.Vector2()
|
||||
this.dragCurrent = new THREE.Vector2()
|
||||
this.lastDragPos = new THREE.Vector2()
|
||||
|
||||
// 点击地面检测
|
||||
this.raycaster = new THREE.Raycaster()
|
||||
this.mouse = new THREE.Vector2()
|
||||
this.groundObjects = []
|
||||
|
||||
// 键盘控制状态
|
||||
this.keys = {
|
||||
w: false, a: false, s: false, d: false,
|
||||
up: false, left: false, down: false, right: false
|
||||
}
|
||||
|
||||
// 区域边界检测
|
||||
this.areaBoundaries = []
|
||||
this.onAreaClick = null
|
||||
|
||||
// 初始化
|
||||
this.initControls()
|
||||
this.updateCameraPosition()
|
||||
}
|
||||
|
||||
initControls() {
|
||||
const canvas = this.domElement
|
||||
|
||||
// 鼠标按下开始拖拽
|
||||
const onMouseDown = (e) => {
|
||||
if (!this.enabled || e.button !== 0) return // 只响应左键
|
||||
|
||||
e.preventDefault()
|
||||
this.isDragging = true
|
||||
this.dragStart.set(e.clientX, e.clientY)
|
||||
this.lastDragPos.set(e.clientX, e.clientY)
|
||||
canvas.style.cursor = 'grabbing'
|
||||
}
|
||||
|
||||
// 鼠标移动处理拖拽
|
||||
const onMouseMove = (e) => {
|
||||
if (!this.enabled) return
|
||||
|
||||
this.dragCurrent.set(e.clientX, e.clientY)
|
||||
|
||||
if (this.isDragging) {
|
||||
const deltaX = this.dragCurrent.x - this.lastDragPos.x
|
||||
const deltaY = this.dragCurrent.y - this.lastDragPos.y
|
||||
|
||||
// 根据拖拽距离移动视角
|
||||
const moveX = -deltaX * this.moveSpeed.drag
|
||||
const moveZ = -deltaY * this.moveSpeed.drag
|
||||
|
||||
// 根据固定45度角度旋转移动方向
|
||||
const angle = -this.cameraAngle
|
||||
const cos = Math.cos(angle)
|
||||
const sin = Math.sin(angle)
|
||||
|
||||
const worldMoveX = (moveX * cos - moveZ * sin)
|
||||
const worldMoveZ = (moveX * sin + moveZ * cos)
|
||||
|
||||
this.setTargetPosition(
|
||||
this.target.x + worldMoveX,
|
||||
this.target.z + worldMoveZ
|
||||
)
|
||||
|
||||
this.lastDragPos.set(e.clientX, e.clientY)
|
||||
}
|
||||
}
|
||||
|
||||
// 鼠标释放停止拖拽
|
||||
const onMouseUp = (e) => {
|
||||
if (!this.enabled || e.button !== 0) return
|
||||
|
||||
this.isDragging = false
|
||||
canvas.style.cursor = 'grab'
|
||||
|
||||
// 检查是否是点击(移动距离很小)
|
||||
const dx = this.dragCurrent.x - this.dragStart.x
|
||||
const dy = this.dragCurrent.y - this.dragStart.y
|
||||
const dragDistance = Math.sqrt(dx * dx + dy * dy)
|
||||
|
||||
if (dragDistance < 5) {
|
||||
this.handleClick(e)
|
||||
}
|
||||
}
|
||||
|
||||
// 鼠标滚轮缩放
|
||||
const onWheel = (e) => {
|
||||
if (!this.enabled) return
|
||||
|
||||
e.preventDefault()
|
||||
const delta = e.deltaY > 0 ? 1.2 : 0.8
|
||||
const newHeight = this.cameraHeight * delta
|
||||
this.cameraHeight = THREE.MathUtils.clamp(newHeight, this.minHeight, this.maxHeight)
|
||||
this.updateCameraPosition()
|
||||
}
|
||||
|
||||
// 点击检测
|
||||
const handleClick = (e) => {
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
this.mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1
|
||||
this.mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1
|
||||
|
||||
this.raycaster.setFromCamera(this.mouse, this.camera)
|
||||
|
||||
// 1. 先检测是否点击了区域边界
|
||||
let areaClicked = false
|
||||
for (const area of this.areaBoundaries) {
|
||||
const intersects = this.raycaster.intersectObject(area.boundary)
|
||||
if (intersects.length > 0) {
|
||||
if (this.onAreaClick) {
|
||||
this.onAreaClick(area.areaId, area.areaName, area.areaType)
|
||||
}
|
||||
areaClicked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 如果没有点击区域,检测地面(仅显示标记,不移动)
|
||||
if (!areaClicked) {
|
||||
const intersects = this.raycaster.intersectObjects(this.groundObjects)
|
||||
if (intersects.length > 0) {
|
||||
const point = intersects[0].point
|
||||
this.showClickMarker(point)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 键盘事件
|
||||
const onKeyDown = (e) => {
|
||||
if (!this.enabled) return
|
||||
|
||||
switch(e.key.toLowerCase()) {
|
||||
case 'w': case 'arrowup': this.keys.w = this.keys.up = true; break
|
||||
case 'a': case 'arrowleft': this.keys.a = this.keys.left = true; break
|
||||
case 's': case 'arrowdown': this.keys.s = this.keys.down = true; break
|
||||
case 'd': case 'arrowright': this.keys.d = this.keys.right = true; break
|
||||
}
|
||||
}
|
||||
|
||||
const onKeyUp = (e) => {
|
||||
switch(e.key.toLowerCase()) {
|
||||
case 'w': case 'arrowup': this.keys.w = this.keys.up = false; break
|
||||
case 'a': case 'arrowleft': this.keys.a = this.keys.left = false; break
|
||||
case 's': case 'arrowdown': this.keys.s = this.keys.down = false; break
|
||||
case 'd': case 'arrowright': this.keys.d = this.keys.right = false; break
|
||||
}
|
||||
}
|
||||
|
||||
// 添加事件监听器
|
||||
canvas.addEventListener('mousedown', onMouseDown)
|
||||
canvas.addEventListener('mousemove', onMouseMove)
|
||||
canvas.addEventListener('mouseup', onMouseUp)
|
||||
canvas.addEventListener('wheel', onWheel)
|
||||
|
||||
// 键盘事件监听在window上
|
||||
window.addEventListener('keydown', onKeyDown)
|
||||
window.addEventListener('keyup', onKeyUp)
|
||||
|
||||
// 鼠标离开画布时停止拖拽
|
||||
canvas.addEventListener('mouseleave', () => {
|
||||
if (this.isDragging) {
|
||||
this.isDragging = false
|
||||
canvas.style.cursor = 'grab'
|
||||
}
|
||||
})
|
||||
|
||||
// 初始化光标样式
|
||||
canvas.style.cursor = 'grab'
|
||||
|
||||
// 保存事件处理器以便清理
|
||||
this.eventHandlers = {
|
||||
onMouseDown, onMouseMove, onMouseUp, onWheel,
|
||||
onKeyDown, onKeyUp, handleClick
|
||||
}
|
||||
this.handleClick = handleClick
|
||||
}
|
||||
|
||||
setTargetPosition(x, z) {
|
||||
// 限制目标位置在边界内
|
||||
const clampedX = THREE.MathUtils.clamp(x, this.boundaryMinX, this.boundaryMaxX)
|
||||
const clampedZ = THREE.MathUtils.clamp(z, this.boundaryMinZ, this.boundaryMaxZ)
|
||||
|
||||
this.target.x = clampedX
|
||||
this.target.z = clampedZ
|
||||
|
||||
this.updateCameraPosition()
|
||||
}
|
||||
|
||||
updateCameraPosition() {
|
||||
// 固定2.5D视角计算
|
||||
const phi = THREE.MathUtils.degToRad(90 - this.cameraPitch)
|
||||
const theta = this.cameraAngle
|
||||
|
||||
const x = this.target.x + this.cameraHeight * Math.sin(phi) * Math.cos(theta)
|
||||
const y = this.target.y + this.cameraHeight * Math.cos(phi)
|
||||
const z = this.target.z + this.cameraHeight * Math.sin(phi) * Math.sin(theta)
|
||||
|
||||
this.camera.position.set(x, y, z)
|
||||
this.camera.lookAt(this.target)
|
||||
}
|
||||
|
||||
update(deltaTime) {
|
||||
if (!this.enabled) return
|
||||
|
||||
// 键盘控制(速度加倍)
|
||||
let moveX = 0, moveZ = 0
|
||||
if (this.keys.w || this.keys.up) moveZ += 1
|
||||
if (this.keys.s || this.keys.down) moveZ -= 1
|
||||
if (this.keys.a || this.keys.left) moveX -= 1
|
||||
if (this.keys.d || this.keys.right) moveX += 1
|
||||
|
||||
if (moveX !== 0 || moveZ !== 0) {
|
||||
const speed = deltaTime ? this.moveSpeed.keyboard * deltaTime * 0.16: this.moveSpeed.keyboard * 0.066
|
||||
|
||||
// 根据固定45度角度旋转移动方向
|
||||
const angle = -this.cameraAngle
|
||||
const cos = Math.cos(angle)
|
||||
const sin = Math.sin(angle)
|
||||
|
||||
const worldMoveX = (moveX * cos - moveZ * sin) * speed
|
||||
const worldMoveZ = (moveX * sin + moveZ * cos) * speed
|
||||
|
||||
this.setTargetPosition(
|
||||
this.target.x + worldMoveX,
|
||||
this.target.z + worldMoveZ
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
showClickMarker(position) {
|
||||
// 移除旧的标记
|
||||
if (this.clickMarker) {
|
||||
this.scene.remove(this.clickMarker)
|
||||
}
|
||||
|
||||
// 创建新的标记(圆形标记)
|
||||
const markerGeometry = new THREE.RingGeometry(cm(50), cm(70), 32)
|
||||
const markerMaterial = new THREE.MeshBasicMaterial({
|
||||
color: 0x00ffff,
|
||||
side: THREE.DoubleSide,
|
||||
transparent: true,
|
||||
opacity: 0.7
|
||||
})
|
||||
const marker = new THREE.Mesh(markerGeometry, markerMaterial)
|
||||
marker.position.copy(position)
|
||||
marker.position.y += cm(5) // 稍微高于地面
|
||||
marker.rotation.x = -Math.PI / 2 // 水平放置
|
||||
|
||||
this.scene.add(marker)
|
||||
this.clickMarker = marker
|
||||
|
||||
// 2秒后淡出移除
|
||||
setTimeout(() => {
|
||||
if (this.clickMarker === marker) {
|
||||
const fadeOut = () => {
|
||||
markerMaterial.opacity -= 0.05
|
||||
if (markerMaterial.opacity > 0) {
|
||||
requestAnimationFrame(fadeOut)
|
||||
} else {
|
||||
this.scene.remove(marker)
|
||||
if (this.clickMarker === marker) {
|
||||
this.clickMarker = null
|
||||
}
|
||||
}
|
||||
}
|
||||
fadeOut()
|
||||
}
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
// 设置边界
|
||||
setBoundary(minX, maxX, minZ, maxZ) {
|
||||
this.boundaryMinX = cm(minX)
|
||||
this.boundaryMaxX = cm(maxX)
|
||||
this.boundaryMinZ = cm(minZ)
|
||||
this.boundaryMaxZ = cm(maxZ)
|
||||
|
||||
// 确保当前目标在边界内
|
||||
this.setTargetPosition(this.target.x, this.target.z)
|
||||
}
|
||||
|
||||
// 添加区域边界(用于区域点击检测)
|
||||
addAreaBoundary(boundaryMesh, areaId, areaName, areaType) {
|
||||
this.areaBoundaries.push({
|
||||
boundary: boundaryMesh,
|
||||
areaId,
|
||||
areaName,
|
||||
areaType
|
||||
})
|
||||
}
|
||||
|
||||
// 设置区域点击回调
|
||||
setOnAreaClick(callback) {
|
||||
this.onAreaClick = callback
|
||||
}
|
||||
|
||||
addGroundObject(object) {
|
||||
this.groundObjects.push(object)
|
||||
}
|
||||
|
||||
// 重置视角到指定位置
|
||||
resetView(x = 0, z = 0) {
|
||||
this.setTargetPosition(x, z)
|
||||
this.cameraHeight = cm(8000)
|
||||
this.updateCameraPosition()
|
||||
}
|
||||
|
||||
dispose() {
|
||||
const canvas = this.domElement
|
||||
const handlers = this.eventHandlers
|
||||
|
||||
if (canvas && handlers) {
|
||||
canvas.removeEventListener('mousedown', handlers.onMouseDown)
|
||||
canvas.removeEventListener('mousemove', handlers.onMouseMove)
|
||||
canvas.removeEventListener('mouseup', handlers.onMouseUp)
|
||||
canvas.removeEventListener('wheel', handlers.onWheel)
|
||||
|
||||
window.removeEventListener('keydown', handlers.onKeyDown)
|
||||
window.removeEventListener('keyup', handlers.onKeyUp)
|
||||
|
||||
canvas.style.cursor = 'default'
|
||||
}
|
||||
|
||||
if (this.clickMarker) {
|
||||
this.scene.remove(this.clickMarker)
|
||||
this.clickMarker = null
|
||||
}
|
||||
}
|
||||
}
|
||||
405
src/utils/overlookControls.ts
Normal file
@ -0,0 +1,405 @@
|
||||
//src/utils/overlookControls.ts
|
||||
|
||||
import * as THREE from 'three'
|
||||
|
||||
// 辅助函数:厘米转Three.js单位(1单位=1cm)
|
||||
const cm = (value: number) => value // Three.js中直接使用厘米为单位
|
||||
|
||||
type AreaBoundary = {
|
||||
boundary: THREE.Object3D
|
||||
areaId: any
|
||||
areaName?: string
|
||||
areaType?: any
|
||||
}
|
||||
|
||||
export class OverlookControls {
|
||||
camera: THREE.Camera
|
||||
domElement: HTMLElement
|
||||
scene: THREE.Scene
|
||||
enabled: boolean
|
||||
|
||||
cameraAngle: number
|
||||
cameraPitch: number
|
||||
targetHeight: number
|
||||
|
||||
cameraHeight: number
|
||||
minHeight: number
|
||||
maxHeight: number
|
||||
|
||||
target: THREE.Vector3
|
||||
|
||||
boundaryMinX: number
|
||||
boundaryMaxX: number
|
||||
boundaryMinZ: number
|
||||
boundaryMaxZ: number
|
||||
|
||||
moveSpeed: { keyboard: number; drag: number }
|
||||
|
||||
isDragging: boolean
|
||||
dragStart: THREE.Vector2
|
||||
dragCurrent: THREE.Vector2
|
||||
lastDragPos: THREE.Vector2
|
||||
|
||||
raycaster: THREE.Raycaster
|
||||
mouse: THREE.Vector2
|
||||
groundObjects: THREE.Object3D[]
|
||||
|
||||
keys: { w: boolean; a: boolean; s: boolean; d: boolean; up: boolean; left: boolean; down: boolean; right: boolean }
|
||||
|
||||
areaBoundaries: AreaBoundary[]
|
||||
onAreaClick: ((areaId: any, areaName?: string, areaType?: any) => void) | null
|
||||
|
||||
eventHandlers: any
|
||||
handleClick: ((e: MouseEvent) => void) | null
|
||||
clickMarker: THREE.Object3D | null
|
||||
|
||||
constructor(camera: THREE.Camera, domElement: HTMLElement, scene: THREE.Scene, config: Record<string, any> = {}) {
|
||||
this.camera = camera
|
||||
this.domElement = domElement
|
||||
this.scene = scene
|
||||
this.enabled = true
|
||||
|
||||
// 2.5D视角固定参数
|
||||
this.cameraAngle = Math.PI / 4 // 45度固定角度
|
||||
this.cameraPitch = 70 // 70度俯仰角(LOL风格)
|
||||
this.targetHeight = cm(0) // 目标在地面
|
||||
|
||||
// 相机高度(缩放)
|
||||
this.cameraHeight = cm(8000) // 初始高度80米
|
||||
this.minHeight = cm(4000) // 最小高度40米
|
||||
this.maxHeight = cm(20000) // 最大高度200米
|
||||
|
||||
// 目标位置(镜头中心点)
|
||||
this.target = new THREE.Vector3(0, 0, 0)
|
||||
|
||||
// 视野边界参数(类似LOL地图边界)
|
||||
this.boundaryMinX = config.boundaryMinX || cm(-30000)
|
||||
this.boundaryMaxX = config.boundaryMaxX || cm(30000)
|
||||
this.boundaryMinZ = config.boundaryMinZ || cm(-30000)
|
||||
this.boundaryMaxZ = config.boundaryMaxZ || cm(30000)
|
||||
|
||||
// 移动速度(厘米/秒)- 键盘速度加速2倍
|
||||
this.moveSpeed = {
|
||||
keyboard: cm(1600), // 键盘移动速度(原800 * 2)
|
||||
drag: cm(0.5) // 拖拽灵敏度系数
|
||||
}
|
||||
|
||||
// 鼠标拖拽控制
|
||||
this.isDragging = false
|
||||
this.dragStart = new THREE.Vector2()
|
||||
this.dragCurrent = new THREE.Vector2()
|
||||
this.lastDragPos = new THREE.Vector2()
|
||||
|
||||
// 点击地面检测
|
||||
this.raycaster = new THREE.Raycaster()
|
||||
this.mouse = new THREE.Vector2()
|
||||
this.groundObjects = []
|
||||
|
||||
// 键盘控制状态
|
||||
this.keys = { w: false, a: false, s: false, d: false, up: false, left: false, down: false, right: false }
|
||||
|
||||
// 区域边界检测
|
||||
this.areaBoundaries = []
|
||||
this.onAreaClick = null
|
||||
|
||||
this.eventHandlers = null
|
||||
this.handleClick = null
|
||||
this.clickMarker = null
|
||||
|
||||
// 初始化
|
||||
this.initControls()
|
||||
this.updateCameraPosition()
|
||||
}
|
||||
|
||||
initControls() {
|
||||
const canvas = this.domElement
|
||||
|
||||
// 鼠标按下开始拖拽
|
||||
const onMouseDown = (e: MouseEvent) => {
|
||||
if (!this.enabled || e.button !== 0) return // 只响应左键
|
||||
|
||||
e.preventDefault()
|
||||
this.isDragging = true
|
||||
this.dragStart.set((e as MouseEvent).clientX, (e as MouseEvent).clientY)
|
||||
this.lastDragPos.set((e as MouseEvent).clientX, (e as MouseEvent).clientY)
|
||||
canvas.style.cursor = 'grabbing'
|
||||
}
|
||||
|
||||
// 鼠标移动处理拖拽
|
||||
const onMouseMove = (e: MouseEvent) => {
|
||||
if (!this.enabled) return
|
||||
|
||||
this.dragCurrent.set(e.clientX, e.clientY)
|
||||
|
||||
if (this.isDragging) {
|
||||
const deltaX = this.dragCurrent.x - this.lastDragPos.x
|
||||
const deltaY = this.dragCurrent.y - this.lastDragPos.y
|
||||
|
||||
// 根据拖拽距离移动视角
|
||||
const moveX = -deltaX * this.moveSpeed.drag
|
||||
const moveZ = -deltaY * this.moveSpeed.drag
|
||||
|
||||
// 根据固定45度角度旋转移动方向
|
||||
const angle = -this.cameraAngle
|
||||
const cos = Math.cos(angle)
|
||||
const sin = Math.sin(angle)
|
||||
|
||||
const worldMoveX = (moveX * cos - moveZ * sin)
|
||||
const worldMoveZ = (moveX * sin + moveZ * cos)
|
||||
|
||||
this.setTargetPosition(this.target.x + worldMoveX, this.target.z + worldMoveZ)
|
||||
|
||||
this.lastDragPos.set(e.clientX, e.clientY)
|
||||
}
|
||||
}
|
||||
|
||||
// 鼠标释放停止拖拽
|
||||
const onMouseUp = (e: MouseEvent) => {
|
||||
if (!this.enabled || e.button !== 0) return
|
||||
|
||||
this.isDragging = false
|
||||
canvas.style.cursor = 'grab'
|
||||
|
||||
// 检查是否是点击(移动距离很小)
|
||||
const dx = this.dragCurrent.x - this.dragStart.x
|
||||
const dy = this.dragCurrent.y - this.dragStart.y
|
||||
const dragDistance = Math.sqrt(dx * dx + dy * dy)
|
||||
|
||||
if (dragDistance < 5) {
|
||||
this.handleClick && this.handleClick(e as MouseEvent)
|
||||
}
|
||||
}
|
||||
|
||||
// 鼠标滚轮缩放
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
if (!this.enabled) return
|
||||
|
||||
e.preventDefault()
|
||||
const delta = e.deltaY > 0 ? 1.2 : 0.8
|
||||
const newHeight = this.cameraHeight * delta
|
||||
this.cameraHeight = THREE.MathUtils.clamp(newHeight, this.minHeight, this.maxHeight)
|
||||
this.updateCameraPosition()
|
||||
}
|
||||
|
||||
// 点击检测
|
||||
const handleClick = (e: MouseEvent) => {
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
this.mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1
|
||||
this.mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1
|
||||
|
||||
this.raycaster.setFromCamera(this.mouse, this.camera)
|
||||
|
||||
// 1. 先检测是否点击了区域边界
|
||||
let areaClicked = false
|
||||
for (const area of this.areaBoundaries) {
|
||||
const intersects = this.raycaster.intersectObject(area.boundary)
|
||||
if (intersects.length > 0) {
|
||||
if (this.onAreaClick) {
|
||||
this.onAreaClick(area.areaId, area.areaName, area.areaType)
|
||||
}
|
||||
areaClicked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 如果没有点击区域,检测地面(仅显示标记,不移动)
|
||||
if (!areaClicked) {
|
||||
const intersects = this.raycaster.intersectObjects(this.groundObjects)
|
||||
if (intersects.length > 0) {
|
||||
const point = intersects[0].point
|
||||
this.showClickMarker(point)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 键盘事件
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (!this.enabled) return
|
||||
|
||||
switch (e.key.toLowerCase()) {
|
||||
case 'w': case 'arrowup': this.keys.w = this.keys.up = true; break
|
||||
case 'a': case 'arrowleft': this.keys.a = this.keys.left = true; break
|
||||
case 's': case 'arrowdown': this.keys.s = this.keys.down = true; break
|
||||
case 'd': case 'arrowright': this.keys.d = this.keys.right = true; break
|
||||
}
|
||||
}
|
||||
|
||||
const onKeyUp = (e: KeyboardEvent) => {
|
||||
switch (e.key.toLowerCase()) {
|
||||
case 'w': case 'arrowup': this.keys.w = this.keys.up = false; break
|
||||
case 'a': case 'arrowleft': this.keys.a = this.keys.left = false; break
|
||||
case 's': case 'arrowdown': this.keys.s = this.keys.down = false; break
|
||||
case 'd': case 'arrowright': this.keys.d = this.keys.right = false; break
|
||||
}
|
||||
}
|
||||
|
||||
// 添加事件监听器
|
||||
canvas.addEventListener('mousedown', onMouseDown)
|
||||
canvas.addEventListener('mousemove', onMouseMove)
|
||||
canvas.addEventListener('mouseup', onMouseUp)
|
||||
canvas.addEventListener('wheel', onWheel)
|
||||
|
||||
// 键盘事件监听在window上
|
||||
window.addEventListener('keydown', onKeyDown)
|
||||
window.addEventListener('keyup', onKeyUp)
|
||||
|
||||
// 鼠标离开画布时停止拖拽
|
||||
canvas.addEventListener('mouseleave', () => {
|
||||
if (this.isDragging) {
|
||||
this.isDragging = false
|
||||
canvas.style.cursor = 'grab'
|
||||
}
|
||||
})
|
||||
|
||||
// 初始化光标样式
|
||||
canvas.style.cursor = 'grab'
|
||||
|
||||
// 保存事件处理器以便清理
|
||||
this.eventHandlers = { onMouseDown, onMouseMove, onMouseUp, onWheel, onKeyDown, onKeyUp, handleClick }
|
||||
this.handleClick = handleClick
|
||||
}
|
||||
|
||||
setTargetPosition(x: number, z: number) {
|
||||
// 限制目标位置在边界内
|
||||
const clampedX = THREE.MathUtils.clamp(x, this.boundaryMinX, this.boundaryMaxX)
|
||||
const clampedZ = THREE.MathUtils.clamp(z, this.boundaryMinZ, this.boundaryMaxZ)
|
||||
|
||||
this.target.x = clampedX
|
||||
this.target.z = clampedZ
|
||||
|
||||
this.updateCameraPosition()
|
||||
}
|
||||
|
||||
updateCameraPosition() {
|
||||
// 固定2.5D视角计算
|
||||
const phi = THREE.MathUtils.degToRad(90 - this.cameraPitch)
|
||||
const theta = this.cameraAngle
|
||||
|
||||
const x = this.target.x + this.cameraHeight * Math.sin(phi) * Math.cos(theta)
|
||||
const y = this.target.y + this.cameraHeight * Math.cos(phi)
|
||||
const z: number = this.target.z + this.cameraHeight * Math.sin(phi) * Math.sin(theta)
|
||||
|
||||
(this.camera.position as THREE.Vector3).set(x, y, z)
|
||||
this.camera.lookAt(this.target)
|
||||
}
|
||||
|
||||
update(deltaTime?: number) {
|
||||
if (!this.enabled) return
|
||||
|
||||
// 键盘控制(速度加倍)
|
||||
let moveX = 0, moveZ = 0
|
||||
if (this.keys.w || this.keys.up) moveZ += 1
|
||||
if (this.keys.s || this.keys.down) moveZ -= 1
|
||||
if (this.keys.a || this.keys.left) moveX -= 1
|
||||
if (this.keys.d || this.keys.right) moveX += 1
|
||||
|
||||
if (moveX !== 0 || moveZ !== 0) {
|
||||
const speed = deltaTime ? this.moveSpeed.keyboard * deltaTime * 0.16 : this.moveSpeed.keyboard * 0.066
|
||||
|
||||
// 根据固定45度角度旋转移动方向
|
||||
const angle = -this.cameraAngle
|
||||
const cos = Math.cos(angle)
|
||||
const sin = Math.sin(angle)
|
||||
|
||||
const worldMoveX = (moveX * cos - moveZ * sin) * speed
|
||||
const worldMoveZ = (moveX * sin + moveZ * cos) * speed
|
||||
|
||||
this.setTargetPosition(this.target.x + worldMoveX, this.target.z + worldMoveZ)
|
||||
}
|
||||
}
|
||||
|
||||
showClickMarker(position: THREE.Vector3) {
|
||||
// 移除旧的标记
|
||||
if (this.clickMarker) {
|
||||
this.scene.remove(this.clickMarker)
|
||||
}
|
||||
|
||||
// 创建新的标记(圆形标记)
|
||||
const markerGeometry = new THREE.RingGeometry(cm(50), cm(70), 32)
|
||||
const markerMaterial = new THREE.MeshBasicMaterial({
|
||||
color: 0x00ffff,
|
||||
side: THREE.DoubleSide,
|
||||
transparent: true,
|
||||
opacity: 0.7
|
||||
})
|
||||
const marker = new THREE.Mesh(markerGeometry, markerMaterial)
|
||||
marker.position.copy(position)
|
||||
marker.position.y += cm(5) // 稍微高于地面
|
||||
marker.rotation.x = -Math.PI / 2 // 水平放置
|
||||
|
||||
this.scene.add(marker)
|
||||
this.clickMarker = marker
|
||||
|
||||
// 2秒后淡出移除
|
||||
setTimeout(() => {
|
||||
if (this.clickMarker === marker) {
|
||||
const fadeOut = () => {
|
||||
markerMaterial.opacity -= 0.05
|
||||
if (markerMaterial.opacity > 0) {
|
||||
requestAnimationFrame(fadeOut)
|
||||
} else {
|
||||
this.scene.remove(marker)
|
||||
if (this.clickMarker === marker) {
|
||||
this.clickMarker = null
|
||||
}
|
||||
}
|
||||
}
|
||||
fadeOut()
|
||||
}
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
// 设置边界
|
||||
setBoundary(minX: number, maxX: number, minZ: number, maxZ: number) {
|
||||
this.boundaryMinX = cm(minX)
|
||||
this.boundaryMaxX = cm(maxX)
|
||||
this.boundaryMinZ = cm(minZ)
|
||||
this.boundaryMaxZ = cm(maxZ)
|
||||
|
||||
// 确保当前目标在边界内
|
||||
this.setTargetPosition(this.target.x, this.target.z)
|
||||
}
|
||||
|
||||
// 添加区域边界(用于区域点击检测)
|
||||
addAreaBoundary(boundaryMesh: THREE.Object3D, areaId: any, areaName?: string, areaType?: any) {
|
||||
this.areaBoundaries.push({ boundary: boundaryMesh, areaId, areaName, areaType })
|
||||
}
|
||||
|
||||
// 设置区域点击回调
|
||||
setOnAreaClick(callback: (areaId: any, areaName?: string, areaType?: any) => void) {
|
||||
this.onAreaClick = callback
|
||||
}
|
||||
|
||||
addGroundObject(object: THREE.Object3D) {
|
||||
this.groundObjects.push(object)
|
||||
}
|
||||
|
||||
// 重置视角到指定位置
|
||||
resetView(x = 0, z = 0) {
|
||||
this.setTargetPosition(x, z)
|
||||
this.cameraHeight = cm(8000)
|
||||
this.updateCameraPosition()
|
||||
}
|
||||
|
||||
dispose() {
|
||||
const canvas = this.domElement
|
||||
const handlers = this.eventHandlers
|
||||
|
||||
if (canvas && handlers) {
|
||||
canvas.removeEventListener('mousedown', handlers.onMouseDown)
|
||||
canvas.removeEventListener('mousemove', handlers.onMouseMove)
|
||||
canvas.removeEventListener('mouseup', handlers.onMouseUp)
|
||||
canvas.removeEventListener('wheel', handlers.onWheel)
|
||||
|
||||
window.removeEventListener('keydown', handlers.onKeyDown)
|
||||
window.removeEventListener('keyup', handlers.onKeyUp)
|
||||
|
||||
canvas.style.cursor = 'default'
|
||||
}
|
||||
|
||||
if (this.clickMarker) {
|
||||
this.scene.remove(this.clickMarker)
|
||||
this.clickMarker = null
|
||||
}
|
||||
}
|
||||
}
|
||||
233
src/utils/request.ts
Normal file
@ -0,0 +1,233 @@
|
||||
import axios from 'axios'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import {
|
||||
getToken, setToken, removeToken
|
||||
} from '@/utils/auth'
|
||||
import router from '@/router'
|
||||
|
||||
// create an axios instance
|
||||
const service = axios.create({
|
||||
baseURL: import.meta.env.VITE_APP_BASE_API,
|
||||
timeout: 10000, // 建议适当延长超时时间
|
||||
// withCredentials: true, // 根据实际情况决定是否开启
|
||||
});
|
||||
|
||||
// 定义业务成功码
|
||||
const SUCCESS_CODES = [200, 20000, 1,0] // 支持多种成功码
|
||||
|
||||
// 错误码映射
|
||||
const ERROR_CODE_MAP = {
|
||||
// 认证相关错误
|
||||
400: '请求参数错误',
|
||||
401: '未授权访问',
|
||||
403: '禁止访问',
|
||||
404: '资源不存在',
|
||||
409: '资源冲突',
|
||||
422: '参数验证失败',
|
||||
500: '服务器内部错误',
|
||||
|
||||
// 打印机错误
|
||||
1001: '参数错误',
|
||||
1002: '打印台不存在',
|
||||
1003: '打印电脑不存在',
|
||||
1004: '保存失败',
|
||||
1005: '删除失败',
|
||||
|
||||
// 业务错误码(根据实际后端调整)
|
||||
40001: '用户名或密码错误',
|
||||
40002: '账号已被禁用',
|
||||
40003: '验证码错误',
|
||||
40004: '账号不存在',
|
||||
40005: '没有操作权限',
|
||||
40006: '访问被拒绝',
|
||||
40010: '数据不存在',
|
||||
40011: '数据重复',
|
||||
40012: '参数验证失败',
|
||||
|
||||
// Token 相关错误
|
||||
50008: '非法的token',
|
||||
50012: '其他客户端登录',
|
||||
50014: 'Token过期',
|
||||
}
|
||||
|
||||
// request interceptor
|
||||
service.interceptors.request.use(
|
||||
config => {
|
||||
config.headers['platform'] ='web';
|
||||
config.headers['project'] ='all';
|
||||
// 添加 token
|
||||
const token = getToken()
|
||||
if (token) {
|
||||
config.headers['Authorization'] = 'Bearer ' + token
|
||||
}
|
||||
|
||||
// 为 GET 请求添加时间戳防止缓存
|
||||
if (config.method === 'get') {
|
||||
config.params = {
|
||||
...(config.params),
|
||||
_t: new Date().getTime(),
|
||||
}
|
||||
}
|
||||
|
||||
return config
|
||||
},
|
||||
error => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// response interceptor
|
||||
service.interceptors.response.use(
|
||||
response => {
|
||||
const headers = response.headers
|
||||
const res = response.data
|
||||
const authHeader = headers['authorization'] || headers['Authorization'];
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
const newToken = authHeader.substring(7)
|
||||
setToken(newToken)
|
||||
}
|
||||
|
||||
// 检查业务状态码
|
||||
if (!SUCCESS_CODES.includes(res.code)) {
|
||||
const errorMessage = (ERROR_CODE_MAP as Record<number | string, string>)[res.code] || res.message || '请求失败'
|
||||
|
||||
// Token 失效处理
|
||||
if ([401, 50008, 50012, 50014].includes(res.code)) {
|
||||
handleTokenExpired()
|
||||
return Promise.reject(new Error(errorMessage))
|
||||
}
|
||||
|
||||
// 权限不足处理
|
||||
if ([403, 40005, 40006].includes(res.code)) {
|
||||
ElMessage.warning('没有操作权限')
|
||||
return Promise.reject(new Error(errorMessage))
|
||||
}
|
||||
|
||||
ElMessage.error(errorMessage)
|
||||
return Promise.reject(new Error(errorMessage))
|
||||
} else {
|
||||
// 请求成功,返回数据
|
||||
return res
|
||||
}
|
||||
},
|
||||
error => {
|
||||
let message = '网络错误,请稍后重试'
|
||||
|
||||
if (error.response) {
|
||||
// 服务器返回了错误状态码
|
||||
const status = error.response.status
|
||||
const data = error.response.data
|
||||
|
||||
// 如果后端返回了格式化错误信息,使用后端的消息
|
||||
if (data && data.message) {
|
||||
message = data.message
|
||||
} else {
|
||||
// 否则使用默认的 HTTP 错误消息
|
||||
switch (status) {
|
||||
case 400: message = '请求参数错误'; break
|
||||
case 401:
|
||||
message = '未授权,请重新登录'
|
||||
handleTokenExpired()
|
||||
break
|
||||
case 403: message = '拒绝访问,没有操作权限'; break
|
||||
case 404: message = '请求资源不存在'; break
|
||||
case 405: message = '请求方法不被允许'; break
|
||||
case 406: message = '仓库有效期过期,拒绝访问'; break
|
||||
case 408: message = '请求超时'; break
|
||||
case 500: message = '服务器内部错误'; break
|
||||
case 501: message = '服务未实现'; break
|
||||
case 502: message = '网关错误'; break
|
||||
case 503: message = '服务不可用'; break
|
||||
case 504: message = '网关超时'; break
|
||||
case 505: message = 'HTTP版本不受支持'; break
|
||||
default: message = `连接错误 ${status}`
|
||||
}
|
||||
}
|
||||
} else if (error.request) {
|
||||
if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
|
||||
message = '请求超时,请检查网络连接'
|
||||
} else {
|
||||
message = '网络连接异常,请检查网络'
|
||||
}
|
||||
} else {
|
||||
message = error.message
|
||||
}
|
||||
|
||||
ElMessage.error(message)
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// Token 过期处理函数
|
||||
let isReloginShow = false
|
||||
function handleTokenExpired() {
|
||||
if (isReloginShow) return
|
||||
isReloginShow = true
|
||||
ElMessageBox.confirm('登录状态已过期,请重新登录', '确认注销', {
|
||||
confirmButtonText: '重新登录',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
}).then(() => {
|
||||
isReloginShow = false
|
||||
removeToken()
|
||||
// 强制刷新页面到登录页
|
||||
window.location.href = '/login'
|
||||
}).catch(() => {
|
||||
isReloginShow = false
|
||||
})
|
||||
}
|
||||
|
||||
// 封装常用的请求方法
|
||||
export const http = {
|
||||
get(url : string, params = {}, config = {}) {
|
||||
return service({
|
||||
method: 'get',
|
||||
url,
|
||||
params,
|
||||
...config
|
||||
})
|
||||
},
|
||||
|
||||
post(url : string, data = {}, config = {}) {
|
||||
return service({
|
||||
method: 'post',
|
||||
url,
|
||||
data,
|
||||
...config
|
||||
})
|
||||
},
|
||||
|
||||
put(url : string, data = {}, config = {}) {
|
||||
return service({
|
||||
method: 'put',
|
||||
url,
|
||||
data,
|
||||
...config
|
||||
})
|
||||
},
|
||||
|
||||
delete(url : string, config = {}) {
|
||||
return service({
|
||||
method: 'delete',
|
||||
url,
|
||||
...config
|
||||
})
|
||||
},
|
||||
|
||||
upload(url : string, formData : FormData, onProgress = null) {
|
||||
const requestConfig: any = {
|
||||
method: 'post',
|
||||
url,
|
||||
data: formData,
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
};
|
||||
if (onProgress) {
|
||||
requestConfig.onUploadProgress = onProgress;
|
||||
}
|
||||
return service(requestConfig);
|
||||
}
|
||||
}
|
||||
|
||||
export default service;
|
||||
1206
src/utils/threeScene.js
Normal file
390
src/utils/threeUtils.js
Normal file
@ -0,0 +1,390 @@
|
||||
|
||||
import * as THREE from 'three'
|
||||
|
||||
// 使用 Three.js 自带的 OrbitControls
|
||||
let OrbitControls = null
|
||||
|
||||
// 异步加载 OrbitControls
|
||||
export const loadOrbitControls = async () => {
|
||||
if (typeof window === 'undefined') return null
|
||||
|
||||
try {
|
||||
const module = await import('three/examples/jsm/controls/OrbitControls.js')
|
||||
OrbitControls = module.OrbitControls
|
||||
console.log('OrbitControls 加载成功')
|
||||
return OrbitControls
|
||||
} catch (error) {
|
||||
console.warn('无法加载 OrbitControls:', error.message)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// 辅助函数:厘米转Three.js单位(1单位=1cm)
|
||||
const cm = (value) => value// Three.js中直接使用厘米为单位
|
||||
|
||||
// 俯瞰模式控制器(增强版)
|
||||
|
||||
|
||||
// 漫游模式控制器(第一人称)- 增强版
|
||||
export class RoamControls {
|
||||
constructor(camera, domElement, scene) {
|
||||
this.camera = camera
|
||||
this.domElement = domElement
|
||||
this.scene = scene
|
||||
this.enabled = true
|
||||
|
||||
// 漫游参数 - 厘米为单位
|
||||
this.moveSpeed = cm(30)// 每秒移动30厘米
|
||||
this.rotateSpeed = 0.002
|
||||
this.jumpForce = cm(50)
|
||||
this.gravity = cm(2)
|
||||
|
||||
// 移动状态
|
||||
this.moveForward = false
|
||||
this.moveBackward = false
|
||||
this.moveLeft = false
|
||||
this.moveRight = false
|
||||
this.moveUp = false
|
||||
this.moveDown = false
|
||||
|
||||
// 视角控制
|
||||
this.isMouseDown = false
|
||||
this.lastMouseX = 0
|
||||
this.lastMouseY = 0
|
||||
this.yaw = 0
|
||||
this.pitch = 0
|
||||
|
||||
// 物理参数
|
||||
this.velocity = new THREE.Vector3()
|
||||
this.onGround = true
|
||||
this.groundHeight = 0
|
||||
|
||||
// 碰撞检测
|
||||
this.collisionObjects = []
|
||||
this.raycaster = new THREE.Raycaster()
|
||||
this.mouse = new THREE.Vector2()
|
||||
|
||||
// 点击检测
|
||||
this.clickableObjects = []// 可点击对象(货架格子)
|
||||
this.onObjectClick = null// 对象点击回调
|
||||
|
||||
// 控制面板
|
||||
this.showUI = true
|
||||
this.uiElements = {}
|
||||
|
||||
this.initControls()
|
||||
this.updateCameraRotation()
|
||||
}
|
||||
|
||||
initControls() {
|
||||
const canvas = this.domElement
|
||||
|
||||
// 鼠标控制
|
||||
const onMouseDown = (e) => {
|
||||
this.isMouseDown = true
|
||||
this.lastMouseX = e.clientX
|
||||
this.lastMouseY = e.clientY
|
||||
canvas.style.cursor = 'none'
|
||||
|
||||
// 请求指针锁定
|
||||
if (canvas.requestPointerLock) {
|
||||
canvas.requestPointerLock()
|
||||
} else if (canvas.mozRequestPointerLock) {
|
||||
canvas.mozRequestPointerLock()
|
||||
} else if (canvas.webkitRequestPointerLock) {
|
||||
canvas.webkitRequestPointerLock()
|
||||
}
|
||||
}
|
||||
|
||||
const onMouseMove = (e) => {
|
||||
if (!this.isMouseDown || !this.enabled) return
|
||||
|
||||
const movementX = e.movementX || e.mozMovementX || e.webkitMovementX || 0
|
||||
const movementY = e.movementY || e.mozMovementY || e.webkitMovementY || 0
|
||||
|
||||
// 更新视角
|
||||
this.yaw -= movementX * this.rotateSpeed
|
||||
this.pitch -= movementY * this.rotateSpeed
|
||||
|
||||
// 限制俯仰角度
|
||||
this.pitch = Math.max(-Math.PI/2, Math.min(Math.PI/2, this.pitch))
|
||||
|
||||
this.updateCameraRotation()
|
||||
}
|
||||
|
||||
const onMouseUp = (e) => {
|
||||
this.isMouseDown = false
|
||||
canvas.style.cursor = 'grab'
|
||||
|
||||
// 退出指针锁定
|
||||
if (document.exitPointerLock) {
|
||||
document.exitPointerLock()
|
||||
} else if (document.mozExitPointerLock) {
|
||||
document.mozExitPointerLock()
|
||||
} else if (document.webkitExitPointerLock) {
|
||||
document.webkitExitPointerLock()
|
||||
}
|
||||
|
||||
// 检测点击对象
|
||||
if (this.clickableObjects.length > 0 && this.onObjectClick) {
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
this.mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1
|
||||
this.mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1
|
||||
|
||||
this.raycaster.setFromCamera(this.mouse, this.camera)
|
||||
const intersects = this.raycaster.intersectObjects(this.clickableObjects, true)
|
||||
|
||||
if (intersects.length > 0) {
|
||||
const object = intersects[0].object
|
||||
let shelfCell = object
|
||||
// 向上查找带有货架信息的父对象
|
||||
while (shelfCell && !shelfCell.userData.shelfCellId) {
|
||||
shelfCell = shelfCell.parent
|
||||
}
|
||||
if (shelfCell && shelfCell.userData.shelfCellId) {
|
||||
this.onObjectClick(
|
||||
shelfCell.userData.shelfCellId,
|
||||
shelfCell.userData.shelfRow,
|
||||
shelfCell.userData.shelfColumn,
|
||||
shelfCell.userData.shelfLevel
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 键盘控制
|
||||
const onKeyDown = (e) => {
|
||||
switch(e.code){
|
||||
case 'KeyW':
|
||||
case 'ArrowUp':
|
||||
this.moveForward = true
|
||||
break
|
||||
case 'KeyS':
|
||||
case 'ArrowDown':
|
||||
this.moveBackward = true
|
||||
break
|
||||
case 'KeyA':
|
||||
case 'ArrowLeft':
|
||||
this.moveLeft = true
|
||||
break
|
||||
case 'KeyD':
|
||||
case 'ArrowRight':
|
||||
this.moveRight = true
|
||||
break
|
||||
case 'Space':
|
||||
if (this.onGround) {
|
||||
this.velocity.y = this.jumpForce
|
||||
this.onGround = false
|
||||
}
|
||||
break
|
||||
case 'ShiftLeft':
|
||||
case 'ShiftRight':
|
||||
this.moveDown = true
|
||||
break
|
||||
case 'Escape':
|
||||
// ESC键返回俯瞰模式
|
||||
if (this.onExitRoam) {
|
||||
this.onExitRoam()
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const onKeyUp = (e) => {
|
||||
switch(e.code){
|
||||
case 'KeyW':
|
||||
case 'ArrowUp':
|
||||
this.moveForward = false
|
||||
break
|
||||
case 'KeyS':
|
||||
case 'ArrowDown':
|
||||
this.moveBackward = false
|
||||
break
|
||||
case 'KeyA':
|
||||
case 'ArrowLeft':
|
||||
this.moveLeft = false
|
||||
break
|
||||
case 'KeyD':
|
||||
case 'ArrowRight':
|
||||
this.moveRight = false
|
||||
break
|
||||
case 'ShiftLeft':
|
||||
case 'ShiftRight':
|
||||
this.moveDown = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 防止右键菜单
|
||||
canvas.addEventListener('contextmenu', (e) => e.preventDefault())
|
||||
|
||||
canvas.addEventListener('mousedown', onMouseDown)
|
||||
canvas.addEventListener('mousemove', onMouseMove)
|
||||
canvas.addEventListener('mouseup', onMouseUp)
|
||||
window.addEventListener('keydown', onKeyDown)
|
||||
window.addEventListener('keyup', onKeyUp)
|
||||
|
||||
// 退出指针锁定时的处理
|
||||
const onPointerLockChange = () => {
|
||||
const pointerLockElement =
|
||||
document.pointerLockElement ||
|
||||
document.mozPointerLockElement ||
|
||||
document.webkitPointerLockElement
|
||||
|
||||
if (pointerLockElement !== canvas) {
|
||||
this.isMouseDown = false
|
||||
canvas.style.cursor = 'grab'
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('pointerlockchange', onPointerLockChange)
|
||||
document.addEventListener('mozpointerlockchange', onPointerLockChange)
|
||||
document.addEventListener('webkitpointerlockchange', onPointerLockChange)
|
||||
|
||||
// 保存事件处理器以便清理
|
||||
this.eventHandlers = {
|
||||
onMouseDown, onMouseMove, onMouseUp,
|
||||
onKeyDown, onKeyUp,
|
||||
onPointerLockChange
|
||||
}
|
||||
}
|
||||
|
||||
updateCameraRotation() {
|
||||
this.camera.rotation.order = 'YXZ'
|
||||
this.camera.rotation.y = this.yaw
|
||||
this.camera.rotation.x = this.pitch
|
||||
}
|
||||
|
||||
update() {
|
||||
if (!this.enabled) return
|
||||
|
||||
// 计算移动方向
|
||||
const direction = new THREE.Vector3()
|
||||
|
||||
if (this.moveForward) {
|
||||
direction.z -= 1
|
||||
}
|
||||
if (this.moveBackward) {
|
||||
direction.z += 1
|
||||
}
|
||||
if (this.moveLeft) {
|
||||
direction.x -= 1
|
||||
}
|
||||
if (this.moveRight) {
|
||||
direction.x += 1
|
||||
}
|
||||
|
||||
// 根据相机方向旋转移动向量
|
||||
direction.applyQuaternion(this.camera.quaternion)
|
||||
direction.y = 0
|
||||
direction.normalize()
|
||||
|
||||
// 垂直移动
|
||||
if (this.moveUp) {
|
||||
direction.y += 1
|
||||
}
|
||||
if (this.moveDown) {
|
||||
direction.y -= 1
|
||||
}
|
||||
|
||||
// 应用移动
|
||||
this.velocity.x = direction.x * this.moveSpeed
|
||||
this.velocity.z = direction.z * this.moveSpeed
|
||||
this.velocity.y = direction.y * this.moveSpeed
|
||||
|
||||
// 应用重力(如果不在跳跃状态)
|
||||
if (!this.onGround) {
|
||||
this.velocity.y -= this.gravity
|
||||
}
|
||||
|
||||
// 碰撞检测
|
||||
const newPosition = this.camera.position.clone()
|
||||
newPosition.x += this.velocity.x
|
||||
newPosition.z += this.velocity.z
|
||||
newPosition.y += this.velocity.y
|
||||
|
||||
// 简单的边界检查
|
||||
let canMove = true
|
||||
for (const obj of this.collisionObjects) {
|
||||
if (obj.geometry.boundingBox) {
|
||||
const box = obj.geometry.boundingBox.clone()
|
||||
box.applyMatrix4(obj.matrixWorld)
|
||||
|
||||
// 检查是否与物体碰撞 - 厘米为单位
|
||||
const playerBox = new THREE.Box3(
|
||||
new THREE.Vector3(newPosition.x - cm(30), newPosition.y - cm(50), newPosition.z - cm(30)),
|
||||
new THREE.Vector3(newPosition.x + cm(30), newPosition.y + cm(170), newPosition.z + cm(30))
|
||||
)
|
||||
|
||||
if (box.intersectsBox(playerBox)) {
|
||||
canMove = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (canMove) {
|
||||
this.camera.position.copy(newPosition)
|
||||
}
|
||||
|
||||
// 限制在地面之上 - 厘米为单位
|
||||
if (this.camera.position.y < this.groundHeight + cm(170)) {
|
||||
this.camera.position.y = this.groundHeight + cm(170)
|
||||
this.onGround = true
|
||||
this.velocity.y = 0
|
||||
} else {
|
||||
this.onGround = false
|
||||
}
|
||||
}
|
||||
|
||||
// 添加可点击对象(货架格子)
|
||||
addClickableObject(object, shelfCellId, row, column, level) {
|
||||
object.userData = {
|
||||
shelfCellId,
|
||||
shelfRow: row,
|
||||
shelfColumn: column,
|
||||
shelfLevel: level,
|
||||
isClickable: true
|
||||
}
|
||||
this.clickableObjects.push(object)
|
||||
}
|
||||
|
||||
// 设置货架格子点击回调
|
||||
setOnObjectClick(callback) {
|
||||
this.onObjectClick = callback
|
||||
}
|
||||
|
||||
// 设置退出漫游回调
|
||||
setOnExitRoam(callback) {
|
||||
this.onExitRoam = callback
|
||||
}
|
||||
|
||||
addCollisionObject(object) {
|
||||
this.collisionObjects.push(object)
|
||||
}
|
||||
|
||||
setGroundHeight(height) {
|
||||
this.groundHeight = height
|
||||
}
|
||||
|
||||
dispose() {
|
||||
const canvas = this.domElement
|
||||
const handlers = this.eventHandlers
|
||||
|
||||
if (canvas && handlers) {
|
||||
canvas.removeEventListener('mousedown', handlers.onMouseDown)
|
||||
canvas.removeEventListener('mousemove', handlers.onMouseMove)
|
||||
canvas.removeEventListener('mouseup', handlers.onMouseUp)
|
||||
canvas.removeEventListener('contextmenu', (e) => e.preventDefault())
|
||||
}
|
||||
|
||||
window.removeEventListener('keydown', handlers.onKeyDown)
|
||||
window.removeEventListener('keyup', handlers.onKeyUp)
|
||||
|
||||
document.removeEventListener('pointerlockchange', handlers.onPointerLockChange)
|
||||
document.removeEventListener('mozpointerlockchange', handlers.onPointerLockChange)
|
||||
document.removeEventListener('webkitpointerlockchange', handlers.onPointerLockChange)
|
||||
}
|
||||
}
|
||||
|
||||
19
src/utils/validate.js
Normal file
@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Created by PanJiaChen on 16/11/18.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} path
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
export function isExternal(path) {
|
||||
return /^(https?:|mailto:|tel:)/.test(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} str
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
export function validUsername(str) {
|
||||
return 1;
|
||||
}
|
||||
698
src/utils/warehouseData.js
Normal file
@ -0,0 +1,698 @@
|
||||
// 基础颜色配置
|
||||
export const warehouseColors = {
|
||||
// 区域颜色
|
||||
area: {
|
||||
storage: '#4CAF50', // 存储区 - 绿色
|
||||
picking: '#2196F3', // 拣选区 - 蓝色
|
||||
packing: '#FF9800', // 包装区 - 橙色
|
||||
sorting: '#9C27B0', // 分拣区 - 紫色
|
||||
buffer: '#795548', // 缓冲区 - 棕色
|
||||
loading: '#607D8B', // 装卸区 - 灰色
|
||||
cold: '#00BCD4', // 冷链区 - 青色
|
||||
hazard: '#F44336' // 危化品区 - 红色
|
||||
},
|
||||
|
||||
// 货架颜色
|
||||
shelf: {
|
||||
frame: '#795548', // 货架框架 - 棕色
|
||||
beam: '#8D6E63', // 横梁 - 浅棕色
|
||||
column: '#5D4037', // 立柱 - 深棕色
|
||||
divider: '#BDBDBD', // 隔板 - 灰色
|
||||
occupied: '#F44336', // 已占用 - 红色
|
||||
empty: '#4CAF50', // 空闲 - 绿色
|
||||
reserved: '#FFC107', // 预留 - 黄色
|
||||
warning: '#FF9800', // 警告 - 橙色
|
||||
block: '#757575' // 禁用 - 深灰
|
||||
},
|
||||
|
||||
// 建筑颜色
|
||||
building: {
|
||||
wall: '#BDBDBD', // 墙壁 - 灰色
|
||||
floor: '#78909C', // 地面 - 蓝灰色
|
||||
roof: '#9E9E9E', // 屋顶 - 中灰色
|
||||
door: '#795548', // 门 - 棕色
|
||||
window: '#B3E5FC', // 窗户 - 浅蓝色
|
||||
column: '#616161', // 建筑立柱 - 深灰色
|
||||
railing: '#546E7A' // 护栏 - 深蓝灰色
|
||||
},
|
||||
|
||||
// 外部区域颜色
|
||||
external: {
|
||||
office: '#673AB7', // 办公室 - 深紫色
|
||||
rest: '#4CAF50', // 休息区 - 绿色
|
||||
equipment: '#607D8B', // 设备区 - 灰色
|
||||
parking: '#795548', // 停车场 - 棕色
|
||||
charging: '#FF9800', // 充电区 - 橙色
|
||||
security: '#F44336', // 安防区 - 红色
|
||||
entrance: '#009688' // 出入口 - 青色
|
||||
}
|
||||
}
|
||||
|
||||
// 生成模拟的仓库数据
|
||||
export function generateWarehouseData() {
|
||||
return {
|
||||
warehouseId: 'WH-2024-001',
|
||||
warehouseName: '智能仓储中心',
|
||||
warehouseType: 'distribution',
|
||||
warehouseSize: {
|
||||
length: 200, // 长度(米)
|
||||
width: 150, // 宽度(米)
|
||||
height: 12 // 高度(米)
|
||||
},
|
||||
areas: generateAreas(),
|
||||
statistics: {
|
||||
totalAreas: 0,
|
||||
totalShelves: 0,
|
||||
totalColumns: 0,
|
||||
totalCells: 0,
|
||||
totalRows: 0,
|
||||
totalLevels: 0,
|
||||
usageRate: 0,
|
||||
capacity: {
|
||||
max: 0,
|
||||
used: 0,
|
||||
available: 0
|
||||
}
|
||||
},
|
||||
buildingInfo: {
|
||||
walls: generateWalls(),
|
||||
doors: generateDoors(),
|
||||
windows: generateWindows(),
|
||||
pillars: generatePillars()
|
||||
},
|
||||
createdAt: '2024-01-01',
|
||||
updatedAt: '2024-01-15'
|
||||
}
|
||||
}
|
||||
|
||||
// 生成区域数据
|
||||
function generateAreas() {
|
||||
const areas = []
|
||||
|
||||
// A区:重型存储区
|
||||
areas.push({
|
||||
id: 'area-A-001',
|
||||
name: 'A区-重型存储',
|
||||
type: 'storage',
|
||||
position: { x: 0, y: 0, z: 0 },
|
||||
size: {
|
||||
length: 80, // 长
|
||||
width: 60, // 宽
|
||||
height: 10 // 高
|
||||
},
|
||||
groundHeight: 0,
|
||||
angle: 0,
|
||||
color: warehouseColors.area.storage,
|
||||
features: {
|
||||
temperature: '常温',
|
||||
humidity: '标准',
|
||||
accessControl: true,
|
||||
fireRating: 'A级',
|
||||
lighting: 'LED照明',
|
||||
ventilation: '自然通风'
|
||||
},
|
||||
shelves: generateStorageShelves('A', 30, 7) // 30排,7列
|
||||
})
|
||||
|
||||
// B区:快速拣选区
|
||||
areas.push({
|
||||
id: 'area-B-001',
|
||||
name: 'B区-快速拣选',
|
||||
type: 'picking',
|
||||
position: { x: 0, y: 0, z: 70 },
|
||||
size: {
|
||||
length: 60,
|
||||
width: 50,
|
||||
height: 8
|
||||
},
|
||||
groundHeight: 0,
|
||||
angle: 0,
|
||||
color: warehouseColors.area.picking,
|
||||
features: {
|
||||
temperature: '常温',
|
||||
humidity: '标准',
|
||||
accessControl: true,
|
||||
fireRating: 'B级',
|
||||
lighting: '高亮度LED',
|
||||
ventilation: '强制通风'
|
||||
},
|
||||
shelves: generatePickingShelves('B', 30, 5) // 30排,5列
|
||||
})
|
||||
|
||||
// C区:包装加工区
|
||||
areas.push({
|
||||
id: 'area-C-001',
|
||||
name: 'C区-包装加工',
|
||||
type: 'packing',
|
||||
position: { x: 90, y: 0, z: 0 },
|
||||
size: {
|
||||
length: 40,
|
||||
width: 30,
|
||||
height: 6
|
||||
},
|
||||
groundHeight: 0,
|
||||
angle: -Math.PI / 4,
|
||||
color: warehouseColors.area.packing,
|
||||
features: {
|
||||
temperature: '常温',
|
||||
humidity: '标准',
|
||||
accessControl: true,
|
||||
fireRating: 'C级',
|
||||
lighting: '工作灯',
|
||||
ventilation: '自然通风'
|
||||
},
|
||||
shelves: generatePackingShelves('C', 5, 3)
|
||||
})
|
||||
|
||||
return areas
|
||||
}
|
||||
|
||||
// 生成存储区货架(重型货架)
|
||||
function generateStorageShelves(prefix, rows, columns) {
|
||||
const shelves = []
|
||||
const shelfWidth = 2.4 // 货架宽度(米)
|
||||
const shelfDepth = 1.2 // 货架深度(米)
|
||||
const aisleWidth = 3.0 // 过道宽度(米)
|
||||
|
||||
// 每个货架有4层,每层2个货位
|
||||
const levels = 4
|
||||
const cellsPerLevel = 2
|
||||
|
||||
for (let row = 0; row < rows; row++) {
|
||||
for (let col = 0; col < columns; col++) {
|
||||
const shelfId = `shelf-${prefix}-${String(row + 1).padStart(3, '0')}-${String(col + 1).padStart(2, '0')}`
|
||||
|
||||
shelves.push({
|
||||
id: shelfId,
|
||||
name: `重型货架${prefix}${row + 1}-${col + 1}`,
|
||||
type: 'heavy',
|
||||
position: {
|
||||
x: col * (shelfWidth + aisleWidth) + shelfWidth / 2 + aisleWidth / 2,
|
||||
y: 0,
|
||||
z: row * (shelfDepth + aisleWidth) + shelfDepth / 2 + aisleWidth / 2
|
||||
},
|
||||
size: {
|
||||
width: shelfWidth,
|
||||
depth: shelfDepth,
|
||||
height: 6.0 // 货架总高6米
|
||||
},
|
||||
orientation: 0,
|
||||
aisleWidth: aisleWidth,
|
||||
material: '重型钢结构',
|
||||
maxLoad: 2000, // 最大承重2000kg
|
||||
safety: {
|
||||
loadIndicator: '正常',
|
||||
stability: '优秀',
|
||||
lastInspection: '2024-01-10'
|
||||
},
|
||||
|
||||
// 货架结构
|
||||
structure: {
|
||||
columns: 3, // 每组货架有3个立柱
|
||||
beams: 4, // 每层有横梁
|
||||
hasTopBeam: false, // 最上面一排没有横梁
|
||||
columnSpacing: 1.2 // 立柱间距
|
||||
},
|
||||
|
||||
// 层级配置
|
||||
levels: Array.from({ length: levels }, (_, levelIndex) => ({
|
||||
levelId: `${shelfId}-L${levelIndex + 1}`,
|
||||
levelNumber: levelIndex + 1,
|
||||
heightFromGround: 0.5 + levelIndex * 1.5, // 层高从地面开始
|
||||
levelHeight: 1.3, // 每层高度1.3米
|
||||
beams: {
|
||||
hasBeam: true,
|
||||
beamHeight: 0.15,
|
||||
beamColor: warehouseColors.shelf.beam
|
||||
},
|
||||
|
||||
// 格子配置(每层2个格子)
|
||||
cells: Array.from({ length: cellsPerLevel }, (_, cellIndex) => {
|
||||
const cellId = `${shelfId}-L${levelIndex + 1}-C${cellIndex + 1}`
|
||||
const isOccupied = Math.random() > 0.4
|
||||
|
||||
return {
|
||||
id: cellId,
|
||||
name: `${prefix}${row + 1}-${col + 1}-L${levelIndex + 1}-C${cellIndex + 1}`,
|
||||
position: {
|
||||
x: -shelfWidth / 2 + shelfWidth / (cellsPerLevel * 2) + (shelfWidth / cellsPerLevel) * cellIndex,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
width: shelfWidth / cellsPerLevel - 0.05, // 格子宽度
|
||||
depth: shelfDepth - 0.1, // 格子深度
|
||||
height: levelIndex === 0 ? 1.2 : 1.3 // 第一层稍低
|
||||
},
|
||||
rowNumber: row + 1,
|
||||
columnNumber: col + 1,
|
||||
levelNumber: levelIndex + 1,
|
||||
cellNumber: cellIndex + 1,
|
||||
status: isOccupied ? 'occupied' : Math.random() > 0.7 ? 'reserved' : 'empty',
|
||||
capacity: {
|
||||
maxWeight: 500,
|
||||
maxVolume: 1.2,
|
||||
currentWeight: isOccupied ? Math.random() * 300 + 100 : 0
|
||||
},
|
||||
goods: isOccupied ? generateGoods() : null,
|
||||
attributes: {
|
||||
temperature: '常温',
|
||||
humidity: '标准',
|
||||
accessType: '正面',
|
||||
lockType: '机械锁'
|
||||
},
|
||||
lastAccessed: isOccupied ? randomDate() : null,
|
||||
inspectionDate: '2024-01-10'
|
||||
}
|
||||
})
|
||||
})),
|
||||
|
||||
// 维护信息
|
||||
maintenance: {
|
||||
lastInspection: '2024-01-10',
|
||||
nextInspection: '2024-04-10',
|
||||
condition: '良好',
|
||||
notes: ''
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return shelves
|
||||
}
|
||||
|
||||
// 生成拣选区货架(流利架)
|
||||
function generatePickingShelves(prefix, rows, columns) {
|
||||
const shelves = []
|
||||
const shelfWidth = 1.8
|
||||
const shelfDepth = 1.0
|
||||
const aisleWidth = 2.8
|
||||
|
||||
const levels = 3
|
||||
const cellsPerLevel = 3
|
||||
|
||||
for (let row = 0; row < rows; row++) {
|
||||
for (let col = 0; col < columns; col++) {
|
||||
const shelfId = `shelf-${prefix}-${String(row + 1).padStart(3, '0')}-${String(col + 1).padStart(2, '0')}`
|
||||
|
||||
shelves.push({
|
||||
id: shelfId,
|
||||
name: `流利架${prefix}${row + 1}-${col + 1}`,
|
||||
type: 'flow',
|
||||
position: {
|
||||
x: col * (shelfWidth + aisleWidth) + shelfWidth / 2 + aisleWidth / 2,
|
||||
y: 0,
|
||||
z: 70 + row * (shelfDepth + aisleWidth) + shelfDepth / 2 + aisleWidth / 2
|
||||
},
|
||||
size: {
|
||||
width: shelfWidth,
|
||||
depth: shelfDepth,
|
||||
height: 4.5
|
||||
},
|
||||
orientation: Math.PI / 2,
|
||||
aisleWidth: aisleWidth,
|
||||
material: '轻型铝材',
|
||||
maxLoad: 800,
|
||||
|
||||
structure: {
|
||||
columns: 2,
|
||||
beams: 3,
|
||||
hasTopBeam: false,
|
||||
columnSpacing: 1.0
|
||||
},
|
||||
|
||||
levels: Array.from({ length: levels }, (_, levelIndex) => ({
|
||||
levelId: `${shelfId}-L${levelIndex + 1}`,
|
||||
levelNumber: levelIndex + 1,
|
||||
heightFromGround: 0.3 + levelIndex * 1.4,
|
||||
levelHeight: 1.2,
|
||||
beams: {
|
||||
hasBeam: true,
|
||||
beamHeight: 0.12,
|
||||
beamColor: '#607D8B'
|
||||
},
|
||||
|
||||
cells: Array.from({ length: cellsPerLevel }, (_, cellIndex) => {
|
||||
const cellId = `${shelfId}-L${levelIndex + 1}-C${cellIndex + 1}`
|
||||
const isOccupied = Math.random() > 0.3
|
||||
|
||||
return {
|
||||
id: cellId,
|
||||
name: `${prefix}${row + 1}-${col + 1}-L${levelIndex + 1}-C${cellIndex + 1}`,
|
||||
position: {
|
||||
x: -shelfWidth / 2 + shelfWidth / (cellsPerLevel * 2) + (shelfWidth / cellsPerLevel) * cellIndex,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
width: shelfWidth / cellsPerLevel - 0.04,
|
||||
depth: shelfDepth - 0.08,
|
||||
height: 1.0
|
||||
},
|
||||
rowNumber: row + 1,
|
||||
columnNumber: col + 1,
|
||||
levelNumber: levelIndex + 1,
|
||||
cellNumber: cellIndex + 1,
|
||||
status: isOccupied ? 'occupied' : 'empty',
|
||||
capacity: {
|
||||
maxWeight: 200,
|
||||
maxVolume: 0.8,
|
||||
currentWeight: isOccupied ? Math.random() * 150 + 50 : 0
|
||||
},
|
||||
goods: isOccupied ? generateGoods() : null,
|
||||
attributes: {
|
||||
flowDirection: 'forward',
|
||||
currentStock: isOccupied ? Math.floor(Math.random() * 15) + 5 : 0,
|
||||
minStock: 5,
|
||||
maxStock: 20
|
||||
},
|
||||
lastAccessed: isOccupied ? randomDate() : null
|
||||
}
|
||||
})
|
||||
})),
|
||||
|
||||
features: ['重力滑道', '先进先出', '电子标签', '缺货报警']
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return shelves
|
||||
}
|
||||
|
||||
// 生成包装区工作台
|
||||
function generatePackingShelves(prefix, rows, columns) {
|
||||
const shelves = []
|
||||
|
||||
for (let row = 0; row < rows; row++) {
|
||||
for (let col = 0; col < columns; col++) {
|
||||
shelves.push({
|
||||
id: `shelf-${prefix}-${row + 1}-${col + 1}`,
|
||||
name: `工作台${prefix}${row + 1}-${col + 1}`,
|
||||
type: 'workbench',
|
||||
position: {
|
||||
x: 90 + col * 5,
|
||||
y: 0,
|
||||
z: row * 6
|
||||
},
|
||||
size: {
|
||||
width: 2.0,
|
||||
depth: 1.5,
|
||||
height: 1.2
|
||||
},
|
||||
orientation: 0,
|
||||
material: '不锈钢',
|
||||
equipment: ['打包机', '称重仪', '标签打印机', '扫描枪'],
|
||||
status: Math.random() > 0.7 ? 'busy' : 'idle',
|
||||
currentTask: Math.random() > 0.7 ? '打包作业中' : '待机'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return shelves
|
||||
}
|
||||
|
||||
// 生成货物数据
|
||||
function generateGoods() {
|
||||
const goodsTypes = [
|
||||
{ category: 'electronics', name: '智能手机', weight: 0.5, volume: 0.002, color: '#2196F3' },
|
||||
{ category: 'electronics', name: '笔记本电脑', weight: 2.5, volume: 0.015, color: '#3F51B5' },
|
||||
{ category: 'clothing', name: '服装', weight: 1.2, volume: 0.008, color: '#E91E63' },
|
||||
{ category: 'food', name: '食品', weight: 3.0, volume: 0.025, color: '#4CAF50' },
|
||||
{ category: 'furniture', name: '家具配件', weight: 8.0, volume: 0.05, color: '#795548' },
|
||||
{ category: 'medical', name: '医疗用品', weight: 1.8, volume: 0.012, color: '#009688' },
|
||||
{ category: 'chemical', name: '化工原料', weight: 15.0, volume: 0.03, color: '#FF9800' },
|
||||
{ category: 'machinery', name: '机械零件', weight: 12.0, volume: 0.04, color: '#607D8B' }
|
||||
]
|
||||
|
||||
const type = goodsTypes[Math.floor(Math.random() * goodsTypes.length)]
|
||||
const quantity = Math.floor(Math.random() * 10) + 1
|
||||
|
||||
return {
|
||||
id: `goods-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
||||
name: type.name,
|
||||
category: type.category,
|
||||
sku: `SKU-${Math.floor(Math.random() * 10000).toString().padStart(6, '0')}`,
|
||||
quantity: quantity,
|
||||
unit: '件',
|
||||
weight: type.weight * quantity,
|
||||
volume: type.volume * quantity,
|
||||
color: type.color,
|
||||
storageRequirements: {
|
||||
temperature: '常温',
|
||||
humidity: '标准',
|
||||
specialHandling: type.category === 'chemical' ? '危险品' : '普通'
|
||||
},
|
||||
expiryDate: type.category === 'food' ? randomDate(30, 180) : null,
|
||||
value: Math.floor(Math.random() * 5000) + 100,
|
||||
supplier: randomSupplier(),
|
||||
arrivedDate: randomDate(1, 30),
|
||||
status: 'in_storage'
|
||||
}
|
||||
}
|
||||
|
||||
// 生成墙壁
|
||||
function generateWalls() {
|
||||
return [
|
||||
// 主墙
|
||||
{
|
||||
id: 'wall-north',
|
||||
name: '北墙',
|
||||
position: { x: 100, y: 0, z: -1 },
|
||||
size: { width: 200, height: 10, depth: 0.5 },
|
||||
rotation: 0,
|
||||
color: warehouseColors.building.wall,
|
||||
type: 'exterior',
|
||||
features: ['防火', '隔音', '保温']
|
||||
},
|
||||
{
|
||||
id: 'wall-south',
|
||||
name: '南墙',
|
||||
position: { x: 100, y: 0, z: 151 },
|
||||
size: { width: 200, height: 10, depth: 0.5 },
|
||||
rotation: 0,
|
||||
color: warehouseColors.building.wall,
|
||||
type: 'exterior'
|
||||
},
|
||||
{
|
||||
id: 'wall-west',
|
||||
name: '西墙',
|
||||
position: { x: -1, y: 0, z: 75 },
|
||||
size: { width: 150, height: 10, depth: 0.5 },
|
||||
rotation: Math.PI / 2,
|
||||
color: warehouseColors.building.wall,
|
||||
type: 'exterior'
|
||||
},
|
||||
{
|
||||
id: 'wall-east',
|
||||
name: '东墙',
|
||||
position: { x: 201, y: 0, z: 75 },
|
||||
size: { width: 150, height: 10, depth: 0.5 },
|
||||
rotation: Math.PI / 2,
|
||||
color: warehouseColors.building.wall,
|
||||
type: 'exterior'
|
||||
},
|
||||
|
||||
// 区域分隔墙
|
||||
{
|
||||
id: 'wall-divider-1',
|
||||
name: 'A-B区分隔墙',
|
||||
position: { x: 40, y: 0, z: 60 },
|
||||
size: { width: 80, height: 8, depth: 0.3 },
|
||||
rotation: 0,
|
||||
color: '#E0E0E0',
|
||||
type: 'interior',
|
||||
hasDoor: true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
// 生成门
|
||||
function generateDoors() {
|
||||
return [
|
||||
{
|
||||
id: 'door-main',
|
||||
name: '主入口',
|
||||
position: { x: 100, y: 0, z: -0.25 },
|
||||
size: { width: 5, height: 4, depth: 0.1 },
|
||||
rotation: 0,
|
||||
color: warehouseColors.building.door,
|
||||
type: 'sliding',
|
||||
direction: '双向',
|
||||
accessControl: true,
|
||||
status: 'closed'
|
||||
},
|
||||
{
|
||||
id: 'door-area-ab',
|
||||
name: 'A-B区通道门',
|
||||
position: { x: 40, y: 0, z: 60 },
|
||||
size: { width: 3, height: 3, depth: 0.1 },
|
||||
rotation: Math.PI / 2,
|
||||
color: warehouseColors.building.door,
|
||||
type: 'swing',
|
||||
direction: '双向',
|
||||
accessControl: true,
|
||||
status: 'open'
|
||||
},
|
||||
{
|
||||
id: 'door-emergency',
|
||||
name: '紧急出口',
|
||||
position: { x: 180, y: 0, z: 150.75 },
|
||||
size: { width: 2, height: 2.5, depth: 0.1 },
|
||||
rotation: Math.PI,
|
||||
color: '#F44336',
|
||||
type: 'emergency',
|
||||
direction: '向外',
|
||||
accessControl: false,
|
||||
status: 'closed'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
// 生成窗户
|
||||
function generateWindows() {
|
||||
const windows = []
|
||||
|
||||
// 北墙窗户
|
||||
for (let i = 0; i < 5; i++) {
|
||||
windows.push({
|
||||
id: `window-north-${i + 1}`,
|
||||
position: { x: 20 + i * 30, y: 3, z: -0.25 },
|
||||
size: { width: 2, height: 1.5, depth: 0.05 },
|
||||
rotation: 0,
|
||||
color: warehouseColors.building.window
|
||||
})
|
||||
}
|
||||
|
||||
// 南墙窗户
|
||||
for (let i = 0; i < 5; i++) {
|
||||
windows.push({
|
||||
id: `window-south-${i + 1}`,
|
||||
position: { x: 20 + i * 30, y: 3, z: 150.75 },
|
||||
size: { width: 2, height: 1.5, depth: 0.05 },
|
||||
rotation: Math.PI,
|
||||
color: warehouseColors.building.window
|
||||
})
|
||||
}
|
||||
|
||||
return windows
|
||||
}
|
||||
|
||||
// 生成立柱
|
||||
function generatePillars() {
|
||||
const pillars = []
|
||||
|
||||
// 主立柱
|
||||
for (let x = 0; x <= 200; x += 20) {
|
||||
for (let z = 0; z <= 150; z += 20) {
|
||||
pillars.push({
|
||||
id: `pillar-${x}-${z}`,
|
||||
position: { x: x, y: 0, z: z },
|
||||
size: { width: 0.6, depth: 0.6, height: 10 },
|
||||
color: warehouseColors.building.column,
|
||||
type: 'structural',
|
||||
material: '钢筋混凝土'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return pillars
|
||||
}
|
||||
|
||||
// 辅助函数
|
||||
function randomSupplier() {
|
||||
const suppliers = ['华为', '小米', '联想', '海尔', '美的', '格力', '三只松鼠', '伊利']
|
||||
return suppliers[Math.floor(Math.random() * suppliers.length)]
|
||||
}
|
||||
|
||||
function randomDate(minDays = 1, maxDays = 365) {
|
||||
const date = new Date()
|
||||
date.setDate(date.getDate() - Math.floor(Math.random() * (maxDays - minDays)) + minDays)
|
||||
return date.toISOString().split('T')[0]
|
||||
}
|
||||
|
||||
// 计算仓库统计信息
|
||||
export function calculateWarehouseStats(warehouseData) {
|
||||
const stats = {
|
||||
totalAreas: warehouseData.areas?.length || 0,
|
||||
totalShelves: 0,
|
||||
totalColumns: 0,
|
||||
totalRows: 0,
|
||||
totalLevels: 0,
|
||||
totalCells: 0,
|
||||
occupiedCells: 0,
|
||||
reservedCells: 0,
|
||||
emptyCells: 0,
|
||||
usageRate: 0,
|
||||
capacity: {
|
||||
max: 0,
|
||||
used: 0,
|
||||
available: 0
|
||||
}
|
||||
}
|
||||
|
||||
if (!warehouseData.areas) return stats
|
||||
|
||||
warehouseData.areas.forEach(area => {
|
||||
if (area.shelves) {
|
||||
stats.totalShelves += area.shelves.length
|
||||
|
||||
area.shelves.forEach(shelf => {
|
||||
// 计算货架结构
|
||||
if (shelf.structure) {
|
||||
stats.totalColumns += shelf.structure.columns || 0
|
||||
}
|
||||
|
||||
// 计算层级和格子
|
||||
if (shelf.levels) {
|
||||
stats.totalLevels += shelf.levels.length
|
||||
|
||||
shelf.levels.forEach(level => {
|
||||
if (level.cells) {
|
||||
stats.totalCells += level.cells.length
|
||||
|
||||
level.cells.forEach(cell => {
|
||||
// 容量计算
|
||||
const cellVolume = cell.size?.width * cell.size?.depth * cell.size?.height || 0
|
||||
const cellWeight = cell.capacity?.maxWeight || 0
|
||||
|
||||
stats.capacity.max += cellWeight
|
||||
|
||||
switch (cell.status) {
|
||||
case 'occupied':
|
||||
stats.occupiedCells++
|
||||
stats.capacity.used += cell.capacity?.currentWeight || 0
|
||||
break
|
||||
case 'reserved':
|
||||
stats.reservedCells++
|
||||
break
|
||||
case 'empty':
|
||||
stats.emptyCells++
|
||||
stats.capacity.available += cellWeight
|
||||
break
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// 计算使用率
|
||||
if (stats.totalCells > 0) {
|
||||
stats.usageRate = Math.round((stats.occupiedCells / stats.totalCells) * 100)
|
||||
}
|
||||
|
||||
// 计算行数(假设每排货架为一行)
|
||||
stats.totalRows = stats.totalShelves > 0 ?
|
||||
Math.floor(Math.sqrt(stats.totalShelves)) : 0
|
||||
|
||||
return stats
|
||||
}
|
||||
|
||||
// 导出默认数据
|
||||
export default {
|
||||
warehouseColors,
|
||||
generateWarehouseData,
|
||||
calculateWarehouseStats
|
||||
}
|
||||
239
src/utils/zhijian.js
Normal file
@ -0,0 +1,239 @@
|
||||
|
||||
|
||||
/**
|
||||
* 通用js方法封装处理
|
||||
* Copyright (c) 2023 zhijian
|
||||
*/
|
||||
|
||||
// 日期格式化
|
||||
export function parseTime(time, pattern) {
|
||||
if (arguments.length === 0 || !time) {
|
||||
return null
|
||||
}
|
||||
const format = pattern || '{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)
|
||||
} else if (typeof time === 'string') {
|
||||
time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// 表单重置
|
||||
export function resetForm(refName) {
|
||||
if (this.$refs[refName]) {
|
||||
this.$refs[refName].resetFields();
|
||||
}
|
||||
}
|
||||
|
||||
// 添加日期范围
|
||||
export function addDateRange(params, dateRange, propName) {
|
||||
let search = params;
|
||||
search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
|
||||
dateRange = Array.isArray(dateRange) ? dateRange : [];
|
||||
if (typeof (propName) === 'undefined') {
|
||||
search.params['beginTime'] = dateRange[0];
|
||||
search.params['endTime'] = dateRange[1];
|
||||
} else {
|
||||
search.params['begin' + propName] = dateRange[0];
|
||||
search.params['end' + propName] = dateRange[1];
|
||||
}
|
||||
return search;
|
||||
}
|
||||
|
||||
// 回显数据字典
|
||||
export function selectDictLabel(datas, value) {
|
||||
if (value === undefined) {
|
||||
return "";
|
||||
}
|
||||
var actions = [];
|
||||
Object.keys(datas).some((key) => {
|
||||
if (datas[key].value == ('' + value)) {
|
||||
actions.push(datas[key].label);
|
||||
return true;
|
||||
}
|
||||
})
|
||||
if (actions.length === 0) {
|
||||
actions.push(value);
|
||||
}
|
||||
return actions.join('');
|
||||
}
|
||||
|
||||
// 回显数据字典(字符串、数组)
|
||||
export function selectDictLabels(datas, value, separator) {
|
||||
if (value === undefined || value.length ===0) {
|
||||
return "";
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value = value.join(",");
|
||||
}
|
||||
var actions = [];
|
||||
var currentSeparator = undefined === separator ? "," : separator;
|
||||
var temp = value.split(currentSeparator);
|
||||
Object.keys(value.split(currentSeparator)).some((val) => {
|
||||
var match = false;
|
||||
Object.keys(datas).some((key) => {
|
||||
if (datas[key].value == ('' + temp[val])) {
|
||||
actions.push(datas[key].label + currentSeparator);
|
||||
match = true;
|
||||
}
|
||||
})
|
||||
if (!match) {
|
||||
actions.push(temp[val] + currentSeparator);
|
||||
}
|
||||
})
|
||||
return actions.join('').substring(0, actions.join('').length - 1);
|
||||
}
|
||||
|
||||
// 字符串格式化(%s )
|
||||
export function sprintf(str) {
|
||||
var args = arguments, flag = true, i = 1;
|
||||
str = str.replace(/%s/g, function () {
|
||||
var arg = args[i++];
|
||||
if (typeof arg === 'undefined') {
|
||||
flag = false;
|
||||
return '';
|
||||
}
|
||||
return arg;
|
||||
});
|
||||
return flag ? str : '';
|
||||
}
|
||||
|
||||
// 转换字符串,undefined,null等转化为""
|
||||
export function parseStrEmpty(str) {
|
||||
if (!str || str == "undefined" || str == "null") {
|
||||
return "";
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
// 数据合并
|
||||
export function mergeRecursive(source, target) {
|
||||
for (var p in target) {
|
||||
try {
|
||||
if (target[p].constructor == Object) {
|
||||
source[p] = mergeRecursive(source[p], target[p]);
|
||||
} else {
|
||||
source[p] = target[p];
|
||||
}
|
||||
} catch (e) {
|
||||
source[p] = target[p];
|
||||
}
|
||||
}
|
||||
return source;
|
||||
};
|
||||
|
||||
/**
|
||||
* 构造树型结构数据
|
||||
* @param {*} data 数据源
|
||||
* @param {*} id id字段 默认 'id'
|
||||
* @param {*} parentId 父节点字段 默认 'parentId'
|
||||
* @param {*} children 孩子节点字段 默认 'children'
|
||||
*/
|
||||
export function handleTree(data, id, parentId, children) {
|
||||
let config = {
|
||||
id: id || 'id',
|
||||
parentId: parentId || 'parentId',
|
||||
childrenList: children || 'children'
|
||||
};
|
||||
|
||||
var childrenListMap = {};
|
||||
var nodeIds = {};
|
||||
var tree = [];
|
||||
|
||||
for (let d of data) {
|
||||
let parentId = d[config.parentId];
|
||||
if (childrenListMap[parentId] == null) {
|
||||
childrenListMap[parentId] = [];
|
||||
}
|
||||
nodeIds[d[config.id]] = d;
|
||||
childrenListMap[parentId].push(d);
|
||||
}
|
||||
|
||||
for (let d of data) {
|
||||
let parentId = d[config.parentId];
|
||||
if (nodeIds[parentId] == null) {
|
||||
tree.push(d);
|
||||
}
|
||||
}
|
||||
|
||||
for (let t of tree) {
|
||||
adaptToChildrenList(t);
|
||||
}
|
||||
|
||||
function adaptToChildrenList(o) {
|
||||
if (childrenListMap[o[config.id]] !== null) {
|
||||
o[config.childrenList] = childrenListMap[o[config.id]];
|
||||
}
|
||||
if (o[config.childrenList]) {
|
||||
for (let c of o[config.childrenList]) {
|
||||
adaptToChildrenList(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
return tree;
|
||||
}
|
||||
|
||||
/**
|
||||
* 参数处理
|
||||
* @param {*} params 参数
|
||||
*/
|
||||
export function tansParams(params) {
|
||||
let result = ''
|
||||
for (const propName of Object.keys(params)) {
|
||||
const value = params[propName];
|
||||
var part = encodeURIComponent(propName) + "=";
|
||||
if (value !== null && value !== "" && typeof (value) !== "undefined") {
|
||||
if (typeof value === 'object') {
|
||||
for (const key of Object.keys(value)) {
|
||||
if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
|
||||
let params = propName + '[' + key + ']';
|
||||
var subPart = encodeURIComponent(params) + "=";
|
||||
result += subPart + encodeURIComponent(value[key]) + "&";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result += part + encodeURIComponent(value) + "&";
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// 验证是否为blob格式
|
||||
export function blobValidate(data) {
|
||||
return data.type !== 'application/json'
|
||||
}
|
||||
// 金额格式化
|
||||
export function amountFormatter(row, column, cellValue, index) {
|
||||
if(cellValue) {
|
||||
return '¥' + cellValue.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
|
||||
}
|
||||
}
|
||||