import { giveFilePostDataInfoForTrue } from '@/webPublic/one_stop_public/Base16';
import { queryOauthActionPath } from '@/webPublic/one_stop_public/utils/queryConfig';
import { Modal } from 'antd';
import { getTransformApi } from '@/webPublic/one_stop_public/2022beidianke/localstorageTransform';
import { getSassApiHeader } from '@/webPublic/one_stop_public/2023yunshangguizhou/utils';
import { getToken } from '@/webPublic/one_stop_public/utils/token';
import { FormdataWrapper, apiUrl, setObjectKey } from "@/webPublic/one_stop_public/Table/globalFunction";

/**
 * 钟是志
 * 2024年7月12日
 * 解决北电科宿管需求 http://scjoyedu.eicp.net:57400/zentao/task-view-3141.html
 * 多个pdf文件合并为一个pdf文件并预览.
 * 使用 pdf-lib 依赖
 * */
export default function getFilesToPdfAndShow(dataList = []) {
	for (let item of dataList) {
		let getFileData = giveFilePostDataInfoForTrue(
			{
				templatePath: item.templatePath,
				params: JSON.stringify({
					...item.listConfig,
					...setObjectKey(item.params),
				}),
				title: `${item.title}.${item.ext}`,
				allValues: JSON.stringify({ ...item.allValues }),
			},
			apiUrl + `/DataColumnApi/exportWord`,
		);
		item.getFileData = getFileData;
	}
	Modal.confirm({
		title: '提示',
		content: '此功能耗时较长,是否确认加载?',
		onOk: async () => {
			let r = [];
			for (let item of dataList) {
				let oneFileBlod = await downloadFileReturnBlob(
					item.getFileData.url,
					{
						...item.getFileData.datas,
						token: getToken(),
					},
					item.title,
					item.ext,
				);
				r.push(oneFileBlod);
			}
      mergePDFBlobs(r);
		},
	});
}

async function downloadFileReturnBlob(url, params, fileName = '导出文件', ext = 'xlsx') {
	const { transformApi, headersApi } = await getTransformApi(url);
	let headers = getSassApiHeader();
	// if(headersApi){
	//   headers.apis = headersApi;
	// }
	return fetch(transformApi, {
		method: 'POST',
		body: FormdataWrapper(params),
		headers,
	})
		.then((res) => {
      return res.blob();
		})
		.then((data) => {
		  return data;
		})
		.catch((err) => {
			console.table(err);
		})
		.finally(() => {
			return true;
		});
}

async function mergePDFBlobs(blobArray) {
  if (blobArray.length < 1) {
    throw new Error('No PDF blobs to merge.');
  }
  const pdf = await import('./pdf-lib.min');
  const mergedPdf = await pdf.PDFDocument.create();
  // 创建一个新的PDF文档
  // 逐个处理每个Blob
  for (const blob of blobArray) {
    // 将Blob转换为Uint8Array
    const arrayBuffer = await blob.arrayBuffer();
    const pdfBytes = new Uint8Array(arrayBuffer);

    // 加载现有的PDF文档
    const existingPdfDoc = await pdf.PDFDocument.load(pdfBytes); // 源文件

    // 复制所有页面到新文档
    const pages = existingPdfDoc.getPages();
    for(let i = 0; i < pages.length; i++){
      const copiedPages = await mergedPdf.copyPages(existingPdfDoc, [i]);
      mergedPdf.addPage(copiedPages[0]);
    }
  }

  // 保存合并后的PDF
  const pdfBytes = await mergedPdf.save();

  // 创建一个Blob对象用于下载
  const mergedBlob = new Blob([pdfBytes], { type: 'application/pdf' });

  // 触发下载
  const url = URL.createObjectURL(mergedBlob);
  Modal.info({
    title: '查看',
    width: 1000,
    content: <div>
      <embed width='100%'
             height='568px'
             name='plugin'
             id='pdfView'
             src={url}
             type='application/pdf'

             internalinstanceid='3'
             title={'查看'} />
    </div>,
    okText: '确定',
    onCancel: () => {
      window.URL.revokeObjectURL(url);
    },
    onOk: () => {
      window.URL.revokeObjectURL(url);
    },
  });
}
