<template>
  <div class="container">
    <!-- 机柜选择卡片 -->
    <a-card class="rack-select-card">
      <template #title>
        <icon-storage />
        选择机柜
      </template>
      <a-row :gutter="16">
        <a-col :span="6">
          <a-select
            v-model="selectedDatacenterId"
            placeholder="请选择数据中心"
            :loading="datacenterListLoading"
            allow-search
            @search="handleDatacenterSearch"
            @change="handleDatacenterChange"
            style="width: 100%"
          >
            <a-option v-for="datacenter in datacenterList" :key="datacenter.value" :value="datacenter.value">
              {{ datacenter.label }}
            </a-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-select
            v-model="selectedFloorId"
            placeholder="请选择楼层"
            :loading="floorListLoading"
            :disabled="!selectedDatacenterId"
            allow-search
            @search="handleFloorSearch"
            @change="handleFloorChange"
            style="width: 100%"
          >
            <a-option v-for="floor in floorList" :key="floor.value" :value="floor.value">
              {{ floor.label }}
            </a-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-select
            v-model="selectedRoomId"
            placeholder="请选择机房"
            :loading="roomListLoading"
            :disabled="!selectedFloorId"
            allow-search
            @search="handleRoomSearch"
            @change="handleRoomChange"
            style="width: 100%"
          >
            <a-option v-for="room in roomList" :key="room.id" :value="room.id">{{ room.name }} ({{ room.code }})</a-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-select
            v-model="selectedRackId"
            placeholder="请选择机柜"
            :loading="rackListLoading"
            :disabled="!selectedRoomId"
            allow-search
            @search="handleRackSearch"
            @change="handleRackChange"
            style="width: 100%"
          >
            <a-option v-for="rack in rackList" :key="rack.id" :value="rack.id">{{ rack.name }} ({{ rack.code }})</a-option>
          </a-select>
        </a-col>
      </a-row>
      <a-row :gutter="16" style="margin-top: 16px">
        <a-col :span="24">
          <a-space>
            <a-tag v-if="rackInfo.height">总U位: {{ rackInfo.height }}</a-tag>
            <a-tag v-if="usedUnits" color="blue">已使用: {{ usedUnits }}</a-tag>
            <a-tag v-if="availableUnits" color="green">空余: {{ availableUnits }}</a-tag>
            <a-tag v-if="usagePercentage" :color="usagePercentage > 80 ? 'red' : 'orange'">使用率: {{ usagePercentage }}%</a-tag>
          </a-space>
        </a-col>
      </a-row>
    </a-card>

    <!-- 操作按钮 -->
    <a-card class="action-card">
      <a-space>
        <a-button type="primary" @click="handleAllocate" :disabled="!selectedRackId">
          <template #icon>
            <icon-plus />
          </template>
          分配U位
        </a-button>
        <a-button type="outline" @click="handleReserve" :disabled="!selectedRackId">
          <template #icon>
            <icon-lock />
          </template>
          预留U位
        </a-button>
        <a-button type="outline" @click="handleRefresh" :disabled="!selectedRackId">
          <template #icon>
            <icon-refresh />
          </template>
          刷新
        </a-button>
      </a-space>
    </a-card>

    <!-- U位列表 -->
    <a-card class="u-position-card" :loading="loading">
      <template #title>
        <icon-apps />
        U位列表
      </template>

      <a-table :data="unitList" :pagination="false" :bordered="{ cell: true }" :scroll="{ x: 1400 }" :loading="loading" size="small">
        <template #columns>
          <!-- <a-table-column title="序号" :width="80">
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column> -->
          <a-table-column title="U位编号" data-index="unit_number" :width="100" />
          <a-table-column title="设备名称" data-index="asset_name" :width="150" />
          <a-table-column title="设备编号" data-index="asset_code" :width="150" />
          <a-table-column title="设备类型" data-index="asset_type" :width="120" />
          <a-table-column title="占用U位" data-index="occupied_units" :width="100" />
          <a-table-column title="预留信息" data-index="reserved_for" :width="150" />
          <a-table-column title="功耗(W)" data-index="power_consumption" :width="100" />
          <a-table-column title="状态" :width="100">
            <template #cell="{ record }">
              <a-tag :color="getUnitStatusColor(record.status)">
                {{ getUnitStatusText(record.status) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="200" fixed="right">
            <template #cell="{ record }">
              <a-space size="small">
                <!-- 禁用/启用按钮（所有状态都显示） -->
                <a-button v-if="record.status !== 'disabled'" type="text" size="small" @click="handleDisable(record)">禁用</a-button>
                <a-button v-else type="text" size="small" @click="handleEnable(record)">启用</a-button>

                <!-- 已占用状态：显示释放按钮 -->
                <a-button v-if="record.status === 'occupied'" type="text" size="small" status="danger" @click="handleRelease(record)">
                  释放
                </a-button>

                <!-- 已预留状态：显示取消预留按钮 -->
                <a-button
                  v-if="record.status === 'reserved'"
                  type="text"
                  size="small"
                  status="danger"
                  @click="handleCancelReservation(record)"
                >
                  取消预留
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 分配U位对话框 -->
    <allocate-unit-dialog
      v-model:visible="allocateVisible"
      :rack-id="selectedRackId!"
      :rack-height="rackInfo.height"
      @success="handleRefresh"
    />

    <!-- 预留U位对话框 -->
    <reserve-unit-dialog
      v-model:visible="reserveVisible"
      :rack-id="selectedRackId!"
      :rack-height="rackInfo.height"
      @success="handleRefresh"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconStorage, IconApps, IconPlus, IconLock, IconRefresh } from '@arco-design/web-vue/es/icon'
import { useRoute } from 'vue-router'
import { fetchUnitList, allocateUnit, reserveUnit, cancelReservation, releaseUnit, updateUnitStatus } from '@/api/ops/unit'
import { fetchDatacenterList, fetchRackListByRoom } from '@/api/ops/rack'
import { fetchFloorListByDatacenter } from '@/api/ops/floor'
import { fetchRoomListByFloor } from '@/api/ops/room'
import { normalizeUnitList } from './utils/unitFallback'
import AllocateUnitDialog from './components/AllocateUnitDialog.vue'
import ReserveUnitDialog from './components/ReserveUnitDialog.vue'

// 状态管理
const loading = ref(false)
const rackListLoading = ref(false)
const datacenterListLoading = ref(false)
const floorListLoading = ref(false)
const roomListLoading = ref(false)
const selectedDatacenterId = ref<number | undefined>(undefined)
const selectedFloorId = ref<number | undefined>(undefined)
const selectedRoomId = ref<number | undefined>(undefined)
const selectedRackId = ref<number | undefined>(undefined)
const rackInfo = ref<any>({})
const datacenterList = ref<{ label: string; value: number }[]>([])
const floorList = ref<{ label: string; value: number }[]>([])
const roomList = ref<any[]>([])
const rackList = ref<any[]>([])
const unitList = ref<any[]>([])
let datacenterSearchTimer: number | undefined
let floorSearchTimer: number | undefined
let roomSearchTimer: number | undefined
let rackSearchTimer: number | undefined
const route = useRoute()

// 对话框可见性
const allocateVisible = ref(false)
const reserveVisible = ref(false)

// 已使用U位
const usedUnits = computed(() => {
  return unitList.value.filter((unit) => unit.status === 'occupied' || unit.status === 'reserved').length
})

// 空余U位
const availableUnits = computed(() => {
  return rackInfo.value.height - usedUnits.value
})

// 使用率
const usagePercentage = computed(() => {
  if (!rackInfo.value.height) return 0
  return Math.round((usedUnits.value / rackInfo.value.height) * 100)
})

const extractList = (res: any): any[] => {
  const candidate = res?.data?.data ?? res?.details?.data ?? res?.data ?? res?.details ?? []
  return Array.isArray(candidate) ? candidate : []
}

// 获取U位状态颜色
const getUnitStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    available: 'green',
    occupied: 'blue',
    reserved: 'orange',
    disabled: 'gray',
  }
  return colorMap[status || ''] || 'gray'
}

