<template>
  <div class="image-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 type="primary" plain :icon="Edit" @click="handleEdit">编辑</el-button>
        <el-button type="success" plain @click="handleSyncToHost">同步到宿主机</el-button>
        <el-button type="warning" plain @click="handleReloadMaster">主控端重新下载</el-button>
        <el-button type="warning" plain @click="handleReloadOnHost">指定宿主机重新下载</el-button>
        <el-button plain :icon="Refresh" @click="loadDetail" :loading="loading">刷新</el-button>
        <el-button type="danger" plain :icon="Delete" @click="handleDelete">删除</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="系统类型">
            <el-tag :type="detail.os_type === 'linux' ? 'success' : 'primary'" size="small">{{ detail.os_type || '-' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="镜像类型">
            <el-tag :type="detail.type === 'system' ? '' : 'warning'" size="small">{{ detail.type === 'system' ? '系统镜像' : '数据镜像' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="statusType(detail.status)" size="small">{{ statusLabel(detail.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="模式">
            <el-tag :type="detail.mode === 'remote' ? 'warning' : 'success'" size="small">{{ detail.mode === 'remote' ? '远端模式' : '本地模式' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="大小">{{ detail.size ? formatSize(detail.size) : '-' }}</el-descriptions-item>
          <el-descriptions-item label="路径" :span="2"><span class="mono-text">{{ detail.path || '-' }}</span></el-descriptions-item>
          <el-descriptions-item label="下载URL" :span="2"><span class="mono-text">{{ detail.url || '-' }}</span></el-descriptions-item>
          <el-descriptions-item label="来源地址" :span="2"><span class="mono-text">{{ detail.source || '-' }}</span></el-descriptions-item>
          <el-descriptions-item label="介绍" :span="2">{{ detail.description || '-' }}</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">
        <template #header>
          <div class="card-header-row">
            <span class="card-title">宿主机同步状态</span>
            <el-button size="small" :icon="Refresh" @click="loadHostStatus" :loading="statusLoading">刷新状态</el-button>
          </div>
        </template>
        <el-table :data="hostStatusList" size="small" stripe border v-loading="statusLoading">
          <el-table-column prop="host_id" label="宿主机ID" width="100" />
          <el-table-column label="宿主机" min-width="120">
            <template #default="{ row }">{{ row.host_name || getHostName(row.host_id) }}</template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="statusType(row.status)" size="small">{{ statusLabel(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="path" label="本地路径" min-width="200" show-overflow-tooltip />
        </el-table>
        <el-empty v-if="hostStatusList.length === 0 && !statusLoading" description="暂无同步数据" />
      </el-card>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑镜像" width="560px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="名称" prop="name"><el-input v-model="formData.name" /></el-form-item>
        <el-form-item label="路径" prop="path"><el-input v-model="formData.path" /></el-form-item>
        <el-form-item label="系统类型">
          <el-select v-model="formData.os_type" style="width: 100%">
            <el-option label="Linux" value="linux" /><el-option label="Windows" value="windows" />
          </el-select>
        </el-form-item>
        <el-form-item label="镜像类型">
          <el-select v-model="formData.type" style="width: 100%">
            <el-option label="系统镜像" value="system" /><el-option label="数据镜像" value="data" />
          </el-select>
        </el-form-item>
        <el-form-item label="镜像模式">
          <el-select v-model="formData.mode" style="width: 100%">
            <el-option label="本地模式" value="local" /><el-option label="远端模式" value="remote" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.status" style="width: 100%">
            <el-option label="等待中" value="pending" /><el-option label="下载中" value="downloading" />
            <el-option label="就绪" value="ready" /><el-option label="错误" value="error" />
          </el-select>
        </el-form-item>
        <el-form-item label="介绍"><el-input v-model="formData.description" type="textarea" :rows="3" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmitEdit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 同步到宿主机弹窗 -->
    <el-dialog v-model="syncDialogVisible" title="同步镜像到宿主机" width="440px" destroy-on-close>
      <el-form label-width="100px">
        <el-form-item label="目标宿主机" required>
          <el-select v-model="syncHostId" placeholder="请选择宿主机" filterable style="width: 100%">
            <el-option v-for="h in hostOptions" :key="h.id" :label="`${h.name} (${h.ip || '#' + h.id})`" :value="h.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="syncDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="actionLoading" @click="submitSync">确定同步</el-button>
      </template>
    </el-dialog>

    <!-- 重下载到宿主机弹窗 -->
    <el-dialog v-model="reloadDialogVisible" title="重新下载镜像到宿主机" width="440px" destroy-on-close>
      <el-form label-width="100px">
        <el-form-item label="镜像">{{ detail?.name || '-' }}</el-form-item>
        <el-form-item label="目标宿主机" required>
          <el-select v-model="reloadHostId" placeholder="请选择宿主机" style="width: 100%">
            <el-option v-for="h in hostOptions" :key="h.id" :label="`${h.name} (${h.ip || '#' + h.id})`" :value="h.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reloadDialogVisible = false">取消</el-button>
        <el-button type="warning" :loading="actionLoading" @click="submitReload">确定重下载</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onActivated, onDeactivated, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import {
  getImageDetail, getImageHostStatus, updateImage, deleteImage,
  syncImageToHost, reloadImage, reloadImageOnHost, getRemoteHostList
} from '@/api/admin/kvmService'
import { useTagsViewStore } from '@/store/tagsViewStore'
import { extractApiError } from '@/utils/kvmErrorUtil'

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

const serviceId = computed(() => parseInt(route.query.service_id) || 0)
const serviceName = computed(() => route.query.service_name || '')
const imageId = computed(() => parseInt(route.query.id) || 0)

const loading = ref(false)
const submitLoading = ref(false)
const statusLoading = ref(false)
const actionLoading = ref(false)
const detail = ref(null)
const hostStatusList = ref([])
const hostOptions = ref([])
const editDialogVisible = ref(false)
const syncDialogVisible = ref(false)
const reloadDialogVisible = ref(false)
const syncHostId = ref('')
const reloadHostId = ref('')
const formRef = ref(null)

const formData = reactive({ name: '', path: '', os_type: 'linux', type: 'system', description: '', status: '', mode: 'local' })
const formRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路径', trigger: 'blur' }]
}

const statusType = (s) => ({ ready: 'success', success: 'success', downloading: 'warning', pending: 'info', error: 'danger', failed: 'danger', not_found: 'warning' }[s] || 'info')
const statusLabel = (s) => ({ ready: '就绪', success: '已同步', downloading: '下载中', pending: '等待中', error: '错误', failed: '失败', not_found: '未同步' }[s] || s || '-')
const formatSize = (bytes) => {
  if (!bytes) return '0 B'; const units = ['B', 'KB', 'MB', 'GB', 'TB']; let i = 0; let size = Number(bytes)
  while (size >= 1024 && i < units.length - 1) { size /= 1024; i++ }
  return size.toFixed(i > 0 ? 1 : 0) + ' ' + units[i]
}
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 getHostName = (hid) => { const h = hostOptions.value.find(x => x.id === hid); return h ? h.name : `#${hid}` }

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

const loadDetail = async () => {
  if (!imageId.value) return
  loading.value = true
  try {
    const res = await getImageDetail({ service_id: serviceId.value, image_id: imageId.value })
    if (res?.data?.code === 200 && res?.data?.data) {
      detail.value = res.data.data.image ?? 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 loadHostStatus = async () => {
  if (!hostOptions.value.length) await loadHostOptions()
  if (!hostOptions.value.length) return
  statusLoading.value = true
  hostStatusList.value = []
  try {
    const results = await Promise.allSettled(
      hostOptions.value.map(h =>
        getImageHostStatus({ service_id: serviceId.value, image_id: imageId.value, host_id: h.id })
          .then(res => {
            const body = res?.data
            if (body?.code === 200 && body?.data) {
              const d = body.data
              const img = d.image || {}
              return { host_id: h.id, host_name: h.name || h.ip, status: d.status || 'not_found', path: img.path || '', image_name: img.name || '', image_status: img.status || '' }
            }
            return { host_id: h.id, host_name: h.name || h.ip, status: 'not_found' }
          })
          .catch(() => ({ host_id: h.id, host_name: h.name || h.ip, status: 'error' }))
      )
    )
    hostStatusList.value = results
      .filter(r => r.status === 'fulfilled' && r.value)
      .map(r => r.value)
  } catch { /* */ } finally { statusLoading.value = false }
}

const handleEdit = () => {
  if (!detail.value) return
  const d = detail.value
  Object.assign(formData, { name: d.name || '', path: d.path || '', os_type: d.os_type || 'linux', type: d.type || 'system', description: d.description || '', status: d.status || '', mode: d.mode || 'local' })
  editDialogVisible.value = true
}

const handleSubmitEdit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const payload = { image_id: imageId.value, service_id: serviceId.value, image_name: formData.name, path: formData.path, os_type: formData.os_type, type: formData.type, description: formData.description || undefined, status: formData.status || undefined, mode: formData.mode }
      Object.keys(payload).forEach(k => { if (payload[k] === undefined) delete payload[k] })
      const res = await updateImage(payload)
      if (res?.data?.code === 200) { ElMessage.success('修改成功'); editDialogVisible.value = false; loadDetail() }
      else ElMessage.error(extractApiError(res?.data, '修改失败'))
    } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '修改失败')) } finally { submitLoading.value = false }
  })
}

const handleSyncToHost = () => { syncHostId.value = ''; syncDialogVisible.value = true }
const handleReloadOnHost = () => { reloadHostId.value = ''; reloadDialogVisible.value = true }

const handleReloadMaster = () => {
  ElMessageBox.confirm(`确定要在主控端重新下载镜像「${detail.value?.name}」吗？`, '重新下载确认', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    actionLoading.value = true
    try {
      const fd = new FormData()
      fd.append('service_id', serviceId.value)
      fd.append('image_id', imageId.value)
      const res = await reloadImage(fd)
      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 submitSync = async () => {
  if (!syncHostId.value) return ElMessage.warning('请选择宿主机')
  actionLoading.value = true
  try {
    const fd = new FormData(); fd.append('service_id', serviceId.value); fd.append('host_id', syncHostId.value)
    const res = await syncImageToHost(fd)
    if (res?.data?.code === 200) { ElMessage.success('已触发同步'); syncDialogVisible.value = false; loadHostStatus() }
    else ElMessage.error(extractApiError(res?.data, '同步失败'))
  } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '同步失败')) } finally { actionLoading.value = false }
}

const submitReload = async () => {
  if (!reloadHostId.value) return ElMessage.warning('请选择宿主机')
  actionLoading.value = true
  try {
    const fd = new FormData(); fd.append('service_id', serviceId.value); fd.append('image_id', imageId.value); fd.append('host_id', reloadHostId.value)
    const res = await reloadImageOnHost(fd)
    if (res?.data?.code === 200) { ElMessage.success('已触发重下载'); reloadDialogVisible.value = false; loadHostStatus() }
    else ElMessage.error(extractApiError(res?.data, '操作失败'))
  } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '操作失败')) } finally { actionLoading.value = false }
}

const handleDelete = () => {
  ElMessageBox.confirm(`确定要删除镜像「${detail.value?.name}」吗？`, '删除确认', {
    confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteImage({ service_id: serviceId.value, image_id: imageId.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 loadedImageId = null
let isPageActive = false

const initPage = async () => {
  if (!imageId.value || loadedImageId === imageId.value) return
  loadedImageId = imageId.value
  loadDetail()
  await loadHostOptions()
  loadHostStatus()
}

const isCurrentRoute = () => route.name === 'VirtImageDetail'

watch(imageId, () => { if (isPageActive && isCurrentRoute()) initPage() })
onActivated(async () => { isPageActive = true; await nextTick(); if (isCurrentRoute() && loadedImageId !== imageId.value) initPage() })
onDeactivated(() => { isPageActive = false })
onMounted(() => { isPageActive = true; initPage() })
</script>

<style scoped>
.image-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; flex-wrap: wrap; }
.main-content { padding: 20px; }
.info-card { margin-bottom: 20px; }
.card-title { font-weight: 600; font-size: 15px; color: #303133; }
.card-header-row { display: flex; justify-content: space-between; align-items: center; }
.mono-text { font-family: 'Consolas', monospace; color: #409eff; font-size: 13px; }
</style>
