<template>
  <div class="volume-detail-page">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" link class="back-btn"><el-icon><ArrowLeft /></el-icon> 返回上一页</el-button>
        <el-divider direction="vertical" />
        <span class="page-title">数据卷详情</span>
      </div>
      <div class="header-right">
        <el-button plain :icon="Refresh" @click="loadDetail" :loading="loading">刷新</el-button>
      </div>
    </div>

    <div class="main-content" v-loading="loading">
      <!-- 基本信息 -->
      <el-card shadow="never" class="info-card" v-if="detail">
        <template #header><span class="card-title">基本信息</span></template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ detail.id }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{ detail.name }}</el-descriptions-item>
          <el-descriptions-item label="大小">{{ detail.size ? detail.size + ' GB' : '-' }}</el-descriptions-item>
          <el-descriptions-item label="系统卷">
            <el-tag :type="detail.is_system ? 'danger' : 'info'" size="small">{{ detail.is_system ? '是' : '否' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="挂载状态">
            <el-tag :type="detail.is_mount ? 'success' : 'info'" size="small">{{ detail.is_mount ? '已挂载' : '未挂载' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="volStatusType(detail.status)" size="small">{{ volStatusLabel(detail.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="宿主机ID">{{ detail.host_id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="宿主机卷ID">{{ detail.host_volume_id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="路径" :span="2"><span class="mono-text">{{ detail.path || '-' }}</span></el-descriptions-item>
          <el-descriptions-item label="目标设备" v-if="detail.target_device">{{ detail.target_device }}</el-descriptions-item>
          <el-descriptions-item label="虚拟机ID" v-if="detail.vm_id">{{ detail.vm_id }}</el-descriptions-item>
          <el-descriptions-item label="镜像ID" v-if="detail.image_id">{{ detail.image_id }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTimestamp(detail.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTimestamp(detail.updated_at) }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 操作 -->
      <el-card shadow="never" class="info-card" v-if="detail">
        <template #header><span class="card-title">操作</span></template>
        <div class="action-buttons">
          <el-button type="primary" plain @click="handleResize">调整大小</el-button>
          <el-button type="success" plain @click="handleMount" v-if="!detail.is_mount">挂载</el-button>
          <el-button type="warning" plain @click="handleUnmount" v-if="detail.is_mount">卸载</el-button>
          <el-button type="info" plain @click="handleTransfer">迁移</el-button>
          <el-button type="danger" plain @click="handleDelete">删除</el-button>
        </div>
      </el-card>
    </div>

    <!-- 调整大小弹窗 -->
    <el-dialog v-model="resizeDialogVisible" title="调整数据卷大小" width="400px" destroy-on-close>
      <el-form label-width="100px">
        <el-form-item label="当前大小">{{ detail?.size || 0 }} GB</el-form-item>
        <el-form-item label="新大小">
          <div class="unit-input-row">
            <el-input-number v-model="resizeForm.size" :min="1" controls-position="right" style="flex:1" />
            <el-select v-model="resizeForm._sizeUnit" class="unit-select"><el-option label="GB" value="GB" /><el-option label="TB" value="TB" /></el-select>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resizeDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="actionLoading" @click="submitResize">确定</el-button>
      </template>
    </el-dialog>

    <!-- 挂载弹窗 -->
    <el-dialog v-model="mountDialogVisible" title="挂载数据卷到虚拟机" width="440px" destroy-on-close>
      <el-form label-width="100px">
        <el-form-item label="数据卷">{{ detail?.name }} ({{ detail?.size }} GB)</el-form-item>
        <el-form-item label="虚拟机" required>
          <div class="bind-selector-row">
            <el-input :model-value="mountVmId ? `VM #${mountVmId}${mountVmName ? ' - ' + mountVmName : ''}` : '未选择'" disabled style="flex: 1" />
            <el-button type="primary" @click="showMountVmSelector = true" style="margin-left: 8px">选择</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="mountDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="actionLoading" @click="submitMount">挂载</el-button>
      </template>
    </el-dialog>

    <!-- 迁移弹窗 -->
    <el-dialog v-model="transferDialogVisible" title="迁移数据卷" width="440px" destroy-on-close>
      <el-alert type="info" :closable="false" style="margin-bottom: 16px">
        将数据卷迁移到另一台宿主机上。迁移过程中数据卷将不可用。
      </el-alert>
      <el-form label-width="100px" v-loading="transferLoading">
        <el-form-item label="数据卷">{{ detail?.name }} ({{ detail?.size }} GB)</el-form-item>
        <el-form-item label="目标宿主机" required>
          <el-select v-model="transferHostId" placeholder="请选择目标宿主机" style="width: 100%" filterable>
            <el-option v-for="h in hostOptions" :key="h.id" :label="`${h.name} (${h.ip || h.id})`" :value="h.id" :disabled="h.id === detail?.host_id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="transferDialogVisible = false">取消</el-button>
        <el-button type="success" :loading="actionLoading" @click="submitTransfer">确定迁移</el-button>
      </template>
    </el-dialog>

    <VmSelectorPopup v-model="showMountVmSelector" :service-id="serviceId" :host-id="detail?.host_id || 0" :current-id="mountVmId" @confirm="vm => { mountVmId = vm.id; mountVmName = vm.name || '' }" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onActivated, onDeactivated, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Refresh } from '@element-plus/icons-vue'
import {
  getVolumeDetail, getRemoteHostList,
  resizeVolume, mountVolume, unmountVolume, transferVolume, deleteVolume
} from '@/api/admin/kvmService'
import { extractApiError } from '@/utils/kvmErrorUtil'
import { useTagsViewStore } from '@/store/tagsViewStore'
import VmSelectorPopup from '@/components/admin/VmSelectorPopup.vue'

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

const serviceId = computed(() => parseInt(route.query.service_id) || 0)
const volumeId = computed(() => parseInt(route.query.volume_id) || 0)

const loading = ref(false)
const actionLoading = ref(false)
const detail = ref(null)
const hostOptions = ref([])

const volStatusType = (s) => ({ ready: 'success', pending: 'info', error: 'danger', unknown: 'warning' }[s] || 'info')
const volStatusLabel = (s) => ({ ready: '就绪', pending: '等待中', error: '错误', unknown: '未知' }[s] || s || '-')

const formatTimestamp = (ts) => {
  if (!ts) return '-'
  if (typeof ts === 'object' && ts.seconds) return new Date(Number(ts.seconds) * 1000).toLocaleString('zh-CN')
  if (typeof ts === 'string' || typeof ts === 'number') { const d = new Date(ts); return isNaN(d.getTime()) ? String(ts) : d.toLocaleString('zh-CN') }
  return '-'
}

const loadHostOptions = async () => {
  try {
    const res = await getRemoteHostList({ service_id: serviceId.value, page: 1, page_size: 10 })
    const body = res?.data
    if (body?.code === 200 && body?.data) {
      const inner = body.data
      hostOptions.value = Array.isArray(inner) ? inner : (inner.hosts || inner.list || inner.data || [])
    }
  } catch { /* */ }
}

const loadDetail = async () => {
  if (!volumeId.value) return
  loading.value = true
  try {
    const res = await getVolumeDetail({ service_id: serviceId.value, volume_id: volumeId.value })
    if (res?.data?.code === 200 && res?.data?.data) {
      detail.value = res.data.data.volume ?? res.data.data.data ?? res.data.data
    } else ElMessage.error(extractApiError(res?.data, '加载失败'))
  } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '加载失败')) } finally { loading.value = false }
}

// 调整大小
const resizeDialogVisible = ref(false)
const resizeForm = reactive({ size: 1, _sizeUnit: 'GB' })
const handleResize = () => {
  if (!detail.value) return
  resizeForm.size = detail.value.size || 10
  resizeForm._sizeUnit = 'GB'
  resizeDialogVisible.value = true
}
const submitResize = async () => {
  actionLoading.value = true
  try {
    const sizeGb = resizeForm._sizeUnit === 'TB' ? resizeForm.size * 1024 : resizeForm.size
    const res = await resizeVolume({ service_id: serviceId.value, volume_id: volumeId.value, size: sizeGb })
    if (res?.data?.code === 200) { ElMessage.success('调整成功'); resizeDialogVisible.value = false; loadDetail() }
    else ElMessage.error(extractApiError(res?.data, '调整失败'))
  } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '调整失败')) } finally { actionLoading.value = false }
}

// 挂载
const mountDialogVisible = ref(false)
const mountVmId = ref(0)
const mountVmName = ref('')
const showMountVmSelector = ref(false)
const handleMount = () => {
  mountVmId.value = 0; mountVmName.value = ''
  mountDialogVisible.value = true
}
const submitMount = async () => {
  if (!mountVmId.value) { ElMessage.warning('请选择虚拟机'); return }
  actionLoading.value = true
  try {
    const res = await mountVolume({ service_id: serviceId.value, volume_id: volumeId.value, vm_id: mountVmId.value })
    if (res?.data?.code === 200) { ElMessage.success('挂载成功'); mountDialogVisible.value = false; loadDetail() }
    else ElMessage.error(extractApiError(res?.data, '挂载失败'))
  } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '挂载失败')) } finally { actionLoading.value = false }
}

// 卸载
const handleUnmount = () => {
  if (!detail.value) return
  ElMessageBox.confirm(`确定要卸载数据卷「${detail.value.name}」吗？`, '卸载确认', {
    confirmButtonText: '卸载', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    actionLoading.value = true
    try {
      const res = await unmountVolume({ service_id: serviceId.value, volume_id: volumeId.value })
      if (res?.data?.code === 200) { ElMessage.success('卸载成功'); loadDetail() }
      else ElMessage.error(extractApiError(res?.data, '卸载失败'))
    } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '卸载失败')) } finally { actionLoading.value = false }
  }).catch(() => {})
}

