<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>

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

      <template #enabled="{ record }">
        <a-tag :color="record.enabled ? 'green' : 'gray'">
          {{ record.enabled ? '启用' : '停用' }}
        </a-tag>
      </template>

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

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

      <template #last_check_time="{ record }">
        {{ formatDateTime(record.last_check_time) }}
      </template>

      <template #actions="{ record }">
        <a-space>
          <a-button type="outline" size="small" @click="handleDetail(record)">
            <template #icon>
              <icon-eye />
            </template>
            详情
          </a-button>
          <a-dropdown trigger="hover">
            <a-button type="primary" size="small">
              管理
              <icon-down />
            </a-button>
            <template #content>
              <a-doption @click="handleEdit(record)">
                <template #icon>
                  <icon-edit />
                </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>

    <StorageFormDialog v-model:visible="formDialogVisible" :record="currentRecord" @success="handleFormSuccess" />

    <StorageDetail v-model:visible="detailVisible" :record="currentRecord" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus, IconDown, IconEdit, IconDelete, IconEye } 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 StorageFormDialog from './components/StorageFormDialog.vue'
import StorageDetail from './components/StorageDetail.vue'
import { columns as columnsConfig } from './config/columns'
import { fetchStorageList, deleteStorage } from '@/api/ops/storage'

const loading = ref(false)
const tableData = ref<any[]>([])
const formDialogVisible = ref(false)
const detailVisible = ref(false)
const currentRecord = ref<any>(null)
const formModel = ref({
  keyword: '',
  enabled: undefined as boolean | 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',
    unknown: 'gray',
  }
  return colorMap[status || ''] || 'gray'
}

const getStatusText = (status?: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    error: '异常',
    unknown: '未知',
  }
  return textMap[status || ''] || '-'
}

const formatDateTime = (dateTime: string | null | undefined) => {
  if (!dateTime || dateTime === '0001-01-01T00:00:00Z') {
    return '-'
  }
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      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}`
  } catch {
    return '-'
  }
}

const fetchStorages = async () => {
  loading.value = true

  try {
    const params: any = {
      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 fetchStorageList(params)

    if (res.code === 0) {
      const responseData = res.details || {}
      tableData.value = responseData.data || []
      pagination.total = responseData.total || 0
    } else {
      Message.error(res.message || '获取存储设备列表失败')
      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
  fetchStorages()
}

const handleFormModelUpdate = (value: any) => {
  formModel.value = value
}

const handleReset = () => {
  formModel.value = {
    keyword: '',
    enabled: undefined,
  }
  pagination.current = 1
  fetchStorages()
}

const handlePageChange = (current: number) => {
  pagination.current = current
  fetchStorages()
}

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

const handleAdd = () => {
  currentRecord.value = null
  formDialogVisible.value = true
}

const handleEdit = (record: any) => {
  currentRecord.value = record
  formDialogVisible.value = true
}

const handleDetail = (record: any) => {
  currentRecord.value = record
  detailVisible.value = true
}

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

const handleDelete = async (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确认删除存储设备 ${record.name} 吗？`,
    onOk: async () => {
      try {
        const res: any = await deleteStorage(record.id)
        if (res.code === 0) {
          Message.success('删除成功')
          fetchStorages()
        } else {
          Message.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除存储设备失败:', error)
        Message.error('删除失败')
      }
    },
  })
}

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

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

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