<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="数据库服务管理"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #toolbar-left>
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <icon-plus />
            </template>
            新增数据库
          </a-button>
          <a-button type="outline" @click="handleCollect">
            <template #icon>
              <icon-sync />
            </template>
            指标采集
          </a-button>
        </a-space>
      </template>

      <!-- ID -->
      <template #id="{ record }">
        {{ record.id }}
      </template>

      <!-- 数据库类型 -->
      <template #type="{ record }">
        <a-tag :color="getTypeColor(record.type)">
          {{ record.type }}
        </a-tag>
      </template>

      <!-- 数据库名 -->
      <template #database="{ record }">
        {{ record.database || '-' }}
      </template>

      <!-- 监控状态 -->
      <template #enabled="{ record }">
        <a-tag :color="record.enabled ? 'green' : 'red'">
          {{ record.enabled ? '已启用' : '已禁用' }}
        </a-tag>
      </template>

      <!-- 进程内采集 -->
      <template #collect_on="{ record }">
        <a-tag :color="record.collect_on ? 'green' : 'red'">
          {{ record.collect_on ? '已启用' : '已禁用' }}
        </a-tag>
      </template>

      <!-- 运行状态 -->
      <template #status="{ record }">
        <a-tag :color="getStatusColor(record.status)">
          {{ getStatusText(record.status) }}
        </a-tag>
      </template>

      <!-- 响应时间 -->
      <template #response_time="{ record }">
        <span :style="{ color: getResponseTimeColor(record.response_time) }">
          {{ record.response_time ? record.response_time.toFixed(2) : '-' }}
        </span>
      </template>

      <!-- 运行时长 -->
      <template #uptime="{ record }">
        {{ formatUptime(record.uptime) }}
      </template>

      <!-- 最后检查时间 -->
      <template #last_check_time="{ record }">
        {{ formatTime(record.last_check_time) }}
      </template>

      <!-- 标签 -->
      <template #tags="{ record }">
        <a-tag
          v-for="(tag, index) in parseTags(record.tags)"
          :key="index"
          style="margin-right: 4px"
        >
          {{ tag }}
        </a-tag>
        <span v-if="!parseTags(record.tags).length">-</span>
      </template>

      <!-- 操作栏 -->
      <template #actions="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="handleDetail(record)">
            详情
          </a-button>
          <a-button type="text" size="small" @click="handleEdit(record)">
            编辑
          </a-button>
          <a-button
            type="text"
            size="small"
            status="danger"
            @click="handleDelete(record)"
          >
            删除
          </a-button>
        </a-space>
      </template>
    </search-table>

    <!-- 新增/编辑对话框 -->
    <FormDialog
      v-model:visible="formDialogVisible"
      :record="currentRecord"
      @success="handleFormSuccess"
    />

    <!-- 详情对话框 -->
    <DetailDialog
      v-model:visible="detailDialogVisible"
      :record-id="currentRecordId"
    />

    <!-- 指标采集对话框 -->
    <CollectDialog
      v-model:visible="collectDialogVisible"
      :service-list="tableData"
      @success="handleRefresh"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import {
  IconPlus,
  IconSync,
  IconEye,
  IconEdit,
  IconDelete,
} from '@arco-design/web-vue/es/icon'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import { searchFormConfig } from './config/search-form'
import { columns as columnsConfig } from './config/columns'
import FormDialog from './components/FormDialog.vue'
import DetailDialog from './components/DetailDialog.vue'
import CollectDialog from './components/CollectDialog.vue'
import {
  fetchDatabaseList,
  deleteDatabase,
  type DatabaseService,
  type DatabaseQueryParams,
} from '@/api/ops/database'

// 状态管理
const loading = ref(false)
const tableData = ref<DatabaseService[]>([])
const formDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const collectDialogVisible = ref(false)
const currentRecord = ref<DatabaseService | null>(null)
const currentRecordId = ref(0)
const formModel = ref({
  keyword: '',
  type: undefined as string | undefined,
  enabled: undefined as boolean | undefined,
  status: undefined as string | undefined,
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

// 表单项配置
const formItems = computed<FormItem[]>(() => searchFormConfig)

// 表格列配置
const columns = computed(() => columnsConfig)

// 获取数据库类型颜色
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    MySQL: 'blue',
    PostgreSQL: 'purple',
    Redis: 'red',
    MongoDB: 'green',
    DM: 'orange',
    KingBase: 'cyan',
  }
  return colorMap[type] || 'gray'
}

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    online: 'green',
    offline: 'red',
    error: 'orange',
  }
  return colorMap[status] || 'gray'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    error: '错误',
  }
  return textMap[status] || '-'
}

