<template>
  <div class="page-wrapper">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <template #header>
        <div class="card-header-title">
          <el-icon><Search /></el-icon>
          <span>搜索条件</span>
        </div>
      </template>
      <el-form :model="query" inline>
        <el-form-item label="所属系统">
          <el-select v-model="query.systemId" placeholder="请选择系统" clearable style="width: 200px" @change="handleSearch">
            <el-option
              v-for="s in systemOptions"
              :key="s.id"
              :label="s.systemName"
              :value="s.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接口路径">
          <el-input v-model="query.apiPath" placeholder="请输入接口路径" clearable />
        </el-form-item>
        <el-form-item label="请求方式">
          <el-select v-model="query.apiMethod" placeholder="全部" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <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-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增接口
      </el-button>
    </div>

    <!-- 表格 -->
    <el-card shadow="never">
      <el-table :data="tableData" border stripe v-loading="loading" style="width: 100%">
        <el-table-column prop="apiPath" label="接口路径" min-width="200" show-overflow-tooltip />
        <el-table-column prop="apiMethod" label="请求方式" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="methodTagType(row.apiMethod)" effect="dark" size="small">
              {{ row.apiMethod }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="apiName" label="接口名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="apiDesc" label="接口描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="dark" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" class-name="ops-col">
          <template #default="{ row }">
            <div class="actions">
              <el-button type="primary" size="small" plain @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" size="small" plain @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
        <!-- 空状态 -->
        <template #empty>
          <el-empty description="暂无接口数据" :image-size="100" />
        </template>
      </el-table>

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

  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

/** 接口类型 */
interface ApiItem {
  id?: string
  systemId: string
  apiPath: string
  apiMethod: string
  apiName: string
  status: number
}

/** 系统选项 */
interface SystemOption {
  id: string
  systemName: string
}

// --- 查询 ---
const query = reactive({
  page: 1,
  pageSize: 10,
  systemId: undefined as string | undefined,
  apiPath: '',
  apiMethod: '',
})

const tableData = ref<ApiItem[]>([])
const total = ref(0)
const loading = ref(false)
const systemOptions = ref<SystemOption[]>([])

// --- 加载系统列表（用于下拉框） ---
async function loadSystems() {
  try {
    const res = await request.post('/zgapi/v1/admin/system/page', { page: 1, pageSize: 100, status: 1 })
    systemOptions.value = res.data?.records ?? []
    // 从 localStorage 取当前用户所在系统，设为默认选中
    const sysId = localStorage.getItem('currentSystemId')
    if (sysId) {
      query.systemId = sysId
    }
  } catch {
    // 错误由拦截器处理
  }
}

// --- 请求方式对应 el-tag 颜色 ---
function methodTagType(method: string) {
  const map: Record<string, string> = {
    GET: 'success',
    POST: 'warning',
    PUT: 'primary',
    DELETE: 'danger',
  }
  return map[method] || 'info'
}

// --- 数据加载 ---
async function fetchData() {
  loading.value = true
  try {
    const params: Record<string, unknown> = {
      page: query.page,
      pageSize: query.pageSize,
    }
    if (query.systemId != null) params.systemId = query.systemId
    if (query.apiPath) params.apiPath = query.apiPath
    if (query.apiMethod) params.apiMethod = query.apiMethod

    const res = await request.post('/zgapi/v1/admin/system/api/page', params)
    tableData.value = res.data?.records ?? []
    total.value = res.data?.total ?? 0
  } catch {
    // 错误由拦截器处理
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  query.page = 1
  fetchData()
}

function handleReset() {
  query.systemId = undefined
  query.apiPath = ''
  query.apiMethod = ''
  query.page = 1
  fetchData()
}

// --- 新增/编辑 ---
const router = useRouter()

function handleAdd() {
  // 携带当前选中的 systemId
  const query: Record<string, string> = {}
  if (query.systemId != null) {
    query.systemId = String(query.systemId)
  }
  router.push({ path: '/admin/api/form', query })
}

function handleEdit(row: ApiItem) {
  router.push('/admin/api/form/' + row.id)
}

// --- 删除 ---
function handleDelete(row: ApiItem) {
  ElMessageBox.confirm(`确认删除接口"${row.apiPath}"吗？`, '删除确认', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      await request.delete(`/zgapi/v1/admin/system/api/${row.id}`)
      ElMessage.success('删除成功')
      fetchData()
    } catch {
      // 错误由拦截器处理
    }
  }).catch(() => {})
}

// 初始化
onMounted(() => {
  loadSystems().then(() => {
    fetchData()
  })
})
</script>

<style scoped>
.page-wrapper {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.card-header-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  color: #303133;
}

.toolbar {
  display: flex;
  justify-content: flex-start;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

@media (max-width: 768px) {
  .page-wrapper { gap: 10px; }
  .page-toolbar { flex-direction: column; gap: 10px; }
  .page-toolbar .el-select { width: 100% !important; }
}
</style>
