useFile.hooks.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { ref, nextTick } from 'vue'
  2. import { UploadCustomRequestOptions } from 'naive-ui'
  3. import { FileTypeEnum } from '@/enums/fileTypeEnum'
  4. import { readFile, goDialog } from '@/utils'
  5. import { useSync } from '@/views/chart/hooks/useSync.hook'
  6. export const useFile = () => {
  7. const importUploadFileListRef = ref()
  8. const { updateComponent } = useSync()
  9. // 上传-前置
  10. //@ts-ignore
  11. const importBeforeUpload = ({ file }) => {
  12. importUploadFileListRef.value = []
  13. const type = file.file.type
  14. if (type !== FileTypeEnum.JSON && type !== FileTypeEnum.TXT) {
  15. window['$message'].warning('仅支持上传 【JSON】 格式文件,请重新上传!')
  16. return false
  17. }
  18. return true
  19. }
  20. // 上传-导入
  21. const importCustomRequest = (options: UploadCustomRequestOptions) => {
  22. const { file } = options
  23. nextTick(() => {
  24. if (file.file) {
  25. readFile(file.file).then((fileData: any) => {
  26. goDialog({
  27. message: '请选择导入方式:',
  28. positiveText: '新增(可撤回)',
  29. negativeText: '覆盖(不可撤回)',
  30. negativeButtonProps: { type: 'info', ghost: false },
  31. // 新增
  32. onPositiveCallback: async () => {
  33. try {
  34. fileData = JSON.parse(fileData)
  35. await updateComponent(fileData, false, true)
  36. window['$message'].success('导入成功!')
  37. } catch (error) {
  38. window['$message'].error('组件导入失败,请检查文件完整性!')
  39. }
  40. },
  41. // 覆盖
  42. onNegativeCallback: async () => {
  43. try {
  44. fileData = JSON.parse(fileData)
  45. await updateComponent(fileData, true, true)
  46. window['$message'].success('导入成功!')
  47. } catch (error) {
  48. window['$message'].error('组件导入失败,请检查文件完整性!')
  49. }
  50. }
  51. })
  52. })
  53. } else {
  54. window['$message'].error('导入失败,请检查数据或联系管理员!')
  55. }
  56. })
  57. }
  58. return {
  59. importUploadFileListRef,
  60. importBeforeUpload,
  61. importCustomRequest
  62. }
  63. }