<template>
  <div class="remote-hg-container">
    <div class="page-header" v-if="!embedded">
      <div class="header-left">
        <el-button @click="goBack" :icon="ArrowLeft">返回</el-button>
        <div class="header-info">
          <h3>宿主机组管理</h3>
          <span class="sub-info" v-if="serviceName">所属主控服务：{{ serviceName }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>新建宿主机组</el-button>
        <el-button @click="loadList"><el-icon><Refresh /></el-icon>刷新</el-button>
      </div>
    </div>
    <div class="embedded-toolbar" v-if="embedded">
      <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>新建宿主机组</el-button>
      <el-button @click="loadList"><el-icon><Refresh /></el-icon>刷新</el-button>
    </div>

    <!-- 列表 -->
    <el-table :data="groupList" v-loading="loading" stripe>
      <el-table-column prop="id" label="ID" width="70" />
      <el-table-column prop="name" label="名称" min-width="160" show-overflow-tooltip />
      <el-table-column prop="note" label="备注" min-width="140" show-overflow-tooltip>
        <template #default="{ row }">{{ row.note || '-' }}</template>
      </el-table-column>
      <el-table-column label="父级组" min-width="140" show-overflow-tooltip>
        <template #default="{ row }">{{ getParentName(row.parent_id) }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="170">
        <template #default="{ row }">{{ formatTimestamp(row.created_at) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleViewDetail(row)">详情</el-button>
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="primary" @click="handleOptimalHost(row)">最优主机</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.page_size"
        :page-sizes="[10, 20, 50]" :total="total" layout="total, sizes, prev, pager, next"
        @size-change="s => { queryParams.page_size = s; queryParams.page = 1; loadList() }"
        @current-change="p => { queryParams.page = p; loadList() }" />
    </div>

    <!-- 新建/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新建宿主机组' : '编辑宿主机组'" width="480px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="宿主机组名称" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.note" type="textarea" :rows="3" placeholder="备注（可选）" />
        </el-form-item>
        <el-form-item label="父级组">
          <el-select v-model="formData.parent_id" placeholder="请选择父级宿主机组" style="width: 100%" clearable @clear="formData.parent_id = 0">
            <el-option :value="0" label="无（顶级分组）" />
            <el-option
              v-for="g in parentOptions"
              :key="g.id"
              :value="g.id"
              :label="`${g.name}（ID: ${g.id}）`"
              :disabled="g.id === formData.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="宿主机组详情" width="560px" destroy-on-close>
      <div v-loading="detailLoading">
        <el-descriptions title="基本信息" :column="2" border v-if="currentDetail">
          <el-descriptions-item label="ID">{{ currentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{ currentDetail.name }}</el-descriptions-item>
          <el-descriptions-item label="父级ID">{{ currentDetail.parent_id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentDetail.note || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTimestamp(currentDetail.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTimestamp(currentDetail.updated_at) }}</el-descriptions-item>
        </el-descriptions>
        <el-descriptions title="父级宿主机组" :column="2" border v-if="parentDetail" style="margin-top: 20px;">
          <el-descriptions-item label="ID">{{ parentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{ parentDetail.name }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ parentDetail.note || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTimestamp(parentDetail.created_at) }}</el-descriptions-item>
        </el-descriptions>
        <el-empty v-if="!parentDetail && currentDetail && !currentDetail.parent_id" description="无父级宿主机组" :image-size="60" style="margin-top: 12px;" />
      </div>
      <template #footer><el-button @click="detailVisible = false">关闭</el-button></template>
    </el-dialog>

    <!-- 最优主机弹窗 -->
    <el-dialog v-model="optimalVisible" title="最优主机配置" width="700px" destroy-on-close>
      <div v-loading="optimalLoading">
        <template v-if="optimalData">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="主机ID">{{ optimalData.host_id }}</el-descriptions-item>
            <el-descriptions-item label="主机名称">{{ optimalData.host_name }}</el-descriptions-item>
          </el-descriptions>
          <h4 style="margin: 16px 0 8px; color: #303133;">资源字段配置</h4>
          <el-table :data="optimalData.fields || []" border stripe size="small">
            <el-table-column prop="name" label="名称" width="110" />
            <el-table-column prop="key" label="Key" width="120">
              <template #default="{ row }"><code>{{ row.key }}</code></template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="80" align="center">
              <template #default="{ row }">
                <el-tag size="small" :type="row.type === 'select' ? 'warning' : ''">{{ row.type }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="范围" min-width="160">
              <template #default="{ row }">
                <template v-if="row.type === 'number'">
                  <span v-if="row.min != null">最小: {{ formatFieldValue(row.key, row.min) }}</span>
                  <span v-if="row.min != null && row.max != null"> / </span>
                  <span v-if="row.max != null">最大: {{ formatFieldValue(row.key, row.max) }}</span>
                  <span v-if="row.step" style="color: #909399; margin-left: 6px;">步长: {{ row.step }}</span>
                </template>
                <span v-else style="color: #c0c4cc;">-</span>
              </template>
            </el-table-column>
            <el-table-column label="必填" width="60" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.must" type="danger" size="small">是</el-tag>
                <span v-else style="color: #c0c4cc;">否</span>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <el-empty v-else :description="optimalError || '暂无数据'" />
      </div>
      <template #footer><el-button @click="optimalVisible = false">关闭</el-button></template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, inject, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, ArrowLeft } from '@element-plus/icons-vue'
import {
  getRemoteHostGroupList, getRemoteHostGroupDetail, createRemoteHostGroup,
  updateRemoteHostGroup, deleteRemoteHostGroup, getOptimalHostInfo
} from '@/api/admin/kvmService'
import { extractApiError } from '@/utils/kvmErrorUtil'

const route = useRoute()
const router = useRouter()
const embedded = inject('embedded', false)
const injectedServiceId = inject('serviceId', null)
const injectedServiceName = inject('serviceName', null)
const serviceId = computed(() => injectedServiceId?.value || parseInt(route.query.service_id) || 0)
const serviceName = computed(() => injectedServiceName?.value || route.query.service_name || '')

const loading = ref(false)
const submitLoading = ref(false)
const detailLoading = ref(false)
const optimalLoading = ref(false)
const groupList = ref([])
const total = ref(0)
const queryParams = reactive({ page: 1, page_size: 10 })

const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const detailVisible = ref(false)
const currentDetail = ref(null)
const parentDetail = ref(null)
const optimalVisible = ref(false)
const optimalData = ref(null)
const optimalError = ref('')

const formData = reactive({ id: undefined, name: '', note: '', parent_id: 0 })
const formRules = { name: [{ required: true, message: '请输入名称', trigger: 'blur' }] }

const parentOptions = computed(() => groupList.value.filter(g => g.id !== formData.id))

const getParentName = (parentId) => {
  if (!parentId) return '-'
  const found = groupList.value.find(g => g.id === parentId)
  return found ? `${found.name}（ID: ${parentId}）` : `ID: ${parentId}`
}

const formatFieldValue = (key, val) => {
  if (val == null) return '-'
  if (key === 'memory') {
    val = Number(val)
    if (val >= 1099511627776) return `${(val / 1099511627776).toFixed(1)} TB`
    if (val >= 1073741824) return `${(val / 1073741824).toFixed(1)} GB`
    if (val >= 1048576) return `${(val / 1048576).toFixed(1)} MB`
    if (val >= 1024) return `${(val / 1024).toFixed(1)} KB`
    return `${val} B`
  }
  if (key === 'system_size') {
    val = Number(val)
    if (val >= 1073741824) return `${(val / 1073741824).toFixed(1)} TB`
    if (val >= 1048576) return `${(val / 1048576).toFixed(1)} GB`
    if (val >= 1024) return `${(val / 1024).toFixed(1)} MB`
    return `${val} KB`
  }
  return val
}

const formatTimestamp = (ts) => {
  if (!ts) return '-'
  if (typeof ts === 'object' && ts.seconds) {
    const d = new Date(Number(ts.seconds) * 1000)
    return d.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
  }
  if (typeof ts === 'string' || typeof ts === 'number') {
    const d = new Date(ts)
    return isNaN(d.getTime()) ? String(ts) : d.toLocaleString('zh-CN')
  }
  return '-'
}

const loadList = async () => {
  if (!serviceId.value) return
  loading.value = true
  try {
    const res = await getRemoteHostGroupList({ service_id: serviceId.value, page: queryParams.page, page_size: queryParams.page_size })
    const body = res?.data
    if (body?.code === 200 && body?.data) {
      const inner = body.data
      groupList.value = inner.host_groups || inner.data || (Array.isArray(inner) ? inner : [])
      total.value = inner.meta?.count ?? inner.all_count ?? inner.total ?? groupList.value.length
    } else {
      groupList.value = []
      total.value = 0
    }
  } catch (e) {
    ElMessage.error('获取宿主机组列表失败')
  } finally { loading.value = false }
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(formData, { id: undefined, name: '', note: '', parent_id: 0 })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(formData, { id: row.id, name: row.name || '', note: row.note || '', parent_id: row.parent_id || 0 })
  dialogVisible.value = true
}

const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const payload = { service_id: serviceId.value, name: formData.name, note: formData.note }
      if (formData.parent_id > 0) payload.parent_id = formData.parent_id
      let res
      if (dialogType.value === 'add') {
        res = await createRemoteHostGroup(payload)
      } else {
        payload.id = formData.id
        res = await updateRemoteHostGroup(payload)
      }
      if (res?.data?.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '创建成功' : '修改成功')
        dialogVisible.value = false
        loadList()
      } else {
        ElMessage.error(extractApiError(res?.data, '操作失败'))
      }
    } catch (e) {
      ElMessage.error(extractApiError(e?.response?.data, '操作失败'))
    } finally { submitLoading.value = false }
  })
}