// 获取U位状态文本
const getUnitStatusText = (status?: string) => {
  const textMap: Record<string, string> = {
    available: '可用',
    occupied: '已占用',
    reserved: '已预留',
    disabled: '已禁用',
  }
  return textMap[status || ''] || '-'
}

// 获取机柜列表
const fetchRacks = async (keyword?: string) => {
  if (!selectedRoomId.value) {
    rackList.value = []
    return
  }
  rackListLoading.value = true

  try {
    const res: any = await fetchRackListByRoom(selectedRoomId.value, { name: keyword })
    rackList.value = extractList(res)
  } catch (error) {
    console.error('获取机柜列表失败:', error)
    Message.error('获取机柜列表失败')
    rackList.value = []
  } finally {
    rackListLoading.value = false
  }
}

const fetchDatacenters = async (keyword?: string) => {
  datacenterListLoading.value = true
  try {
    const res: any = await fetchDatacenterList({ keyword })
    const rows = extractList(res)
    datacenterList.value = rows.map((d: any) => ({
      label: d.name || d.code || String(d.id),
      value: d.id,
    }))
  } catch (error) {
    console.error('获取数据中心列表失败:', error)
    Message.error('获取数据中心列表失败')
    datacenterList.value = []
  } finally {
    datacenterListLoading.value = false
  }
}

