<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="tagColorOnOff(record.enabled)">
          <template v-if="record.enabled">已启用</template>
          <template v-else>已禁用</template>
        </a-tag>
      </template>

      <template #data_collection="{ record }">
        <a-tag :color="tagColorOnOff(record.collect_on)">
          <template v-if="record.collect_on">已启用</template>
          <template v-else>未启用</template>
        </a-tag>
      </template>
      <template #collect_method="{ record }">
        <a-tag :color="tagColorCollectMethod(record.collect_method)">
          <template v-if="record.collect_method === 'snmp'">SNMP</template>
          <template v-else>API</template>
        </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="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="860" 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 } 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 { fetchRoomDeviceList, deleteRoomDevice, type RoomDeviceItem, type RoomDeviceListParams } from '@/api/ops/room-device'

const loading = ref(false)
const tableData = ref<RoomDeviceItem[]>([])
const formDialogVisible = ref(false)
const quickConfigVisible = ref(false)
const detailVisible = ref(false)
const currentRecord = ref<RoomDeviceItem | null>(null)
const formModel = ref({
  keyword: '',
  enabled: undefined as boolean | undefined,
  device_category: undefined as string | undefined,
})

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

const formItems = computed<FormItem[]>(() => searchFormConfig)
const columns = computed(() => columnsConfig)

/** 避免在模板 :color 中写 ? : 三元，部分 Vue/Vite 版本会误解析冒号 */
const tagColorOnOff = (on: boolean | undefined) => (on ? 'green' : 'gray')
const tagColorCollectMethod = (m: string | undefined) =>
  m === 'snmp' ? 'purple' : 'arcoblue'

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

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

    const response: any = await fetchRoomDeviceList(params)

    if (response && response.details) {
      tableData.value = response.details?.data || []
      pagination.total = response.details?.total || 0
    } 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
  fetchRoomDeviceData()
}

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

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

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

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

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

const handleQuickConfig = (record: RoomDeviceItem) => {
  currentRecord.value = record
  quickConfigVisible.value = true
}

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

const handleDetail = (record: RoomDeviceItem) => {
  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 = () => {
  fetchRoomDeviceData()
}

const handleDelete = (record: RoomDeviceItem) => {
  Modal.confirm({
    title: '确认删除',
    content: `确认删除机房设备 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        await deleteRoomDevice(record.id)
        Message.success('删除成功')
        fetchRoomDeviceData()
      } catch (error) {
        console.error('删除机房设备失败:', error)
        Message.error('删除失败')
      }
    },
  })
}

fetchRoomDeviceData()
</script>

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

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