<template>
  <div class="container">
    <!-- 页面头部 -->
    <div class="page-header">
      <a-button type="text" @click="handleBack">
        <template #icon>
          <icon-left />
        </template>
        返回列表
      </a-button>
      <h2 class="page-title">{{ pageTitle }}</h2>
    </div>

    <!-- 机柜信息卡片 -->
    <a-card class="info-card" :loading="loading">
      <template #title>
        <icon-storage /> 机柜信息
      </template>
      
      <a-row :gutter="24">
        <a-col :span="6">
          <div class="info-item">
            <div class="info-label">机柜编码</div>
            <div class="info-value">{{ rackInfo.code || '-' }}</div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="info-item">
            <div class="info-label">机柜总U位</div>
            <div class="info-value">{{ rackInfo.height || 0 }}</div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="info-item">
            <div class="info-label">已使用U位</div>
            <div class="info-value">{{ usedUnits }}</div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="info-item">
            <div class="info-label">使用率</div>
            <div class="info-value">
              <a-progress
                :percent="usagePercentage"
                :size="'small'"
                :color="
                  usagePercentage > 80
                    ? '#f53f3f'
                    : usagePercentage > 50
                      ? '#ff7d00'
                      : '#00b42a'
                "
              />
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="info-item">
            <div class="info-label">空余U位</div>
            <div class="info-value">{{ availableUnits }}</div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="info-item">
            <div class="info-label">空余率</div>
            <div class="info-value">
              <a-progress
                :percent="availablePercentage"
                :size="'small'"
                :color="'#00b42a'"
              />
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="info-item">
            <div class="info-label">总功耗</div>
            <div class="info-value">{{ totalPower }}W</div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="info-item">
            <div class="info-label">状态</div>
            <div class="info-value">
              <a-tag :color="getRackStatusColor(rackInfo.status)">
                {{ getRackStatusText(rackInfo.status) }}
              </a-tag>
            </div>
          </div>
        </a-col>
      </a-row>
    </a-card>

    <!-- U位管理卡片 -->
    <a-card class="u-position-card" :loading="loading">
      <template #title>
        <icon-apps /> U位列表
      </template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="handleAllocate">
            <template #icon>
              <icon-plus />
            </template>
            分配U位
          </a-button>
          <a-button type="outline" @click="handleReserve">
            <template #icon>
              <icon-lock />
            </template>
            预留U位
          </a-button>
          <a-button type="outline" @click="handleRefresh">
            <template #icon>
              <icon-refresh />
            </template>
            刷新
          </a-button>
        </a-space>
      </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="rackId"
      :rack-height="rackInfo.height"
      @success="handleRefresh"
    />

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

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

const route = useRoute()
const router = useRouter()

// 状态管理
const loading = ref(false)
const rackId = ref<number>(0)
const rackName = ref<string>('')
const rackInfo = ref<any>({})
const unitList = ref<any[]>([])

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

// 页面标题
const pageTitle = computed(() => {
  return rackName.value ? `${rackName.value} - U位详情` : 'U位详情'
})

// 已使用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 availablePercentage = computed(() => {
  if (!rackInfo.value.height) return 0
  return Math.round((availableUnits.value / rackInfo.value.height) * 100)
})

// 总功耗
const totalPower = computed(() => {
  return unitList.value.reduce((total, unit) => {
    return total + (unit.power_consumption || 0)
  }, 0)
})

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

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

// 获取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 || ''] || '-'
}

// 获取U位列表
const fetchUnits = async () => {
  loading.value = true
  
  try {
    const res = await fetchUnitList(rackId.value)
    
    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 handleBack = () => {
  router.push('/ops/datacenter/u-position')
}

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

// 分配U位
const handleAllocate = () => {
  allocateVisible.value = true
}

// 预留U位
const handleReserve = () => {
  reserveVisible.value = true
}

// 禁用U位
const handleDisable = async (record: any) => {
  try {
    Modal.confirm({
      title: '确认禁用',
      content: `确认禁用 U位 ${record.unit_number} 吗？`,
      onOk: async () => {
        const res = await updateUnitStatus({
          rack_id: rackId.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 () => {
        const res = await updateUnitStatus({
          rack_id: rackId.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
        
        const res = await releaseUnit({
          rack_id: rackId.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
        
        const res = await cancelReservation({
          rack_id: rackId.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(() => {
  rackId.value = Number(route.query.rack_id)
  rackName.value = (route.query.rack_name as string) || ''
  
  if (!rackId.value) {
    Message.error('缺少机柜ID')
    router.push('/ops/datacenter/u-position')
    return
  }
  
  fetchUnits()
})
</script>

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

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

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background: #fff;
  padding: 16px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .page-title {
    flex: 1;
    margin: 0;
    margin-left: 16px;
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
  }
}

.info-card {
  margin-bottom: 20px;

  .info-item {
    margin-bottom: 16px;

    .info-label {
      font-size: 13px;
      color: #86909c;
      margin-bottom: 8px;
    }

    .info-value {
      font-size: 16px;
      font-weight: 500;
      color: #1d2129;
    }
  }
}

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