<template>
  <div class="main-wrapper py-5" style="background: #f1f3f5;">
    <div class="container">
      <!-- 外层卡片：淡色背景，与白色小卡片形成对比 -->
      <div class="card p-4 mb-4">
        <div class="row mb-3 align-items-center">
          <div class="col-md-6">
            <h4 class="mb-0">API 列表</h4>
            <div class="small text-muted">下面显示公开的 API 及其使用示例（与套餐关联）。</div>
          </div>
          <div class="col-md-6 text-right">
            <input
              type="text"
              v-model="search"
              class="form-control d-inline-block w-auto"
              placeholder="搜索 API 名称或描述"
            />
          </div>
        </div>

        <div class="row">
          <div
            v-for="api in filteredApis"
            :key="api.id"
            class="col-12 col-md-6 col-lg-4 mb-4"
          >
            <!-- 小卡片：白底、轻边框、轻阴影 -->
            <div class="card api-card h-100">
              <div class="card-body d-flex flex-column">
                <div class="d-flex justify-content-between align-items-start mb-3">
                  <h5 class="card-title mb-0">{{ api.name }}</h5>
                  <span :class="['badge','badge-pill', 'method-badge', 'method-' + api.method.toLowerCase()]">
                    {{ api.method }}
                  </span>
                </div>

                <p class="card-text text-muted mb-2" style="flex-grow:0.2;">
                  {{ api.description }}
                </p>

                <div class="endpoint mb-3 px-2 py-1 bg-light rounded small endpoint-box">
                  <code>{{ baseUrl + '/api/public' + api.endpoint }}</code>
                </div>

                <!-- 套餐：如果存在，显示为 tag 列表（白卡底上用浅色 tag）-->
                <div v-if="api.packages && api.packages.length" class="mb-3">
                  <p class="mb-1"><strong>对应套餐：</strong></p>
                  <div>
                    <span
                      v-for="(pkg, idx) in api.packages"
                      :key="idx"
                      class="pkg-badge mr-2"
                      :title="pkg"
                    >
                      {{ pkg }}
                    </span>
                  </div>
                </div>

                <!-- 详细示例（保持紧凑） -->
                <div class="mt-auto">
                  <p class="mb-1 font-weight-bold">示例详情：</p>
                  <pre class="code-block mb-2"><code>{{ api.example }}</code></pre>

                  <div v-if="api.requestExample">
                    <p class="mb-1"><strong>请求参数：</strong></p>
                    <pre class="code-block small"><code>{{ api.requestExample.request }}</code></pre>

                    <p class="mb-1 mt-3"><strong>响应参数：</strong></p>
                    <pre class="code-block small"><code>{{ api.requestExample.response }}</code></pre>

                    <p class="mb-1 mt-3"><strong>响应体格式：</strong></p>
                    <pre class="code-block small"><code>{{ api.requestExample.responseType }}</code></pre>
                  </div>
                </div>

              </div>
            </div>
          </div>

          <div v-if="filteredApis.length === 0" class="col-12 text-center text-muted">
            未找到匹配的 API。
          </div>
        </div>

        <!-- 加载提示（保持你原有逻辑：v-if 控制） -->
        <div class="text-center mt-3" v-if="!isLoaded">
          <card-loading />
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import axiosIntance from '@/request/request'
import CardLoading from '../../components/CardLoading.vue';

