<template>
  <div class="page-container">
    <div class="header">
      <h1>SkitPanel 短剧管理面板</h1>
      <p class="subtitle">一站式短剧资源管理与刮削工具</p>
    </div>

    <!-- 配置提示 -->
    <el-alert
      v-if="showConfigAlert"
      title="请先前往 系统配置 页面完成必要设置，以确保所有功能正常使用。"
      type="warning"
      show-icon
      :closable="false"
      class="config-alert"
    >
        <router-link to="/config" class="config-link">前往配置</router-link>
    </el-alert>

    <!-- 资源统计 -->
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>资源统计</span>
          <el-button type="primary" :icon="'Refresh'" :loading="loading.stats" @click="fetchStats">
            刷新统计
          </el-button>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :sm="12" :md="8" :lg="4" v-for="item in statItems" :key="item.key" class="stat-col">
          <div :class="['stat-card', item.colorClass]">
            <div class="stat-content">
              <span class="stat-title">{{ item.title }}</span>
              <span class="stat-value">{{ stats[item.key] ?? 'N/A' }}</span>
            </div>
            <el-icon class="stat-icon" :size="28"><component :is="item.icon" /></el-icon>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 系统组件状态 -->
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>系统组件状态</span>
          <el-button type="primary" :icon="'Connection'" :loading="loading.components" @click="runAllTests">
            测试所有组件
          </el-button>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :md="24" :lg="12" v-for="item in statusItems" :key="item.id" class="status-col">
          <div class="status-item">
            <div class="status-label">
              <el-icon><component :is="item.icon" /></el-icon>
              <span>{{ item.label }}</span>
            </div>
            <div class="status-indicator">
              <el-icon v-if="item.status === 'pending'" class="is-loading"><Loading /></el-icon>
              <el-tag v-else :type="getStatusType(item.status)">
                <el-icon style="margin-right: 4px;"><component :is="getStatusIcon(item.status)" /></el-icon>
                {{ item.message }}
              </el-tag>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import * as api from '../api'; 
// 引入所有 Element Plus 图标
import { Folder, VideoPlay, Download, Search, Link, SetUp, QuestionFilled, Check, Close, Loading } from '@element-plus/icons-vue';

// --- 响应式状态 ---

// 加载状态
const loading = reactive({
  stats: false,
  components: false,
});

// 是否显示配置警告
const showConfigAlert = ref(false);

// 资源统计数据
const stats = ref({
  local_skits: 0,
  fnos_items: 0,
  emby_items: 0,
  plex_items: 0,
  qb_total: 0,
  tr_total: 0,
});

// 统计卡片的静态配置
const statItems = [
  { key: 'local_skits', title: '本地资源数量', icon: Folder, colorClass: 'bg-blue' },
  { key: 'fnos_items', title: '飞牛媒体库数量', icon: VideoPlay, colorClass: 'bg-green' },
  { key: 'emby_items', title: 'Emby媒体库数量', icon: VideoPlay, colorClass: 'bg-purple' },
  { key: 'plex_items', title: 'Plex媒体库数量', icon: VideoPlay, colorClass: 'bg-cyan' },
  { key: 'qb_total', title: 'QB总任务数', icon: Download, colorClass: 'bg-orange' },
  { key: 'tr_total', title: 'TR总任务数', icon: Download, colorClass: 'bg-red' },
];

// 系统组件状态
const statusItems = ref([
  { id: 'douban_cookie', label: '豆瓣 Cookie', icon: Search, status: 'untested', message: '未测试' },
  { id: 'ptskit_cookie', label: '站点 Cookie', icon: SetUp, status: 'untested', message: '未测试' },
  { id: 'local_path', label: '本地资源映射', icon: Folder, status: 'untested', message: '未测试' },
  { id: 'qbittorrent', label: 'qBittorrent连通性', icon: Download, status: 'untested', message: '未测试' },
  { id: 'transmission', label: 'Transmission连通性', icon: Download, status: 'untested', message: '未测试' },
  { id: 'fnos', label: '飞牛媒体库连通性', icon: Link, status: 'untested', message: '未测试' },
  { id: 'emby', label: 'Emby服务器连通性', icon: Link, status: 'untested', message: '未测试' },
  { id: 'plex', label: 'Plex服务器连通性', icon: Link, status: 'untested', message: '未测试' },
]);

