<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-button type="primary" @click="handleAdd">
          <template #icon>
            <icon-plus />
          </template>
          新增中间件
        </a-button>
      </template>

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

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

      <!-- Agent 配置 -->
      <template #agent_config="{ record }">
        <a-tag :color="record.agent_config ? 'green' : 'gray'">
          {{ record.agent_config ? '已配置' : '未配置' }}
        </a-tag>
      </template>

      <!-- 数据采集 -->
      <template #data_collection="{ record }">
        <a-tag :color="record.collect_on ? 'green' : 'gray'">
          {{ record.collect_on ? '已启用' : '未启用' }}
        </a-tag>
      </template>

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

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

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

      <!-- 操作栏 - 下拉菜单 -->
      <template #actions="{ record }">
        <a-space>
          <a-dropdown trigger="hover">
            <a-button type="primary" size="small">
              管理
              <icon-down />
            </a-button>
            <template #content>
              <a-doption @click="handleDetail(record)">
                <template #icon>
                  <icon-eye />
                </template>
                详情
              </a-doption>
              <a-doption @click="handleEdit(record)">
                <template #icon>
                  <icon-edit />
                </template>
                编辑
              </a-doption>
              <!-- <a-doption @click="handleQuickConfig(record)">
                <template #icon>
                  <icon-settings />
                </template>
                采集配置
              </a-doption> -->
              <a-doption @click="handleDelete(record)" style="color: rgb(var(--danger-6))">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
    </search-table>

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

    <!-- 快捷配置对话框 -->
    <QuickConfigDialog v-model:visible="quickConfigVisible" :record="currentRecord" @success="handleFormSuccess" />

    <!-- 详情抽屉 -->
    <a-drawer v-model:visible="detailVisible" :width="800" title="中间件详情" :footer="false" unmount-on-close>
      <Detail
        v-if="currentRecord"
        :record="currentRecord"
        @edit="handleDetailEdit"
        @quick-config="handleDetailQuickConfig"
        @delete="handleDetailDelete"
      />
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus, IconDown, IconEdit, IconDelete, IconEye, IconSettings } 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 FormDialog from './components/FormDialog.vue'
import QuickConfigDialog from './components/QuickConfigDialog.vue'
import Detail from './components/Detail.vue'
import { columns as columnsConfig } from './config/columns'
import { fetchMiddlewareList, deleteMiddleware, type MiddlewareItem, type MiddlewareListParams } from '@/api/ops/middleware'

// 状态管理
const loading = ref(false)
const tableData = ref<MiddlewareItem[]>([])
const formDialogVisible = ref(false)
const quickConfigVisible = ref(false)
const detailVisible = ref(false)
const currentRecord = ref<MiddlewareItem | null>(null)
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 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 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 '-'
  if (time.startsWith('0001-01-01')) return '-'
  const date = new Date(time)
  if (Number.isNaN(date.getTime())) return '-'
  if (date.getFullYear() <= 1970) return '-'
  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 fetchMiddlewareData = async () => {
  loading.value = true

  try {
    const params: MiddlewareListParams = {
      page: pagination.current,
      size: pagination.pageSize,
      keyword: formModel.value.keyword,
      enabled: formModel.value.enabled,
    }

    const response: any = await fetchMiddlewareList(params)

    if (response && response.details) {
      tableData.value = response.details?.data
      pagination.total = response.details?.total
    } else {
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取中间件列表失败:', error)
    Message.error('获取中间件列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

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

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

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

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

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

// 新增中间件
const handleAdd = () => {
  currentRecord.value = null
  formDialogVisible.value = true
}

// 快捷配置
const handleQuickConfig = (record: MiddlewareItem) => {
  currentRecord.value = record
  quickConfigVisible.value = true
}

// 编辑中间件
const handleEdit = (record: MiddlewareItem) => {
  currentRecord.value = record
  formDialogVisible.value = true
}

// 查看详情
const handleDetail = (record: MiddlewareItem) => {
  currentRecord.value = record
  detailVisible.value = true
}

// 详情页面操作
const handleDetailEdit = () => {
  detailVisible.value = false
  formDialogVisible.value = true
}

const handleDetailQuickConfig = () => {
  detailVisible.value = false
  quickConfigVisible.value = true
}

const handleDetailDelete = () => {
  detailVisible.value = false
  if (currentRecord.value) {
    handleDelete(currentRecord.value)
  }
}

const handleFormSuccess = () => {
  fetchMiddlewareData()
}

// 删除中间件
const handleDelete = (record: MiddlewareItem) => {
  Modal.confirm({
    title: '确认删除',
    content: `确认删除中间件服务 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        await deleteMiddleware(record.id)
        Message.success('删除成功')
        fetchMiddlewareData()
      } catch (error) {
        console.error('删除中间件失败:', error)
        Message.error('删除失败')
      }
    },
  })
}

// 初始化加载数据
fetchMiddlewareData()
</script>

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

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