<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getApiTypeOptions, getModelLibraryList, getModelTypeOptions, getProviderList } from '@/api/model';
import type { ModelApiTypeOption, ModelLibraryDto, ModelTypeOption } from '@/api/model/types';
import { Search, CopyDocument, HomeFilled } from '@element-plus/icons-vue';

const router = useRouter();

const loading = ref(false);
const modelList = ref<ModelLibraryDto[]>([]);
const totalCount = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选条件
const searchKey = ref('');
const selectedProvider = ref<string>('');
const selectedModelType = ref<number | undefined>(undefined);
const selectedApiType = ref<number | undefined>(undefined);
const isPremiumOnly = ref(false);

// 供应商列表
const providerList = ref<string[]>(['全部供应商']);

// 模型类型选项
const modelTypeOptions = ref<ModelTypeOption[]>([
  { label: '全部类型', value: undefined as any },
]);

// API类型选项
const apiTypeOptions = ref<ModelApiTypeOption[]>([
  { label: '全部API类型', value: undefined as any },
]);

async function fetchModelList() {
  loading.value = true;
  try {
    const params = {
      searchKey: searchKey.value || undefined,
      providerName: selectedProvider.value && selectedProvider.value !== '全部供应商' ? selectedProvider.value : undefined,
      modelType: selectedModelType.value,
      modelApiType: selectedApiType.value,
      isPremiumOnly: isPremiumOnly.value || undefined,
      skipCount: currentPage.value,
      maxResultCount: pageSize.value,
    };

    const response = await getModelLibraryList(params);
    const data = response.data;

    modelList.value = data.items;
    totalCount.value = data.totalCount;
  }
  catch (error) {
    console.error('获取模型列表失败:', error);
    ElMessage.error('获取模型列表失败');
  }
  finally {
    loading.value = false;
  }
}

// 获取所有供应商列表（用于筛选栏）
async function fetchProviderList() {
  try {
    const response = await getProviderList();
    providerList.value = ['全部供应商', ...response.data.sort()];
  }
  catch (error) {
    console.error('获取供应商列表失败:', error);
  }
}

// 获取模型类型选项
async function fetchModelTypeOptions() {
  try {
    const response = await getModelTypeOptions();
    modelTypeOptions.value = [
      { label: '全部类型', value: undefined as any },
      ...response.data,
    ];
  }
  catch (error) {
    console.error('获取模型类型选项失败:', error);
  }
}

// 获取API类型选项
async function fetchApiTypeOptions() {
  try {
    const response = await getApiTypeOptions();
    apiTypeOptions.value = [
      { label: '全部API类型', value: undefined as any },
      ...response.data,
    ];
  }
  catch (error) {
    console.error('获取API类型选项失败:', error);
  }
}

function copyModelId(modelId: string) {
  navigator.clipboard.writeText(modelId).then(() => {
    ElMessage.success('模型ID已复制');
  });
}

function resetFilters() {
  searchKey.value = '';
  selectedProvider.value = '';
  selectedModelType.value = undefined;
  selectedApiType.value = undefined;
  isPremiumOnly.value = false;
  currentPage.value = 1;
}

function selectProvider(provider: string) {
  selectedProvider.value = provider === selectedProvider.value ? '' : provider;
  currentPage.value = 1;
}

function handlePageChange(page: number) {
  currentPage.value = page;
  fetchModelList();
}

function handleSizeChange(size: number) {
  pageSize.value = size;
  currentPage.value = 1;
  fetchModelList();
}

function goToHome() {
  router.push('/');
}

// 监听筛选条件变化，自动刷新数据
// 搜索关键词使用防抖，其他条件立即触发
let searchTimer: ReturnType<typeof setTimeout> | null = null;
watch(searchKey, () => {
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  searchTimer = setTimeout(() => {
    currentPage.value = 1;
    fetchModelList();
  }, 500);
});

watch([selectedProvider, selectedModelType, selectedApiType, isPremiumOnly], () => {
  currentPage.value = 1;
  fetchModelList();
}, { deep: true });

onMounted(() => {
  fetchProviderList();
  fetchModelTypeOptions();
  fetchApiTypeOptions();
  fetchModelList();
});
</script>