// 迁移
const transferDialogVisible = ref(false)
const transferHostId = ref('')
const transferLoading = ref(false)
const handleTransfer = async () => {
  transferHostId.value = ''
  transferDialogVisible.value = true
  if (!hostOptions.value.length) {
    transferLoading.value = true
    try { await loadHostOptions() } finally { transferLoading.value = false }
  }
}
const submitTransfer = async () => {
  if (!transferHostId.value) { ElMessage.warning('请选择目标宿主机'); return }
  actionLoading.value = true
  try {
    const fd = new FormData()
    fd.append('service_id', serviceId.value)
    fd.append('volume_id', volumeId.value)
    fd.append('host_id', transferHostId.value)
    const res = await transferVolume(fd)
    if (res?.data?.code === 200) { ElMessage.success('迁移已触发'); transferDialogVisible.value = false; loadDetail() }
    else ElMessage.error(extractApiError(res?.data, '迁移失败'))
  } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '迁移失败')) } finally { actionLoading.value = false }
}

// 删除
const handleDelete = () => {
  if (!detail.value) return
  ElMessageBox.confirm(`确定要删除数据卷「${detail.value.name}」吗？此操作不可恢复！`, '删除确认', {
    confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteVolume({ service_id: serviceId.value, volume_id: volumeId.value })
      if (res?.data?.code === 200) { ElMessage.success('删除成功'); goBack() }
      else ElMessage.error(extractApiError(res?.data, '删除失败'))
    } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '删除失败')) }
  }).catch(() => {})
}

