Browse Source

数据备份/挂接

master
xuhuajiao 1 day ago
parent
commit
4687e2cf52
  1. 20
      src/api/system/sql.js
  2. 57
      src/utils/upload.js
  3. 2
      src/views/collectReorganizi/batchConnection/module/detail.vue
  4. 38
      src/views/collectReorganizi/batchConnection/module/form.vue
  5. 276
      src/views/components/category/PreviewForm.vue
  6. 203
      src/views/components/category/preUpload.vue
  7. 808
      src/views/components/category/preUpload2.vue
  8. 186
      src/views/system/database/index.vue

20
src/api/system/sql.js

@ -36,4 +36,22 @@ export function FetchrestoreDatabase(params) {
})
}
export default { add, FetchBackupName, del, FetchrestoreDatabase }
// 初始化自动备份数据库设置
export function FetchDatabaseSaveSetting(params) {
return request({
url: 'api/database/getDatabaseSaveSetting',
method: 'get',
params
})
}
// 保存自动备份数据库设置
export function FetchSaveDatabaseSaveSetting(data) {
return request({
url: 'api/database/saveDatabaseSaveSetting',
method: 'post',
data
})
}
export default { add, FetchBackupName, del, FetchrestoreDatabase, FetchDatabaseSaveSetting, FetchSaveDatabaseSaveSetting }

57
src/utils/upload.js

@ -81,45 +81,48 @@ export function modelUpload(api, file, name) {
// 收集库 - 批量挂接
// export function batchMountUpload(api, file, params) {
export function batchMountUpload(api, params) {
var data = new FormData()
// for (const item in file) { // 现在
// data.append('file', file[item])
// }
data.append('categoryId', params.categoryId)
data.append('mountType', params.mountType)
data.append('checkRepeatType', params.checkRepeatType)
data.append('matchingMode', params.matchingMode)
data.append('fields', params.fields)
data.append('fondsId', params.fondsId)
data.append('upfilePath', params.upfilePath)
// var data = new FormData()
// data.append('categoryId', params.categoryId)
// data.append('mountType', params.mountType)
// data.append('checkRepeatType', params.checkRepeatType)
// data.append('matchingMode', params.matchingMode)
// data.append('fields', params.fields)
// data.append('fondsId', params.fondsId)
// data.append('upfilePath', params.upfilePath)
const jsonData = JSON.stringify(params)
const config = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': getToken()
}
},
transformRequest: [(data) => data]
}
return axios.post(api, data, config)
return axios.post(api, jsonData, config)
}
// 收集库 - 远程挂接
export function remoteConnectiontUpload(api, params) {
var data = new FormData()
data.append('account', params.account)
data.append('cAddress', params.cAddress)
data.append('cPassword', params.cPassword)
data.append('cPort', params.cPort)
data.append('categoryId', params.categoryId)
data.append('checkRepeatType', params.checkRepeatType)
data.append('matchingMode', params.matchingMode)
data.append('fields', params.fields)
data.append('protocol', params.protocol)
data.append('zipFilePath', params.zipFilePath)
data.append('fondsId', params.fondsId)
// var data = new FormData()
// data.append('account', params.account)
// data.append('cAddress', params.cAddress)
// data.append('cPassword', params.cPassword)
// data.append('cPort', params.cPort)
// data.append('categoryId', params.categoryId)
// data.append('checkRepeatType', params.checkRepeatType)
// data.append('matchingMode', params.matchingMode)
// data.append('fields', params.fields)
// data.append('protocol', params.protocol)
// data.append('zipFilePath', params.zipFilePath)
// data.append('fondsId', params.fondsId)
const jsonData = JSON.stringify(params)
const config = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': getToken()
}
},
transformRequest: [(data) => data]
}
return axios.post(api, data, config)
return axios.post(api, jsonData, config)
}
// 在线编研附件

2
src/views/collectReorganizi/batchConnection/module/detail.vue

@ -20,7 +20,7 @@
</template>
</el-table-column>
<el-table-column prop="reason" label="详情" />
<el-table-column prop="create_time" label="操作时间">
<el-table-column prop="create_time" label="操作时间" width="150px">
<template slot-scope="scope">
<div>{{ scope.row.create_time | parseTime }}</div>
</template>

38
src/views/collectReorganizi/batchConnection/module/form.vue