const fetchFloors = async (keyword?: string) => {
  if (!selectedDatacenterId.value) {
    floorList.value = []
    return
  }
  floorListLoading.value = true
  try {
    const res: any = await fetchFloorListByDatacenter(selectedDatacenterId.value, {
      name: keyword || undefined,
    })
    const rows = extractList(res)
    floorList.value = rows.map((floor: any) => ({
      label: floor.name || floor.code || String(floor.id),
      value: floor.id,
    }))
  } catch (error) {
    console.error('获取楼层列表失败:', error)
    Message.error('获取楼层列表失败')
    floorList.value = []
  } finally {
    floorListLoading.value = false
  }
}

const fetchRooms = async (keyword?: string) => {
  if (!selectedFloorId.value) {
    roomList.value = []
    return
  }
  roomListLoading.value = true
  try {
    const res: any = await fetchRoomListByFloor(selectedFloorId.value, {
      name: keyword || undefined,
    })
    roomList.value = extractList(res)
  } catch (error) {
    console.error('获取机房列表失败:', error)
    Message.error('获取机房列表失败')
    roomList.value = []
  } finally {
    roomListLoading.value = false
  }
}

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

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

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

const handleRackSearch = (keyword: string) => {
  if (!selectedRoomId.value) return
  if (rackSearchTimer) {
    window.clearTimeout(rackSearchTimer)
  }
  rackSearchTimer = window.setTimeout(() => {
    fetchRacks(keyword?.trim() || undefined)
  }, 300)
}

const handleDatacenterChange = async (datacenterId?: number | string) => {
  if (datacenterId !== undefined && datacenterId !== null && datacenterId !== '') {
    selectedDatacenterId.value = Number(datacenterId)
  }
  selectedFloorId.value = undefined
  selectedRoomId.value = undefined
  selectedRackId.value = undefined
  rackInfo.value = {}
  rackList.value = []
  roomList.value = []
  floorList.value = []
  unitList.value = []
  await fetchFloors()
}

const handleFloorChange = async (floorId?: number | string) => {
  if (floorId !== undefined && floorId !== null && floorId !== '') {
    selectedFloorId.value = Number(floorId)
  }
  selectedRoomId.value = undefined
  selectedRackId.value = undefined
  rackInfo.value = {}
  rackList.value = []
  roomList.value = []
  unitList.value = []
  await fetchRooms()
}

const handleRoomChange = async (roomId?: number | string) => {
  if (roomId !== undefined && roomId !== null && roomId !== '') {
    selectedRoomId.value = Number(roomId)
  }
  selectedRackId.value = undefined
  rackInfo.value = {}
  rackList.value = []
  unitList.value = []
  await fetchRacks()
}

// 机柜变化
const handleRackChange = (rackId: number) => {
  if (rackId) {
    fetchUnits(rackId)
  } else {
    unitList.value = []
    rackInfo.value = {}
  }
}

