/* eslint-disable no-prototype-builtins */
import { IImageIoService, IWorkbookData, LocaleType, merge, Univer, UniverInstanceType } from '@univerjs/core';
// 数据验证
import { UniverDataValidationPlugin } from '@univerjs/data-validation';
import { defaultTheme } from '@univerjs/design';
import DesignZhCN from '@univerjs/design/locale/zh-CN';
import { UniverDocsPlugin } from '@univerjs/docs';
// 图片
import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing';
import { UniverDocsUIPlugin } from '@univerjs/docs-ui';
import DocsUIZhCN from '@univerjs/docs-ui/locale/zh-CN';
import { UniverDrawingPlugin } from '@univerjs/drawing';
import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui';
import DrawingUIZhCN from '@univerjs/drawing-ui/locale/zh-CN';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
// 查找 & 替换
import { UniverFindReplacePlugin } from '@univerjs/find-replace';
import FindReplaceZhCN from '@univerjs/find-replace/locale/zh-CN';
import { UniverSheetsPlugin } from '@univerjs/sheets';
// 条件格式
import { UniverSheetsConditionalFormattingPlugin } from '@univerjs/sheets-conditional-formatting';
import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-conditional-formatting-ui';
import SheetsConditionalFormattingUIZhCN from '@univerjs/sheets-conditional-formatting-ui/locale/zh-CN';
// 十字高亮
import { UniverSheetsCrosshairHighlightPlugin } from '@univerjs/sheets-crosshair-highlight';
import SheetsCrosshairHighlightZhCN from '@univerjs/sheets-crosshair-highlight/locale/zh-CN';
import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation';
import { UniverSheetsDataValidationUIPlugin } from '@univerjs/sheets-data-validation-ui';
import SheetsDataValidationZhCN from '@univerjs/sheets-data-validation-ui/locale/zh-CN';
import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing';
import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';
import SheetsDrawingUIZhCN from '@univerjs/sheets-drawing-ui/locale/zh-CN';
// 筛选
import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import { UniverSheetsFilterUIPlugin } from '@univerjs/sheets-filter-ui';
import SheetsFilterUIZhCN from '@univerjs/sheets-filter-ui/locale/zh-CN';
import { UniverSheetsFindReplacePlugin } from '@univerjs/sheets-find-replace';
import SheetsFindReplaceZhCN from '@univerjs/sheets-find-replace/locale/zh-CN';
import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
import { UniverSheetsFormulaUIPlugin } from '@univerjs/sheets-formula-ui';
import SheetsFormulaUIZhCN from '@univerjs/sheets-formula-ui/locale/zh-CN';
// 超链接
import { UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';
import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';
import SheetsHyperLinkUIZhCN from '@univerjs/sheets-hyper-link-ui/locale/zh-CN';
import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';
import { UniverSheetsNumfmtUIPlugin } from '@univerjs/sheets-numfmt-ui';
import SheetsNumfmtUIZhCN from '@univerjs/sheets-numfmt-ui/locale/zh-CN';
// 排序
import { UniverSheetsSortPlugin } from '@univerjs/sheets-sort';
import { UniverSheetsSortUIPlugin } from '@univerjs/sheets-sort-ui';
import SheetsSortUIZhCN from '@univerjs/sheets-sort-ui/locale/zh-CN';
import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';
// import { UniverSheetsThreadCommentUIPlugin } from '@univerjs/sheets-thread-comment-ui';
import SheetsThreadCommentUIZhCN from '@univerjs/sheets-thread-comment-ui/locale/zh-CN';
import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
import SheetsUIZhCN from '@univerjs/sheets-ui/locale/zh-CN';
// 禅编译器
import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';
import SheetsZenEditorZhCN from '@univerjs/sheets-zen-editor/locale/zh-CN';
import SheetsZhCN from '@univerjs/sheets/locale/zh-CN';
// 评论/批注
import { UniverThreadCommentPlugin } from '@univerjs/thread-comment';
import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';
import ThreadCommentUIZhCN from '@univerjs/thread-comment-ui/locale/zh-CN';
import { UniverUIPlugin } from '@univerjs/ui';
import UIZhCN from '@univerjs/ui/locale/zh-CN';
// uniscript
// import { UniverUniscriptPlugin } from '@univerjs/uniscript';
// import UniscriptZhCN from '@univerjs/uniscript/locale/zh-CN';
// 水印
import { UniverWatermarkPlugin } from '@univerjs/watermark';
// 打印
// import { UniverSheetsPrintPlugin } from '@univerjs-pro/sheets-print';

import { JnpfSheetsCellImagePlugin } from '../plugins/sheet-cell-image.plugin';
// 自定义
import { JnpfSheetsCellPlugin } from '../plugins/sheet-cell.plugin';
import { JnpfSheetsDialogPlugin } from '../plugins/sheet-dialog.plugin';
import { JnpfSheetsExcelFilePlugin } from '../plugins/sheet-excel-file.plugin';
import { JnpfSheetsFloatDomPlugin } from '../plugins/sheet-float-dom.plugin';
import { JnpfSheetsFloatEchartPlugin } from '../plugins/sheet-float-echart.plugin';
import { JnpfSheetsFloatImagePlugin } from '../plugins/sheet-float-image.plugin';
import { JnpfSheetsPreviewPlugin } from '../plugins/sheet-preview.plugin';
import { JnpfSheetsPrintPlugin } from '../plugins/sheet-print.plugin';
import { JnpfSheetsRangePlugin } from '../plugins/sheet-range.plugin';
import { DefaultFloatEchartHeight, DefaultFloatEchartWidth, JnpfUniverFloatEchartKey, JnpfUniverFloatImageKey } from './define';
import { correctSheetCellData, isEmptyObject, isNullOrUndefined, moveArrayValueToEnd } from './index';

// 创建univer实例
export function createUniverInstance(config: any) {
  const { container, contextMenu, footer, header, workbookData, darkMode } = config ?? {};

  const univerInstance = new Univer({
    locale: LocaleType.ZH_CN,
    locales: {
      [LocaleType.ZH_CN]: merge(
        {},
        DesignZhCN,
        UIZhCN,
        DocsUIZhCN,
        SheetsZhCN,
        SheetsUIZhCN,
        SheetsNumfmtUIZhCN,
        SheetsFormulaUIZhCN,
        SheetsFilterUIZhCN,
        SheetsSortUIZhCN,
        SheetsDataValidationZhCN,
        SheetsConditionalFormattingUIZhCN,
        SheetsHyperLinkUIZhCN,
        DrawingUIZhCN,
        SheetsDrawingUIZhCN,
        ThreadCommentUIZhCN,
        SheetsThreadCommentUIZhCN,
        FindReplaceZhCN,
        SheetsFindReplaceZhCN,
        SheetsCrosshairHighlightZhCN,
        SheetsZenEditorZhCN,
        // UniscriptZhCN,
      ),
    },
    theme: defaultTheme,
    darkMode,
  });

  univerInstance.registerPlugin(UniverRenderEnginePlugin);
  univerInstance.registerPlugin(UniverFormulaEnginePlugin);
  univerInstance.registerPlugin(UniverUIPlugin, {
    container,
    contextMenu,
    footer,
    header,
  });
  univerInstance.registerPlugin(UniverDocsPlugin);
  univerInstance.registerPlugin(UniverDocsUIPlugin);
  univerInstance.registerPlugin(UniverSheetsPlugin);
  univerInstance.registerPlugin(UniverSheetsUIPlugin, {
    menu: {
      'sheet.command.delete-range-move-left-confirm': {
        hidden: true,
      },
      'sheet.command.delete-range-move-up-confirm': {
        hidden: true,
      },
      'sheet.command.add-range-protection-from-toolbar': {
        hidden: true,
      },
      'sheet.command.add-range-protection-from-context-menu': {
        hidden: true,
      },
      'sheet.contextMenu.permission': {
        hidden: true,
      }
    },
  });
  // univerInstance.registerPlugin(UniverSheetsUIPlugin);
  univerInstance.registerPlugin(UniverSheetsFormulaPlugin);
  univerInstance.registerPlugin(UniverSheetsFormulaUIPlugin);
  univerInstance.registerPlugin(UniverSheetsNumfmtPlugin);
  univerInstance.registerPlugin(UniverSheetsNumfmtUIPlugin);

  // 这个和注销的冲突掉了
  univerInstance.registerPlugin(UniverSheetsHyperLinkPlugin);
  univerInstance.registerPlugin(UniverSheetsHyperLinkUIPlugin);

  univerInstance.registerPlugin(UniverDocsDrawingPlugin);
  univerInstance.registerPlugin(UniverDrawingPlugin, {
    override: [[IImageIoService, null]],
  });
  univerInstance.registerPlugin(UniverDrawingUIPlugin);
  univerInstance.registerPlugin(UniverSheetsDrawingPlugin);
  univerInstance.registerPlugin(UniverSheetsDrawingUIPlugin);

  univerInstance.registerPlugin(UniverFindReplacePlugin);
  univerInstance.registerPlugin(UniverSheetsFindReplacePlugin);
  univerInstance.registerPlugin(UniverSheetsFilterPlugin);
  univerInstance.registerPlugin(UniverSheetsFilterUIPlugin);
  univerInstance.registerPlugin(UniverSheetsSortPlugin);
  univerInstance.registerPlugin(UniverSheetsSortUIPlugin);
  univerInstance.registerPlugin(UniverDataValidationPlugin);
  univerInstance.registerPlugin(UniverSheetsDataValidationPlugin);
  univerInstance.registerPlugin(UniverSheetsDataValidationUIPlugin, {
    showEditOnDropdown: true,
  });
  univerInstance.registerPlugin(UniverSheetsConditionalFormattingPlugin);
  univerInstance.registerPlugin(UniverSheetsConditionalFormattingUIPlugin);
  univerInstance.registerPlugin(UniverSheetsCrosshairHighlightPlugin);
  univerInstance.registerPlugin(UniverThreadCommentPlugin);
  univerInstance.registerPlugin(UniverThreadCommentUIPlugin);
  univerInstance.registerPlugin(UniverSheetsThreadCommentPlugin);
  // univerInstance.registerPlugin(UniverSheetsThreadCommentUIPlugin);
  // univerInstance.registerPlugin(UniverUniscriptPlugin);
  univerInstance.registerPlugin(UniverSheetsZenEditorPlugin);
  univerInstance.registerPlugin(UniverWatermarkPlugin);

  // univerInstance.registerPlugin(UniverSheetsPrintPlugin);

  univerInstance.registerPlugin(JnpfSheetsCellPlugin);
  univerInstance.registerPlugin(JnpfSheetsRangePlugin);
  univerInstance.registerPlugin(JnpfSheetsDialogPlugin);
  univerInstance.registerPlugin(JnpfSheetsExcelFilePlugin);
  univerInstance.registerPlugin(JnpfSheetsFloatDomPlugin);
  univerInstance.registerPlugin(JnpfSheetsFloatEchartPlugin);
  univerInstance.registerPlugin(JnpfSheetsCellImagePlugin);
  univerInstance.registerPlugin(JnpfSheetsFloatImagePlugin);
  univerInstance.registerPlugin(JnpfSheetsPreviewPlugin);
  univerInstance.registerPlugin(JnpfSheetsPrintPlugin);

  univerInstance.createUnit(UniverInstanceType.UNIVER_SHEET, workbookData);
  return univerInstance;
}

// 解析创建univer实例的快照数据
export function analysisCreateUnitData(workbookData: IWorkbookData | string, createMode: string, isReadonly: boolean) {
  try {
    const parseWorkbookData = typeof workbookData === 'string' ? JSON.parse(workbookData) : workbookData;

    if (createMode === 'design' && !isReadonly) {
      // 设计模式并且非只读的情况下直接返回快照
      return parseWorkbookData;
    }

    const { resources = [] } = parseWorkbookData ?? {};

    // 主要是预览的情况下不让图表可操作
    const updatedResources = resources?.map((resource: any) => {
      if (resource?.name === 'SHEET_DRAWING_PLUGIN') {
        const parseResourceData = JSON.parse(resource?.data ?? '{}');

        const updatedParseResourceData = Object.fromEntries(
          Object.entries(parseResourceData)?.map(([sheetKey, sheetResourceOption]: any) => {
            const sheetResourceOptionData = sheetResourceOption?.data || {};

            const updateSheetResourceOption = Object.fromEntries(
              Object.entries(sheetResourceOptionData).map(([floatDomKey, floatDomValue]: any) => {
                const { componentKey, ...floatDomValueRest } = floatDomValue || {};

                return componentKey === JnpfUniverFloatEchartKey || componentKey === JnpfUniverFloatImageKey
                  ? [
                      floatDomKey,
                      {
                        ...floatDomValueRest,
                        allowTransform: false,
                        componentKey,
                      },
                    ]
                  : [floatDomKey, floatDomValue];
              }),
            );

            return [sheetKey, { ...sheetResourceOption, data: updateSheetResourceOption }];
          }),
        );

        return {
          ...resource,
          data: JSON.stringify(updatedParseResourceData),
        };
      } else {
        return resource;
      }
    });

    return {
      ...parseWorkbookData,
      resources: updatedResources,
    };
  } catch (error) {
    console.error(error);
    return {};
  }
}

// 整理设计的数据
export function arrangeDesignWorkbookData(snapshot: any, floatEchartDataCaches: any, floatImageDataCaches: any) {
  const updateFloatEcharts: Record<string, any> = {};
  const updateCellEcharts: Record<string, any> = {};
  const updateFloatImages: Record<string, any> = {};

  // 给悬浮图表和悬浮图片增加float dom的id 并且剔除已被删除的悬浮图表和悬浮图片数据
  const { resources = [], sheets = {} } = snapshot ?? {};

  const updatedResources = resources?.map((resource: any) => {
    if (resource?.name === 'SHEET_DRAWING_PLUGIN') {
      const parseResourceData = JSON.parse(resource?.data ?? '{}');

      const updatedParseResourceData = Object.fromEntries(
        Object.entries(parseResourceData)?.map(([sheetKey, sheetResourceOption]: any) => {
          const sheetResourceOptionData = sheetResourceOption?.data || {};

          const updateSheetResourceOption = Object.fromEntries(
            Object.entries(sheetResourceOptionData).map(([floatDomKey, floatDomValue]: any) => {
              const { componentKey, drawingId, data = {}, ...floatDomValueRest } = floatDomValue || {};

              if (componentKey === JnpfUniverFloatEchartKey) {
                if (floatEchartDataCaches?.hasOwnProperty(drawingId)) {
                  const { height = DefaultFloatEchartHeight, width = DefaultFloatEchartWidth } = floatDomValue.transform ?? {};

                  updateFloatEcharts[drawingId] = {
                    ...floatEchartDataCaches[drawingId],
                    height: Math.floor(height),
                    width: Math.floor(width),
                  }; // store中的悬浮图表数据过滤
                }

                // const domId = floatEchartDataCaches?.[drawingId]?.domId;
                // const updatedProps = {
                //   ...props,
                //   id: domId,
                // };

                return [
                  floatDomKey,
                  {
                    ...floatDomValueRest,
                    componentKey,
                    drawingId,
                    data,
                  },
                ];
              } else if (componentKey === JnpfUniverFloatImageKey) {
                if (floatImageDataCaches?.hasOwnProperty(drawingId)) {
                  updateFloatImages[drawingId] = { ...floatImageDataCaches[drawingId] }; // store中的悬浮图片数据过滤
                }

                // const domId = floatImageDataCaches?.[drawingId]?.domId;
                // const updatedProps = {
                //   ...data,
                //   id: domId,
                // };

                return [
                  floatDomKey,
                  {
                    ...floatDomValueRest,
                    componentKey,
                    drawingId,
                    data,
                  },
                ];
              } else {
                return [floatDomKey, floatDomValue];
              }
            }),
          );

          return [sheetKey, { ...sheetResourceOption, data: updateSheetResourceOption }];
        }),
      );

      return {
        ...resource,
        data: JSON.stringify(updatedParseResourceData),
      };
    } else {
      return resource;
    }
  });

  // 取出所有自定义的custom并整理单元格图表的数据
  const customs: any[] = [];
  for (const sheetKey in sheets) {
    const sheet = sheets[sheetKey];
    const sheetCellData = sheet?.cellData;
    if (!sheetCellData) {
      continue;
    }

    for (const rowKey in sheetCellData) {
      const row = sheetCellData[rowKey];

      for (const colKey in row) {
        const cellData = row[colKey] ?? {};
        const custom = cellData?.custom;

        if (custom && !isEmptyObject(custom)) {
          if (custom.type === 'chart') {
            if (!isNullOrUndefined(custom)) {
              const { chartType, color, drawingId, height, type, width, ...restOption } = custom ?? {};
              updateCellEcharts[drawingId] = {
                col: colKey,
                drawingId,
                echartType: chartType,
                height,
                option: restOption,
                row: rowKey,
                sheet: sheetKey,
                width,
              };
            }
          } else {
            if (custom.type !== 'jsbarcode' && custom.type !== 'qrCode') {
              customs.push({
                cellData,
                col: colKey,
                row: rowKey,
                sheetId: sheetKey,
              });
            }
          }
        }
      }
    }
  }

  return {
    cellEcharts: updateCellEcharts,
    customs,
    floatEcharts: updateFloatEcharts,
    floatImages: updateFloatImages,
    snapshot: {
      ...snapshot,
      resources: updatedResources,
    },
  };
}

// 整理预览的数据
export function arrangePreviewWorkbookData(designWorkbookData: any, floatEchartToUniverImgDataCaches: any, floatImageToUniverImgDataCaches: any) {
  const { customs, floatEcharts, floatImages, snapshot } = designWorkbookData ?? {};

  const { resources = [], sheets } = snapshot ?? {};
  const updateSheets = { ...sheets };

  Object.entries(sheets)?.forEach(([sheetKey, sheetInfo]: any) => {
    const { cellData, columnCount, rowCount } = sheetInfo ?? {};

    const resource = resources.find((resourceInfo: any) => resourceInfo?.name === 'SHEET_DRAWING_PLUGIN');
    const parseResourceData = JSON.parse(resource?.data ?? '{}');

    const hasFloatDom = !isEmptyObject(parseResourceData) && parseResourceData[sheetKey]?.order?.length;

    const updateCellData = hasFloatDom ? correctSheetCellData(cellData, rowCount, columnCount, true) : correctSheetCellData(cellData, rowCount, columnCount);

    updateSheets[sheetKey] = {
      ...sheets[sheetKey],
      cellData: updateCellData,
    };
  });

  const updatedResources = resources?.map((resource: any) => {
    if (resource?.name === 'SHEET_DRAWING_PLUGIN') {
      const parseResourceData = JSON.parse(resource?.data ?? '{}');

      const updatedParseResourceData = Object.fromEntries(
        Object.entries(parseResourceData)?.map(([sheetKey, sheetResourceOption]: any) => {
          const { data: sheetResourceOptionData = {}, order: originalOrder = [] } = sheetResourceOption || {};

          let sheetOrder = [...originalOrder]; // 使用一个可变的引用来追踪顺序更新

          const updatedSheetData = Object.fromEntries(
            Object.entries(sheetResourceOptionData).map(([floatDomKey, floatDomValue]: any) => {
              const { componentKey, drawingId, data, sheetTransform, subUnitId, transform, unitId } = floatDomValue || {};

              if (componentKey === JnpfUniverFloatEchartKey) {
                const { id: domId } = data ?? {};

                sheetOrder = moveArrayValueToEnd(sheetOrder, drawingId);

                const source = floatEchartToUniverImgDataCaches?.[domId] ?? '';

                return [
                  floatDomKey,
                  {
                    drawingId,
                    drawingType: 0,
                    imageSourceType: 'BASE64',
                    sheetTransform,
                    source,
                    subUnitId,
                    transform,
                    unitId,
                    data,
                  },
                ];
              } else if (componentKey === JnpfUniverFloatImageKey) {
                const { id: domId } = data ?? {};

                sheetOrder = moveArrayValueToEnd(sheetOrder, drawingId);

                const source = floatImageToUniverImgDataCaches?.[domId] ?? '';

                return [
                  floatDomKey,
                  {
                    drawingId,
                    drawingType: 0,
                    imageSourceType: source?.startsWith('data:image/') ? 'BASE64' : 'URL',
                    sheetTransform,
                    source,
                    subUnitId,
                    transform,
                    unitId,
                    data,
                  },
                ];
              } else {
                return [floatDomKey, floatDomValue];
              }
            }),
          );

          return [sheetKey, { ...sheetResourceOption, data: updatedSheetData, order: sheetOrder }];
        }),
      );

      return {
        ...resource,
        data: JSON.stringify(updatedParseResourceData),
      };
    } else {
      return resource;
    }
  });

  return {
    customs,
    floatEcharts,
    floatImages,
    snapshot: {
      ...snapshot,
      resources: updatedResources,
      sheets: updateSheets,
    },
  };
}

// 判断当前工作本是不是含有自定义的 float dom
export function judgeSheetHasCustomFloatDom(data: any): boolean {
  return Object.values(data).some(
    (floatDomValue: any) => floatDomValue?.componentKey === JnpfUniverFloatEchartKey || floatDomValue?.componentKey === JnpfUniverFloatImageKey,
  );
}

// 监听插入悬浮图表
export function onInsertedFloatEchart(jnpfUniverStore: any, command: any) {
  const { drawingId } = command?.params ?? {};
  if (!drawingId) {
    return;
  }

  const floatEchartDataCaches = jnpfUniverStore?.floatEchartDataCaches ?? {};

  const updateItems = {
    ...floatEchartDataCaches,
    [drawingId]: command?.params,
  };

  jnpfUniverStore?.setFloatEchartDataCaches(updateItems);
}

// 监听插入悬浮图片
export function onInsertedFloatImage(jnpfUniverStore: any, command: any) {
  const { drawingId } = command?.params ?? {};
  if (!drawingId) {
    return;
  }

  const floatImageDataCaches = jnpfUniverStore?.floatImageDataCaches ?? {};

  const updateItems = {
    ...floatImageDataCaches,
    [drawingId]: command?.params,
  };

  jnpfUniverStore?.setFloatImageDataCaches(updateItems);
}

// 更新浮动元素的storeId
export function updateFloatStoreId(snapshot: any, dynamicJnpfUniverStoreId: string) {
  const { resources, ...rest } = snapshot ?? {};
  if (!resources) {
    return '{}';
  }

  const updatedResources = resources?.map((resource: any) => {
    if (resource?.name === 'SHEET_DRAWING_PLUGIN') {
      const parseResourceData = JSON.parse(resource?.data ?? '{}');

      const updatedParseResourceData = Object.fromEntries(
        Object.entries(parseResourceData)?.map(([sheetKey, sheetResourceOption]: any) => {
          const { data: sheetResourceOptionData = {}, order: originalOrder = [] } = sheetResourceOption || {};

          const sheetOrder = [...originalOrder]; // 使用一个可变的引用来追踪顺序更新

          const updatedSheetData = Object.fromEntries(
            Object.entries(sheetResourceOptionData).map(([floatDomKey, floatDomValue]: any) => {
              const { componentKey, data } = floatDomValue || {};

              if (componentKey === JnpfUniverFloatEchartKey || componentKey === JnpfUniverFloatImageKey) {
                const newData = {
                  ...data,
                  piniaStoreId: dynamicJnpfUniverStoreId,
                };

                return [
                  floatDomKey,
                  {
                    ...floatDomValue,
                    data: newData,
                  },
                ];
              } else {
                return [floatDomKey, floatDomValue];
              }
            }),
          );

          return [sheetKey, { ...sheetResourceOption, data: updatedSheetData, order: sheetOrder }];
        }),
      );

      return {
        ...resource,
        data: JSON.stringify(updatedParseResourceData),
      };
    } else {
      return resource;
    }
  });

  return JSON.stringify({
    ...rest,
    resources: updatedResources,
  });
}
