import JSZip from 'jszip'; import { type RcFile } from 'antd/lib/upload'; import { importProjectZip, loopHandle, ProjectExportMainConfigType, ProjectExportMainFileName, } from '@easytwin/core'; import { _globalLoadingInfo } from '../../pages/module'; import { setRecoilExternalState } from '../../RecoilExternalStatePortal'; import { FileApi } from '../File'; import { importProject } from './api'; import { resolve } from '../../utils'; /** * 导入项目压缩包 * @param { ImportProjectQuery } query * @returns { Promise } */ export async function importZip( query: importProjectZip, addProjectNamePrefix = true, ): Promise { try { const { file, groupId } = query; setRecoilExternalState(_globalLoadingInfo, { loading: true, tip: '文件正在上传中...', }); JSZip.loadAsync(file).then(async (zip) => { setRecoilExternalState(_globalLoadingInfo, { loading: true, tip: '正在读取入口配置文件...', }); const data = await zip.file(ProjectExportMainFileName)?.async('string'); if (!data) { return; } const mainConfgData: ProjectExportMainConfigType = JSON.parse(data); const { import: importUrls } = mainConfgData; setRecoilExternalState(_globalLoadingInfo, { loading: true, tip: '正在读取资源数据...', }); // 获取文件数据 const fileInfos: { url: string }[] = JSON.parse( (await zip.file(resolve(importUrls.file))?.async('string')) || '[]', ); // 获取项目信息 const projectInfo = JSON.parse( (await zip.file(resolve(importUrls.project))?.async('string')) || '[]', ); // 遍历创建资源文件 await loopHandle(fileInfos, async (fileInfo, index) => { const { url } = fileInfo; const name = url.slice(url.lastIndexOf('.')); // 创建资源文件 if (url) { const blob = await zip.file(resolve(url))?.async('blob'); if (blob) { await FileApi.upload(name, blob); } setRecoilExternalState(_globalLoadingInfo, { loading: true, tip: `同步文件数据(${index}/${fileInfos.length})`, }); } }); /** * 同步项目数据 */ const { project } = projectInfo; await importProject({ ...projectInfo, groupId, project: { ...project, name: `${addProjectNamePrefix ? '导入项目_' : ''}${project.name || '未命名'}`, }, }); setRecoilExternalState(_globalLoadingInfo, { loading: false, tip: null, }); }); } catch (err) { console.error('importProject:', err); return Promise.reject('导入项目失败!'); } }