// 获取响应时间颜色
const getResponseTimeColor = (responseTime: number) => {
  if (!responseTime) return ''
  if (responseTime >= 1000) return 'rgb(var(--danger-6))'
  if (responseTime >= 500) return 'rgb(var(--warning-6))'
  return 'rgb(var(--success-6))'
}

// 格式化运行时长
const formatUptime = (uptime: number) => {
  if (!uptime) return '-'
  const days = Math.floor(uptime / 86400)
  const hours = Math.floor((uptime % 86400) / 3600)
  const minutes = Math.floor((uptime % 3600) / 60)
  if (days > 0) {
    return `${days}天 ${hours}小时`
  }
  if (hours > 0) {
    return `${hours}小时 ${minutes}分钟`
  }
  return `${minutes}分钟`
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 解析标签
const parseTags = (tags: string) => {
  if (!tags) return []
  return tags.split(',').filter((t) => t.trim())
}

// 获取数据库列表
const fetchList = async () => {
  loading.value = true
  try {
    const params: DatabaseQueryParams = {
      page: pagination.current,
      size: pagination.pageSize,
    }

    if (formModel.value.keyword) {
      params.keyword = formModel.value.keyword
    }
    if (formModel.value.enabled !== undefined) {
      params.enabled = formModel.value.enabled
    }

    const res: any = await fetchDatabaseList(params)
    tableData.value = res?.details?.data || []
    pagination.total = res?.details?.total || 0

    // 前端过滤数据库类型（API不支持type过滤）
    if (formModel.value.type) {
      tableData.value = tableData.value.filter(
        (item) => item.type === formModel.value.type
      )
      pagination.total = tableData.value.length
    }

    // 前端过滤运行状态（API不支持status过滤）
    if (formModel.value.status) {
      tableData.value = tableData.value.filter(
        (item) => item.status === formModel.value.status
      )
      pagination.total = tableData.value.length
    }
  } catch (error) {
    console.error('获取数据库列表失败:', error)
    Message.error('获取数据库列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchList()
}

// 处理表单模型更新
const handleFormModelUpdate = (value: any) => {
  formModel.value = value
}

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    type: undefined,
    enabled: undefined,
    status: undefined,
  }
  pagination.current = 1
  fetchList()
}

// 分页变化
const handlePageChange = (current: number) => {
  pagination.current = current
  fetchList()
}

// 刷新
const handleRefresh = () => {
  fetchList()
  Message.success('数据已刷新')
}

// 新增数据库
const handleAdd = () => {
  currentRecord.value = null
  formDialogVisible.value = true
}

// 查看详情
const handleDetail = (record: DatabaseService) => {
  currentRecordId.value = record.id
  detailDialogVisible.value = true
}

// 编辑数据库
const handleEdit = (record: DatabaseService) => {
  currentRecord.value = record
  formDialogVisible.value = true
}

// 指标采集
const handleCollect = () => {
  collectDialogVisible.value = true
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchList()
}

// 删除数据库
const handleDelete = (record: DatabaseService) => {
  Modal.confirm({
    title: '确认删除',
    content: `确认删除数据库服务「${record.name}」吗？此操作为软删除。`,
    onOk: async () => {
      try {
        await deleteDatabase(record.id)
        Message.success('删除成功')
        fetchList()
      } catch (error: any) {
        console.error('删除数据库失败:', error)
        if (error?.response?.data?.message) {
          Message.error(error.response.data.message)
        } else {
          Message.error('删除失败')
        }
      }
    },
  })
}

// 初始化加载数据
onMounted(() => {
  fetchList()
})
</script>

<script lang="ts">
export default {
  name: 'DatabaseServiceManage',
}
</script>

<style scoped lang="less">
.container {
  margin-top: 20px;
}
</style>
