<template>
    <!-- 强制更新检查 -->
    <!-- <UpdateChecker v-if="false" @ready="updateReady = true" /> -->
    <UpdateChecker v-if="!isDev && isElectronEnv && !updateReady" @ready="updateReady = true" />

    <template v-else>
        <!-- 滚动通知栏（登录页和工作台都显示） -->
        <NoticeBar />

        <!-- 登录页面 -->
        <LoginPage v-if="currentPage === 'login'" @login-success="handleLoginSuccess" class="animate-fadeIn" />

        <template v-else>
            <!-- 配置页面 - 使用 v-show 保持状态 -->
            <div class="h-full w-full animate-fadeIn" v-show="currentPage === 'config'">
                <ConfigPage @go-to-browser="handleGoToBrowser" @logout="handleLogout" />
                <!-- 更新通知组件：启动时已在 UpdateChecker 检查，此处暂不显示 -->
                <!-- <UpdateNotification /> -->
            </div>

            <!-- 浏览器页面 -->
            <div class="h-full w-full animate-fadeIn" v-show="currentPage === 'browser'">
                <WorkbenchLayout :account-groups="accountGroups" :rotation-status="rotationStatus"
                    :greeting-stats="greetingStats" :automation-logs="automationLogs" @go-back="handleGoToConfig"
                    @stop-all="handleStopAll" @logout="handleLogout" />
            </div>
        </template>
    </template>

    <!-- 关闭中加载遮罩 -->
    <div v-if="isClosing" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg p-8 flex flex-col items-center">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mb-4"></div>
            <p class="text-lg font-medium text-gray-800">关闭中，请稍候...</p>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { isElectron, getAppVersion } from './utils/electronBridge'
import LoginPage from './pages/LoginPage.vue'
import ConfigPage from './pages/ConfigPage.vue'
import UpdateChecker from './pages/UpdateChecker.vue'
import WorkbenchLayout from './layout/WorkbenchLayout.vue'
import UpdateNotification from './components/UpdateNotification.vue'
import NoticeBar from './components/NoticeBar.vue'
import { useNoticeStore } from './stores/noticeStore'
import { ElMessage } from 'element-plus'
import { getPermissions } from './utils/storage'

// Constants
const USER_KEY = 'user_data'
const CONFIG_KEY = 'autoDm_runConfig'

// State
const updateReady = ref(false)
const currentPage = ref('login')
const isLoading = ref(false)
const isClosing = ref(false)
const automationStatus = ref({})
const accountGroups = ref([])
const viewAccountMap = ref({})
const rotationStatus = ref(null)
const greetingStats = ref({ greetingCount: 0, inviteCount: 0 })
const automationLogs = ref([])

const isElectronEnv = isElectron()
const isDev = window.location.port === '5173'

// 公告通知
const noticeStore = useNoticeStore()
noticeStore.fetchNotices()

// 定期检查新通知
let noticeCheckInterval = null
const startNoticeCheck = () => {
    // 每 5 分钟检查一次新通知
    noticeCheckInterval = setInterval(() => {
        noticeStore.fetchNotices()
    }, 5 * 60 * 1000)
}

const stopNoticeCheck = () => {
    if (noticeCheckInterval) {
        clearInterval(noticeCheckInterval)
        noticeCheckInterval = null
    }
}

