/**
 * 动态加载ai脚本
* @param aiToken 
* @param aiId 
*/
export const loadAiScript = (aiToken: string, aiId: string) => {
    return new Promise((resolve, reject) => {

        const configScript = document.createElement('script');
        configScript.textContent = `
            window.difyChatbotConfig = {
                token: '${aiToken}',
                baseUrl: '${window.location.protocol}//dify.data-it.tech/chat'
            };
        `;
        
        // baseUrl: '${window.location.protocol}//dify.data-it.tech/chat'
        configScript.async = true;
        configScript.setAttribute('data-name', 'aiConfig')
        document.head.appendChild(configScript);

        const script = document.createElement('script');
        const httpUrl = () => {
            // 协议
            const agreement = window.location.protocol;
            // 地址
            const host = window.location.host;
            return `${agreement}//${host}`
        }

        script.src = httpUrl() + '/js/embedBase.min.js';
        script.id = aiId;
        script.setAttribute('data-name', 'adScript')
        script.async = true;

        script.onload = () => {
            resolve(0);
        };

        script.onerror = () => {
            reject();
        };

        // 将 script 标签添加到 document.head 中
        document.head.appendChild(script);

    })
}

/**
 * 销毁ai相关脚本
 */
export const destructionAiScript = () => {
    // 销毁head中对应的脚本
    removeScript('aiConfig');
    removeScript('adScript');
    // 删除aiscript创建的dom元素
    const aiBtnDom = document.getElementById('dify-chatbot-bubble-button');
    if (aiBtnDom) {
        aiBtnDom.remove();
    }
    const aiWindowDom = document.getElementById('dify-chatbot-bubble-window');
    if (aiWindowDom) {
        aiWindowDom.remove();
    }
};


const removeScript = (dataName: string) => {
    const scripts = document.head.querySelectorAll(`script[data-name="${dataName}"]`);
    scripts.forEach(script => {
        document.head.removeChild(script);
    });
}

export const aiBtnMove = () => {
    const dragItem = document.getElementById('dify-chatbot-bubble-button');

    let isDragging = false;
    let startX, startY, offsetX, offsetY;

    dragItem.addEventListener('mousedown', (e) => {
        // 开始拖动
        isDragging = false; // 初始设置为非拖动
        dragItem.style.cursor = 'grabbing';

        // 记录鼠标的初始位置和元素的偏移位置
        startX = e.clientX;
        startY = e.clientY;
        offsetX = dragItem.offsetLeft;
        offsetY = dragItem.offsetTop;

        // 防止选中文字
        e.preventDefault();

        // 监听鼠标移动和释放
        const mouseMoveHandler = (e) => {
            const dx = e.clientX - startX;
            const dy = e.clientY - startY;

            if (Math.abs(dx) > 5 || Math.abs(dy) > 5) {
                isDragging = true; // 标记为拖动
                dragItem.style.left = offsetX + dx + 'px';
                dragItem.style.top = offsetY + dy + 'px';
            }
        };

        const mouseUpHandler = () => {
            document.removeEventListener('mousemove', mouseMoveHandler);
            document.removeEventListener('mouseup', mouseUpHandler);
            dragItem.style.cursor = 'grab';
        };

        document.addEventListener('mousemove', mouseMoveHandler);
        document.addEventListener('mouseup', mouseUpHandler);
    });

    dragItem.addEventListener('click', (e) => {
        if (isDragging) {
            e.preventDefault(); // 阻止默认行为
            e.stopPropagation(); // 阻止事件冒泡
        }
    });
}