// ==UserScript==
// @name         获取采购数据（外网）
// @namespace    http://tampermonkey.net/
// @description  创建一个按钮发起指定API请求并将数据发送到后端保存
// @author       You
// @match        https://ims.ynydtk.com:8443/buyv2/*
// @grant        none
// ==/UserScript==

(async () => {
	"use strict";

	// 创建按钮元素
	const button = document.createElement("button");
	button.textContent = "发送数据";
	button.style.position = "fixed";
	button.style.top = "62px";
	button.style.left = "50%";
	button.style.transform = "translateX(-50%)";
	button.style.zIndex = "9999";
	button.style.padding = "8px 16px";
	button.style.backgroundColor = "#4caf50";
	button.style.color = "white";
	button.style.border = "none";
	button.style.borderRadius = "4px";
	button.style.cursor = "pointer";

	document.body.appendChild(button);

	button.addEventListener("click", async () => {
		button.innerText = "请求中...";
		try {
			// 获取 bidding_token
			let biddingToken = localStorage.getItem("bidding_token");
			if (biddingToken) {
				biddingToken = biddingToken.replace("|String", "");
			} else {
				throw new Error("未找到bidding_token");
			}
			console.log("已获取到bidding_token：", biddingToken);

			const headers = {
				"accept": "application/json, text/plain, */*",
				"accept-encoding": "gzip, deflate, br, zstd",
				"accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
				"btoken": `${biddingToken}`,
				"connection": "keep-alive",
				"cookie": "__windowopenmode=1",
				"dnt": "1",
				"host": "ims.ynydtk.com:8443",
				"jnpf-origin": "pc",
				"referer": "https://ims.ynydtk.com:8443/buyv2/",
				"sec-ch-ua": "\"Not(A:Brand\";v=\"99\", \"Google Chrome\";v=\"133\", \"Chromium\";v=\"133\"",
				"sec-ch-ua-mobile": "?0",
				"sec-ch-ua-platform": "\"macOS\"",
				"sec-fetch-dest": "empty",
				"sec-fetch-mode": "cors",
				"sec-fetch-site": "same-origin",
				"sec-gpc": "1",
				"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
			};

			const list_url = "https://ims.ynydtk.com:8443/biddingApi/api/workflow/Engine/FlowBefore/List/2?n=1741232825&currentPage=1&pageSize=500&sort=desc&sidx=&keyword=&startTime=&endTime=&templateId=&flowId=&flowUrgent=&flowCategory=&creatorUserId="

			const post_url1 = "https://www.dyxcloud.com/getdata/post1/";
			const post_url2 = "https://www.dyxcloud.com/getdata/post2/";

			// 获取list数据
			const response = await fetch(list_url, {
				method: "GET",
				headers: headers,
			});

			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}

			const list_data = await response.json();
			console.log("请求成功，data:");
			console.log(list_data);

			const list_data_list = list_data.data.list;

			// 处理数据，确保每条数据都有必要的字段
			const processedData = list_data_list.map(item => {
				return {
					...item,
					remark: item.remark || '', // 如果remark不存在，设置为空字符串
					// 可以在这里添加其他字段的默认值
				};
			});

			// 保存数据到Django后端，整个全部发送，后端自动分条处理
			const postResponse1 = await fetch(post_url1, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
				body: JSON.stringify(processedData),
			});

			if (!postResponse1.ok) {
				const errorData = await postResponse1.json();
				throw new Error(`发送数据失败: ${errorData.message || '未知错误'}`);
			}

			console.log("list数据发送成功");

			// 分条处理每条数据
			for (const item of list_data_list) {
				const content_url = `https://ims.ynydtk.com:8443/biddingApi/api/workflow/Engine/FlowBefore/${item.processId}?n=${item.id}&taskNodeId=${item.thisStepId}&taskOperatorId=${item.id}&flowId=${item.flowId}`;

				// 获取每条数据的详细信息
				const contentResponse = await fetch(content_url, {
					method: "GET",
					headers: headers,
				});

				if (!contentResponse.ok) {
					console.error(`获取 ${item.id} 详情失败，status: ${contentResponse.status}`);
					continue;
				}

				const contentData = await contentResponse.json();

				// 检查并提取表单数据
				let formData = null;
				if (contentData.data && contentData.data.formData) {
					formData = contentData.data.formData;
				} else if (contentData.data && contentData.data.data && contentData.data.data.formData) {
					formData = contentData.data.data.formData;
				}

				if (!formData) {
					console.error(`ID ${item.id} 未找到表单数据，跳过发送`);
					continue;
				}

				// 处理详情数据，确保数据格式正确
				const processedContentData = {
					formData: formData,
					id: item.id,
					processId: item.processId
				};

				// 在发送前打印数据结构
				console.log(`准备发送 ID ${item.id} 的数据:`, processedContentData);

				// 发送每条详情数据到post_url2
				try {
					const postResponse2 = await fetch(post_url2, {
						method: "POST",
						headers: {
							"Content-Type": "application/json",
						},
						body: JSON.stringify(processedContentData),
					});

					if (!postResponse2.ok) {
						const errorData = await postResponse2.json();
						console.error(`ID ${item.id} 的详情数据发送失败:`, errorData);
						continue;
					}

					console.log(`ID ${item.id} 的详情数据发送成功`);
				} catch (error) {
					console.error(`ID ${item.id} 的详情数据发送出错:`, error);
					continue;
				}
			}

			button.innerText = "所有数据已发送";
		} catch (error) {
			console.error("请求失败:", error);
			alert("请求失败: " + error.message);
			button.innerText = "发起请求";
		}
		console.log('success');
	});
})();