import { nextTick } from 'vue';

/**
 * 页面全局 Loading
 * @method setCss 载入 css（可选）
 * @method start 创建 loading
 * @method done 移除 loading
 */
export const NextLoadingzdy = {
    // 可选：如果想用外部 CSS 文件，可以保留这个方法
    setCss: () => {
        // 留空或者你可以注入内联样式
    },
    // 创建 loading
    start: () => {
        const bodys: Element = document.body;

        // 构建 HTML + 内联样式，防止依赖额外文件
        const div = document.createElement('div');
        div.setAttribute('class', 'loading-next');

        const htmls = `
			<style>
				.loading-next {
					position: fixed;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					background-color: rgba(255, 255, 255, 0.2);
					z-index: 999999;
					display: flex;
					align-items: center;
					justify-content: center;
					flex-direction: column;
					transition: opacity 0.3s ease;
				}
				.loading-ring {
					display: inline-block;
					width: 30px;
					height: 30px;
					border: 6px solid #409eff;
					border-radius: 50%;
					border-top-color: #34d399;
					animation: spin 1s ease-in-out infinite;
				}
				.loading-text {
					margin-top: 20px;
					font-size: 16px;
					color: #409eff;
					font-weight: bold;
				}

				@keyframes spin {
					to { transform: rotate(360deg); }
				}
			</style>

			<div class="loading-ring"></div>
			<div class="loading-text">加载中...</div>
		`;

        div.innerHTML = htmls;
        bodys.appendChild(div);

        window.nextLoading = true;
    },
    // 移除 loading
    done: () => {
        nextTick(() => {
            setTimeout(() => {
                window.nextLoading = false;
                const el = document.querySelector('.loading-next');
                if (el) {
                    el.style.opacity = '0';
                    setTimeout(() => {
                        el.parentNode?.removeChild(el);
                    }, 300);
                }
            }, 800);
        });
    },
};