<script setup lang="ts">
import {ref, onMounted, computed} from "vue";

interface AccountItem {
    id: number;
    platform: string;
    nickname: string;
    loginStatus: string;
    hasCookies: boolean;
    updatedAt: number;
}

const emit = defineEmits<{
    (e: 'change'): void;
}>();

const platforms = [
    {key: 'douyin', name: '*音', icon: '📱', color: '#000000'},
    {key: 'kuaishou', name: '*手', icon: '🎬', color: '#FF6900'},
    {key: 'shipin', name: '*频号', icon: '📺', color: '#07C160'},
    {key: 'xiaohongshu', name: '*红书', icon: '📕', color: '#FF2442'},
];

const activePlatform = ref('douyin');
const accounts = ref<AccountItem[]>([]);
const loading = ref(false);
const operatingId = ref<number | null>(null);

// 当前平台的账号列表
const currentAccounts = computed(() => {
    return accounts.value.filter(a => a.platform === activePlatform.value);
});

// 加载账号列表
async function loadAccounts() {
    loading.value = true;
    try {
        const result = await window.$mapi.publish.listAccounts();
        if (result.success) {
            accounts.value = result.data;
        }
    } catch (e: any) {
        console.error('加载账号失败:', e);
    } finally {
        loading.value = false;
    }
}

// 添加账号
async function addAccount() {
    try {
        const result = await window.$mapi.publish.addAccount({
            platform: activePlatform.value,
        });
        if (result.success) {
            // 添加后立即发起登录
            await loadAccounts();
            await setupLogin(result.data.id);
        }
    } catch (e: any) {
        console.error('添加账号失败:', e);
    }
}

// 设置登录（打开浏览器扫码）
async function setupLogin(accountId: number) {
    operatingId.value = accountId;
    try {
        const result = await window.$mapi.publish.login({
            platform: activePlatform.value,
            accountId,
        });
        if (result.success) {
            await loadAccounts();
            emit('change');
        } else {
            alert('登录失败: ' + (result.message || '未知错误'));
        }
    } catch (e: any) {
        console.error('登录失败:', e);
        alert('登录失败: ' + (e.message || '未知错误'));
    } finally {
        operatingId.value = null;
    }
}

// 测试登录状态
async function testLogin(accountId: number) {
    operatingId.value = accountId;
    try {
        const result = await window.$mapi.publish.checkLoginStatus({
            platform: activePlatform.value,
            accountId,
            checkBrowser: true,
        });
        if (result.success && result.isLoggedIn) {
            alert('✅ 登录状态有效');
        } else {
            alert('⚠️ 登录状态已失效，请重新登录');
        }
    } catch (e: any) {
        console.error('测试登录失败:', e);
    } finally {
        operatingId.value = null;
    }
}

// 删除账号
async function deleteAccount(accountId: number) {
    try {
        // 找到要删除的账号的平台
        const account = accounts.value.find(a => a.id === accountId);
        const platform = account?.platform || activePlatform.value;

        // 1. 先删除数据库记录（最重要，不能被浏览器操作阻塞）
        const result = await window.$mapi.publish.deleteAccount({ accountId });
        if (result.success) {
            await loadAccounts();
            emit('change'); // 通知父组件刷新登录状态

            // 2. 后台异步清理浏览器数据（不阻塞 UI）
            setTimeout(async () => {
                try { await window.$mapi.publish.closeBrowser({ platform }); } catch (e) { /* 忽略 */ }
            }, 100);
        }
    } catch (e: any) {
        console.error('删除账号失败:', e);
    }
}

// 获取登录状态文本和颜色
function getStatusInfo(status: string, hasCookies: boolean) {
    if (status === 'active' && hasCookies) {
        return {text: '已登录', color: '#52c41a', dot: '🟢'};
    }
    if (status === 'expired') {
        return {text: '已过期', color: '#faad14', dot: '🟡'};
    }
    return {text: '未登录', color: '#999', dot: '⚪'};
}

// 格式化时间
function formatTime(timestamp: number) {
    if (!timestamp) return '';
    const d = new Date(timestamp);
    return `${d.getMonth() + 1}/${d.getDate()} ${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`;
}

onMounted(() => {
    loadAccounts();
});
</script>