// Lifecycle
onMounted(() => {
    // Set Title
    getAppVersion().then(version => {
        document.title = `Yolo终端v${version}`
    }).catch(() => {
        document.title = 'Yolo终端'
    })

    console.log('[App]', !isDev, isElectronEnv, !updateReady.value)
    // Check Login
    try {
        const userData = localStorage.getItem(USER_KEY)
        if (userData) {
            const user = JSON.parse(userData)
            if (user && user.tokenValue) {
                currentPage.value = 'browser'
                void syncAutotkPermissionLimit()
            }
        }
    } catch { } // eslint-disable-line no-empty

    // Listeners
    if (isElectronEnv) {
        window.electronAPI.onRequestClearLogin(() => {
            console.log('[App] 收到清除登录状态请求')
            localStorage.removeItem(USER_KEY)
        })

        // 应用关闭事件
        window.electronAPI.onAppClosingStart(async () => {
            console.log('[App] 收到应用关闭开始事件')
            isClosing.value = true
            // 隐藏所有视图，避免遮罩被视图盖住
            if (isElectron()) {
                window.electronAPI.hideViews().catch((e) => {
                    console.warn('[App] 隐藏视图失败:', e)
                })

                await handleStopAll()
            }
        })

        window.electronAPI.onAppClosingComplete(() => {
            console.log('[App] 收到应用关闭完成事件')
            isClosing.value = false
        })

        // Rotation Status
        window.electronAPI.getRotationStatus().then(status => {
            rotationStatus.value = status
        }).catch(console.error)

        window.electronAPI.onRotationStatusChanged(status => {
            rotationStatus.value = status
            console.log('[App] 收到轮换状态变化123:', status)
            // Auto switch tab if group changes
            if (status && status.currentActiveGroup && status.enabled) {
                console.log('[App] 收到轮换状态变化456:', status)
                const targetTab = tabs.value.find(t => t.label === status.currentActiveGroup || t.id === status.currentActiveGroup)
                if (targetTab && targetTab.id !== currentTab.value) {
                    console.log('[App] 自动切换到轮换组789:', targetTab.id)
                    handleTabSwitch(targetTab.id)
                }
            }
        })

        // Stats
        window.electronAPI.getGreetingStats().then(stats => {
            greetingStats.value = stats
        }).catch(console.error)

        window.electronAPI.onGreetingStatsChanged(stats => {
            greetingStats.value = stats
        })

        // Logs
        window.electronAPI.onAutomationLog(log => {
            automationLogs.value = [...automationLogs.value.slice(-99), { ...log, timestamp: Date.now() }]
        })
    }

    window.addEventListener('beforeunload', handleBeforeUnload)
    window.addEventListener('storage', handleStorageChange)
    // 监听账号组配置更新事件
    window.addEventListener('config-updated', handleConfigUpdate)

    window.addEventListener('auth-expired', handleAuthExpired)

    loadConfig()

    // 启动定期检查新通知
    startNoticeCheck()
    console.log('[App] 已启动通知检查')

    // Health Check
    startHealthCheck()
})

onUnmounted(() => {
    window.removeEventListener('beforeunload', handleBeforeUnload)
    window.removeEventListener('storage', handleStorageChange)
    window.removeEventListener('config-updated', handleConfigUpdate)
    window.removeEventListener('auth-expired', handleAuthExpired)
    stopNoticeCheck()
    console.log('[App] 已停止通知检查')
    stopHealthCheck()
})

// Handlers
const handleBeforeUnload = () => {
    localStorage.removeItem(USER_KEY)
}

const handleStorageChange = (e) => {
    if (e.key === CONFIG_KEY) {
        loadConfig()
    }
}

const syncAutotkPermissionLimit = async () => {
    if (!isElectron()) return
    try {
        const permissions = getPermissions()
        const hasAutotkPermission = permissions?.autotk === 1
        const hasWebAiPermission = permissions?.webAi === 1
        if (hasAutotkPermission || hasWebAiPermission) return
        await window.electronAPI.updateAutomationConfig({
            filters: {
                maxAnchorCount: 1
            }
        })
    } catch (e) {
        console.warn('[App] 同步 autotk 权限限制失败:', e)
    }
}

const clearLoginState = () => {
    localStorage.removeItem(USER_KEY)
    localStorage.removeItem('user')
    localStorage.removeItem('token')
}

const handleLoginSuccess = async () => {
    currentPage.value = 'browser'
    await syncAutotkPermissionLimit()
}

// 处理配置更新事件
const handleConfigUpdate = () => {
    console.log('[App] 收到配置更新事件，重新加载配置')
    loadConfig()
}

