<template>
  <div class="app-container">
    <!-- 头部搜索区域 -->
    <div class="search-section">
      <div class="custom-main-w">
        <h1 class="page-title">一站链接全球API资源</h1>
        <h2 class="page-subtitle">找API、找服务商、找资料</h2>
        <div class="search-box">
          <el-input
              v-model="searchQuery"
              placeholder="可输入应用名称/分类名称"
              @keyup.enter="handleSearch"
              clearable
          >
            <template #append>
              <el-button type="primary" @click="handleSearch">
                <el-icon style="margin-right: 8px">
                  <Search />
                </el-icon>
                立即搜索
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </div>

    <!-- API分类标签 -->
    <div class="category-tabs-wrapper">
      <div class="custom-main-w">
        <el-tabs
            v-model="activeCategory"
            class="category-tabs"
            @tab-change="handleCategoryChange"
        >
          <el-tab-pane label="全部" name="" />
          <el-tab-pane
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :name="String(category.id)"
          />
        </el-tabs>
      </div>
    </div>

    <!-- API列表区域 -->
    <div class="api-list custom-main-w">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <el-row :gutter="30" v-else-if="apiList.length > 0">
        <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            v-for="api in apiList"
            :key="api.id"
        >
          <APICard
              :id="api.id"
              :coverImage="api.coverImage"
              :priceInfo="api.priceInfo"
              :title="api.name"
              :description="api.description"
              :tag="getAppTag(api)"
          />
        </el-col>
      </el-row>

      <div v-else class="empty-container">
        <el-empty description="暂无应用数据" />
      </div>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container custom-main-w" v-if="total > 0">
      <el-pagination
          v-model="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<script>
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import APICard from './components/APICard.vue';
import { getAppInfoList, getAppCategoryList } from '@/api/marketplace';

export default {
  name: 'Marketplace',
  components: {
    APICard,
    Search
  },
  data() {
    return {
      searchQuery: '',
      activeCategory: '',
      apiList: [],
      categoryList: [],
      loading: false,
      currentPage: 1,
      pageSize: 9,
      total: 0,
      _searchTimer: null
    };
  },
  methods: {
    async getCategoryList() {
      try {
        const response = await getAppCategoryList();
        if (response.code === 0) {
          this.categoryList = response.data || [];
        } else {
          ElMessage.error(response.msg || '获取分类列表失败');
        }
      } catch (error) {
        console.error('获取分类列表失败:', error);
        ElMessage.error('获取分类列表失败');
      }
    },
    async getAppList() {
      try {
        this.loading = true;
        const params = {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          // activeCategory 为空（即选择了全部）时，不传 categoryId
          categoryId: this.activeCategory
              ? parseInt(this.activeCategory, 10)
              : undefined,
          searchQuery: this.searchQuery || undefined
        };
        const response = await getAppInfoList(params);
        if (response.code === 0) {
          this.apiList = response.data.list || [];
          this.total = response.data.total || 0;
        } else {
          ElMessage.error(response.msg || '获取应用列表失败');
        }
      } catch (error) {
        console.error('获取应用列表失败:', error);
        ElMessage.error('获取应用列表失败');
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.getAppList();
    },
    handleCategoryChange() {
      this.currentPage = 1;
      this.getAppList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getAppList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getAppList();
    },
    getAppImage() {
      return ``;
    },
    getAppTag(api) {
      const m = this.categoryList.find(c => c.id === api.categoryId);
      return m ? m.name : '';
    }
  },
  watch: {
    searchQuery(newVal) {
      if (this._searchTimer) clearTimeout(this._searchTimer);
      this._searchTimer = setTimeout(() => {
        if (newVal === '') this.handleSearch();
      }, 500);
    }
  },
  mounted() {
    this.getCategoryList();
    this.getAppList();
  }
};
</script>

<style scoped lang="scss">
/* 搜索区域 */
.search-section {
  text-align: center;
  padding: 120px 0 100px;
  background: linear-gradient(180deg, #e1edff 0%, rgba(255, 255, 255, 0) 100%);
}

.page-title {
  font-size: 36px;
  margin-bottom: 12px;
  font-weight: bold;
  color: #333;
}

.page-subtitle {
  font-size: 20px;
  color: #666;
  margin-bottom: 20px;
}

.search-box {
  max-width: 700px;
  margin: 20px auto 0;
  :deep(.el-input__wrapper) {
    padding: 14px 14px;
    border-radius: 50px 0 0 50px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  }
  :deep(.el-input-group__append) {
    border-radius: 0 50px 50px 0;
    background-color: var(--el-color-primary) !important;
    color: #fff;
    font-weight: bold;
    padding: 0 24px;
  }
}

/* 分类 Tabs */
.category-tabs-wrapper {
  margin-bottom: 50px;
  padding: 20px 0;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

:deep(.el-tabs__header) {
  margin: 0;
}

:deep(.el-tabs__nav-wrap) {
  max-width: 1440px;
  min-width: 1200px;
  margin: 0 auto;
}

:deep(.el-tabs__nav-wrap::after) {
  content: none !important;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  padding: 12px 20px !important;
  margin-right: 16px;
  border-radius: 4px;
  transition: all 0.2s;
}

:deep(.el-tabs__item.is-active) {
  color: #fff;
  background-color: var(--el-color-primary) !important;
  font-weight: bold;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
}

:deep(.el-tabs__active-bar) {
  background-color: transparent;
}

/* API 列表 */
.api-list {
  background: #f9f9fb;
  padding: 40px 20px;
  border-radius: 8px;
  margin-bottom: 50px;
  min-height: 400px;
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
  text-align: center;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  margin-bottom: 50px;
}

.app-container {
  padding-top: 90px;
}
</style>
