<!--
  组件名称：DeployServers.vue
  组件描述：自动化部署测试 - 服务器管理页面（CRUD + 连接测试）

  @author czj
  @date 2026-08-12
-->

<template>
  <div class="deploy-servers-page">
    <div class="page-header">
      <h2>服务器管理</h2>
      <el-button type="primary" @click="openCreateDialog">
        <el-icon><Plus /></el-icon>新增服务器
      </el-button>
    </div>

    <el-card shadow="never">
      <el-table :data="servers" v-loading="loading" stripe style="width: 100%">
        <el-table-column prop="name" label="名称" min-width="140" />
        <el-table-column label="地址" min-width="160">
          <template #default="{ row }">
            {{ row.host }}:{{ row.port }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column label="认证方式" width="100">
          <template #default="{ row }">
            {{ row.authType === 'key' ? '密钥' : '密码' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="110">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)" size="small">
              {{ statusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="160" show-overflow-tooltip />
        <el-table-column label="更新时间" width="170">
          <template #default="{ row }">
            {{ formatTime(row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" :loading="testingId === row.id" @click="testConnection(row)">测试</el-button>
            <el-button link type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-popconfirm title="确定删除此服务器？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑服务器' : '新增服务器'" width="640px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="如：560 部署服务器" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="认证方式">
              <el-radio-group v-model="form.authType">
                <el-radio value="password">密码</el-radio>
                <el-radio value="key">密钥</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="主机地址" prop="host">
              <el-input v-model="form.host" placeholder="如：192.168.5.60" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="端口" prop="port">
              <el-input-number v-model="form.port" :min="1" :max="65535" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="SSH 登录用户名" />
        </el-form-item>
        <el-form-item v-if="form.authType === 'password'" label="密码" prop="password">
          <el-input v-model="form.password" type="password" show-password placeholder="SSH 登录密码" />
          <div v-if="isEdit" class="form-tip">留空表示不修改原密码</div>
        </el-form-item>
        <el-form-item v-else label="私钥" prop="privateKey">
          <el-input v-model="form.privateKey" type="textarea" :rows="4" placeholder="-----BEGIN OPENSSH PRIVATE KEY-----&#10;...&#10;-----END OPENSSH PRIVATE KEY-----" />
          <div v-if="isEdit" class="form-tip">留空表示不修改原私钥</div>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="2" placeholder="备注信息（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 服务器管理：维护远程部署目标服务器（SSH 连接信息）
 */

import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  listServers,
  createServer,
  updateServer,
  deleteServer,
  testServerConnection,
} from '@/api/deploy'
import type { DeployServer, DeployServerCreate } from '@/types/deploy'

const loading = ref(false)
const servers = ref<DeployServer[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const testingId = ref('')
const editId = ref('')
const formRef = ref()

const defaultForm = (): DeployServerCreate => ({
  name: '',
  host: '',
  port: 22,
  username: '',
  password: '',
  authType: 'password',
  privateKey: '',
  description: '',
})

const form = reactive<DeployServerCreate>(defaultForm())

const rules = {
  name: [{ required: true, message: '请输入服务器名称', trigger: 'blur' }],
  host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口号', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  privateKey: [{ required: true, message: '请输入私钥内容', trigger: 'blur' }],
}

/** 加载服务器列表 */
async function loadServers() {
  loading.value = true
  try {
    const res = await listServers({ limit: 100 })
    servers.value = res.items
  } catch (e: any) {
    ElMessage.error('加载服务器列表失败: ' + (e.message || ''))
  } finally {
    loading.value = false
  }
}

/** 打开新增弹窗 */
function openCreateDialog() {
  isEdit.value = false
  editId.value = ''
  Object.assign(form, defaultForm())
  dialogVisible.value = true
}

/** 打开编辑弹窗 */
function openEditDialog(row: DeployServer) {
  isEdit.value = true
  editId.value = row.id
  Object.assign(form, {
    name: row.name,
    host: row.host,
    port: row.port,
    username: row.username,
    password: '',
    authType: row.authType,
    privateKey: '',
    description: row.description || '',
  })
  dialogVisible.value = true
}

/** 保存服务器 */
async function handleSave() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  saving.value = true
  try {
    if (isEdit.value) {
      await updateServer(editId.value, form)
      ElMessage.success('服务器已更新')
    } else {
      await createServer(form)
      ElMessage.success('服务器已创建')
    }
    dialogVisible.value = false
    await loadServers()
  } catch (e: any) {
    ElMessage.error('保存失败: ' + (e.message || ''))
  } finally {
    saving.value = false
  }
}

/** 删除服务器 */
async function handleDelete(row: DeployServer) {
  try {
    await deleteServer(row.id)
    ElMessage.success('服务器已删除')
    await loadServers()
  } catch (e: any) {
    ElMessage.error('删除失败: ' + (e.message || ''))
  }
}

/** 测试连接 */
async function testConnection(row: DeployServer) {
  testingId.value = row.id
  try {
    const res = await testServerConnection(row.id)
    if (res.success) {
      ElMessage.success(`连接成功: ${res.serverName} (${res.host}:${res.port})`)
    } else {
      ElMessage.warning('连接失败: ' + res.message)
    }
    await loadServers()
  } catch (e: any) {
    ElMessage.error('测试连接失败: ' + (e.message || ''))
  } finally {
    testingId.value = ''
  }
}

/** 状态标签类型 */
function statusType(status: string) {
  const map: Record<string, string> = { online: 'success', offline: 'danger', unknown: 'info' }
  return map[status] || 'info'
}

/** 状态标签文字 */
function statusLabel(status: string) {
  const map: Record<string, string> = { online: '在线', offline: '离线', unknown: '未知' }
  return map[status] || status
}

/** 格式化时间 */
function formatTime(t: string) {
  return t?.replace('T', ' ').substring(0, 19) || '-'
}

onMounted(() => {
  loadServers()
})
</script>

<style scoped>
.deploy-servers-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  margin-top: 4px;
}
</style>