let healthCheckInterval = null

const resetToLogin = async (message) => {
    if (message) {
        ElMessage.error(message)
    }

    stopHealthCheck()
    clearLoginState()
    currentPage.value = 'login'

    if (isElectron()) {
        try {
            await window.electronAPI.hideViews()
            await handleStopAll()
        } catch (e) {
            console.warn('[App] 娓呯悊瑙嗗浘澶辫触:', e)
        }
    }

}

const handleAuthExpired = async (event) => {
    await resetToLogin(event?.detail?.message)
}

const startHealthCheck = () => {
    const check = async () => {
        if (currentPage.value === 'login' || !isElectron()) return
        try {
            const result = await window.electronAPI.checkHealth()
            if (result.success && result.code === 40400) {
                await resetToLogin(result.message); return
                // 隐藏所有 BrowserView 并停止自动化，防止视图悬浮在登录页上方
                // try {
                //     await window.electronAPI.hideViews()
                //     await handleStopAll()
                // } catch (e) {
                //     console.warn('[App] 清理视图失败:', e)
                // }
                // currentPage.value = 'login'
            }
        } catch (error) {
            console.error('[App] 健康检查失败:', error)
        }
    }
    check()
    healthCheckInterval = setInterval(check, 5000)
}

const stopHealthCheck = () => {
    if (healthCheckInterval) clearInterval(healthCheckInterval)
}


const loadConfig = () => {
    try {
        const savedConfig = localStorage.getItem(CONFIG_KEY)
        if (savedConfig) {
            const config = JSON.parse(savedConfig)
            accountGroups.value = config.accountGroups || []

            const map = {}
            config.accountGroups.forEach((group, groupIndex) => {
                const viewsPerGroup = 3
                group.accounts.forEach((account, accIndex) => {
                    const viewId = groupIndex * viewsPerGroup + accIndex + 1
                    if (viewId <= 9 && account.email && account.pwd) {
                        map[viewId] = { ...account, group: group.name }
                    }
                })
            })
            viewAccountMap.value = map
        }
    } catch { } // eslint-disable-line no-empty
}

watch(currentPage, (newVal) => {
    if (newVal === 'browser') {
        loadConfig()
    }
})

// Actions

const handleGoToBrowser = async () => {
    if (isElectron()) {
        await window.electronAPI.showViews()
    }
    currentPage.value = 'browser'
}

const handleGoToConfig = async () => {
    if (isElectron()) {
        await window.electronAPI.hideViews()
    }
    currentPage.value = 'config'
}

const handleLogout = async () => {
    stopHealthCheck()
    currentPage.value = 'login'
    clearLoginState()

    if (isElectron()) {
        try { await window.electronAPI.logout() } catch (e) { console.warn('[App] logout失败:', e) }
        try {
            await window.electronAPI.hideViews()
            await handleStopAll()
        } catch (e) {
            console.warn('[App] 清理视图失败:', e)
        }
    }
}

const handleStopAll = async () => {
    if (!isElectron()) return

    console.log('[App] 开始并行停止所有任务...')

    await Promise.allSettled(
        Array.from({ length: 9 }, (_, i) => i + 1).map(viewId =>
            window.electronAPI.stopTikTokAutomation(viewId).catch((e) => {
                console.warn(`[App] 停止视图 ${viewId} 失败:`, e)
            })
        )
    )

    try {
        await window.electronAPI.updateAutomationConfig({
            rotationEnabled: false
        })
    } catch (e) {
        console.warn('[App] 停止轮换服务失败:', e)
    }

    automationStatus.value = {}
    rotationStatus.value = null

    try {
        console.log('[App] 正在清空缓存...')
        if (window.electronAPI.clearAllCache) await window.electronAPI.clearAllCache()
        console.log('[App] 缓存清空完成')
    } catch (e) {
        console.warn('[App] 清空缓存失败:', e)
    }

    console.log('[App] 已并行停止所有任务并清空缓存')
}
</script>
