<template>
  <div class="endpoint-list">
    <div class="page-header">
      <h2>接口管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleSync" :loading="syncing">
          <el-icon><Refresh /></el-icon> 手动同步
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="路径/简述/operationId"
            clearable
            style="width: 200px"
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="方法">
          <el-select v-model="searchForm.method" placeholder="全部" clearable style="width: 100px" @change="handleSearch">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
            <el-option label="PATCH" value="PATCH" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 接口列表 -->
    <el-card class="table-card">
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column label="方法" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="getMethodType(row.method)" size="small">{{ row.method }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" min-width="300" show-overflow-tooltip />
        <el-table-column prop="summary" label="简述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="tags" label="标签" min-width="150" show-overflow-tooltip />
        <el-table-column label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.deprecated === 1" type="danger" size="small">废弃</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="showDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next"
          @size-change="loadData"
          @current-change="loadData"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <EndpointDetailDialog v-model="detailVisible" :detail="selectedDetail" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getEndpointList, syncEndpoints, getEndpointDetail, type ApiEndpointItem, type ApiEndpointDetail } from '@/api/endpoint'
import EndpointDetailDialog from './EndpointDetailDialog.vue'

const loading = ref(false)
const syncing = ref(false)
const detailVisible = ref(false)
const selectedDetail = ref<ApiEndpointDetail | null>(null)

const searchForm = reactive({
  keyword: '',
  method: '',
  tags: ''
})

const tableData = ref<ApiEndpointItem[]>([])
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

const loadData = async () => {
  loading.value = true
  try {
    const res: any = await getEndpointList({
      current: pagination.current,
      size: pagination.size,
      keyword: searchForm.keyword || undefined,
      method: searchForm.method || undefined,
      tags: searchForm.tags || undefined
    })
    tableData.value = res.data.records || []
    pagination.total = res.data.total || 0
  } catch (e: any) {
    ElMessage.error('加载失败: ' + e.message)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.method = ''
  searchForm.tags = ''
  handleSearch()
}

const handleSync = async () => {
  syncing.value = true
  try {
    await syncEndpoints()
    ElMessage.success('同步任务已提交，请稍后刷新查看结果')
    setTimeout(() => loadData(), 5000)
  } catch (e: any) {
    ElMessage.error('同步失败: ' + e.message)
  } finally {
    syncing.value = false
  }
}

const showDetail = async (row: ApiEndpointItem) => {
  selectedDetail.value = null
  detailVisible.value = true
  try {
    const res: any = await getEndpointDetail(row.operationId)
    selectedDetail.value = res.data
  } catch {
    ElMessage.error('加载详情失败')
  }
}

const getMethodType = (method: string): string => {
  const types: Record<string, string> = {
    GET: 'success',
    POST: 'primary',
    PUT: 'warning',
    DELETE: 'danger',
    PATCH: 'info'
  }
  return types[method] || 'info'
}

onMounted(() => loadData())
</script>

<style scoped lang="scss">
.endpoint-list {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      color: var(--el-text-color-primary);
    }
  }

  .search-card {
    margin-bottom: 16px;
  }

  .pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
