<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="handleCreate">
          <template #icon>
            <icon-plus />
          </template>
          新建机房
        </a-button>
      </template>

      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
      </template>

      <template #datacenter="{ record }">
        {{ record.datacenter?.name || '-' }}
      </template>

      <template #floor="{ record }">
        {{ record.floor?.name || '-' }}
      </template>

      <template #status="{ record }">
        <a-tag :color="statusMap[record.status]?.color || 'gray'">
          {{ statusMap[record.status]?.text || record.status }}
        </a-tag>
      </template>

      <template #actions="{ record }">
        <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"
          :disabled="!record.has3D"
          :style="{ color: record.has3D ? undefined : 'rgb(var(--gray-6))' }"
          @click="handleThreeDRoom"
        >
          3d机房
        </a-button>
        <a-button type="text" size="small" status="danger" @click="handleDelete(record)">删除</a-button>
      </template>
    </search-table>

    <room-form-dialog v-model:visible="formVisible" :room="editingRoom" @success="handleFormSuccess" />

    <room-detail-dialog v-model:visible="detailVisible" :room-id="currentRoomId" />
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import { useRouter } from 'vue-router'
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 { deleteRoom, fetchRoomList } from '@/api/ops/room'
import { fetchDatacenterList, fetchFloorListByDatacenter } from '@/api/ops/floor'
import RoomFormDialog from './components/RoomFormDialog.vue'
import RoomDetailDialog from './components/RoomDetailDialog.vue'

const router = useRouter()

const statusMap: Record<string, { text: string; color: string }> = {
  planning: { text: '规划中', color: 'blue' },
  construction: { text: '建设中', color: 'orange' },
  operating: { text: '运营中', color: 'green' },
  maintenance: { text: '维护中', color: 'gold' },
  offline: { text: '已下线', color: 'red' },
}

const loading = ref(false)
const tableData = ref<any[]>([])
const formModel = ref({
  keyword: '',
  datacenter_id: undefined as number | undefined,
  floor_id: undefined as number | undefined,
  status: '',
})

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

const datacenterSelectOptions = ref<{ label: string; value: number }[]>([])
const floorSelectOptions = ref<{ label: string; value: number }[]>([])
let datacenterSearchTimer: number | undefined
let floorSearchTimer: number | undefined

const formItems = computed<FormItem[]>(() =>
  searchFormConfig.map((item) => {
    if (item.field === 'datacenter_id') {
      return {
        ...item,
        options: datacenterSelectOptions.value,
        allowSearch: true,
        onSearch: handleDatacenterSearch,
      }
    }
    if (item.field === 'floor_id') {
      return {
        ...item,
        options: floorSelectOptions.value,
        allowSearch: true,
        onSearch: handleFloorSearch,
        disabled: !formModel.value.datacenter_id,
      }
    }
    return item
  })
)

const columns = computed(() => columnsConfig)

const currentRoomId = ref<number | undefined>(undefined)
const editingRoom = ref<any>(null)

const formVisible = ref(false)
const detailVisible = ref(false)

const loadDatacenterOptions = async (keyword?: string) => {
  try {
    const res: any = await fetchDatacenterList({ keyword })
    if (res.code === 0) {
      const list = res.details || []
      datacenterSelectOptions.value = Array.isArray(list)
        ? list.map((d: any) => ({
            label: d.name || d.code || String(d.id),
            value: d.id,
          }))
        : []
    }
  } catch (error) {
    console.error('获取数据中心列表失败:', error)
    Message.error('获取数据中心列表失败')
    datacenterSelectOptions.value = []
  }
}

const loadFloorOptions = async (datacenterId?: number, keyword?: string) => {
  if (!datacenterId) {
    floorSelectOptions.value = []
    return
  }
  try {
    const res: any = await fetchFloorListByDatacenter(datacenterId, { name: keyword })
    if (res.code === 0) {
      const list = res.details?.data ?? res.data ?? res.details ?? []
      floorSelectOptions.value = Array.isArray(list)
        ? list.map((f: any) => ({
            label: f.name || String(f.id),
            value: f.id,
          }))
        : []
    }
  } catch (error) {
    console.error('获取楼层列表失败:', error)
    Message.error('获取楼层列表失败')
    floorSelectOptions.value = []
  }
}

const handleDatacenterSearch = (keyword: string) => {
  if (datacenterSearchTimer) {
    window.clearTimeout(datacenterSearchTimer)
  }
  datacenterSearchTimer = window.setTimeout(() => {
    loadDatacenterOptions(keyword?.trim() || undefined)
  }, 300)
}

const handleFloorSearch = (keyword: string) => {
  if (!formModel.value.datacenter_id) return
  if (floorSearchTimer) {
    window.clearTimeout(floorSearchTimer)
  }
  floorSearchTimer = window.setTimeout(() => {
    loadFloorOptions(formModel.value.datacenter_id, keyword?.trim() || undefined)
  }, 300)
}

watch(
  () => formModel.value.datacenter_id,
  (newId, oldId) => {
    if (newId !== oldId) {
      formModel.value.floor_id = undefined
    }
    loadFloorOptions(newId)
  }
)

const fetchRooms = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
      datacenter_id: formModel.value.datacenter_id ?? undefined,
      floor_id: formModel.value.floor_id ?? undefined,
      status: formModel.value.status || undefined,
    }

    const res: any = await fetchRoomList(params)
    tableData.value = res.details?.data || []
    pagination.total = res.details?.total || 0
  } catch (error) {
    console.error('获取机房列表失败:', error)
    Message.error('获取机房列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchRooms()
}

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

const handleReset = () => {
  formModel.value = {
    keyword: '',
    datacenter_id: undefined,
    floor_id: undefined,
    status: '',
  }
  pagination.current = 1
  fetchRooms()
}

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

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

const handleCreate = () => {
  editingRoom.value = null
  formVisible.value = true
}

const handleEdit = (record: any) => {
  editingRoom.value = record
  formVisible.value = true
}

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

const handleThreeDRoom = () => {
  router.push('/datacenter/room')
}

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

const handleFormSuccess = () => {
  formVisible.value = false
  fetchRooms()
}

onMounted(() => {
  loadDatacenterOptions()
  fetchRooms()
})
</script>

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

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