<template>
  <div class="page-container">
    <PageHeader title="插件管理" :icon="Connection" />

    <el-card class="plugins-card" shadow="hover" v-loading="pluginsStore.loading">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="card-title">
              <el-icon class="header-icon"><Box /></el-icon>
              插件列表
            </span>
            <el-tag v-if="pluginsStore.totalCount > 0" size="small" type="info" class="count-tag">
              共 {{ pluginsStore.totalCount }} 个
            </el-tag>
          </div>
          <div class="header-actions">
            <el-button type="success" @click="handleCrawlAll" size="large" :loading="crawlingAll">
              <el-icon class="btn-icon"><Promotion /></el-icon>
              全部爬取
            </el-button>
            <el-button type="primary" @click="handleRefresh" size="large">
              <el-icon class="btn-icon"><Refresh /></el-icon>
              刷新列表
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="pluginsStore.plugins">
        <el-table-column prop="name" label="插件名称" min-width="180">
          <template #default="{ row }">
            <div class="plugin-name">
              <el-icon class="plugin-icon"><Connection /></el-icon>
              <span class="plugin-name-text">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述" min-width="220">
          <template #default="{ row }">
            <span class="plugin-description">{{ row.description || '暂无描述' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.enabled"
              @change="(val) => handleToggle(row.id, val)"
              class="theme-switch"
            />
          </template>
        </el-table-column>

        <el-table-column label="统计" width="180">
          <template #default="{ row }">
            <div class="plugin-stats">
              <div class="stat-item">
                <el-icon class="stat-icon success"><CircleCheck /></el-icon>
                <span class="stat-value success">{{ row.success_count || 0 }}</span>
              </div>
              <div class="stat-item">
                <el-icon class="stat-icon failed"><CircleClose /></el-icon>
                <span class="stat-value failed">{{ row.failure_count || 0 }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="last_run" label="最后运行" width="180">
          <template #default="{ row }">
            <span class="last-run">{{ formatTime(row.last_run) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleCrawl(row.id)"
              :loading="crawlingPlugin === row.id"
              :disabled="!row.enabled"
            >
              <el-icon class="btn-icon"><Promotion /></el-icon>
              爬取
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-empty 
        v-if="pluginsStore.isEmpty" 
        description="暂无插件" 
        :image-size="120"
      />

      <!-- 爬取结果提示 -->
      <el-alert
        v-if="lastCrawlResult"
        :title="lastCrawlResult.message"
        :type="lastCrawlResult.type"
        closable
        class="crawl-result"
        @close="lastCrawlResult = null"
      >
        <template v-if="lastCrawlResult.data">
          <div class="crawl-stats">
            <span v-if="lastCrawlResult.data.total_crawled !== undefined">
              爬取: {{ lastCrawlResult.data.total_crawled }}
            </span>
            <span v-if="lastCrawlResult.data.proxy_count !== undefined">
              爬取: {{ lastCrawlResult.data.proxy_count }}
            </span>
            <span v-if="lastCrawlResult.data.valid_count !== undefined" class="valid-count">
              有效: {{ lastCrawlResult.data.valid_count }}
            </span>
            <span v-if="lastCrawlResult.data.invalid_count !== undefined" class="invalid-count">
              无效: {{ lastCrawlResult.data.invalid_count }}
            </span>
          </div>
        </template>
      </el-alert>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Connection, 
  Refresh, 
  Promotion, 
  CircleCheck, 
  CircleClose,
  Box
} from '@element-plus/icons-vue'
import { usePluginsStore } from '../stores/plugins'
import { pluginsAPI } from '../api'
import { formatTime } from '../utils/format'
import PageHeader from '../components/PageHeader.vue'

const pluginsStore = usePluginsStore()
const crawlingPlugin = ref(null)
const crawlingAll = ref(false)
const lastCrawlResult = ref(null)

// ==================== 事件处理 ====================
async function handleRefresh() {
  await pluginsStore.fetchPlugins()
  ElMessage.success('插件列表已刷新')
}

async function handleToggle(pluginId, enabled) {
  const success = await pluginsStore.togglePlugin(pluginId, enabled)
  if (success) {
    ElMessage.success(enabled ? '插件已启用' : '插件已禁用')
  } else {
    // 失败时刷新列表恢复状态
    await pluginsStore.fetchPlugins()
  }
}

async function handleCrawl(pluginId) {
  try {
    crawlingPlugin.value = pluginId
    lastCrawlResult.value = null
    
    const response = await pluginsAPI.crawlPlugin(pluginId)
    
    if (response.code === 200) {
      lastCrawlResult.value = {
        type: 'success',
        message: response.message,
        data: response.data
      }
      // 刷新插件统计
      await pluginsStore.fetchPlugins()
    } else {
      lastCrawlResult.value = {
        type: 'error',
        message: response.message || '爬取失败'
      }
    }
  } catch (error) {
    lastCrawlResult.value = {
      type: 'error',
      message: '爬取过程出错'
    }
  } finally {
    crawlingPlugin.value = null
  }
}

async function handleCrawlAll() {
  try {
    // 确认是否爬取所有插件
    const enabledPlugins = pluginsStore.plugins.filter(p => p.enabled)
    if (enabledPlugins.length === 0) {
      ElMessage.warning('没有启用的插件')
      return
    }

    await ElMessageBox.confirm(
      `确定要运行所有 ${enabledPlugins.length} 个启用的插件吗？这将爬取并验证所有代理。`,
      '批量爬取确认',
      {
        confirmButtonText: '开始爬取',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    crawlingAll.value = true
    lastCrawlResult.value = null
    
    const response = await pluginsAPI.crawlAll()
    
    if (response.code === 200) {
      lastCrawlResult.value = {
        type: 'success',
        message: response.message,
        data: response.data
      }
      ElMessage.success('批量爬取完成')
      // 刷新插件统计
      await pluginsStore.fetchPlugins()
    } else {
      lastCrawlResult.value = {
        type: 'error',
        message: response.message || '批量爬取失败'
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量爬取失败:', error)
      lastCrawlResult.value = {
        type: 'error',
        message: '批量爬取过程出错'
      }
    }
  } finally {
    crawlingAll.value = false
  }
}

// ==================== 生命周期 ====================
onMounted(async () => {
  await pluginsStore.fetchPlugins()
})
</script>

<style scoped>
.plugins-card {
  border-radius: var(--radius-lg);
  background: var(--surface);
  border: 1px solid var(--border);
}

.plugins-card:hover {
  border-color: var(--border-light);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-icon {
  margin-right: 8px;
  color: var(--primary);
}

.count-tag {
  background: var(--surface-2) !important;
  border-color: var(--border) !important;
  color: var(--text-muted) !important;
}

.btn-icon {
  margin-right: 4px;
}

.plugin-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.plugin-icon {
  color: var(--primary);
  filter: drop-shadow(0 0 6px rgba(146, 124, 255, 0.3));
}

.plugin-name-text {
  font-weight: 500;
  color: var(--text-primary);
}

.plugin-description {
  color: var(--text-secondary);
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.plugin-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-icon {
  font-size: 14px;
}

.stat-icon.success {
  color: var(--success);
}

.stat-icon.failed {
  color: var(--danger);
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
}

.stat-value.success {
  color: var(--success);
}

.stat-value.failed {
  color: var(--danger);
}

.last-run {
  color: var(--text-muted);
  font-size: 14px;
}

.crawl-result {
  margin-top: 16px;
}

.crawl-stats {
  margin-top: 8px;
  display: flex;
  gap: 16px;
  font-size: 13px;
}

.valid-count {
  color: var(--success);
}

.invalid-count {
  color: var(--danger);
}
</style>