const handleViewDetail = async (row) => {
  detailVisible.value = true
  detailLoading.value = true
  currentDetail.value = row
  parentDetail.value = null
  try {
    const res = await getRemoteHostGroupDetail({ service_id: serviceId.value, id: row.id })
    if (res?.data?.code === 200 && res?.data?.data) {
      const inner = res.data.data
      currentDetail.value = inner.host_group || inner
      parentDetail.value = inner.parent_host_group || null
    }
  } catch { /* fallback */ }
  finally { detailLoading.value = false }
}


const handleOptimalHost = async (row) => {
  optimalVisible.value = true
  optimalLoading.value = true
  optimalData.value = null
  optimalError.value = ''
  try {
    const res = await getOptimalHostInfo({ service_id: serviceId.value, host_group_id: row.id })
    if (res?.data?.code === 200) {
      optimalData.value = res.data.data
    } else {
      optimalError.value = extractApiError(res?.data, '暂无最优主机数据')
    }
  } catch {
    optimalError.value = '暂无最优主机数据'
  } finally { optimalLoading.value = false }
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除宿主机组「${row.name}」吗？`, '删除确认', {
    confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteRemoteHostGroup({ service_id: serviceId.value, id: row.id })
      if (res?.data?.code === 200) { ElMessage.success('删除成功'); loadList() }
      else ElMessage.error(extractApiError(res?.data, '删除失败'))
    } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '删除失败')) }
  }).catch(() => {})
}

const goBack = () => { router.push('/virtualization/kvm-service') }

onMounted(() => { if (serviceId.value) loadList() })
</script>

<style scoped>
.remote-hg-container { padding: 20px; }
</style>