// --- 方法 ---

// 检查初始配置
const checkInitialConfig = async () => {
  try {
    const res = await api.getInitialCheck(); // 假设的API
    showConfigAlert.value = !res.is_configured;
  } catch (error) {
    console.error("检查初始配置失败:", error);
    showConfigAlert.value = true; // 出错时也提示配置
  }
};

// 获取资源统计
const fetchStats = async () => {
  loading.stats = true;
  try {
    const data = await api.getDashboardStats(); // 假设的API
    stats.value = data;
    ElMessage.success('统计信息已更新！');
  } catch (error) {
    console.error("获取统计信息失败:", error);
    ElMessage.error('获取统计信息失败。');
  } finally {
    loading.stats = false;
  }
};

// 运行所有组件测试
const runAllTests = async () => {
  loading.components = true;
  // 立即将所有状态设置为'pending'
  statusItems.value.forEach(item => {
    item.status = 'pending';
    item.message = '测试中...';
  });
  
  try {
    const results = await api.testAllComponents(); // 假设的API
    // 更新状态
    statusItems.value.forEach(item => {
      if (results[item.id]) {
        item.status = results[item.id].status;
        item.message = results[item.id].message;
      } else {
        item.status = 'unconfigured';
        item.message = '未配置';
      }
    });
     ElMessage.success('所有组件测试完成！');
  } catch (error) {
    console.error("测试组件失败:", error);
    ElMessage.error('测试组件时发生错误。');
    // 失败时重置状态
    statusItems.value.forEach(item => {
        item.status = 'error';
        item.message = '测试失败';
    });
  } finally {
    loading.components = false;
  }
};

// 根据状态返回 Element Plus 的 Tag 类型
const getStatusType = (status) => {
  switch (status) {
    case 'success':
    case 'configured':
      return 'success';
    case 'error':
      return 'danger';
    case 'unconfigured':
      return 'info';
    case 'untested':
    default:
      return 'warning';
  }
};

// 根据状态返回图标
const getStatusIcon = (status) => {
  switch (status) {
    case 'success':
    case 'configured':
      return Check;
    case 'error':
      return Close;
    case 'pending':
        return Loading;
    case 'unconfigured':
    case 'untested':
    default:
      return QuestionFilled;
  }
}

// --- 生命周期钩子 ---
onMounted(() => {
  checkInitialConfig();
  fetchStats();
  // 可选择在页面加载时自动运行一次测试
  // runAllTests();
});

</script>

<style scoped>
.page-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.subtitle {
  color: #888;
  margin-top: 5px;
}

.config-alert {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
.config-link {
    margin-left: 10px;
    font-weight: bold;
    color: var(--el-color-primary);
    text-decoration: none;
}

.box-card {
  margin-bottom: 20px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
}

.stat-col {
  margin-bottom: 20px;
}
@media (max-width: 768px) {
  .stat-col {
    width: 50%;
  }
}
@media (max-width: 500px) {
  .stat-col {
    width: 100%;
  }
}

.stat-card {
  padding: 20px;
  border-radius: 8px;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  opacity: 0.9;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-top: 5px;
}

.stat-icon {
  opacity: 0.8;
}

/* 背景色 */
.bg-blue { background: linear-gradient(135deg, #409EFF, #79bbff); }
.bg-green { background: linear-gradient(135deg, #67C23A, #95d475); }
.bg-purple { background: linear-gradient(135deg, #9b59b6, #b37acb); }
.bg-cyan { background: linear-gradient(135deg, #16a085, #3ccdae); }
.bg-orange { background: linear-gradient(135deg, #E6A23C, #eebe77); }
.bg-red { background: linear-gradient(135deg, #F56C6C, #f89898); }

.status-col {
  margin-bottom: 10px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background-color: #f9f9f9;
  border-radius: 6px;
  border: 1px solid var(--el-border-color-lighter);
}

.status-label {
  display: flex;
  align-items: center;
  font-size: 15px;
}
.status-label .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.status-indicator .el-tag {
  font-size: 13px;
  display: inline-flex;
  align-items: center;
}

</style>