// 获取U位列表
const fetchUnits = async (rackId?: number) => {
  const targetRackId = rackId || selectedRackId.value

  if (!targetRackId) return

  loading.value = true

  try {
    const res = await fetchUnitList(targetRackId)

    if (res.code === 0) {
      const payload = res?.details ?? res?.data ?? {}
      rackInfo.value = payload?.rack || {}
      unitList.value = normalizeUnitList(payload?.units, rackInfo.value?.height)
    } else {
      Message.error(res.message || '获取U位列表失败')
    }
  } catch (error) {
    console.error('获取U位列表失败:', error)
    Message.error('获取U位列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新
const handleRefresh = () => {
  if (selectedRackId.value) {
    fetchUnits(selectedRackId.value)
    Message.success('数据已刷新')
  }
}

// 分配U位
const handleAllocate = () => {
  if (!selectedRackId.value) {
    Message.warning('请先选择机柜')
    return
  }
  allocateVisible.value = true
}

// 预留U位
const handleReserve = () => {
  if (!selectedRackId.value) {
    Message.warning('请先选择机柜')
    return
  }
  reserveVisible.value = true
}

// 禁用U位
const handleDisable = async (record: any) => {
  try {
    Modal.confirm({
      title: '确认禁用',
      content: `确认禁用 U位 ${record.unit_number} 吗？`,
      onOk: async () => {
        if (!selectedRackId.value) {
          Message.warning('请先选择机柜')
          return
        }

        const res = await updateUnitStatus({
          rack_id: selectedRackId.value,
          start_unit: record.unit_number,
          end_unit: record.unit_number,
          status: 'disabled',
        })

        if (res.code === 0) {
          Message.success('禁用成功')
          fetchUnits()
        } else {
          Message.error(res.message || '禁用失败')
        }
      },
    })
  } catch (error) {
    console.error('禁用U位失败:', error)
  }
}

// 启用U位
const handleEnable = async (record: any) => {
  try {
    Modal.confirm({
      title: '确认启用',
      content: `确认启用 U位 ${record.unit_number} 吗？`,
      onOk: async () => {
        if (!selectedRackId.value) {
          Message.warning('请先选择机柜')
          return
        }

        const res = await updateUnitStatus({
          rack_id: selectedRackId.value,
          start_unit: record.unit_number,
          end_unit: record.unit_number,
          status: 'available',
        })

        if (res.code === 0) {
          Message.success('启用成功')
          fetchUnits()
        } else {
          Message.error(res.message || '启用失败')
        }
      },
    })
  } catch (error) {
    console.error('启用U位失败:', error)
  }
}

// 释放U位
const handleRelease = async (record: any) => {
  try {
    Modal.confirm({
      title: '确认释放',
      content: `确认释放 U位 ${record.unit_number} 吗？`,
      onOk: async () => {
        const endUnit = record.occupied_units > 1 ? record.unit_number + record.occupied_units - 1 : record.unit_number

        if (!selectedRackId.value) {
          Message.warning('请先选择机柜')
          return
        }

        const res = await releaseUnit({
          rack_id: selectedRackId.value,
          start_unit: record.unit_number,
          end_unit: endUnit,
        })

        if (res.code === 0) {
          Message.success('释放成功')
          fetchUnits()
        } else {
          Message.error(res.message || '释放失败')
        }
      },
    })
  } catch (error) {
    console.error('释放U位失败:', error)
  }
}

// 取消预留
const handleCancelReservation = async (record: any) => {
  try {
    Modal.confirm({
      title: '确认取消预留',
      content: `确认取消 U位 ${record.unit_number} 的预留吗？`,
      onOk: async () => {
        const endUnit = record.occupied_units > 1 ? record.unit_number + record.occupied_units - 1 : record.unit_number

        if (!selectedRackId.value) {
          Message.warning('请先选择机柜')
          return
        }

        const res = await cancelReservation({
          rack_id: selectedRackId.value,
          start_unit: record.unit_number,
          end_unit: endUnit,
        })

        if (res.code === 0) {
          Message.success('取消预留成功')
          fetchUnits()
        } else {
          Message.error(res.message || '取消预留失败')
        }
      },
    })
  } catch (error) {
    console.error('取消预留失败:', error)
  }
}

// 初始化
onMounted(() => {
  fetchDatacenters()
  const rackId = Number(route.query.rack_id)
  if (Number.isFinite(rackId) && rackId > 0) {
    selectedRackId.value = rackId
    fetchUnits(rackId)
  }
})
</script>

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

<style scoped lang="less">
.container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.rack-select-card {
  margin-bottom: 16px;
}

.action-card {
  margin-bottom: 16px;

  :deep(.arco-card-body) {
    padding: 12px 20px;
  }
}

.u-position-card {
  :deep(.arco-card-body) {
    padding: 0;
  }
}
</style>