const goBack = () => {
  tagsViewStore.delVisitedView(route)
  router.back()
}

let loadedVolumeId = null
let isPageActive = false

const initPage = () => {
  if (!volumeId.value || loadedVolumeId === volumeId.value) return
  loadedVolumeId = volumeId.value
  loadDetail()
}

watch(volumeId, () => { if (isPageActive) initPage() })
onActivated(() => { isPageActive = true; if (loadedVolumeId !== volumeId.value) initPage() })
onDeactivated(() => { isPageActive = false })
onMounted(() => { isPageActive = true; initPage() })
</script>

<style scoped>
.volume-detail-page { padding: 0; }
.page-header { display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; background: #fff; border-bottom: 1px solid #ebeef5; flex-wrap: wrap; gap: 8px; }
.header-left { display: flex; align-items: center; gap: 0; }
.back-btn { font-size: 14px; color: #606266; }
.back-btn:hover { color: #409eff; }
.page-title { font-size: 16px; font-weight: 600; color: #303133; }
.header-right { display: flex; gap: 8px; }
.main-content { padding: 20px; }
.info-card { margin-bottom: 20px; }
.card-title { font-weight: 600; font-size: 15px; color: #303133; }
.action-buttons { display: flex; flex-wrap: wrap; gap: 8px; }
.unit-input-row { display: flex; align-items: center; gap: 6px; width: 100%; }
.unit-select { width: 90px; flex-shrink: 0; }
</style>
