<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 #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 #rack_type="{ record }">
        <a-tag :color="getRackTypeColor(record.rack_type)">
          {{ getRackTypeText(record.rack_type) }}
        </a-tag>
      </template>

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

      <!-- 使用率 -->
      <template #utilization_rate="{ record }">
        <a-progress
          :percent="Math.min(Math.max((Number(record.utilization_rate) || 0) / 100, 0), 1)"
          :size="'small'"
          :color="(record.utilization_rate || 0) > 80 ? '#f53f3f' : (record.utilization_rate || 0) > 50 ? '#ff7d00' : '#00b42a'"
        />
      </template>

      <!-- 操作 -->
      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleView(record)">查看</a-button>
        <a-button type="text" size="small" @click="handleEdit(record)">编辑</a-button>
        <a-button type="text" size="small" @click="handleUnitManagement(record)">U位管理</a-button>
        <a-button type="text" size="small" status="danger" @click="handleDelete(record)">删除</a-button>
      </template>
    </search-table>

    <!-- 机柜表单对话框（新建/编辑） -->
    <rack-form-dialog v-model:visible="formVisible" :rack="editingRack" @success="handleFormSuccess" />

    <!-- 机柜详情对话框 -->
    <rack-detail-dialog v-model:visible="detailVisible" :rack-id="currentRackId" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } 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 { fetchRackList, fetchDatacenterList, deleteRack } from '@/api/ops/rack'
import { fetchFloorListByDatacenter } from '@/api/ops/floor'
import { fetchRoomListByFloor } from '@/api/ops/room'
import RackDetailDialog from './components/RackDetailDialog.vue'
import RackFormDialog from './components/RackFormDialog.vue'

const router = useRouter()

// 状态管理
const loading = ref(false)
const tableData = ref<any[]>([])
const formModel = ref({
  keyword: '',
  datacenter_id: undefined,
  floor_id: undefined,
  room_id: undefined,
  rack_type: undefined,
  status: undefined,
})

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

// 表单项配置
const datacenterSelectOptions = ref<{ label: string; value: number }[]>([])
const floorSelectOptions = ref<{ label: string; value: number }[]>([])
const roomSelectOptions = ref<{ label: string; value: number }[]>([])
let datacenterSearchTimer: number | undefined
let floorSearchTimer: number | undefined
let roomSearchTimer: 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,
      }
    }
    if (item.field === 'room_id') {
      return {
        ...item,
        options: roomSelectOptions.value,
        allowSearch: true,
        onSearch: handleRoomSearch,
        disabled: !formModel.value.floor_id,
      }
    }
    return item
  })
)

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

// 当前选中的机柜
const currentRackId = ref<number | null>(null)
const editingRack = 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?.data ?? res.data ?? res.details ?? []
      const rows = Array.isArray(list) ? list : []
      datacenterSelectOptions.value = rows.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 = []
    roomSelectOptions.value = []
    return
  }
  try {
    const res: any = await fetchFloorListByDatacenter(datacenterId, { name: keyword })
    if (res.code === 0) {
      const list = res.details?.data ?? res.data ?? res.details ?? []
      const rows = Array.isArray(list) ? list : []
      floorSelectOptions.value = rows.map((floor: any) => ({
        label: floor.name || String(floor.id),
        value: floor.id,
      }))
    }
  } catch (error) {
    console.error('加载楼层列表失败:', error)
    Message.error('加载楼层列表失败')
    floorSelectOptions.value = []
  }
}

const loadRoomOptions = async (floorId?: number, keyword?: string) => {
  if (!floorId) {
    roomSelectOptions.value = []
    return
  }
  try {
    const res: any = await fetchRoomListByFloor(floorId, { name: keyword })
    if (res.code === 0) {
      const list = res.details?.data ?? res.data ?? res.details ?? []
      const rows = Array.isArray(list) ? list : []
      roomSelectOptions.value = rows.map((room: any) => ({
        label: room.name || String(room.id),
        value: room.id,
      }))
    }
  } catch (error) {
    console.error('加载机房列表失败:', error)
    Message.error('加载机房列表失败')
    roomSelectOptions.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)
}

const handleRoomSearch = (keyword: string) => {
  if (!formModel.value.floor_id) return
  if (roomSearchTimer) {
    window.clearTimeout(roomSearchTimer)
  }
  roomSearchTimer = window.setTimeout(() => {
    loadRoomOptions(formModel.value.floor_id, keyword?.trim() || undefined)
  }, 300)
}

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

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

// 获取机柜类型颜色
const getRackTypeColor = (type?: string) => {
  const colorMap: Record<string, string> = {
    standard: 'blue',
    blade: 'cyan',
    network: 'purple',
    storage: 'orange',
    custom: 'gray',
  }
  return colorMap[type || ''] || 'gray'
}

// 获取机柜类型文本
const getRackTypeText = (type?: string) => {
  const textMap: Record<string, string> = {
    standard: '标准机柜',
    blade: '刀片机柜',
    network: '网络机柜',
    storage: '存储机柜',
    custom: '定制机柜',
  }
  return textMap[type || ''] || '-'
}

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

// 获取状态文本
const getStatusText = (status?: string) => {
  const textMap: Record<string, string> = {
    idle: '空闲',
    in_use: '使用中',
    reserved: '已预留',
    maintenance: '维护中',
    offline: '已下线',
  }
  return textMap[status || ''] || '-'
}

// 获取机柜列表
const fetchRacks = 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,
      room_id: formModel.value.room_id ?? undefined,
      rack_type: formModel.value.rack_type || undefined,
      status: formModel.value.status || undefined,
    }

    const res = await fetchRackList(params)

    const payload = res?.data ?? res?.details ?? {}
    tableData.value = Array.isArray(payload?.data) ? payload.data : []
    pagination.total = payload?.total ?? 0
  } catch (error) {
    console.error('获取机柜列表失败:', error)
    Message.error('获取机柜列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

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

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

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    datacenter_id: undefined,
    floor_id: undefined,
    room_id: undefined,
    rack_type: undefined,
    status: undefined,
  }
  pagination.current = 1
  fetchRacks()
}

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

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

// 新增机柜
const handleAdd = () => {
  editingRack.value = null
  formVisible.value = true
}

// 编辑机柜
const handleEdit = (record: any) => {
  editingRack.value = record
  formVisible.value = true
}

// 查看详情
const handleView = (record: any) => {
  currentRackId.value = record.id
  detailVisible.value = true
}

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

// U位管理
const handleUnitManagement = (record: any) => {
  router.push({
    path: '/datacenter/u-position',
    query: { rack_id: record.id, rack_name: record.name },
  })
}

// 表单成功回调
const handleFormSuccess = () => {
  formVisible.value = false
  fetchRacks()
}

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

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

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