<template>
  <div class="model-library-container">
    <!-- 顶部横幅 -->
    <div class="banner-section">
      <div class="banner-content">
        <div class="banner-header">
          <div class="banner-left">
            <h1 class="banner-title">AI模型广场</h1>
            <p class="banner-subtitle">
              探索并接入全球顶尖AI模型，覆盖文本生成、图像理解、代码辅助等多个领域
            </p>
          </div>
          <div class="banner-right">
            <!-- 统计信息卡片 -->
            <div class="stats-cards">
              <div class="stat-card">
                <div class="stat-icon">
                  <el-icon><i-ep-box /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ totalCount }}</div>
                  <div class="stat-label">模型</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon">
                  <el-icon><i-ep-office-building /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ providerList.length - 1 }}</div>
                  <div class="stat-label">供应商</div>
                </div>
              </div>
            </div>
            <el-button
              :icon="HomeFilled"
              class="home-btn"
              round
              @click="goToHome"
            >
              返回首页
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <div class="content-wrapper">
        <!-- 左侧筛选栏 -->
        <aside class="filter-sidebar">
          <div class="filter-section">
            <div class="filter-header">
              <h3 class="filter-title">
                <el-icon><i-ep-filter /></el-icon>
                筛选条件
              </h3>
              <el-button link type="primary" size="small" @click="resetFilters">
                重置
              </el-button>
            </div>

            <!-- 搜索框 -->
            <div class="filter-group">
              <el-input
                v-model="searchKey"
                placeholder="搜索模型..."
                clearable
                size="default"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>

            <!-- 供应商 -->
            <div class="filter-group">
              <h4 class="filter-group-title">供应商</h4>
              <div class="filter-options">
                <div
                  v-for="provider in providerList.filter(p => p !== '全部供应商')"
                  :key="provider"
                  class="filter-option"
                  :class="{ active: selectedProvider === provider }"
                  @click="selectedProvider = selectedProvider === provider ? '' : provider; currentPage = 1"
                >
                  <span class="option-label">{{ provider }}</span>
                  <span v-if="selectedProvider === provider" class="option-check">
                    <el-icon><i-ep-check /></el-icon>
                  </span>
                </div>
              </div>
            </div>

            <!-- 模型类型 -->
            <div class="filter-group">
              <h4 class="filter-group-title">模型类型</h4>
              <div class="filter-options">
                <div
                  v-for="option in modelTypeOptions.filter(o => o.value !== undefined)"
                  :key="option.value"
                  class="filter-option"
                  :class="{ active: selectedModelType === option.value }"
                  @click="selectedModelType = option.value"
                >
                  <span class="option-label">{{ option.label }}</span>
                  <span v-if="selectedModelType === option.value" class="option-check">
                    <el-icon><i-ep-check /></el-icon>
                  </span>
                </div>
              </div>
            </div>

            <!-- API类型 -->
            <div class="filter-group">
              <h4 class="filter-group-title">API类型</h4>
              <div class="filter-options">
                <div
                  v-for="option in apiTypeOptions.filter(o => o.value !== undefined)"
                  :key="option.value"
                  class="filter-option"
                  :class="{ active: selectedApiType === option.value }"
                  @click="selectedApiType = option.value"
                >
                  <span class="option-label">{{ option.label }}</span>
                  <span v-if="selectedApiType === option.value" class="option-check">
                    <el-icon><i-ep-check /></el-icon>
                  </span>
                </div>
              </div>
            </div>

            <!-- 计费类型 -->
            <div class="filter-group">
              <h4 class="filter-group-title">计费类型</h4>
              <div class="filter-options">
                <div
                  class="filter-option"
                  :class="{ active: !isPremiumOnly }"
                  @click="isPremiumOnly = false"
                >
                  <span class="option-label">全部模型</span>
                  <span v-if="!isPremiumOnly" class="option-check">
                    <el-icon><i-ep-check /></el-icon>
                  </span>
                </div>
                <div
                  class="filter-option"
                  :class="{ active: isPremiumOnly }"
                  @click="isPremiumOnly = true"
                >
                  <span class="option-label">仅尊享模型</span>
                  <span v-if="isPremiumOnly" class="option-check">
                    <el-icon><i-ep-check /></el-icon>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </aside>

        <!-- 右侧模型列表 -->
        <main class="model-list-section">
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-wrapper">
            <el-skeleton :rows="8" animated />
          </div>

          <!-- 空状态 -->
          <div v-else-if="modelList.length === 0" class="empty-wrapper">
            <el-empty description="未找到符合条件的模型">
              <el-button type="primary" @click="resetFilters">
                清除筛选条件
              </el-button>
            </el-empty>
          </div>

          <!-- 模型网格 -->
          <div v-else class="model-grid">
            <div
              v-for="model in modelList"
              :key="model.modelId"
              class="model-card"
            >
              <div class="model-card-header">
                <div class="model-icon">
                  <img
                    v-if="model.iconUrl"
                    :src="model.iconUrl"
                    :alt="model.name"
                    class="icon-img"
                  >
                  <div v-else class="icon-placeholder">
                    {{ model.name.charAt(0).toUpperCase() }}
                  </div>
                </div>
                <div class="model-info">
                  <h3 class="model-name">
                    {{ model.name }}
                  </h3>
                  <div class="model-provider">
                    {{ model.providerName }}
                  </div>
                </div>
                <el-button
                  circle
                  size="small"
                  :icon="CopyDocument"
                  class="copy-btn"
                  @click="copyModelId(model.modelId)"
                />
              </div>

              <p v-if="model.description" class="model-description">
                {{ model.description }}
              </p>
              <p v-else class="model-description placeholder">
                {{ model.modelId }}
              </p>

              <div class="model-footer">
                <div class="model-tags">
                  <el-tag v-if="model.isPremium" size="small" type="warning" effect="dark">
                    尊享
                  </el-tag>
                  <el-tag size="small" effect="plain">
                    {{ model.modelTypeName }}
                  </el-tag>
                  <el-tag size="small" effect="plain">
                    {{ model.modelApiTypeName }}
                  </el-tag>
                </div>
                <div class="model-pricing">
                  <div class="price-item">
                    <span class="price-label">输入</span>
                    <span class="price-value">¥{{ model.multiplierShow }}</span>
                  </div>
                  <div class="price-divider">|</div>
                  <div class="price-item">
                    <span class="price-label">输出</span>
                    <span class="price-value">¥{{ (model.multiplierShow * 2).toFixed(4) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div v-if="totalCount > 0 && !loading" class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              prev-text="上一页"
              next-text="下一页"
              background
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </main>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.model-library-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #f5f7fa 0%, #ffffff 100%);

  // 顶部横幅
  .banner-section {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 40px 24px;
    position: relative;
    overflow: hidden;

    // 装饰性背景元素
    &::before,
    &::after {
      content: '';
      position: absolute;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.08);
    }

    &::before {
      width: 400px;
      height: 400px;
      top: -200px;
      right: -100px;
    }

    &::after {
      width: 300px;
      height: 300px;
      bottom: -150px;
      left: -100px;
    }

    .banner-content {
      max-width: 1400px;
      margin: 0 auto;
      position: relative;
      z-index: 1;

      .banner-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 32px;

        .banner-left {
          flex: 1;

          .banner-title {
            font-size: 36px;
            font-weight: 800;
            color: white;
            margin: 0 0 12px 0;
            letter-spacing: -0.5px;
          }

          .banner-subtitle {
            font-size: 15px;
            color: rgba(255, 255, 255, 0.95);
            margin: 0;
            line-height: 1.6;
            max-width: 600px;
          }
        }

        .banner-right {
          display: flex;
          align-items: center;
          gap: 16px;

          // 统计卡片
          .stats-cards {
            display: flex;
            gap: 12px;

            .stat-card {
              background: rgba(255, 255, 255, 0.15);
              backdrop-filter: blur(10px);
              border: 1px solid rgba(255, 255, 255, 0.25);
              border-radius: 12px;
              padding: 12px 16px;
              display: flex;
              align-items: center;
              gap: 12px;
              transition: all 0.3s;

              &:hover {
                background: rgba(255, 255, 255, 0.2);
                transform: translateY(-2px);
              }

              .stat-icon {
                width: 40px;
                height: 40px;
                background: rgba(255, 255, 255, 0.25);
                border-radius: 8px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 20px;
                color: white;
              }

              .stat-info {
                .stat-value {
                  font-size: 24px;
                  font-weight: 700;
                  color: white;
                  line-height: 1;
                  margin-bottom: 4px;
                }

                .stat-label {
                  font-size: 12px;
                  color: rgba(255, 255, 255, 0.85);
                }
              }
            }
          }

          .home-btn {
            background: rgba(255, 255, 255, 0.25);
            border: 1px solid rgba(255, 255, 255, 0.4);
            color: white;
            backdrop-filter: blur(10px);
            padding: 10px 24px;
            font-weight: 500;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

            &:hover {
              background: rgba(255, 255, 255, 0.35);
              transform: translateY(-2px);
              box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
            }
          }
        }
      }
    }
  }

  // 主内容区
  .main-content {
    padding: 32px 24px;

    .content-wrapper {
      max-width: 1400px;
      margin: 0 auto;
      display: flex;
      gap: 24px;

      // 左侧筛选栏
      .filter-sidebar {
        width: 260px;
        flex-shrink: 0;

        .filter-section {
          background: white;
          border-radius: 16px;
          padding: 20px;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
          position: sticky;
          top: 24px;

          .filter-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 2px solid #f0f0f0;

            .filter-title {
              font-size: 16px;
              font-weight: 700;
              color: #303133;
              margin: 0;
              display: flex;
              align-items: center;
              gap: 8px;
            }
          }

          .filter-group {
            margin-bottom: 24px;

            &:last-child {
              margin-bottom: 0;
            }

            .filter-group-title {
              font-size: 13px;
              font-weight: 600;
              color: #606266;
              margin: 0 0 12px 0;
              text-transform: uppercase;
              letter-spacing: 0.5px;
            }

            .filter-options {
              display: flex;
              flex-direction: column;
              gap: 4px;

              .filter-option {
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 8px;
                padding: 10px 12px;
                border-radius: 8px;
                cursor: pointer;
                transition: all 0.2s;
                user-select: none;

                .option-label {
                  font-size: 14px;
                  color: #606266;
                  flex: 1;
                }

                .option-check {
                  color: #667eea;
                  font-size: 16px;
                  display: flex;
                  align-items: center;
                }

                &:hover {
                  background: #f5f7fa;
                }

                &.active {
                  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
                  border: 1px solid rgba(102, 126, 234, 0.3);

                  .option-label {
                    color: #667eea;
                    font-weight: 600;
                  }
                }
              }
            }
          }
        }
      }

      // 右侧模型列表
      .model-list-section {
        flex: 1;
        min-width: 0;

        .loading-wrapper,
        .empty-wrapper {
          background: white;
          border-radius: 16px;
          padding: 80px 40px;
          text-align: center;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
        }

        // 模型网格
        .model-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
          gap: 20px;
          margin-bottom: 32px;

          .model-card {
            background: white;
            border-radius: 16px;
            padding: 24px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
            border: 1px solid #f0f0f0;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            cursor: pointer;
            position: relative;
            overflow: hidden;

            &::before {
              content: '';
              position: absolute;
              top: 0;
              left: 0;
              right: 0;
              height: 4px;
              background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
              opacity: 0;
              transition: opacity 0.3s;
            }

            &:hover {
              transform: translateY(-4px);
              box-shadow: 0 12px 32px rgba(102, 126, 234, 0.15);
              border-color: #667eea;

              &::before {
                opacity: 1;
              }

              .copy-btn {
                opacity: 1;
              }
            }

            .model-card-header {
              display: flex;
              gap: 16px;
              margin-bottom: 16px;

              .model-icon {
                width: 56px;
                height: 56px;
                flex-shrink: 0;

                .icon-img {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                  border-radius: 12px;
                  border: 2px solid #f0f0f0;
                }

                .icon-placeholder {
                  width: 100%;
                  height: 100%;
                  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                  border-radius: 12px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  color: white;
                  font-size: 24px;
                  font-weight: 700;
                }
              }

              .model-info {
                flex: 1;
                min-width: 0;

                .model-name {
                  font-size: 18px;
                  font-weight: 600;
                  color: #303133;
                  margin: 0 0 6px 0;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }

                .model-provider {
                  font-size: 13px;
                  color: #909399;
                  font-weight: 500;
                }
              }

              .copy-btn {
                flex-shrink: 0;
                opacity: 0;
                transition: opacity 0.3s;
              }
            }

            .model-description {
              font-size: 14px;
              color: #606266;
              line-height: 1.7;
              margin: 0 0 20px 0;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              min-height: 48px;

              &.placeholder {
                color: #c0c4cc;
                font-family: 'Monaco', 'Menlo', monospace;
                font-size: 12px;
              }
            }

            .model-footer {
              display: flex;
              justify-content: space-between;
              align-items: center;
              gap: 16px;
              padding-top: 16px;
              border-top: 1px solid #f0f0f0;

              .model-tags {
                display: flex;
                flex-wrap: wrap;
                gap: 6px;
              }

              .model-pricing {
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 13px;
                white-space: nowrap;

                .price-item {
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  gap: 2px;

                  .price-label {
                    font-size: 11px;
                    color: #909399;
                  }

                  .price-value {
                    font-size: 14px;
                    font-weight: 600;
                    color: #303133;
                  }
                }

                .price-divider {
                  color: #dcdfe6;
                }
              }
            }
          }
        }

        // 分页
        .pagination-wrapper {
          display: flex;
          justify-content: center;
          padding: 32px 0;

          :deep(.el-pagination) {
            gap: 8px;

            .btn-prev,
            .btn-next {
              border-radius: 10px;
              padding: 0 16px;
              font-weight: 500;
              transition: all 0.3s;

              &:hover:not(:disabled) {
                color: #667eea;
                transform: translateY(-2px);
              }
            }

            .el-pager li {
              border-radius: 10px;
              min-width: 40px;
              height: 40px;
              line-height: 40px;
              transition: all 0.3s;

              &:hover {
                color: #667eea;
                transform: translateY(-2px);
              }

              &.is-active {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
              }
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .model-library-container .main-content .content-wrapper .model-list-section .model-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
}

@media (max-width: 768px) {
  .model-library-container {
    .banner-section {
      padding: 32px 16px;

      .banner-content .banner-header {
        flex-direction: column;
        align-items: flex-start;

        .banner-left .banner-title {
          font-size: 28px;
        }

        .banner-left .banner-subtitle {
          font-size: 14px;
        }

        .banner-right {
          width: 100%;
          flex-direction: column-reverse;

          .stats-cards {
            width: 100%;
            flex-direction: row;

            .stat-card {
              flex: 1;
              justify-content: center;
            }
          }

          .home-btn {
            width: 100%;
            justify-content: center;
          }
        }
      }
    }

    .main-content {
      padding: 24px 16px;

      .content-wrapper {
        flex-direction: column;

        .filter-sidebar {
          width: 100%;

          .filter-section {
            position: relative;
            top: 0;
          }
        }

        .model-list-section {
          .model-grid {
            grid-template-columns: 1fr;
            gap: 16px;

            .model-card {
              .model-footer {
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;

                .model-pricing {
                  width: 100%;
                  justify-content: space-around;
                  padding: 12px;
                  background: #f5f7fa;
                  border-radius: 8px;
                }
              }
            }
          }

          .pagination-wrapper {
            :deep(.el-pagination) {
              flex-wrap: wrap;
              justify-content: center;

              .btn-prev,
              .btn-next {
                padding: 0 12px;
                min-width: 60px;
              }

              .el-pager li {
                min-width: 36px;
                height: 36px;
                line-height: 36px;
              }
            }
          }
        }
      }
    }
  }
}

// 平板适配
@media (min-width: 769px) and (max-width: 1024px) {
  .model-library-container .main-content .content-wrapper .model-list-section .model-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }
}
</style>