@ -47,7 +47,8 @@
</div> -->
<div v-for="item in fileList" :key="item.name" class="file-list">
<i class="iconfont icon-xiaowenjian" />
{{ item.file_name }}
<!-- {{ item.file_name }} -->
{{ item }}
</div>
<el-input v-show="false" v-model="form.file" />
<!-- 大文件上传 -->
@ -240,13 +241,13 @@ export default {
console.log('handleSuccessResource', filePath)
console.log('handleSuccessResource', fileName)
console.log('handleSuccessResource', jsonArrayToSend)
console.log('handleSuccessResource', jsonArrayToSend[0].fileJsonString)
// console.log('handleSuccessResource', jsonArrayToSend[0].fileJsonString)
const fileJson = JSON.parse(jsonArrayToSend[0].fileJsonString)
fileJson[0].file_path = filePath
fileJson[0].is_quote = null
fileJson[0].last_modified = jsonArrayToSend[0].last_modified
this.fileList = fileJson
// const fileJson = JSON.parse(jsonArrayToSend[0].fileJsonString)
// fileJson[0].file_path = filePath
// fileJson[0].is_quote = null
// fileJson[0].last_modified = jsonArrayToSend[0].last_modified
this.fileList = fileName
this.upfilePath = filePath
},
handleErrorResource(res) {
@ -305,9 +306,9 @@ export default {
} else {
const params = {
'account': this.form.filePath.account,
'cAddress': this.form.filePath.caddress,
'cPassword': this.form.filePath.cpassword,
'cPort': this.form.filePath.cport,
'caddress': this.form.filePath.caddress,
'cpassword': this.form.filePath.cpassword,
'cport': this.form.filePath.cport,
'categoryId': this.selectedCategory.id,
'fondsId': this.selectedCategory.fondsId,
'checkRepeatType': this.form.checkRepeatType,
@ -409,12 +410,17 @@ export default {
if (val) {
this.fileRemoteOptions = []
FetchFileByRemoteConnection({ 'id': val.id }).then(res => {
this.fileRemoteOptions = res.map(item => {
const json = {}
json.value = item
json.name = item
return json
})
if (res) {
this.fileRemoteOptions = res.map(item => {
const json = {}
json.value = item
json.name = item
return json
})
} else {
this.fileRemoteOptions = []
}
this.fileRemoteLoading = false
})
}

276
src/views/components/category/PreviewForm.vue

@ -1283,164 +1283,166 @@ export default {
}
console.log('this.addOrUpdateForm', this.addOrUpdateForm)
console.log('this.addOrUpdateForm.archive_no', this.addOrUpdateForm.archive_no)
this.$refs[formName].validate((valid, fields) => {
if (valid) {
delete this.addOrUpdateForm.id
this.$emit('formLoadingShow', true)
//
if (this.isDesFormType === 'prearchiveLibrary') {
if (this.fileOriginal === null) {
this.$message({ message: '请上传电子原件', type: 'error', offset: 8 })
this.$emit('formLoadingShow', false)
return false
}
// delete this.addOrUpdateForm.fileOriginal
const params = {
'id': this.archivesType === 'edit' ? this.arcId : null,
'ids': null,
'documentId': categoryId,
'delMan': null,
'jsonString': JSON.stringify(this.addOrUpdateForm),
'fileJsonString': this.fileJsonString,
'fondsAffiliation': this.selectedDocument.fondsId
this.$nextTick(() => {
console.log('this.addOrUpdateForm.archive_no', this.addOrUpdateForm.archive_no)
this.$refs[formName].validate((valid, fields) => {
if (valid) {
delete this.addOrUpdateForm.id
this.$emit('formLoadingShow', true)
//
if (this.isDesFormType === 'prearchiveLibrary') {
if (this.fileOriginal === null) {
this.$message({ message: '请上传电子原件', type: 'error', offset: 8 })
this.$emit('formLoadingShow', false)
return false
}
// delete this.addOrUpdateForm.fileOriginal
const params = {
'id': this.archivesType === 'edit' ? this.arcId : null,
'ids': null,
'documentId': categoryId,
'delMan': null,
'jsonString': JSON.stringify(this.addOrUpdateForm),
'fileJsonString': this.fileJsonString,
'fondsAffiliation': this.selectedDocument.fondsId
}
console.log('this.fileJsonString', JSON.parse(this.fileJsonString))
console.log('params', params)
prearchEdit(params).then(res => {
if (res) {
this.$message({ message: res.message, type: 'success', offset: 8 })
this.$emit('close-dialog')
this.crud.refresh()
this.fileOriginal = null
}
this.$emit('formLoadingShow', false)
})
} else if (this.isDesFormType === 'mergeFile') {
console.log('this.fileJsonString', JSON.parse(this.fileJsonString))
console.log('params', params)
prearchEdit(params).then(res => {
if (res) {
this.$message({ message: res.message, type: 'success', offset: 8 })
this.$emit('close-dialog')
this.crud.refresh()
this.fileOriginal = null
}
this.$emit('formLoadingShow', false)
})
} else if (this.isDesFormType === 'mergeFile') {
//
const params = {
'fondsAffiliation': this.selectedCategory.fondsId,
'archivesId': null,
'archivesIds': this.mergeFileArcIds,
'documentId': categoryId,
'categoryId': this.mergeFileCategory,
'archivesNo': this.addOrUpdateForm.archive_no,
'jsonString': JSON.stringify(this.addOrUpdateForm)
}
console.log('合并成件this.selectedCategory', this.selectedCategory)
console.log('params', params)
FetchMergeToFile(params).then(res => {
if (res.code !== 500) {
this.$message({ message: res, type: 'success', offset: 8 })
} else {
this.$message({ message: res.message, type: 'error', offset: 8 })
}
this.$emit('close-dialog')
this.crud.refresh()
this.$emit('formLoadingShow', false)
})
} else {
//
let parentsId = null
// 2 3 / 4 6
if (this.isTitleType === 2) {
parentsId = null
} else if (this.isTitleType === 3) {
if (this.selectedCategory.arrangeType === 1) {
parentsId = null
} else {
parentsId = this.parentsData.parentsProjectId
}
} else if (this.isTitleType === 4) {
//
parentsId = this.parentsData.parentsAnjuanId
} else if (this.isTitleType === 6) {
//
parentsId = this.parentsData.parentsJuanneiId
}
let params
if (quickPaperArcId && quickPaperArcId.length !== 0 && this.archivesType === 'add') {
// archivesIds archivesIdthis.arcId = null
params = {
'archivesId': this.arcId,
'archivesIds': quickPaperArcId,
'categoryId': categoryId,
'parentsId': parentsId,
'categoryLevel': 2,
'jsonString': JSON.stringify(this.addOrUpdateForm)
}
} else if (this.selectedCategory.arrangeType === 3 && this.activeIndex === 1 && this.archivesType === 'add') {
// parentsId === null
params = {
'archivesId': this.arcId,
'archivesIds': null,
'categoryId': categoryId,
'parentsId': null,
'categoryLevel': this.collectLevel,
'jsonString': JSON.stringify(this.addOrUpdateForm)
}
} else {
params = {
'archivesId': this.arcId,
'archivesIds': null,
'categoryId': categoryId,
'parentsId': parentsId,
'categoryLevel': this.collectLevel,
const params = {
'fondsAffiliation': this.selectedCategory.fondsId,
'archivesId': null,
'archivesIds': this.mergeFileArcIds,
'documentId': categoryId,
'categoryId': this.mergeFileCategory,
'archivesNo': this.addOrUpdateForm.archive_no,
'jsonString': JSON.stringify(this.addOrUpdateForm)
}
}
console.log(params)
if (this.archivesType === 'add') {
collectAdd(params).then(res => {
console.log('res', res)
console.log('合并成件this.selectedCategory', this.selectedCategory)
console.log('params', params)
FetchMergeToFile(params).then(res => {
if (res.code !== 500) {
this.$message({ message: res, type: 'success', offset: 8 })
this.$emit('close-dialog', parentsId)
if (arcAddType === 1) {
localStorage.setItem('savePrevFromData', JSON.stringify(this.addOrUpdateForm))
setTimeout(() => {
this.$emit('handleForm', 'add', 0)
}, 1000)
} else {
localStorage.removeItem('savePrevFromData')
}
} else {
this.$message({ message: res.message, type: 'error', offset: 8 })
this.$emit('close-dialog', parentsId)
}
this.$emit('close-dialog')
this.crud.refresh()
this.$emit('formLoadingShow', false)
})
} else {
collectEdit(params).then(res => {
console.log('res-collectEdit', res)
if (res.code !== 500) {
this.$message({ message: res, type: 'success', offset: 8 })
this.$emit('close-dialog', parentsId)
//
let parentsId = null
// 2 3 / 4 6
if (this.isTitleType === 2) {
parentsId = null
} else if (this.isTitleType === 3) {
if (this.selectedCategory.arrangeType === 1) {
parentsId = null
} else {
this.$message({ message: res.message, type: 'error', offset: 8 })
this.$emit('close-dialog', parentsId)
parentsId = this.parentsData.parentsProjectId
}
this.$emit('formLoadingShow', false)
})
} else if (this.isTitleType === 4) {
//
parentsId = this.parentsData.parentsAnjuanId
} else if (this.isTitleType === 6) {
//
parentsId = this.parentsData.parentsJuanneiId
}
let params
if (quickPaperArcId && quickPaperArcId.length !== 0 && this.archivesType === 'add') {
// archivesIds archivesIdthis.arcId = null
params = {
'archivesId': this.arcId,
'archivesIds': quickPaperArcId,
'categoryId': categoryId,
'parentsId': parentsId,
'categoryLevel': 2,
'jsonString': JSON.stringify(this.addOrUpdateForm)
}
} else if (this.selectedCategory.arrangeType === 3 && this.activeIndex === 1 && this.archivesType === 'add') {
// parentsId === null
params = {
'archivesId': this.arcId,
'archivesIds': null,
'categoryId': categoryId,
'parentsId': null,
'categoryLevel': this.collectLevel,
'jsonString': JSON.stringify(this.addOrUpdateForm)
}
} else {
params = {
'archivesId': this.arcId,
'archivesIds': null,
'categoryId': categoryId,
'parentsId': parentsId,
'categoryLevel': this.collectLevel,
'jsonString': JSON.stringify(this.addOrUpdateForm)
}
}
console.log(params)
if (this.archivesType === 'add') {
collectAdd(params).then(res => {
console.log('res', res)
if (res.code !== 500) {
this.$message({ message: res, type: 'success', offset: 8 })
this.$emit('close-dialog', parentsId)
if (arcAddType === 1) {
localStorage.setItem('savePrevFromData', JSON.stringify(this.addOrUpdateForm))
setTimeout(() => {
this.$emit('handleForm', 'add', 0)
}, 1000)
} else {
localStorage.removeItem('savePrevFromData')
}
} else {
this.$message({ message: res.message, type: 'error', offset: 8 })
this.$emit('close-dialog', parentsId)
}
this.$emit('formLoadingShow', false)
})
} else {
collectEdit(params).then(res => {
console.log('res-collectEdit', res)
if (res.code !== 500) {
this.$message({ message: res, type: 'success', offset: 8 })
this.$emit('close-dialog', parentsId)
} else {
this.$message({ message: res.message, type: 'error', offset: 8 })
this.$emit('close-dialog', parentsId)
}
this.$emit('formLoadingShow', false)
})
}
}
}
} else {
console.log('error submit!!')
if (this.isDesFormType === 'arcives') {
for (const field in fields) {
if (fields[field].length > 0) {
} else {
console.log('error submit!!')
if (this.isDesFormType === 'arcives') {
for (const field in fields) {
if (fields[field].length > 0) {
// console.log(` ${field} : ${fields[field][0].message}`)
if (field === 'archive_no') {
console.log('档号有问题')
this.$emit('repeatDataShow', this.archivesSummaryResponse)
if (field === 'archive_no') {
console.log('档号有问题')
this.$emit('repeatDataShow', this.archivesSummaryResponse)
}
}
}
}
return false
}
return false
}
})
})
},
handleClose(done) {

203
src/views/components/category/preUpload.vue

@ -143,7 +143,7 @@ export default {
},
//
chunkApiPath() {
return this.isBatchMount === 'true' ? '/api/collect/chunk' : '/api/minioUpload/chunk'
return this.isBatchMount === 'true' ? '/api/collect/chunkZip' : '/api/minioUpload/chunk'
}
},
@ -534,91 +534,148 @@ export default {
})
try {
const processFiles = validFiles.map(async(fileItem) => {
let response
if (this.isBatchMount === 'true') {
const fileItem = validFiles[0]
const file = fileItem.file
const json = {}
const jsonArray = []
const jsonString = {}
if (file.type.startsWith('image')) {
const fileBase64 = await this.getBase64(file)
const imgRes = await this.getImgPx(fileBase64)
jsonString.file_dpi = `${imgRes.width}px*${imgRes.height}px`
} else {
jsonString.file_dpi = ''
}
jsonString.file_name = file.name
jsonString.file_size = file.size
jsonString.file_type = file.name.split('.').pop() || ''
jsonString.last_modified = file.lastModified
jsonString.file_path = ''
jsonString.sequence = null
jsonString.archive_id = this.arcId
jsonString.create_time = nowDate
jsonString.id = null
jsonString.file_thumbnail = ''
jsonArray.push(jsonString)
console.log('file.lastModified', file.lastModified)
if (this.isBatchMount === 'true') {
json.categoryId = this.selectedCategory.id
} else {
json.documentId = this.selectedDocument.id
}
const totalChunks = Math.ceil(file.size / this.CHUNK_SIZE)
const chunksExist = await this.checkAllChunksExist(fileItem.md5, totalChunks)
if (!chunksExist) {
throw new Error(`${file.name}】部分分片未上传完成,无法合并`)
}
json.archivesId = this.arcId
json.identifier = fileItem.md5
json.filename = file.name
json.totalChunks = totalChunks
json.totalSize = file.size
json.fileJsonString = JSON.stringify(jsonArray)
return json
})
const jsonArray = await Promise.all(processFiles)
// URL
const mergeApiUrl = this.isBatchMount === 'true'
? `${this.baseApi}/api/collect/merge`
: `${this.baseApi}/api/minioUpload/merge`
//
const response = await axios.post(mergeApiUrl, jsonArray, {
headers: {
'Authorization': getToken(),
'Content-Type': 'application/json'
const mergeParams = {
identifier: fileItem.md5,
totalChunks: totalChunks,
filename: file.name
}
})
this.totalMergeEndTime = new Date().getTime()
const totalMergeDuration = this.getTimeDiff(this.totalMergeStartTime, this.totalMergeEndTime)
if (response.data.code === 200) {
this.btnLoading = false
this.showMessage('所有文件上传并合并成功', 'success')
validFiles.forEach((fileItem) => {
fileItem.mergeEndTime = new Date().getTime()
const mergeDuration = this.getTimeDiff(fileItem.mergeStartTime, fileItem.mergeEndTime)
console.log(`【文件${fileItem.file.name}】合并结束时间:${this.formatTime(fileItem.mergeEndTime)},合并耗时:${mergeDuration}`)
fileItem.successMsg = '上传成功!'
fileItem.merging = false
//
const mergeApiUrl = `${this.baseApi}/api/collect/mergeZip`
response = await axios.post(mergeApiUrl, mergeParams, {
headers: {
'Authorization': getToken(),
'Content-Type': 'application/json'
}
})
console.log(`【整体合并】所有文件合并完成,整体合并耗时:${totalMergeDuration}`)
this.$emit('onUploadSuccess', response.data.data, validFiles.map(f => f.file.name), jsonArray)
this.uploadMinioVisible = false
this.fileList = [] //
this.totalMergeEndTime = new Date().getTime()
const totalMergeDuration = this.getTimeDiff(this.totalMergeStartTime, this.totalMergeEndTime)
if (response.data.code === 200) {
this.btnLoading = false
this.showMessage('所有文件上传并合并成功', 'success')
validFiles.forEach((fileItem) => {
fileItem.mergeEndTime = new Date().getTime()
const mergeDuration = this.getTimeDiff(fileItem.mergeStartTime, fileItem.mergeEndTime)
console.log(`【文件${fileItem.file.name}】合并结束时间:${this.formatTime(fileItem.mergeEndTime)},合并耗时:${mergeDuration}`)
fileItem.successMsg = '上传成功!'
fileItem.merging = false
})
console.log(`【整体合并】所有文件合并完成,整体合并耗时:${totalMergeDuration}`)
this.$emit('onUploadSuccess', response.data.data, validFiles.map(f => f.file.name), '')
this.uploadMinioVisible = false
this.fileList = [] //
} else {
this.btnLoading = false
throw new Error(response.data.msg || '合并失败')
}
} else {
this.btnLoading = false
throw new Error(response.data.msg || '合并失败')
const processFiles = validFiles.map(async(fileItem) => {
const file = fileItem.file
const json = {}
const jsonArray = []
const jsonString = {}
if (file.type.startsWith('image')) {
const fileBase64 = await this.getBase64(file)
const imgRes = await this.getImgPx(fileBase64)
jsonString.file_dpi = `${imgRes.width}px*${imgRes.height}px`
} else {
jsonString.file_dpi = ''
}
jsonString.file_name = file.name
jsonString.file_size = file.size
jsonString.file_type = file.name.split('.').pop() || ''
jsonString.last_modified = file.lastModified
jsonString.file_path = ''
jsonString.sequence = null
jsonString.archive_id = this.arcId
jsonString.create_time = nowDate
jsonString.id = null
jsonString.file_thumbnail = ''
jsonArray.push(jsonString)
console.log('file.lastModified', file.lastModified)
if (this.isBatchMount === 'true') {
json.categoryId = this.selectedCategory.id
} else {
json.documentId = this.selectedDocument.id
}
const totalChunks = Math.ceil(file.size / this.CHUNK_SIZE)
const chunksExist = await this.checkAllChunksExist(fileItem.md5, totalChunks)
if (!chunksExist) {
throw new Error(`${file.name}】部分分片未上传完成,无法合并`)
}
json.archivesId = this.arcId
json.identifier = fileItem.md5
json.filename = file.name
json.totalChunks = totalChunks
json.totalSize = file.size
json.fileJsonString = JSON.stringify(jsonArray)
return json
})
const jsonArray = await Promise.all(processFiles)
const mergeApiUrl = `${this.baseApi}/api/minioUpload/merge`
response = await axios.post(mergeApiUrl, jsonArray, {
headers: {
'Authorization': getToken(),
'Content-Type': 'application/json'
}
})
this.totalMergeEndTime = new Date().getTime()
const totalMergeDuration = this.getTimeDiff(this.totalMergeStartTime, this.totalMergeEndTime)
if (response.data.code === 200) {
this.btnLoading = false
this.showMessage('所有文件上传并合并成功', 'success')
validFiles.forEach((fileItem) => {
fileItem.mergeEndTime = new Date().getTime()
const mergeDuration = this.getTimeDiff(fileItem.mergeStartTime, fileItem.mergeEndTime)
console.log(`【文件${fileItem.file.name}】合并结束时间:${this.formatTime(fileItem.mergeEndTime)},合并耗时:${mergeDuration}`)
fileItem.successMsg = '上传成功!'
fileItem.merging = false
})
console.log(`【整体合并】所有文件合并完成,整体合并耗时:${totalMergeDuration}`)
this.$emit('onUploadSuccess', response.data.data, validFiles.map(f => f.file.name), jsonArray)
this.uploadMinioVisible = false
this.fileList = [] //
} else {
this.btnLoading = false
throw new Error(response.data.msg || '合并失败')
}
}
// URL
// const mergeApiUrl = this.isBatchMount === 'true'
// ? `${this.baseApi}/api/collect/merge`
// : `${this.baseApi}/api/minioUpload/merge`
// //
// const response = await axios.post(mergeApiUrl, jsonArray, {
// headers: {
// 'Authorization': getToken(),
// 'Content-Type': 'application/json'
// }
// })
} catch (err) {
this.btnLoading = false
this.totalMergeEndTime = new Date().getTime()

808
src/views/components/category/preUpload2.vue

@ -0,0 +1,808 @@
<template>
<div class="upload-minio">
<!-- 文件选择按钮与隐藏的input -->
<el-button
v-if="isPreFile !== 'true'"
type="primary"
:disabled="!isCaValid || isCheckingCa"
icon="el-icon-upload"
@click="uploadMinioVisible=true"
>
选择文件
</el-button>
<!--<input
type="file"
multiple
:disabled="!isCaValid || isCheckingCa"
:accept="fileAcceptType"
class="file-input"
@change="handleFileSelect"
> -->
<el-dialog
title="文件列表"
class="minio-file"
:close-on-click-modal="false"
:modal-append-to-body="false"
append-to-body
:visible.sync="uploadMinioVisible"
:before-close="handleCloseDialog"
width="600px"
>
<div class="uploader-drop" style="margin-bottom: 20px;">
<div class="uploader-btn" @click="triggerFileInput">
<p>{{ isBatchMount !== 'true' ? '点击上传(可多文件上传)' : "点击上传ZIP包(可多文件上传)" }}</p>
<div style="margin: 20px 0 0 0;">
<i class="iconfont icon-tianjiawenjian upload-icon" />
<input
ref="fileInput"
type="file"
multiple
:disabled="!isCaValid || isCheckingCa"
:accept="fileAcceptType"
class="file-input"
style="display: none;"
@change="handleFileSelect"
>
</div>
</div>
</div>
<!-- <el-button
type="success"
style="margin-bottom: 20px"
:disabled="fileList.some(item => item.uploading || item.merging) || fileList.length === 0"
@click="handleUploadConfirm"
>
开始上传
</el-button> -->
<div v-if="fileList.length !== 0" style="max-height: 400px; overflow: hidden; overflow-y: scroll;">
<div
v-for="(fileItem, index) in fileList"
:key="index"
class="file-item"
>
<div class="file-name">
{{ fileItem.file.name }}
<span class="file-size">{{ formatFileSize(fileItem.file.size) }}</span>
<i class="iconfont icon-shanchu" @click="handleDeleteFile(index)" />
</div>
<!-- 上传进度条 -->
<div v-if="fileItem.uploading" class="progress-wrapper">
<span class="progress-text">上传进度: {{ fileItem.progress }}%</span>
<div class="progress-bar" :style="{ width: fileItem.progress + '%' }" />
</div>
<!-- 合并中状态 -->
<div v-if="fileItem.merging" class="merge-loading ">
<span>合并中...</span>
</div>
<!-- 上传错误信息 -->
<p v-if="fileItem.errorMsg" class="error">{{ fileItem.errorMsg }}</p>
<!-- 上传成功 -->
<p v-if="fileItem.successMsg" class="success">{{ fileItem.successMsg }}</p>
</div>
</div>
<div slot="footer" class="dialog-footer" style="margin-top: 0;">
<el-button type="text" @click="handleCloseDialog">取消</el-button>
<el-button :disabled="fileList.some(item => item.uploading || item.merging) || fileList.length === 0" :loading="btnLoading" type="primary" @click="handleUploadConfirm">保存</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import { FetchCheckCaValidity } from '@/api/system/auth2'
import axios from 'axios'
import SparkMD5 from 'spark-md5'
import { getToken } from '@/utils/auth'
import { getCurrentTime } from '@/utils/index'
export default {
name: 'MinioMultiChunkUpload',
props: {
selectedDocument: {
type: Object,
default: () => ({})
},
arcId: {
type: String,
default: ''
},
selectedCategory: {
type: Object,
default: () => ({})
},
isBatchMount: {
type: String,
default: ''
},
isPreFile: {
type: String,
default: ''
}
},
data() {
return {
btnLoading: false,
uploadMinioVisible: false, //
fileList: [], //
CHUNK_SIZE: 5 * 1024 * 1024, // (5MB)
totalMergeStartTime: null, //
totalMergeEndTime: null, //
allChunksUploaded: false, //
isCaValid: false, // CA
isCheckingCa: false, // CA
baseApi: process.env.NODE_ENV === 'production' ? window.g.ApiUrl : process.env.VUE_APP_BASE_API
}
},
//
computed: {
fileAcceptType() {
return this.isBatchMount === 'true' ? '.zip' : ''
},
//
chunkApiPath() {
return this.isBatchMount === 'true' ? '/api/collect/chunk' : '/api/minioUpload/chunk'
}
},
mounted() {
this.getCheckCaValidity() // CA
},
methods: {
triggerFileInput() {
this.$refs.fileInput.click()
},
handleDeleteFile(index) {
// /
const fileItem = this.fileList[index]
if (fileItem.uploading || fileItem.merging) {
this.showMessage('当前文件正在上传/合并中,无法删除', 'warning')
return
}
//
this.fileList.splice(index, 1)
this.showMessage('文件已移除', 'success')
},
formatFileSize(bytes) {
if (bytes === 0) return '0.00MB'
const mb = bytes / (1024 * 1024) // 1MB = 1024KB = 1024*1024B
return mb.toFixed(2) + 'MB'
},
/**
* 工具方法格式化时间戳为易读的本地时间带毫秒
* @param {number} timestamp - 时间戳
* @returns {string} 格式化后的时间字符串
*/
formatTime(timestamp) {
if (!timestamp) return '无'
return new Date(timestamp).toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
millisecond: '3-digit'
})
},
/**
* 工具方法计算两个时间戳的差值并格式化
* @param {number} start - 开始时间戳
* @param {number} end - 结束时间戳
* @returns {string} 格式化的耗时字符串
*/
getTimeDiff(start, end) {
if (!start || !end) return '0ms'
const diff = end - start
if (diff < 1000) return `${diff}ms`
if (diff < 60000) return `${(diff / 1000).toFixed(2)}s`
return `${(diff / 60000).toFixed(2)}min`
},
/**
* 工具方法获取图片分辨率
* @param {string} base64 - 图片base64编码
* @returns {Promise<{width: number, height: number}>} 图片宽高
*/
getImgPx(base64) {
return new Promise((resolve) => {
const img = new Image()
img.onload = () => {
resolve({ width: img.width, height: img.height })
}
img.src = base64
})
},
/**
* 工具方法将文件转为base64
* @param {File} file - 文件对象
* @returns {Promise<string>} base64编码
*/
getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => resolve(reader.result)
reader.onerror = (err) => reject(err)
})
},
/**
* 工具方法显示提示信息
* @param {string} msg - 提示内容
* @param {string} type - 类型success/error
*/
showMessage(message, type) {
this.$message({ message, type, offset: 8 })
},
/**
* 重置上传状态
*/
resetUploadState() {
this.allChunksUploaded = false
this.btnLoading = false
},
/**
* 校验CA证书有效性
*/
async getCheckCaValidity() {
try {
this.isCheckingCa = true
const res = await FetchCheckCaValidity()
this.isCaValid = !!res //
if (!this.isCaValid) {
this.showMessage('CA证书不在有效期内,无法进行分片上传', 'error')
}
} catch (err) {
this.isCaValid = false
this.showMessage('CA证书校验失败:' + err.message, 'error')
console.error('CA校验接口异常:', err)
} finally {
this.isCheckingCa = false
}
},
/**
* 手动重新校验CA证书
*/
recheckCa() {
this.getCheckCaValidity()
},
/**
* 多文件选择处理函数选择后打开弹框仅初始化文件列表不上传
* @param {Event} e - 选择文件的事件对象
*/
async handleFileSelect(e) {
// 1. CA
if (this.isCheckingCa) {
this.showMessage('正在校验CA证书,请稍候...', 'warning')
e.target.value = ''
return
}
if (!this.isCaValid) {
this.showMessage('CA证书不在有效期内,无法上传文件', 'error')
e.target.value = ''
return
}
// 2.
const selectedFiles = Array.from(e.target.files)
if (selectedFiles.length === 0) return
//
const newFileList = selectedFiles.map(file => ({
file,
uploading: false,
merging: false,
progress: 0,
errorMsg: '',
successMsg: '',
md5: '',
md5StartTime: null,
md5EndTime: null,
chunkUploadStartTime: null,
chunkUploadEndTime: null,
mergeStartTime: null,
mergeEndTime: null
}))
this.fileList = [...this.fileList, ...newFileList]
// 3.
this.uploadMinioVisible = true
// inputchange
e.target.value = ''
},
/**
* 单个文件的分片上传流程
* @param {Object} fileItem - 文件状态对象
*/
async uploadFileChunks(fileItem) {
const file = fileItem.file
fileItem.uploading = true
fileItem.progress = 0
fileItem.errorMsg = ''
fileItem.successMsg = ''
try {
// MD5
const fileMd5 = await this.calculateFileMd5(file, fileItem)
fileItem.md5 = fileMd5
console.log(`${file.name}】文件MD5:`, fileMd5)
//
const totalChunks = Math.ceil(file.size / this.CHUNK_SIZE)
console.log(`${file.name}】总分片数:`, totalChunks)
//
fileItem.chunkUploadStartTime = new Date().getTime()
console.log(`${file.name}】分片上传开始时间:${this.formatTime(fileItem.chunkUploadStartTime)}`)
const uploadedChunks = []
for (let i = 0; i < totalChunks; i++) {
//
const checkResult = await this.checkChunkExists(fileMd5, i)
if (!checkResult.exists) {
//
await this.uploadSingleChunk(file, fileMd5, i)
}
uploadedChunks.push(i)
fileItem.progress = Math.round((uploadedChunks.length / totalChunks) * 100)
}
//
fileItem.chunkUploadEndTime = new Date().getTime()
console.log(`${file.name}】分片上传结束时间:${this.formatTime(fileItem.chunkUploadEndTime)},耗时:${this.getTimeDiff(fileItem.chunkUploadStartTime, fileItem.chunkUploadEndTime)}`)
fileItem.progress = 100
} catch (err) {
const fileName = file.name
if (fileItem.chunkUploadStartTime && !fileItem.chunkUploadEndTime) {
fileItem.chunkUploadEndTime = new Date().getTime()
console.log(`${fileName}】分片上传异常结束时间:${this.formatTime(fileItem.chunkUploadEndTime)},耗时:${this.getTimeDiff(fileItem.chunkUploadStartTime, fileItem.chunkUploadEndTime)}`)
}
fileItem.errorMsg = '分片上传失败: ' + (err.message || '未知错误')
console.error(`${fileName}】分片上传流程异常:`, err.message)
this.allChunksUploaded = false
} finally {
fileItem.uploading = false
}
},
/**
* 计算文件MD5
* @param {File} file - 待上传的文件
* @param {Object} fileItem - 文件状态对象
* @returns {Promise<string>} 文件的MD5值
*/
calculateFileMd5(file, fileItem) {
return new Promise((resolve, reject) => {
fileItem.md5StartTime = new Date().getTime()
console.log(`${file.name}】MD5计算开始时间:${this.formatTime(fileItem.md5StartTime)}`)
const spark = new SparkMD5.ArrayBuffer()
const fileReader = new FileReader()
const chunkSize = 2 * 1024 * 1024
let offset = 0
const loadNextChunk = () => {
const blob = file.slice(offset, offset + chunkSize)
fileReader.readAsArrayBuffer(blob)
}
fileReader.onload = (e) => {
spark.append(e.target.result)
offset += chunkSize
if (offset < file.size) {
loadNextChunk()
} else {
fileItem.md5EndTime = new Date().getTime()
console.log(`${file.name}】MD5计算结束时间:${this.formatTime(fileItem.md5EndTime)},耗时:${this.getTimeDiff(fileItem.md5StartTime, fileItem.md5EndTime)}`)
resolve(spark.end())
}
}
fileReader.onerror = (err) => reject(err)
loadNextChunk()
})
},
/**
* 校验所有分片是否存在
* @param {string} fileMd5 - 文件MD5
* @param {number} totalChunks - 总分片数
* @returns {Promise<boolean>} 所有分片是否都存在
*/
async checkAllChunksExist(fileMd5, totalChunks) {
for (let i = 0; i < totalChunks; i++) {
const result = await this.checkChunkExists(fileMd5, i)
if (!result.exists) {
console.warn(`${fileMd5}】分片${i}未上传`)
return false
}
}
return true
},
/**
* 检查分片是否已存在
* @param {string} fileMd5 - 文件MD5
* @param {number} chunkIndex - 分片索引
* @returns {Promise<Object>} 分片存在状态
*/
async checkChunkExists(fileMd5, chunkIndex) {
// 使chunkApiPath
const response = await axios.get(`${this.baseApi}${this.chunkApiPath}`, {
params: { fileMd5, chunkIndex },
headers: { 'Authorization': getToken() }
})
if (response.data.code !== 200) {
throw new Error('检查分片失败: ' + response.data.msg)
}
return response.data.data
},
/**
* 上传单个分片
* @param {File} file - 待上传的文件
* @param {string} fileMd5 - 文件MD5
* @param {number} chunkIndex - 分片索引
*/
async uploadSingleChunk(file, fileMd5, chunkIndex) {
const start = chunkIndex * this.CHUNK_SIZE
const end = Math.min(start + this.CHUNK_SIZE, file.size)
const chunkBlob = file.slice(start, end)
const formData = new FormData()
formData.append('file', chunkBlob, `${fileMd5}_${chunkIndex}`)
formData.append('fileMd5', fileMd5)
formData.append('chunkIndex', chunkIndex)
// 使chunkApiPath
const response = await axios.post(`${this.baseApi}${this.chunkApiPath}`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': getToken()
}
})
if (response.data.code !== 200) {
throw new Error(`分片${chunkIndex}上传失败: ` + response.data.msg)
}
},
/**
* 批量上传并合并弹框内点击按钮触发核心修改点新增串行上传逻辑
*/
async handleUploadConfirm() {
if (this.fileList.length === 0) {
this.showMessage('请先选择要上传的文件!', 'warning')
return
}
// /
const pendingFiles = this.fileList.filter(item => !item.successMsg && !item.errorMsg)
if (pendingFiles.length === 0) {
this.showMessage('暂无待上传的文件!', 'warning')
return
}
this.btnLoading = true
// 1.
this.allChunksUploaded = true
for (const fileItem of pendingFiles) {
await this.uploadFileChunks(fileItem)
//
if (fileItem.errorMsg) {
this.allChunksUploaded = false
}
}
// 2.
if (!this.allChunksUploaded) {
this.btnLoading = false
this.showMessage('部分文件分片上传失败,无法执行合并', 'error')
return
}
const validFiles = this.fileList.filter(item => !item.errorMsg && item.progress === 100)
if (validFiles.length === 0) {
this.btnLoading = false
this.showMessage('无有效分片上传完成的文件!', 'error')
return
}
this.totalMergeStartTime = new Date().getTime()
console.log(`【整体合并】所有文件分片上传完成,开始合并,合并开始时间:${this.formatTime(this.totalMergeStartTime)}`)
const nowDate = getCurrentTime()
validFiles.forEach(fileItem => {
fileItem.merging = true
fileItem.mergeStartTime = new Date().getTime()
console.log(`【文件${fileItem.file.name}】合并开始时间:${this.formatTime(fileItem.mergeStartTime)}`)
})
try {
//
if (this.isBatchMount === 'true') {
//
const fileItem = validFiles[0]
const file = fileItem.file
const totalChunks = Math.ceil(file.size / this.CHUNK_SIZE)
const chunksExist = await this.checkAllChunksExist(fileItem.md5, totalChunks)
if (!chunksExist) {
throw new Error(`${file.name}】部分分片未上传完成,无法合并`)
}
//
const mergeParams = {
identifier: fileItem.md5,
totalChunks: totalChunks,
filename: file.name
}
//
const mergeApiUrl = `${this.baseApi}/api/collect/mergeZip`
const response = await axios.post(mergeApiUrl, mergeParams, {
headers: {
'Authorization': getToken(),
'Content-Type': 'application/json'
}
})
this.handleMergeSuccess(response, validFiles, nowDate)
} else {
//
const processFiles = validFiles.map(async(fileItem) => {
const file = fileItem.file
const json = {}
const jsonArray = []
const jsonString = {}
if (file.type.startsWith('image')) {
const fileBase64 = await this.getBase64(file)
const imgRes = await this.getImgPx(fileBase64)
jsonString.file_dpi = `${imgRes.width}px*${imgRes.height}px`
} else {
jsonString.file_dpi = ''
}
jsonString.file_name = file.name
jsonString.file_size = file.size
jsonString.file_type = file.name.split('.').pop() || ''
jsonString.last_modified = file.lastModified
jsonString.file_path = ''
jsonString.sequence = null
jsonString.archive_id = this.arcId
jsonString.create_time = nowDate
jsonString.id = null
jsonString.file_thumbnail = ''
jsonArray.push(jsonString)
console.log('file.lastModified', file.lastModified)
const totalChunks = Math.ceil(file.size / this.CHUNK_SIZE)
const chunksExist = await this.checkAllChunksExist(fileItem.md5, totalChunks)
if (!chunksExist) {
throw new Error(`${file.name}】部分分片未上传完成,无法合并`)
}
json.documentId = this.selectedDocument.id
json.archivesId = this.arcId
json.identifier = fileItem.md5
json.filename = file.name
json.totalChunks = totalChunks
json.totalSize = file.size
json.fileJsonString = JSON.stringify(jsonArray)
return json
})
const jsonArray = await Promise.all(processFiles)
const mergeApiUrl = `${this.baseApi}/api/minioUpload/merge`
const response = await axios.post(mergeApiUrl, jsonArray, {
headers: {
'Authorization': getToken(),
'Content-Type': 'application/json'
}
})
this.handleMergeSuccess(response, validFiles, nowDate, jsonArray)
}
} catch (err) {
this.btnLoading = false
this.totalMergeEndTime = new Date().getTime()
const totalMergeDuration = this.getTimeDiff(this.totalMergeStartTime, this.totalMergeEndTime)
console.log(`合并失败,耗时:${totalMergeDuration},异常信息:`, err)
this.showMessage(`文件合并失败: ${err.message}`, 'error')
validFiles.forEach(fileItem => {
fileItem.merging = false
fileItem.errorMsg = fileItem.errorMsg || `合并失败: ${err.message}`
})
this.$emit('onUploadError', err)
} finally {
this.resetUploadState()
}
},
/**
* 处理合并成功的通用逻辑
*/
handleMergeSuccess(response, validFiles, nowDate, jsonArray = null) {
this.totalMergeEndTime = new Date().getTime()
const totalMergeDuration = this.getTimeDiff(this.totalMergeStartTime, this.totalMergeEndTime)
if (response.data.code === 200) {
this.btnLoading = false
this.showMessage('所有文件上传并合并成功', 'success')
validFiles.forEach((fileItem) => {
fileItem.mergeEndTime = new Date().getTime()
const mergeDuration = this.getTimeDiff(fileItem.mergeStartTime, fileItem.mergeEndTime)
console.log(`【文件${fileItem.file.name}】合并结束时间:${this.formatTime(fileItem.mergeEndTime)},合并耗时:${mergeDuration}`)
fileItem.successMsg = '上传成功!'
fileItem.merging = false
})
console.log(`【整体合并】所有文件合并完成,整体合并耗时:${totalMergeDuration}`)
//
const fileNames = validFiles.map(f => f.file.name)
this.$emit('onUploadSuccess', response.data.data, fileNames, jsonArray || response.data.data)
this.uploadMinioVisible = false
this.fileList = [] //
} else {
this.btnLoading = false
throw new Error(response.data.msg || '合并失败')
}
},
/**
* 关闭弹框时清空文件列表
*/
handleCloseDialog() {
this.uploadMinioVisible = false
this.fileList = []
this.resetUploadState()
}
}
}
</script>
<style scoped>
.upload-minio {
position: relative;
margin-top: 10px;
}
.uploader-drop{
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
height: 120px;
border: none;
background-color: #f5f5f5;
.uploader-btn{
border: none;
i{
font-size: 32px;
color: #1F55EB;
}
&:hover{
background-color: transparent;
}
}
.el-upload__tip{
font-size: 12px;
color: #A6ADB6;
}
}
.file-input {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 36px;
padding: 5px;
opacity: 0;
cursor: pointer;
z-index: 10;
}
/* 弹框内空提示 */
.empty-tip {
text-align: center;
color: #999;
padding: 20px 0;
}
.file-item {
width: 100%;
border: 1px dashed #409eff;
padding: 10px;
border-radius: 4px;
margin-bottom: 10px;
}
.file-name {
position: relative;
font-weight: 500;
color: #333;
margin-bottom: 8px;
}
.icon-shanchu{
position: absolute;
right: -7px;
top: 0;
font-size: 20px;
color: #1F55EB;
cursor: pointer;
&:hover {
color: #ff4444;
transform: scale(1.1);
transition: all 0.2s ease;
}
}
.progress-wrapper {
display: flex;
flex-direction: column;
gap: 5px;
}
.progress-bar {
height: 10px;
background-color: #42b983;
transition: width 0.3s ease;
border-radius: 10px;
}
.progress-text {
font-size: 14px;
color: #666;
}
.merge-loading {
color: #1890ff;
font-size: 14px;
}
.success {
color: #00C851;
font-size: 14px;
margin: 5px 0 0 0;
}
.error {
color: #ff4444;
font-size: 14px;
margin: 5px 0 0 0;
}
.minio-file{
.el-dialog{
.el-dialog__body{
padding: 15px 0 30px 0 !important;
}
}
}
.file-size {
color: #666;
font-weight: normal;
font-size: 12px;
margin-left: 8px;
}
</style>

186
src/views/system/database/index.vue

@ -11,24 +11,35 @@
</template>
</rrOperation>
</div>
<crudOperation :permission="permission">
<template v-slot:middle>
<el-button slot="reference" size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0" @click="toVerify('del')">
<i class="iconfont icon-shanchu" />
删除
</el-button>
</template>
<template v-slot:right>
<el-button :loading="crud.downloadLoading" size="mini" :disabled="crud.selections.length !== 1" @click="toVerify('download')">
<i class="iconfont icon-daochu" />
导出
</el-button>
<el-button size="mini" :disabled="crud.selections.length !== 1" @click="toVerify('return')">
<i class="iconfont icon-huifu" />
还原
</el-button>
</template>
</crudOperation>
<div style="display: flex; justify-content: space-between; align-items: center;">
<crudOperation :permission="permission">
<template v-slot:middle>
<el-button slot="reference" size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0" @click="toVerify('del')">
<i class="iconfont icon-shanchu" />
删除
</el-button>
</template>
<template v-slot:right>
<el-button :loading="crud.downloadLoading" size="mini" :disabled="crud.selections.length !== 1" @click="toVerify('download')">
<i class="iconfont icon-daochu" />
导出
</el-button>
<el-button size="mini" :disabled="crud.selections.length !== 1" @click="toVerify('return')">
<i class="iconfont icon-huifu" />
还原
</el-button>
</template>
</crudOperation>
<div class="backups-item">
<p>自动备份</p>
<el-switch
v-model="isEnable"
@change="saveDatabaseSaveSetting"
/>
<i style="color: #0348f3; margin-left: 12px; cursor: pointer;" class="iconfont icon-zishebeiguanli" @click="backupsVisible = true" />
</div>
</div>
</div>
<div class="container-wrap">
<span class="right-top-line" />
@ -81,7 +92,7 @@
</el-dialog>
<!-- form -->
<el-dialog append-to-body :close-on-click-modal="false" :modal-append-to-body="false" :before-close="crud.cancelCU" :visible="formVisible" :title="crud.status.title">
<el-dialog append-to-body :close-on-click-modal="false" :modal-append-to-body="false" :before-close="handleClose" :visible="formVisible" :title="crud.status.title">
<span class="dialog-right-top" />
<span class="dialog-left-bottom" />
<div class="setting-dialog">
@ -99,6 +110,47 @@
</div>
</div>
</el-dialog>
<!-- 自动备份设置 -->
<el-dialog class="backups-dialog" append-to-body :close-on-click-modal="false" :modal-append-to-body="false" :before-close="handleClose" :visible="backupsVisible" title="自动备份设置">
<span class="dialog-right-top" />
<span class="dialog-left-bottom" />
<div class="setting-dialog">
<!-- :rules="rules" -->
<el-form ref="backupsForm" :model="backupsForm" size="small" label-width="100px">
<el-form-item label="自动备份时间" prop="backupTime">
<el-time-picker
v-model="backupsForm.backupTime"
placeholder="自动备份时间"
value-format="HH:mm:ss"
:picker-options="{
selectableRange: '00:00:00 - 23:59:59'
}"
style="width: 200px;"
/>
</el-form-item>
<el-form-item label="自动删除备份" prop="isAutoDelete">
<el-switch
v-model="backupsForm.isAutoDelete"
/>
</el-form-item>
<el-form-item label="备份保留时间" prop="backupSaveTime">
<el-select v-model="backupsForm.backupSaveTime" placeholder="请选择" style="width: 200px;">
<el-option
v-for="item in timeOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="text" @click="handleClose">取消</el-button>
<el-button type="primary" @click="saveDatabaseSaveSetting">保存</el-button>
</div>
</div>
</el-dialog>
</div>
</template>
@ -153,6 +205,19 @@ export default {
filename: [
{ required: true, message: '备份名称不可为空', trigger: 'blur' }
]
},
isEnable: true,
backupsVisible: false,
timeOptions: [
{ value: 7, label: '7天' },
{ value: 10, label: '10天' },
{ value: 30, label: '30天' }
],
backupsForm: {
id: null,
backupTime: '00:00:00',
isAutoDelete: true,
backupSaveTime: 7
}
}
},
@ -162,6 +227,7 @@ export default {
])
},
created() {
},
methods: {
[CRUD.HOOK.beforeToCU](crud, form, btn) {
@ -187,6 +253,9 @@ export default {
this.crud.query.endTime = null
}
},
[CRUD.HOOK.afterRefresh]() {
this.getDatabaseSaveSetting()
},
//
[CRUD.HOOK.afterValidateCU](crud) {
console.log(crud.form)
@ -250,6 +319,64 @@ export default {
console.log(err)
})
},
getDatabaseSaveSetting() {
crudSql.FetchDatabaseSaveSetting().then((res) => {
console.log(res)
if (res.code !== 500) {
let backupTimeStr = '00:00:00'
if (Array.isArray(res.backupTime) && res.backupTime.length >= 2) {
const hour = res.backupTime[0] ? res.backupTime[0].toString().padStart(2, '0') : '00'
const minute = res.backupTime[1] ? res.backupTime[1].toString().padStart(2, '0') : '00'
const second = res.backupTime[2] ? res.backupTime[2].toString().padStart(2, '0') : '00'
backupTimeStr = `${hour}:${minute}:${second}`
}
this.backupsForm.id = res.id
this.backupsForm.backupTime = backupTimeStr
this.backupsForm.isAutoDelete = res.isAutoDelete
this.backupsForm.backupSaveTime = res.backupSaveTime
this.isEnable = res.isEnable
}
}).catch((err) => {
//
console.error('获取备份设置失败:', err)
this.$message({
message: '获取备份设置失败,请重试',
type: 'error',
offset: 8
})
})
},
saveDatabaseSaveSetting() {
console.log('this.backupsForm', this.backupsForm)
// const timeParts = this.backupsForm.backupTime.split(':')
// const backupTimeObj = {
// hour: parseInt(timeParts[0], 10), //
// minute: parseInt(timeParts[1], 10), //
// second: parseInt(timeParts[2], 10) //
// }
const requestParams = {
backupSaveTime: this.backupsForm.backupSaveTime,
backupTime: this.backupsForm.backupTime ? this.backupsForm.backupTime : '00:00:00',
id: this.backupsForm.id,
isAutoDelete: this.backupsForm.isAutoDelete,
isEnable: this.isEnable
}
crudSql.FetchSaveDatabaseSaveSetting(requestParams).then((res) => {
console.log(res)
if (res.code !== 500) {
this.$message({ message: '设置成功', type: 'success', offset: 8 })
} else {
this.$message({ message: res.message || '设置失败', type: 'error', offset: 8 })
}
this.handleClose()
this.crud.toQuery()
}).catch((err) => {
console.error('设置失败:', err)
this.$message({ message: '网络异常,保存失败', type: 'error', offset: 8 })
this.handleClose()
})
},
handleClose() {
if (this.$refs.verfiyForm) {
this.verfiyForm.verifyCode = ''
@ -261,6 +388,12 @@ export default {
this.crud.form.remarks = null
this.formVisible = false
}
if (this.$refs.backupsForm) {
this.backupsForm.backupTime = '00:00:00'
this.backupsForm.isAutoDelete = true
this.backupsForm.backupSaveTime = '7'
this.backupsVisible = false
}
},
toDelete(data) {
this.$confirm('此操作将删除当前所选数据' + '<span>你是否还要继续?</span>', '提示', {
@ -337,4 +470,19 @@ export default {
::v-deep div.el-dialog__footer {
text-align: center;
}
.backups-item{
display: flex;
justify-content: flex-start;
align-items: center;
p{
font-size: 14px;
padding-right: 10px;
line-height: 32px;
}
}
.backups-dialog{
::v-deep .el-dialog{
width: 360px !important;
}
}
</style>
Loading…
Cancel
Save