// ==UserScript==
// @name         企信登录（外网）
// @namespace    http://tampermonkey.net/
// @version      2025-04-02
// @description  企信自动登录
// @author       You
// @match        https://ims.ynydtk.com:8443/
// @icon         https://www.google.com/s2/favicons?sz=64&domain=ynydtk.com
// @grant        none
// ==/UserScript==

(function () {
    "use strict";

    const users = {
        "杜奕新": { phone: "15198716095", password: "Q{dr.086589)", left: "0px" },
        "郭希恒": { phone: "18519953030", password: "Gxh!108790", left: "100px" },
        "张成伟": { phone: "15987134500", password: "Zcw@#$4500", left: "200px" }
    };

    const accountInput = document.querySelector("input[placeholder=\"请输入手机号\"]");
    const passwordInput = document.querySelector("input[placeholder=\"请输入密码\"]");
    const captchaInput = document.querySelector("input[placeholder=\"请输入验证码\"]");
    const captchaImage = document.querySelector("#app > div.un-screen.ut-h-screen.ut-w-screen.ut-flex.ut-justify-center.ut-items-center > div > div.ut-rounded-sm.ui-shadow-md.ut-p-4.ut-flex.ut-flex-col.ut-relative > div > div.ut-px-2.sm\\:ut-px-8.ut-py-4 > div:nth-child(2) > form > div:nth-child(3) > div > div > div > div > img");
    const getcodeButtn = document.querySelector("#app > div.un-screen.ut-h-screen.ut-w-screen.ut-flex.ut-justify-center.ut-items-center > div > div.ut-rounded-sm.ui-shadow-md.ut-p-4.ut-flex.ut-flex-col.ut-relative > div > div.ut-px-2.sm\\:ut-px-8.ut-py-4 > div:nth-child(2) > form > div:nth-child(4) > div > div > div > div > div");
    const codeInput = document.querySelector("input[placeholder='请输入短信验证码']");

    function createModelInput() {
        const modelInput = document.createElement("input");
        modelInput.type = "text";
        modelInput.autocomplete = "off";
        modelInput.setAttribute("data-1p-ignore", "true");

        Object.assign(modelInput.style, {
            position: "absolute",
            top: "-38px",
            left: "-195px",
            height: "35px",
            width: "180px",
            padding: "5px 10px",
            fontSize: "14px",
            border: "2px solid #ccc",
            borderRadius: "8px",
            outline: "none",
            transition: "border-color 0.3s ease",
            backgroundColor: "#fff",
            boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
            textAlign: "center" // 添加文本居中样式
        });

        modelInput.placeholder = "请输入模型名称(默认: chatgpt-4o-latest)";
        const savedModel = localStorage.getItem("captchaModel") || "chatgpt-4o-latest";
        modelInput.value = savedModel;

        modelInput.addEventListener("change", () => {
            localStorage.setItem("captchaModel", modelInput.value);
            console.log("模型名称已保存:", modelInput.value);
        });

        modelInput.addEventListener("focus", () => modelInput.style.borderColor = "#6572FB");
        modelInput.addEventListener("blur", () => modelInput.style.borderColor = "#ccc");

        return modelInput;
    }

    function createButton(text, userData) {
        const button = document.createElement("button");
        button.textContent = text;
        Object.assign(button.style, {
            backgroundColor: "#6672fb",
            border: "none",
            color: "white",
            textAlign: "center",
            textDecoration: "none",
            display: "inline-block",
            fontSize: "16px",
            margin: "4px 2px",
            cursor: "pointer",
            borderRadius: "5px",
            transition: "box-shadow 0.3s ease-in-out",
            height: "30px",
            width: "85px",
            position: "absolute",
            top: "-40px",
            left: userData.left
        });
        button.addEventListener("mouseover", () => button.style.boxShadow = "0 4px 8px 0 rgba(0, 0, 0, 0.2)");
        button.addEventListener("mouseout", () => button.style.boxShadow = "none");
        button.addEventListener("click", () => {
            fillInputs(userData.phone, userData.password);
            recognizeCaptcha();
        });
        return button;
    }

    function fillInputs(phone, password) {
        if (accountInput) simulateInput(accountInput, phone);
        if (passwordInput) simulateInput(passwordInput, password);
    }

    function simulateInput(element, text) {
        element.value = text;
        element.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
    }

    function captureImageToBase64(img) {
        return new Promise((resolve, reject) => {
            if (!img || !(img instanceof HTMLImageElement)) {
                reject(new Error("无效的图片元素"));
                return;
            }

            if (!img.complete || img.naturalWidth === 0) {
                img.onload = () => convertImage(img, resolve);
                img.onerror = () => reject(new Error("图片加载失败"));
                return;
            }
            convertImage(img, resolve);
        });
    }

    function convertImage(img, resolve) {
        const canvas = document.createElement("canvas");
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        const ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        resolve(canvas.toDataURL("image/png"));
    }

    function recognizeCaptcha() {
        if (!captchaImage) {
            console.error("验证码图片未找到");
            return;
        }
        if (!captchaInput) {
            console.error("验证码输入框未找到");
            return;
        }

        captureImageToBase64(captchaImage).then(base64Image => {
            const url = "https://one.ocoolai.com/v1/chat/completions";
            const apiKey = "sk-u6Abbrq7DehKfk9m4728AeB565Bd480bBd8c2a178b4d6b13";
            const headers = {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${apiKey}`
            };
            const modelName = localStorage.getItem("captchaModel") || "chatgpt-4o-latest";
            const data = {
                "model": modelName,
                "stream": false,
                "messages": [
                    { "role": "system", "content": "You are a helpful assistant." },
                    {
                        "role": "user",
                        "content": [
                            { "type": "text", "text": "请准确识别这张验证码图片中的文字，它包含 4 个数字。请只返回完整的 4 位数字验证码，不添加任何多余说明或空格。" },
                            { "type": "image_url", "image_url": { "url": base64Image } }
                        ]
                    }
                ],
                "max_tokens": 10
            };

            fetch(url, { method: "POST", headers, body: JSON.stringify(data) })
                .then(response => {
                    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                    return response.json();
                })
                .then(result => {
                    const captchaText = result.choices?.[0]?.message?.content || "";
                    if (captchaText) {
                        if (captchaText.length !== 4 || !/^\d{4}$/.test(captchaText)) {
                            console.warn("验证码格式不正确:", captchaText);
                        }
                        simulateInput(captchaInput, captchaText);
                        captchaInput.focus();
                        setTimeout(() => getcodeButtn?.click(), 500);
                        setTimeout(() => codeInput?.focus(), 500);
                    } else {
                        console.error("API 未返回验证码:", result);
                    }
                })
                .catch(err => console.error("验证码识别失败:", err));
        }).catch(err => console.error("图片转换失败:", err));
    }

    accountInput.style.position = "relative";
    const modelInput = createModelInput();
    accountInput.parentNode.insertBefore(modelInput, accountInput);

    Object.entries(users).forEach(([name, data]) => {
        const button = createButton(name, data);
        accountInput.parentNode.insertBefore(button, accountInput);
    });
})();