<template>
  <el-dialog v-model="visible" title="选择数据卷" width="750px" append-to-body @close="handleClose">
    <div class="selector-container">
      <div class="filter-bar">
        <el-input v-model="keyword" placeholder="搜索数据卷" clearable style="width: 200px" @keyup.enter="handleSearch" @clear="handleSearch">
          <template #prefix><el-icon><Search /></el-icon></template>
        </el-input>
        <el-select v-model="statusFilter" placeholder="状态" clearable style="width: 120px" @change="handleSearch">
          <el-option label="就绪" value="ready" />
          <el-option label="等待中" value="pending" />
        </el-select>
        <el-button :icon="Refresh" @click="loadList" circle />
      </div>
      <el-table v-loading="loading" :data="list" highlight-current-row @current-change="handleCurrentChange"
        :height="340" :row-class-name="rowClassName" size="small" stripe>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="名称" min-width="160" show-overflow-tooltip />
        <el-table-column label="大小" width="90">
          <template #default="{ row }">{{ row.size ? row.size + ' GB' : '-' }}</template>
        </el-table-column>
        <el-table-column label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_system ? 'danger' : ''" size="small">{{ row.is_system ? '系统盘' : '数据盘' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="挂载" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_mount ? 'warning' : 'success'" size="small">{{ row.is_mount ? '已挂载' : '未挂载' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <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="180" show-overflow-tooltip />
      </el-table>
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]" :total="total" layout="total, sizes, prev, pager, next" small
          @size-change="s => { pageSize = s; page = 1; loadList() }"
          @current-change="p => { page = p; loadList() }" />
      </div>
    </div>
    <template #footer>
      <div style="display: flex; justify-content: space-between; width: 100%">
        <el-button type="success" @click="handleCreate">创建数据卷</el-button>
        <div style="display: flex; gap: 8px">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" :disabled="!selectedItem" @click="handleConfirm">确认选择</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getVolumeList } from '@/api/admin/kvmService'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  serviceId: { type: Number, default: 0 },
  hostId: { type: Number, default: 0 }
})

const emit = defineEmits(['update:modelValue', 'confirm', 'create'])

const visible = ref(false)
const loading = ref(false)
const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const keyword = ref('')
const statusFilter = ref('')
const selectedItem = ref(null)

watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    page.value = 1
    keyword.value = ''
    statusFilter.value = ''
    selectedItem.value = null
    loadList()
  }
})
watch(visible, (val) => emit('update:modelValue', val))

const handleSearch = () => { page.value = 1; loadList() }

const loadList = async () => {
  if (!props.serviceId || !props.hostId) return
  loading.value = true
  try {
    const params = { service_id: props.serviceId, host_id: props.hostId, page: page.value, count: pageSize.value }
    if (keyword.value) params.keyword = keyword.value
    if (statusFilter.value) params.status = statusFilter.value
    const res = await getVolumeList(params)
    if (res?.data?.code === 200 && res?.data?.data) {
      const inner = res.data.data
      list.value = inner.data || inner.volumes || (Array.isArray(inner) ? inner : [])
      total.value = inner.meta?.count ?? inner.total ?? list.value.length
    } else { list.value = []; total.value = 0 }
  } catch { list.value = []; total.value = 0 } finally { loading.value = false }
}

const statusType = (s) => ({ ready: 'success', pending: 'warning', error: 'danger' }[s] || 'info')
const statusLabel = (s) => ({ ready: '就绪', pending: '等待中', creating: '创建中', error: '错误' }[s] || s || '-')

const rowClassName = ({ row }) => row.id === selectedItem.value?.id ? 'selected-row' : ''
const handleCurrentChange = (row) => { selectedItem.value = row }
const handleConfirm = () => {
  if (selectedItem.value) {
    emit('confirm', selectedItem.value)
    visible.value = false
  }
}
const handleClose = () => { selectedItem.value = null }
const handleCreate = () => {
  visible.value = false
  emit('create')
}
</script>

<style scoped>
.selector-container { min-height: 200px; }
.filter-bar { display: flex; gap: 8px; margin-bottom: 12px; align-items: center; }
.pagination-wrapper { display: flex; justify-content: flex-end; margin-top: 12px; }
:deep(.selected-row) { background-color: #ecf5ff !important; }
:deep(.el-table__body tr) { cursor: pointer; }
</style>
