import { ipcMain } from 'electron'
|
import fs from 'fs'
|
import os from 'os'
|
import moment from 'moment'
|
import path from 'path'
|
import { uuid } from './toolClass'
|
const xlsx = require('node-xlsx')
|
const Store = require('electron-store')
|
const ExportTasks = new Store('ExportTasks')
|
const DownloadConfig = new Store('DownloadConfig')
|
const EXPORT_TASKS = 'ExportTasks'
|
const DOWNLOAD_SAVE_FOLDER = 'FileDownloadSaveFolder'
|
|
// 默认路径
|
const homeDir = os.homedir()
|
let DOWNLOAD_PATH = ''
|
const FileDownloadSaveFolder = DownloadConfig.get(DOWNLOAD_SAVE_FOLDER)
|
if (FileDownloadSaveFolder) {
|
DOWNLOAD_PATH = FileDownloadSaveFolder
|
} else {
|
if (os.platform() === 'win32') {
|
// Windows 系统下的 "Downloads" 文件夹路径
|
DOWNLOAD_PATH = path.join(homeDir, 'Downloads')
|
} else {
|
// macOS 和 Linux 系统下的 "Downloads" 文件夹路径
|
DOWNLOAD_PATH = path.join(homeDir, 'Downloads')
|
}
|
}
|
|
let mainWindow: any = null
|
let request: any = null
|
|
let token = ''
|
let taskList: any = []
|
|
export const init = (win, req) => {
|
mainWindow = win
|
request = req
|
loadTasks()
|
}
|
|
type CmsItemProps = {
|
path: string
|
storeId?: number
|
repositoryId?: number
|
type?: string
|
paging: {
|
Start: number
|
Size: number
|
}
|
sort?: Record<string, any>
|
linkTypes?: string[]
|
fields?: {
|
[key: string]: []
|
}
|
filters?: {
|
[key: string]: string[]
|
}
|
subQuery?: {}
|
keyword?: string
|
itemId?: number
|
resType?: any
|
}
|
|
class ExportTask {
|
// 初始状态
|
static INIT = 0
|
// 处理中
|
static LOADING = 1
|
// 暂停中
|
static PAUSE = 2
|
// 完成
|
static FINISHED = 3
|
// 失败
|
static FAILED = 4
|
|
public data
|
|
constructor(data) {
|
this.initData(data)
|
this.start()
|
}
|
|
// 新建任务
|
initData = (data) => {
|
if (data.id) {
|
this.data = { ...data }
|
} else {
|
this.data = {
|
id: uuid(8),
|
startDate: moment().format('YYYY-MM-DD HH:mm:ss'),
|
endDate: '',
|
bookTpl: null, // 图书模板(Excel模板)
|
fileTpl: null, // 文件导出模板
|
tplInfo: data.tplInfo,
|
bookInfo: data.bookInfo, // 导出的图书
|
typeKeyMap: null,
|
state: ExportTask.INIT, // 任务状态
|
fileTypeList: [], // 需下载文件类型
|
tabHeader: [], // Excel表头数据
|
tabData: [], // Excel表头数据
|
temporaryFolderPath: '', // 临时文件夹目录
|
bookFolderPath: null, // 图书文件夹path
|
fileMd5List: {}, // 图书文件
|
taskPath: '',
|
progressInfo: {
|
// 进程信息
|
createTask: ExportTask.INIT,
|
temporaryFolder: ExportTask.INIT,
|
handleFile: {},
|
handleBook: {
|
state: ExportTask.INIT,
|
info: {
|
success: 0,
|
failed: 0,
|
total: 0
|
}
|
},
|
handleFolder: {},
|
handleExcel: ExportTask.INIT
|
}
|
}
|
}
|
this.preloadData(this.data)
|
}
|
|
// 开始任务
|
start = () => {
|
const task = this.data
|
task.state = ExportTask.LOADING
|
// 请求数据
|
if (
|
!task.fileTypeList ||
|
!task.fileTypeList.length ||
|
!task.tabHeader ||
|
!task.tabHeader.length
|
) {
|
this.preloadData(task)
|
} else {
|
// 临时文件夹
|
if (!task.temporaryFolderPath) {
|
this.createTemporaryFolder(task)
|
}
|
}
|
}
|
|
// 预处理数据
|
preloadData = (task) => {
|
// 先请求相关数据,并预处理
|
task.progressInfo.createTask = ExportTask.LOADING
|
this.getTplInfo(task.tplInfo).then((data) => {
|
console.log(data)
|
if (data) {
|
let fileTypeList = []
|
for (let i = 0; i < task.fileTpl.fileData.length; i++) {
|
const folderItem = task.fileTpl.fileData[i]
|
fileTypeList = fileTypeList.concat(folderItem.fileType)
|
}
|
task.fileTypeList = fileTypeList
|
// 处理图书模板创建excel表头
|
const tabHeader: any = []
|
for (let j = 0; j < task.bookTpl.fieldKeys.length; j++) {
|
const field = task.bookTpl.fieldKeys[j]
|
tabHeader.push({
|
key: field.typeField.refCode,
|
label: field.title
|
})
|
}
|
task.tabHeader = tabHeader
|
task.progressInfo.handleBook.info.total = task.bookInfo.length
|
this.sendProgressInfo()
|
// 临时文件夹
|
if (!task.temporaryFolderPath) {
|
this.createTemporaryFolder(task)
|
}
|
}
|
})
|
}
|
|
// 获取模板信息
|
getTplInfo = (data) => {
|
if (data.type == 'user') {
|
return request({
|
url: '/identity/User/GetUserKey',
|
method: 'post',
|
headers: {
|
Authorization: 'bearer ' + token
|
},
|
data: {
|
userKeyList: [{ storeKey: 'personImportTemplate', key: data.key }]
|
}
|
})
|
.then((res) => {
|
if (res && res.length > 0) {
|
try {
|
return JSON.parse(res[0].value)
|
} catch (error) {
|
return null
|
}
|
}
|
})
|
.catch((error) => {
|
console.log(error)
|
})
|
}
|
if (data.type == 'sys') {
|
return request({
|
url: '/identity/Sys/GetSysKey',
|
method: 'post',
|
headers: {
|
Authorization: 'bearer ' + token
|
},
|
data: {
|
userKeyList: [{ storeKey: 'sysImportTemplate', key: data.key }]
|
}
|
}).then((res) => {
|
if (res && res.length > 0) {
|
try {
|
return JSON.parse(res[0].value)
|
} catch (error) {
|
return null
|
}
|
}
|
})
|
}
|
}
|
|
// 创建临时文件夹
|
createTemporaryFolder = (task) => {
|
task.progressInfo.temporaryFolder = ExportTask.LOADING
|
this.sendProgressInfo()
|
// 临时文件夹名称
|
const folderName = 'TF' + moment().valueOf()
|
// 创建临时文件夹
|
const folderPath = path.join(DOWNLOAD_PATH, folderName)
|
fs.mkdirSync(folderPath, { recursive: true })
|
task.temporaryFolderPath = folderPath
|
// 更新状态
|
task.progressInfo.temporaryFolder = ExportTask.FINISHED
|
this.sendProgressInfo()
|
this.createBookFolder(task)
|
}
|
|
// 创建图书文件夹
|
createBookFolder = (task) => {
|
if (!task.bookFolderPath) task.bookFolderPath = {}
|
// 在临时文件夹中创建不同书籍文件夹
|
for (let i = 0; i < task.bookInfo.length; i++) {
|
const book = task.bookInfo[i]
|
if (book.ISBN) book.ISBN = book.ISBN.replace(new RegExp('-', 'gm'), '')
|
const folderPath = path.join(
|
task.temporaryFolderPath,
|
book.name + (book.ISBN ? '(' + book.ISBN + ')' : '')
|
)
|
fs.mkdirSync(folderPath, { recursive: true })
|
task.bookFolderPath[book.id] = folderPath
|
task.fileMd5List[book.id] = []
|
task.progressInfo.handleFile[book.id] = {
|
state: ExportTask.INIT,
|
info: {
|
success: 0,
|
failed: 0,
|
total: 0
|
}
|
}
|
task.progressInfo.handleFolder[book.id] = ExportTask.INIT
|
this.sendProgressInfo()
|
// 获取图书信息
|
this.getBookData(book, task)
|
}
|
}
|
|
// 获取图书信息
|
getBookData(book, task) {
|
task.progressInfo.handleBook.state = ExportTask.LOADING
|
this.sendProgressInfo()
|
// const idPath = book.idPath.slice(0, book.idPath.lastIndexOf('\\'))
|
// this.getCmsItem(book.storeId, book.repoId, idPath, book.id, task.typeKeyMap)
|
// .then((result) => {
|
// const bookInfo = result.data.data[0].datas[0].datas
|
// for (const key in bookInfo) {
|
// if (bookInfo[key]) {
|
// try {
|
// bookInfo[key] = JSON.parse(bookInfo[key])[0].Value
|
// } catch (error) {
|
// console.log(error)
|
// }
|
// }
|
// }
|
// task.tabData.push(bookInfo)
|
// task.progressInfo.handleBook.info.success++
|
// // 获取文件信息
|
// this.getFileData(book, task)
|
// this.sendProgressInfo()
|
// if (task.progressInfo.handleBook.info.success == task.progressInfo.handleBook.info.total) {
|
// task.progressInfo.handleBook.state = ExportTask.FINISHED
|
// this.sendProgressInfo()
|
// this.exportExcel(task)
|
// }
|
// })
|
// .catch((e) => {
|
// console.error(e)
|
// })
|
}
|
|
// 获取文件信息
|
getFileData(book, task) {
|
task.progressInfo.handleFile[book.id].state = ExportTask.LOADING
|
this.sendProgressInfo()
|
// let requestIndex = 0
|
// let bookFile = []
|
for (let i = 0; i < book.getFilePaths.length; i++) {
|
// const filePath = book.getFilePaths[i]
|
// this.getCmsItem({
|
// repo: {
|
// storeId: book.storeId,
|
// repoId: book.repoId
|
// },
|
// parent: { idPath: filePath },
|
// paging: { Start: 0, Size: 10 },
|
// sysTypes: ['CmsFile'],
|
// recursion: true
|
// })
|
// .then((result) => {
|
// bookFile = bookFile.concat(result.datas)
|
// requestIndex++
|
// if (requestIndex == book.getFilePaths.length) {
|
// this.handleBookFile(book, task, bookFile)
|
// }
|
// })
|
// .catch((e) => {
|
// console.error(e)
|
// })
|
}
|
}
|
|
// 处理图书文件
|
handleBookFile = (book, task, bookFile) => {
|
// 获取到图书下所有文件信息
|
const bookFileList = bookFile.filter((item) => {
|
return item.datas.LinkFile && task.fileTypeList.indexOf(item.type) > -1
|
})
|
// 需判断去重,同样的文件只下载一个(如果同样的文件移动两次,第二次会报错;如果是要移动至多个文件夹,移动时能兼容)
|
const newBookFileList: any = []
|
for (let i = 0; i < bookFileList.length; i++) {
|
const exists = newBookFileList.filter((item) => {
|
return bookFileList[i].linkFile[0].File.Md5 == item.linkFile[0].File.Md5
|
})
|
if (!exists.length) {
|
newBookFileList.push(bookFileList[i])
|
}
|
}
|
task.progressInfo.handleFile[book.id].info.total = newBookFileList.length
|
this.sendProgressInfo()
|
if (newBookFileList && newBookFileList.length) {
|
for (let i = 0; i < newBookFileList.length; i++) {
|
const item = newBookFileList[i]
|
const linkInfo = JSON.parse(item.datas.LinkFile)[0]
|
linkInfo.File.MetaData = JSON.parse(linkInfo.File.MetaData)
|
linkInfo.File.itemType = item.type
|
task.fileMd5List[book.id].push(linkInfo.File)
|
// 调用下载队列进行下载(异步)
|
// const downloadPath = path.join(
|
// task.bookFolderPath[book.id],
|
// linkInfo.File.MetaData.fileName
|
// )
|
// const info = new DownloadInfo(
|
// apps.resAppId,
|
// linkInfo.File.Md5,
|
// 0,
|
// linkInfo.File.MetaData.size,
|
// downloadPath
|
// )
|
// const downloadTask = new DownloadTask(info)
|
// downloadTask.start((downloadInfo) => {
|
// task.progressInfo.handleFile[book.id].info.success++
|
// this.sendProgressInfo()
|
// // let isbn = path.basename(path.dirname(downloadInfo.path));
|
// for (let i = 0; i < task.fileMd5List[book.id].length; i++) {
|
// const item = task.fileMd5List[book.id][i]
|
// if (item.Md5 == downloadInfo.md5 && !item.path) {
|
// item.path = downloadInfo.path
|
// break
|
// }
|
// }
|
// if (
|
// task.progressInfo.handleFile[book.id].info.success ==
|
// task.progressInfo.handleFile[book.id].info.total
|
// ) {
|
// task.progressInfo.handleFile[book.id].state = ExportTask.FINISHED
|
// this.sendProgressInfo()
|
// this.handleBookFileMerge(task, book.id)
|
// }
|
// })
|
}
|
} else {
|
task.progressInfo.handleFile[book.id].state = ExportTask.FINISHED
|
task.progressInfo.handleFolder[book.id] = ExportTask.FINISHED
|
this.sendProgressInfo()
|
this.taskSucess(task)
|
}
|
}
|
|
// 按文件模板合并图书文件
|
handleBookFileMerge = (task, key) => {
|
task.progressInfo.handleFolder[key] = ExportTask.LOADING
|
this.sendProgressInfo()
|
const fileTpl = task.fileTpl
|
const typeToFolderList = {}
|
if (task.bookTpl.tplType == 1 || !task.bookTpl.tplType) {
|
// 按图书导出
|
// 创建模板对应的文件夹
|
for (let i = 0; i < fileTpl.fileData.length; i++) {
|
const item = fileTpl.fileData[i]
|
// 创建文件夹
|
const folderPath = path.join(task.bookFolderPath[key], item.fileName)
|
fs.mkdirSync(folderPath, { recursive: true })
|
for (let z = 0; z < item.fileType.length; z++) {
|
const typeItem = item.fileType[z]
|
if (!typeToFolderList[typeItem]) {
|
typeToFolderList[typeItem] = []
|
}
|
typeToFolderList[typeItem].push({
|
folderName: item.fileName,
|
folderPath: folderPath
|
})
|
}
|
}
|
} else if (task.bookTpl.tplType == 2) {
|
// 按文件夹导出
|
// 创建模板对应的文件夹
|
for (let i = 0; i < fileTpl.fileData.length; i++) {
|
const item = fileTpl.fileData[i]
|
// 创建文件夹
|
const folderPath = path.join(task.temporaryFolderPath, item.fileName)
|
const stat = fs.existsSync(folderPath)
|
if (!stat) {
|
fs.mkdirSync(folderPath, { recursive: true })
|
}
|
for (let z = 0; z < item.fileType.length; z++) {
|
const typeItem = item.fileType[z]
|
if (!typeToFolderList[typeItem]) {
|
typeToFolderList[typeItem] = []
|
}
|
typeToFolderList[typeItem].push({
|
folderName: item.fileName,
|
folderPath: folderPath
|
})
|
}
|
}
|
}
|
// 移动文件对应类型文件至文件夹
|
for (let j = 0; j < task.fileMd5List[key].length; j++) {
|
let file = task.fileMd5List[key][j]
|
if (typeToFolderList[file.itemType] && typeToFolderList[file.itemType].length > 0) {
|
// 处理重命名
|
file = this.handleRename(task, file, key)
|
if (typeToFolderList[file.itemType].length > 1) {
|
// 一个类型对应多个文件夹时,先复制后移动
|
for (let n = 0; n < typeToFolderList[file.itemType].length; n++) {
|
const folder = typeToFolderList[file.itemType][n]
|
if (n < typeToFolderList[file.itemType].length - 1) {
|
// 复制
|
fs.copyFileSync(file.path, path.join(folder.folderPath, file.MetaData.fileName))
|
} else {
|
// 移动
|
fs.renameSync(file.path, path.join(folder.folderPath, file.MetaData.fileName))
|
}
|
}
|
} else {
|
// 直接移动
|
fs.renameSync(
|
file.path,
|
path.join(typeToFolderList[file.itemType][0].folderPath, file.MetaData.fileName)
|
)
|
}
|
}
|
}
|
// 如果按文件夹导出,需删除图书文件夹
|
if (task.bookTpl.tplType == 2) {
|
try {
|
fs.rmdirSync(task.bookFolderPath[key])
|
} catch (error) {
|
console.log(error)
|
}
|
}
|
|
task.progressInfo.handleFolder[key] = ExportTask.FINISHED
|
this.sendProgressInfo()
|
this.taskSucess(task)
|
}
|
|
// 处理重命名
|
handleRename = (task, file, bookId) => {
|
// 获取图书信息
|
const bookInfo = task.tabData.filter((item) => {
|
return item.Id == bookId
|
})
|
const renameData = task.fileTpl.renameData
|
if (!renameData) {
|
return file
|
}
|
for (let i = 0; i < renameData.length; i++) {
|
const renameItem = renameData[i]
|
if (renameItem.fileType == file.itemType) {
|
let newFileName = ''
|
const oldFileName = file.MetaData.fileName
|
const suffix = oldFileName.substring(oldFileName.lastIndexOf('.') + 1, oldFileName.length)
|
// 拼接前置字符
|
if (renameItem.firstTxt) {
|
newFileName += renameItem.firstTxt
|
}
|
// 拼接替换名称
|
const field = renameItem.renameField.split('/')[0]
|
if (bookInfo.length && bookInfo[0][field]) {
|
let fieldTxt = bookInfo[0][field]
|
// 处理特殊字符
|
const reg = new RegExp('[\\/:*?"<>]', 'g')
|
fieldTxt = fieldTxt.replace(reg, '')
|
for (let z = 0; z < renameItem.formatTxt.length; z++) {
|
const formatItem = renameItem.formatTxt[z]
|
if (formatItem == 'nbsp') {
|
fieldTxt = fieldTxt.replace(new RegExp(' ', 'gm'), '')
|
} else {
|
fieldTxt = fieldTxt.replace(new RegExp(formatItem, 'gm'), '')
|
}
|
}
|
newFileName += fieldTxt
|
} else {
|
const oldName = oldFileName.substring(0, oldFileName.lastIndexOf('.'))
|
newFileName += oldName
|
}
|
// 拼接后置字符
|
if (renameItem.lastTxt) {
|
newFileName += renameItem.lastTxt
|
}
|
// 拼接后缀
|
newFileName = newFileName + '.' + suffix
|
// 返回数据
|
file.MetaData.fileName = newFileName
|
return file
|
}
|
}
|
return file
|
}
|
|
// 导出excel
|
exportExcel = (task) => {
|
task.progressInfo.handleExcel = ExportTask.LOADING
|
this.sendProgressInfo()
|
const excelPath = path.join(task.temporaryFolderPath, '图书信息.xls')
|
console.log(task)
|
const excelData: any = []
|
const headerData: any = []
|
for (let i = 0; i < task.tabHeader.length; i++) {
|
const header = task.tabHeader[i]
|
headerData.push(header.label)
|
}
|
const tableData: any = []
|
for (let z = 0; z < task.tabData.length; z++) {
|
const tabItem = task.tabData[z]
|
const itemData: any = []
|
for (let j = 0; j < task.tabHeader.length; j++) {
|
const headerItem = task.tabHeader[j]
|
itemData.push(tabItem[headerItem.key])
|
}
|
tableData.push(itemData)
|
}
|
excelData.push(headerData)
|
excelData.push(...tableData)
|
console.log(excelData)
|
const buffer = xlsx.build([{ name: 'Sheet', data: excelData }])
|
fs.writeFileSync(excelPath, buffer)
|
task.progressInfo.handleExcel = ExportTask.FINISHED
|
this.sendProgressInfo()
|
this.taskSucess(task)
|
}
|
|
// 完成
|
taskSucess = (task) => {
|
let bookFileState = true
|
for (const key in task.progressInfo.handleFolder) {
|
if (task.progressInfo.handleFolder[key] !== ExportTask.FINISHED) {
|
bookFileState = false
|
break
|
}
|
}
|
if (bookFileState && task.progressInfo.handleExcel === ExportTask.FINISHED) {
|
// const obj = path.parse(task.temporaryFolderPath)
|
// const creactTime = parseInt(obj.base.replace('TF', ''))
|
const newFolderName = task.bookTpl.name + '_' + task.key
|
const newPath = path.join(path.dirname(task.temporaryFolderPath), newFolderName)
|
fs.renameSync(task.temporaryFolderPath, newPath)
|
task.taskPath = newPath
|
task.endDate = moment().format('YYYY-MM-DD HH:mm:ss')
|
task.state = ExportTask.FINISHED
|
this.sendProgressInfo()
|
}
|
}
|
|
// 发送进度信息
|
sendProgressInfo = () => {}
|
|
// 获取用于显示的数据
|
// getShowData = () => {
|
// const showDataList = []
|
// for (let i = 0; i < this.taskList.length; i++) {
|
// const taskItem = this.taskList[i]
|
// const obj = {
|
// id: taskItem.id,
|
// bookTplName: taskItem.bookTpl.name,
|
// fileTplName: taskItem.fileTpl.name,
|
// bookInfo: {
|
// name: taskItem.bookInfo.name,
|
// ISBN: taskItem.bookInfo.ISBN
|
// },
|
// state: taskItem.state,
|
// progressInfo: taskItem.progressInfo,
|
// startDate: taskItem.startDate,
|
// endDate: taskItem.endDate,
|
// taskPath: taskItem.taskPath
|
// }
|
// showDataList.unshift(obj)
|
// }
|
// return showDataList
|
// }
|
|
getCmsItem = ({
|
path,
|
storeId,
|
repositoryId,
|
type,
|
paging,
|
sort,
|
linkTypes,
|
fields,
|
filters,
|
subQuery,
|
keyword,
|
itemId,
|
resType
|
}: CmsItemProps) => {
|
const query = {
|
AccessControl: {
|
Path: path,
|
StoreId: storeId + '',
|
RepositoryId: repositoryId + '',
|
Type: type ? type : '\\'
|
},
|
PageQuery: paging,
|
SortQuery: sort ? [sort] : [],
|
CreateDate: [],
|
Description: [],
|
Name: [],
|
RefCode: [],
|
Type: [],
|
TypeId: [],
|
State: [],
|
Tag: [],
|
LinkDepartment: [],
|
LinkOrg: [],
|
LinkInfo: [],
|
LinkId: [],
|
LinkOrder: [],
|
LinkParentId: [],
|
LinkFile: [],
|
LinkType: linkTypes ?? [],
|
LinkStore: [],
|
LinkRepository: [],
|
LinkPath: [],
|
LinkAppId: [],
|
Creator: [],
|
...fields,
|
...filters,
|
...subQuery
|
}
|
|
if (keyword) {
|
delete query.Name
|
query['Name*'] = [keyword]
|
}
|
if (itemId) query['Id='] = [`${itemId}`]
|
const body = { query: JSON.stringify({ Query: [{ Q1: query }] }) }
|
return request({
|
url: '/resource/ResourceItem/QueryCmsItem',
|
method: 'post',
|
headers: {
|
Authorization: 'bearer ' + token
|
},
|
data: body
|
}).then((res) => {
|
if (res && res.length > 0) {
|
const data = res[0]
|
const datas = this.handleCmsItemListRequestData(
|
data.datas,
|
fields,
|
path,
|
storeId,
|
repositoryId
|
)
|
return { datas, total: data.totalCount }
|
} else {
|
return { datas: [], total: 0 }
|
}
|
})
|
}
|
|
handleCmsItemListRequestData = (datas, fields, path?, storeId?, repositoryId?) => {
|
const dataList = []
|
for (let i = 0; i < datas.length; i++) {
|
const item = datas[i]
|
const _fields = {}
|
const _datas = []
|
if (fields != null) {
|
for (let fieldKey in fields) {
|
// 兼容筛选条件的字段值获取,因为后台筛选和取值只能传一个,都会返回值
|
fieldKey = fieldKey.replace(/[!=<>*]/g, '')
|
if (item.datas[fieldKey]) {
|
let values = []
|
if (typeof item.datas[fieldKey] == 'string') {
|
values = JSON.parse(item.datas[fieldKey])
|
} else {
|
values = item.datas[fieldKey]
|
}
|
if (values?.length > 0) {
|
// 用字段名处理返回的字段值
|
if (values[0].Value) {
|
_fields[fieldKey] = values[0].Value
|
values[0].sequenceNum = values[0].SequenceNum
|
}
|
// 兼容处理数据返回的key是CmsItemData
|
// if (values[0].CmsItemData) {
|
// _fields[fieldKey] = values[0].CmsItemData.Value;
|
// values[0].sequenceNum = values[0].CmsItemData.SequenceNum;
|
// }
|
|
item.datas[fieldKey] = values[0]
|
if (values?.length > 1) {
|
const isFile = values.find((citem) => citem.FileList?.length > 0)
|
const dataItems = this.deduplicateArray(values, 'FieldId')
|
if (!isFile) {
|
_datas.push(dataItems[0])
|
} else {
|
const customFile = {
|
customFileList: values,
|
name: fieldKey,
|
md5: _fields[fieldKey]
|
}
|
_datas.push(customFile)
|
}
|
} else {
|
_datas.push(values[0])
|
}
|
}
|
}
|
}
|
}
|
|
if (item.datas.LogQuery) {
|
item.datas.LogQuery = JSON.parse(item.datas.LogQuery)
|
}
|
|
const subDatas = {}
|
if (item.subDatas) {
|
for (let subData of item.subDatas) {
|
const tag = subData.queryTag.replace('Query', '')
|
subDatas[tag] = subData.datas
|
}
|
}
|
|
dataList.push({
|
...item,
|
id: item.id,
|
name: item.datas.Name,
|
icon: item.datas.Icon,
|
storeId: storeId,
|
repositoryId: repositoryId,
|
refCode: item.datas.RefCode === '[]' ? null : item.datas.RefCode,
|
state: item.datas.State,
|
type: item.datas.Type,
|
tag: item.datas.Tag,
|
creator: item.datas.Creator ? JSON.parse(item.datas.Creator) : undefined,
|
linkType: item.datas.LinkType,
|
childrenCount: parseInt(item.datas.ChildrenCount ?? '0'),
|
childrenFolderCount: parseInt(item.datas.ChildrenFolderCount ?? '0'),
|
childrenChannelCount: parseInt(item.datas.ChildrenChannelCount ?? '0'),
|
childrenCmsItemCount: parseInt(item.datas.ChildrenCmsItemCount ?? '0'),
|
childrenFileCount: parseInt(item.datas.ChildrenFileCount ?? '0'),
|
createDate: moment(item.datas.CreateDate).format('YYYY-MM-DD HH:mm:ss'),
|
description: item.datas.Description,
|
sysType: item.datas.SysType,
|
idPath: path + '\\' + item.id,
|
typeId: parseInt(item.datas.TypeId),
|
linkAppId: item.datas.linkAppId,
|
linkFile: JSON.parse(item.datas.LinkFile ?? '[]'),
|
linkInfo: item.datas.LinkInfo ? JSON.parse(item.datas.LinkInfo) : [],
|
linkPath: item.datas.LinkPath ?? null,
|
linkOrg: item.datas.linkOrg ? JSON.parse(item.datas.linkOrg) : [],
|
linkDepartment: item.datas.linkDepartment ? JSON.parse(item.datas.linkDepartment) : [],
|
..._fields,
|
datas: item.datas,
|
fieldList: _datas,
|
subDatas
|
})
|
}
|
return dataList
|
}
|
|
//数组去重
|
deduplicateArray = (arr, idKey) => {
|
const seen = {}
|
const deduplicatedArray = arr.filter((item) => {
|
const id = item[idKey]
|
if (!seen[id]) {
|
seen[id] = true
|
return true
|
}
|
return false
|
})
|
return deduplicatedArray
|
}
|
}
|
|
// 本地缓存加载任务列表
|
const loadTasks = () => {
|
const txt = ExportTasks.get(EXPORT_TASKS, '[]')
|
try {
|
taskList = JSON.parse(txt)
|
} catch (error) {
|
taskList = []
|
}
|
}
|
|
// 本地缓存记录任务列表
|
const saveTasks = () => {
|
ExportTasks.set(EXPORT_TASKS, JSON.stringify(taskList))
|
}
|
|
const updateTask = (data?) => {
|
// 调用渲染进程
|
if (data) {
|
mainWindow.webContents.send('exportTaskChange', JSON.stringify(data))
|
const index = taskList.findIndex((item) => item.id == data.id)
|
taskList[index] = data
|
} else {
|
mainWindow.webContents.send('exportTaskChange')
|
}
|
saveTasks()
|
}
|
|
// 获取任务列表
|
ipcMain.on('getExportTasks', (ev, data) => {
|
// 页面会先获取任务列表,在获取列表时将token挂载
|
mainWindow.webContents
|
.executeJavaScript('localStorage.getItem("token");', true)
|
.then((result) => {
|
token = result
|
})
|
const returnData = JSON.parse(JSON.stringify(taskList))
|
ev.returnValue = returnData
|
})
|
|
// 新建任务
|
ipcMain.on('newExportTask', async (ev, data) => {
|
// 判断下载目录是否存在
|
if (!fs.existsSync(DOWNLOAD_PATH)) {
|
// 未获取到默认下载目录
|
mainWindow.webContents.send(
|
'showMessage',
|
JSON.stringify({
|
showType: 'ExportTask',
|
type: 'notDownloadFolder',
|
msg: JSON.stringify(data)
|
})
|
)
|
} else {
|
mainWindow.webContents.send(
|
'showMessage',
|
JSON.stringify({
|
showType: 'ExportTask',
|
type: 'showState',
|
msg: '检测到导出任务,正在创建...'
|
})
|
)
|
const task = new ExportTask(data)
|
if (!data.id && data.autoPlay) {
|
await task.start()
|
}
|
if (task.data) {
|
taskList.push(task.data)
|
updateTask(task)
|
}
|
mainWindow.webContents.send(
|
'showMessage',
|
JSON.stringify({
|
showType: 'ExportTask',
|
type: 'showState',
|
msg: ''
|
})
|
)
|
}
|
})
|
|
// 删除任务
|
ipcMain.on('cleanExportTask', (ev, id) => {
|
// const item = taskList.find((item) => item.id == id)
|
// if (item.state == 'download') {
|
// const task = new DownloadTask(item)
|
// task.pause()
|
// }
|
|
taskList = taskList.filter((item) => item.id != id)
|
updateTask()
|
ev.returnValue = true
|
})
|
|
// 清空任务
|
ipcMain.on('cleanAllExportTask', (ev) => {
|
// for (let i = 0; i < taskList.length; i++) {
|
// const item = taskList[i]
|
// if (item.state == 'download') {
|
// const task = new DownloadTask(item)
|
// task.pause()
|
// }
|
// }
|
|
taskList = []
|
updateTask()
|
ev.returnValue = true
|
})
|