<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getTargets,
  createTarget,
  updateTarget,
  deleteTarget,
  testConnection,
} from '@/api/service-manage'
import type {
  ManageTarget,
  CreateManageTargetRequest,
  TestManageTargetRequest,
} from '@/types/service-manage'

// ============================================================
// 列表
// ============================================================

const loading = ref(false)
const targets = ref<ManageTarget[]>([])

async function loadTargets() {
  loading.value = true
  try {
    const res = await getTargets()
    if (res.success) {
      targets.value = res.targets
    }
  } finally {
    loading.value = false
  }
}

// ============================================================
// 新增/编辑对话框
// ============================================================

const dialogVisible = ref(false)
const dialogTitle = ref('新增目标')
const editingId = ref('')

const emptyForm = (): CreateManageTargetRequest => ({
  name: '',
  host: '',
  port: 443,
  protocol: 'https',
  auth_type: 'password',
  username: '',
  password: '',
})

const form = ref<CreateManageTargetRequest>(emptyForm())
const formRef = ref<FormInstance>()

const rules: FormRules = {
  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' }],
}

function openCreate() {
  dialogTitle.value = '新增目标'
  editingId.value = ''
  form.value = emptyForm()
  dialogVisible.value = true
}

function openEdit(target: ManageTarget) {
  dialogTitle.value = '编辑目标'
  editingId.value = target.id
  form.value = {
    name: target.name,
    host: target.host,
    port: target.port,
    protocol: target.protocol,
    auth_type: target.auth_type,
    username: target.username,
    password: '',
  }
  dialogVisible.value = true
}

// ============================================================
// 测试连接
// ============================================================

const testing = ref(false)

async function handleTestConnection() {
  const payload: TestManageTargetRequest = {
    host: form.value.host,
    port: form.value.port,
    protocol: form.value.protocol,
    username: form.value.username,
    password: form.value.password,
  }
  if (!payload.host) {
    ElMessage.warning('请先填写主机地址')
    return
  }
  testing.value = true
  try {
    const res = await testConnection(payload)
    if (res.success) {
      ElMessage.success(res.message || '连接成功')
    } else {
      ElMessage.error(res.message || '连接失败')
    }
  } finally {
    testing.value = false
  }
}

// ============================================================
// 保存
// ============================================================

async function handleSave() {
  if (!formRef.value) return
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  const loadingIns = ElLoading.service({ text: '正在保存...' })
  try {
    if (editingId.value) {
      const res = await updateTarget(editingId.value, form.value)
      if (res.success) ElMessage.success('目标更新成功')
    } else {
      const res = await createTarget(form.value)
      if (res.success) ElMessage.success('目标新增成功')
    }
    dialogVisible.value = false
    await loadTargets()
  } finally {
    loadingIns.close()
  }
}

// ============================================================
// 删除
// ============================================================

async function handleDelete(target: ManageTarget) {
  try {
    await ElMessageBox.confirm(
      `确定要删除目标「${target.name}」吗？`,
      '删除确认',
      { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
    )
  } catch {
    return // 用户取消
  }

  const loadingIns = ElLoading.service({ text: '正在删除...' })
  try {
    const res = await deleteTarget(target.id)
    if (res.success) {
      ElMessage.success('目标已删除')
      await loadTargets()
    }
  } finally {
    loadingIns.close()
  }
}

// ============================================================
// 初始化
// ============================================================

onMounted(loadTargets)
</script>

<template>
  <div class="page-target-config">
    <div class="section-head">
      <h1 class="section-title">🎯 目标配置</h1>
      <el-button type="primary" @click="openCreate">＋ 新增目标</el-button>
    </div>

    <el-card class="table-card" shadow="never">
      <el-table v-loading="loading" :data="targets" stripe>
        <el-table-column prop="name" label="名称" min-width="160" />
        <el-table-column label="地址" min-width="160">
          <template #default="{ row }">
            <span>{{ row.protocol }}://{{ row.host }}:{{ row.port }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column label="密码" width="90">
          <template #default="{ row }">
            <el-tag size="small" :type="row.has_password ? 'success' : 'info'">
              {{ row.has_password ? '已设置' : '未设置' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openEdit(row as ManageTarget)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row as ManageTarget)">删除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无目标配置，点击右上角「新增目标」添加" />
        </template>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="520px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入目标名称（如：5.44 统一管理平台）" />
        </el-form-item>
        <el-form-item label="地址" prop="host">
          <el-input v-model="form.host" placeholder="请输入目标服务器 IP 或域名" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input-number v-model="form.port" :min="1" :max="65535" style="width: 180px" />
        </el-form-item>
        <el-form-item label="协议" prop="protocol">
          <el-radio-group v-model="form.protocol">
            <el-radio value="https">HTTPS</el-radio>
            <el-radio value="http">HTTP</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="认证方式" prop="auth_type">
          <el-radio-group v-model="form.auth_type">
            <el-radio value="password">密码</el-radio>
            <el-radio value="token">Token</el-radio>
            <el-radio value="none">无</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="form.auth_type === 'password'">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入登录用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password" show-password placeholder="请输入登录密码" />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :loading="testing" @click="handleTestConnection">测试连接</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.page-target-config {
  padding: 0 0 40px;
}

.section-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  font-weight: 700;
  margin: 0;
  color: $gray-900;
}

.table-card {
  border-radius: 12px;

  :deep(.el-card__body) {
    padding: 0;
  }
}
</style>