export default {
  components: { CardLoading },
  name: 'ApiList',
  data() {
    return {
      search: '',
      pageIndex: 1,
      pageSize: 100,
      desc: false,
      apiList: [],
      baseUrl: '',
      isLoaded: false
    }
  },
  computed: {
    filteredApis() {
      const term = this.search.trim().toLowerCase();
      return term
        ? this.apiList.filter(api =>
            api.name.toLowerCase().includes(term) ||
            api.description.toLowerCase().includes(term)
          )
        : this.apiList;
    }
  },
  methods: {
    async loadApiList() {
      this.isLoaded = false
      try {
        const res = await this.$api.getPublicApiList(
          this.pageIndex,
          this.pageSize,
          this.desc
        );
        if (res.code === 1000) {
          this.apiList = res.data.map(item => {
            const ex = item.apiRequestExamples && item.apiRequestExamples[0];
            return {
              id: item.id,
              name: item.name,
              description: item.description,
              endpoint: item.endpoint.startsWith('/') ? item.endpoint : `/${item.endpoint}`,
              method: this.mapMethod(item.method),
              badgeClass: this.mapBadge(item.method),
              example: this.buildExample(item),
              requestExample: ex ? {
                request: ex.request,
                response: ex.response,
                responseType: ex.responseType
              } : null,
              packages: [] // 如果你后续调用 getApiPackages，会填充
            };
          });
        } else {
          this.$alert(res.message, 'danger');
        }
      } catch (e) {
        this.$alert('加载 API 列表失败', 'danger');
        console.error(e);
      } finally {
        this.isLoaded = true
      }
    },
    mapMethod(code) {
      switch(code) {
        case 1: return 'GET';
        case 2: return 'POST';
        case 3: return 'PUT';
        case 4: return 'DELETE';
        default: return 'GET';
      }
    },
    mapBadge(code) {
      switch(code) {
        case 1: return 'info';
        case 2: return 'success';
        case 3: return 'warning';
        case 4: return 'danger';
        default: return 'secondary';
      }
    },
    buildExample(item) {
      const method = this.mapMethod(item.method);
      const url = item.endpoint;
      if (method === 'GET') {
        return `axios.get('${url}')\n  .then(res => console.log(res.data));`;
      } else {
        return `axios.${method.toLowerCase()}('${url}', { /* 参数 */ })\n  .then(res => console.log(res.data));`;
      }
    }
  },
  created() {
    this.loadApiList();
    this.baseUrl = axiosIntance.defaults.baseURL
  }
}
</script>

<style scoped>
/* 颜色变量，便于快速调整 */
:root {
  --outer-bg: #f6fbff; /* 外层卡的淡色背景 */
  --card-shadow: rgba(16,24,40,0.06);
  --card-border: rgba(16,24,40,0.06);
  --pkg-bg: #eef6ff;
}

/* 外层容器卡（与白色小卡形成对比） */
.card {
  background: var(--outer-bg);
  border-radius: 10px;
  padding: 18px;
  box-shadow: 0 1px 0 rgba(0,0,0,0.02);
}

/* 小卡片样式：白底、边框、轻阴影 */
.api-card {
  background: #fff;
  border: 1px solid var(--card-border);
  border-radius: 8px;
  box-shadow: 0 2px 6px var(--card-shadow);
  transition: transform .18s ease, box-shadow .18s ease;
}
.api-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 8px 20px rgba(16,24,40,0.08);
}

/* 方法 badge（更柔和的配色） */
.method-badge {
  padding: 6px 8px;
  font-weight: 600;
  color: #fff;
  font-size: 0.78rem;
  border-radius: 999px;
}
.method-get { background:#17a2b8; }     /* GET */
.method-post { background:#28a745; }    /* POST */
.method-put { background:#ffc107; color:#212529; } /* PUT */
.method-delete { background:#dc3545; }  /* DELETE */

/* endpoint 区块 */
.endpoint-box {
  background: #fafbfd;
  border: 1px dashed rgba(0,0,0,0.03);
  color: #333;
}

/* 套餐 tag 样式 */
.pkg-badge {
  display:inline-block;
  background: var(--pkg-bg);
  color: #0366d6;
  padding: 4px 8px;
  border-radius: 999px;
  font-size: 0.85rem;
  border: 1px solid rgba(3,102,214,0.06);
}

/* code block 样式（保持高对比）*/
.code-block {
  background: #1f2937; /* 深色更适合代码示例 */
  color: #e6eef8;
  padding: 0.65rem;
  border-radius: 6px;
  font-size: 0.82rem;
  line-height: 1.45;
  overflow-x: auto;
  max-height: 160px;
  margin-bottom: 0.5rem;
}

/* 细微调整 */
.card-title { font-size: 1.05rem; font-weight: 600; }
.endpoint code { font-size: 0.92rem; }
.small { font-size: 0.85rem; }
</style>