<template>
    <div class="account-manager">
        <!-- 平台标签切换 -->
        <div class="platform-tabs">
            <div
                v-for="p in platforms" :key="p.key"
                class="platform-tab"
                :class="{active: activePlatform === p.key}"
                @click="activePlatform = p.key"
            >
                <span class="tab-icon">{{ p.icon }}</span>
                <span class="tab-name">{{ p.name }}</span>
                <span class="tab-count" v-if="accounts.filter(a => a.platform === p.key).length > 0">
                    {{ accounts.filter(a => a.platform === p.key).length }}
                </span>
            </div>
        </div>

        <!-- 账号列表 -->
        <div class="account-list">
            <div v-if="loading" class="loading-state">
                <a-spin />
            </div>

            <template v-else>
                <div
                    v-for="account in currentAccounts"
                    :key="account.id"
                    class="account-card"
                >
                    <div class="account-info">
                        <span class="status-dot">{{ getStatusInfo(account.loginStatus, account.hasCookies).dot }}</span>
                        <div class="account-detail">
                            <div class="account-nickname">{{ account.nickname || '未命名' }}</div>
                            <div class="account-meta">
                                <span class="status-text" :style="{color: getStatusInfo(account.loginStatus, account.hasCookies).color}">
                                    {{ getStatusInfo(account.loginStatus, account.hasCookies).text }}
                                </span>
                                <span v-if="account.updatedAt" class="update-time">
                                    · {{ formatTime(account.updatedAt) }}
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="account-actions">
                        <a-button
                            size="small"
                            :loading="operatingId === account.id"
                            @click="setupLogin(account.id)"
                        >
                            {{ account.hasCookies ? '重新登录' : '扫码登录' }}
                        </a-button>
                        <a-button
                            v-if="account.hasCookies"
                            size="small"
                            :loading="operatingId === account.id"
                            @click="testLogin(account.id)"
                        >
                            测试
                        </a-button>
                        <a-popconfirm
                            content="确定删除此账号？"
                            @ok="deleteAccount(account.id)"
                        >
                            <a-button size="small" status="danger">
                                删除
                            </a-button>
                        </a-popconfirm>
                    </div>
                </div>

                <!-- 空状态 -->
                <div v-if="currentAccounts.length === 0" class="empty-state">
                    <div class="empty-text">暂无{{ platforms.find(p => p.key === activePlatform)?.name }}账号</div>
                </div>
            </template>

            <!-- 添加账号按钮 -->
            <div class="add-account-btn" @click="addAccount">
                <span class="add-icon">+</span>
                <span>添加{{ platforms.find(p => p.key === activePlatform)?.name }}账号</span>
            </div>
        </div>
    </div>
</template>

<style scoped>
.account-manager {
    padding: 0;
}

.platform-tabs {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
    flex-wrap: wrap;
}

.platform-tab {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 8px 16px;
    border-radius: 8px;
    cursor: pointer;
    background: #f5f5f5;
    border: 2px solid transparent;
    transition: all 0.2s;
    font-size: 14px;
}

.platform-tab:hover {
    background: #e8e8e8;
}

.platform-tab.active {
    background: #e6f4ff;
    border-color: #1890ff;
    color: #1890ff;
}

.tab-icon {
    font-size: 16px;
}

.tab-count {
    background: #1890ff;
    color: white;
    font-size: 11px;
    padding: 0 6px;
    border-radius: 10px;
    min-width: 18px;
    text-align: center;
    line-height: 18px;
}

.account-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.account-card {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    border: 1px solid #e8e8e8;
    border-radius: 10px;
    background: white;
    transition: all 0.2s;
}

.account-card:hover {
    border-color: #1890ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.account-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.status-dot {
    font-size: 14px;
}

.account-detail {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.account-nickname {
    font-weight: 500;
    font-size: 14px;
}

.account-meta {
    font-size: 12px;
    color: #999;
}

.status-text {
    font-weight: 500;
}

.account-actions {
    display: flex;
    gap: 6px;
}

.loading-state {
    text-align: center;
    padding: 32px;
}

.empty-state {
    text-align: center;
    padding: 24px;
    color: #999;
}

.add-account-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 12px;
    border: 2px dashed #d9d9d9;
    border-radius: 10px;
    cursor: pointer;
    color: #999;
    transition: all 0.2s;
    font-size: 14px;
}

.add-account-btn:hover {
    border-color: #1890ff;
    color: #1890ff;
}

.add-icon {
    font-size: 18px;
    font-weight: bold;
}
</style>
