// ==UserScript==
// @name         企信-合并功能脚本
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  合并采购内容自适应高度和样式切换器功能
// @author       You
// @match        https://qx.ynydtk.cn:8443/buyv2/*
// @grant        GM_addStyle
// @grant        GM_getValue
// @grant        GM_setValue
// @run-at       document-end
// ==/UserScript==

(function () {
	'use strict';

	// 检查样式是否已应用的存储键
	const STYLE_APPLIED_KEY = 'custom_style_applied';
	const HIGHLIGHT_APPLIED_KEY = 'highlight_applied';

	// 自定义样式
	const customStyle = `
        .el-radio.is-checked .el-radio__label {
            color: red !important;
            font-weight: bold !important;
            background-color: lightgreen !important;
            padding: 2px 6px 2px 2px !important;
            border-radius: 4px !important;
        }
    `;

	// 创建样式元素
	let styleElement = null;

	// 目标 input 元素的选择器
	const inputSelector = 'input[type="text"][disabled="disabled"][readonly="readonly"].el-input__inner[placeholder="请选择采购方式"]';

	// 创建一个 MutationObserver 实例
	const observer = new MutationObserver(mutations => {
		mutations.forEach(mutation => {
			if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
				for (const node of mutation.addedNodes) {
					// 检查新添加的节点是否包含目标 input 元素
					if (node.nodeType === Node.ELEMENT_NODE && node.querySelector(inputSelector)) {
						processInput();
						return; // 找到目标，立即返回，避免重复处理
					}
				}
			}
		});
	});

	// 创建按钮容器
	const buttonContainer = document.createElement("div");
	buttonContainer.style.position = "fixed";
	buttonContainer.style.top = "70px";
	buttonContainer.style.left = "57%";
	buttonContainer.style.transform = "translateX(-50%)";
	buttonContainer.style.zIndex = "9999";
	buttonContainer.style.display = "flex";
	buttonContainer.style.gap = "20px";

	// 添加按钮交互效果的样式
	const style = document.createElement("style");
	style.textContent = `
        @media print {
            #adjust-height-btn,
            #toggle-style-btn {
                display: none !important;
            }
        }

        /* --- 按钮悬浮和点击效果 --- */

        /* 调整高度按钮 (#409eff) */
        #adjust-height-btn:hover {
            background-color: #66b1ff !important;
            transform: translateY(-2px);
            box-shadow: 0 4px 14px rgba(0, 0, 0, 0.25) !important;
        }
        #adjust-height-btn:active {
            background-color: #3a8ee6 !important;
            transform: translateY(0);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2) !important;
        }

        /* 样式切换按钮 (#67c23a 绿色 / #f44336 红色) */
        #toggle-style-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 14px rgba(0, 0, 0, 0.25) !important;
        }
        #toggle-style-btn:active {
            transform: translateY(0);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2) !important;
        }

        /* 绿色状态悬浮效果 */
        #toggle-style-btn.green-state:hover {
            background-color: #85ce61 !important;
        }
        #toggle-style-btn.green-state:active {
            background-color: #5daf34 !important;
        }

        /* 红色状态悬浮效果 */
        #toggle-style-btn.red-state:hover {
            background-color: #f56c6c !important;
        }
        #toggle-style-btn.red-state:active {
            background-color: #dd6161 !important;
        }
    `;
	document.head.appendChild(style);

	// 辅助函数：创建按钮
	function createButton(text, id, color, onClick) {
		const button = document.createElement("button");
		button.textContent = text;
		button.id = id;
		button.style.padding = "10px 20px";
		button.style.backgroundColor = color;
		button.style.color = "white";
		button.style.border = "none";
		button.style.borderRadius = "4px";
		button.style.cursor = "pointer";
		button.style.boxShadow = "0 2px 10px rgba(0, 0, 0, 0.2)";
		button.style.fontSize = "14px";
		button.style.fontWeight = "bold";
		button.style.transition = "all 0.2s ease-in-out";
		button.addEventListener("click", onClick);
		return button;
	}

	// 处理输入框高亮功能
	function processInput() {
		// 获取目标 input 元素
		const inputElement = document.querySelector(inputSelector);

		if (inputElement) {
			console.log("找到目标 input 元素:", inputElement);
			// 获取 el-select 组件的父元素
			const elSelect = inputElement.closest('.el-select');
			if (!elSelect) {
				console.error('找不到 el-select 组件');
				return;
			}

			// 模拟点击 el-select，展开下拉菜单
			elSelect.click();

			// 短暂延迟后，查找选中的 span 元素
			setTimeout(() => {
				// 查找下拉菜单中带有 selected 类的 li 元素下的 span
				const selectedSpan = elSelect.querySelector('.el-select-dropdown__item.selected > span');
				let inputValue = '';

				if (selectedSpan) {
					inputValue = selectedSpan.textContent.trim();
				}

				// 移除之前的 span 元素，避免重复添加
				const existingSpan = inputElement.nextElementSibling;
				if (existingSpan && existingSpan.classList.contains('highlighted-text')) {
					existingSpan.remove();
					inputElement.style.display = '';  // 恢复显示
				}

				// 创建一个 span 元素来包裹文字并添加背景色
				const span = document.createElement('span');
				span.classList.add('highlighted-text');
				span.textContent = inputValue;

				// 隐藏 input 元素，并将 span 元素插入到 input 元素后面，模拟文字高亮效果
				inputElement.style.display = 'none';
				inputElement.parentNode.insertBefore(span, inputElement.nextSibling);

				// 设置 span 元素的样式
				span.style.backgroundColor = 'lightgreen';
				span.style.padding = '0 2px';
				span.style.borderRadius = '3px';
				span.style.font = window.getComputedStyle(inputElement).font;
				span.style.color = 'red';
				span.style.fontSize = '16px';
				span.style.fontWeight = 'bold';
				span.style.position = 'relative';
				span.style.left = '31%';
				span.style.top = '0px';
				span.style.whiteSpace = 'nowrap';

				// 再次点击 el-select，关闭下拉菜单
				elSelect.click();
			}, 2000);
		}
	}

	// 调整文本区域高度
	// function adjustTextareas() {
	// 	const textareas = document.querySelectorAll('.el-textarea__inner');
	// 	textareas.forEach(textarea => {
	// 		if (textarea.disabled) {
	// 			textarea.style.height = 'auto';
	// 			textarea.style.height = textarea.scrollHeight + 'px';
	// 		}
	// 	});
	// }

	// 应用样式
	function applyStyle() {
		if (!styleElement) {
			styleElement = document.createElement('style');
			styleElement.id = 'custom-radio-style';
			styleElement.textContent = customStyle;
			document.head.appendChild(styleElement);
		}
	}

	// 移除样式
	function removeStyle() {
		if (styleElement) {
			styleElement.remove();
			styleElement = null;
		}
	}

	// 更新按钮状态
	function updateButtonState(button, isStyleApplied, isHighlightApplied) {
		let text = '应用';
		let backgroundColor = '#67c23a';
		let className = 'green-state';

		if (isStyleApplied || isHighlightApplied) {
			text = '取消';
			backgroundColor = '#f44336';
			className = 'red-state';
		}

		button.textContent = text + '样式';
		button.style.backgroundColor = backgroundColor;
		button.className = className;
	}

	// 创建按钮
	function createButtons() {
		// 1. 创建"调整高度"按钮
		// const adjustHeightButton = createButton("调整高度", "adjust-height-btn", "#409eff", adjustTextareas);

		// 2. 创建"样式切换"按钮
		const toggleStyleButton = createButton("应用样式", "toggle-style-btn", "#67c23a", function () {
			// 初始化状态
			let isStyleApplied = GM_getValue(STYLE_APPLIED_KEY, false);
			let isHighlightApplied = GM_getValue(HIGHLIGHT_APPLIED_KEY, false);

			// 切换状态
			isStyleApplied = !isStyleApplied;
			isHighlightApplied = !isHighlightApplied;

			// 保存状态
			GM_setValue(STYLE_APPLIED_KEY, isStyleApplied);
			GM_setValue(HIGHLIGHT_APPLIED_KEY, isHighlightApplied);

			updateButtonState(toggleStyleButton, isStyleApplied, isHighlightApplied);

			// 应用/移除样式
			if (isStyleApplied) {
				applyStyle();
			} else {
				removeStyle();
			}

			// 启动/停止监听高亮
			if (isHighlightApplied) {
				observer.observe(document.body, {
					childList: true,
					subtree: true,
				});
				processInput();
			} else {
				observer.disconnect();
				const inputElement = document.querySelector(inputSelector);
				if (inputElement) {
					const existingSpan = inputElement.nextElementSibling;
					if (existingSpan && existingSpan.classList.contains('highlighted-text')) {
						existingSpan.remove();
						inputElement.style.display = '';  // 恢复显示
					}
				}
			}
		});

		// 初始化样式切换按钮状态
		let isStyleApplied = GM_getValue(STYLE_APPLIED_KEY, false);
		let isHighlightApplied = GM_getValue(HIGHLIGHT_APPLIED_KEY, false);

		updateButtonState(toggleStyleButton, isStyleApplied, isHighlightApplied);

		if (isStyleApplied) {
			applyStyle();
		}
		if (isHighlightApplied) {
			observer.observe(document.body, {
				childList: true,
				subtree: true,
			});
		}

		// 将按钮添加到容器
		// buttonContainer.appendChild(adjustHeightButton);
		buttonContainer.appendChild(toggleStyleButton);

		// 将容器添加到页面
		document.body.appendChild(buttonContainer);
	}

	// 等待页面加载完成后创建按钮
	if (document.readyState === 'complete' || document.readyState === 'interactive') {
		setTimeout(createButtons, 1200);
	} else {
		document.addEventListener('DOMContentLoaded', function () {
			setTimeout(createButtons, 1200);
		});
	}
})();