<template>
  <el-dialog v-model="visible" title="选择数据卷进行挂载" width="680px" append-to-body @close="handleClose">
    <div class="selector-toolbar">
      <el-input v-model="keyword" placeholder="搜索数据卷名称" clearable style="width:200px"
        @keyup.enter="loadList" @clear="loadList">
        <template #prefix><el-icon><Search /></el-icon></template>
      </el-input>
      <el-button :icon="Refresh" @click="loadList" :loading="loading">刷新</el-button>
      <el-button type="primary" :icon="Plus" @click="showCreate = true">新建数据卷</el-button>
    </div>
    <el-table :data="list" v-loading="loading" highlight-current-row
      @current-change="row => selected = row" :height="280" stripe size="small">
      <el-table-column prop="id" label="ID" width="70" />
      <el-table-column prop="name" label="名称" min-width="160" show-overflow-tooltip />
      <el-table-column label="大小" width="80">
        <template #default="{ row }">{{ 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.status === 'ready' ? 'success' : 'info'" size="small">{{ row.status || '-' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="挂载" width="80">
        <template #default="{ row }">
          <el-tag :type="row.is_mount ? 'success' : 'info'" size="small">{{ row.is_mount ? '已挂载' : '未挂载' }}</el-tag>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-if="!list.length && !loading" :image-size="60" description="暂无数据卷" />
    <div class="selector-footer-bar">
      <span v-if="selected" style="color:#606266;font-size:13px">已选：{{ selected.name }} (ID: {{ selected.id }})</span>
      <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[10,20]" :total="total"
        layout="total,sizes,prev,pager,next" small background
        @size-change="s => { pageSize = s; page = 1; loadList() }"
        @current-change="p => { page = p; loadList() }" />
    </div>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :disabled="!selected || !!selected.is_mount" @click="handleConfirm">
        {{ selected?.is_mount ? '已挂载' : '确定挂载' }}
      </el-button>
    </template>
  </el-dialog>

  <!-- 新建数据卷弹窗 -->
  <el-dialog v-model="showCreate" title="新建数据卷" width="440px" append-to-body destroy-on-close>
    <el-form :model="createForm" label-width="100px">
      <el-form-item label="名称" required><el-input v-model="createForm.name" placeholder="数据卷名称" /></el-form-item>
      <el-form-item label="大小">
        <div class="unit-input-row">
          <el-input-number v-model="createForm.size" :min="1" controls-position="right" style="flex:1" />
          <el-select v-model="createForm._sizeUnit" class="unit-select"><el-option label="GB" value="GB" /><el-option label="TB" value="TB" /></el-select>
        </div>
      </el-form-item>
      <el-form-item label="目标设备名"><el-input v-model="createForm.target_device" placeholder="不填自动生成" /></el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showCreate = false">取消</el-button>
      <el-button type="primary" :loading="createLoading" @click="submitCreate">创建</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getUserVmVolumeList, createUserVmVolume } from '@/api/admin/userVm'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  userGoodsId: { type: Number, default: 0 }
})
const emit = defineEmits(['update:modelValue', 'confirm'])

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 selected = ref(null)

const showCreate = ref(false)
const createLoading = ref(false)
const createForm = reactive({ name: '', size: 10, _sizeUnit: 'GB', target_device: '' })

watch(() => props.modelValue, (v) => { visible.value = v; if (v) { selected.value = null; loadList() } })
watch(visible, (v) => emit('update:modelValue', v))

const loadList = async () => {
  if (!props.userGoodsId) return
  loading.value = true
  try {
    const res = await getUserVmVolumeList({ user_goods_id: props.userGoodsId, page: page.value, count: pageSize.value })
    if (res?.data?.code === 200 && res?.data?.data) {
      const d = res.data.data
      list.value = d.data || (Array.isArray(d) ? d : [])
      total.value = d.all_count ?? d.total ?? list.value.length
    }
  } catch { /* */ } finally { loading.value = false }
}

const submitCreate = async () => {
  if (!createForm.name) { ElMessage.warning('请输入名称'); return }
  createLoading.value = true
  try {
    const sizeGb = createForm._sizeUnit === 'TB' ? createForm.size * 1024 : createForm.size
    const res = await createUserVmVolume({
      user_goods_id: props.userGoodsId,
      name: createForm.name,
      size: sizeGb,
      target_device: createForm.target_device
    })
    if (res?.data?.code === 200) {
      ElMessage.success('创建成功')
      showCreate.value = false
      Object.assign(createForm, { name: '', size: 10, _sizeUnit: 'GB', target_device: '' })
      loadList()
    } else ElMessage.error(res?.data?.message || '创建失败')
  } catch { ElMessage.error('创建失败') } finally { createLoading.value = false }
}

const handleClose = () => { visible.value = false }
const handleConfirm = () => {
  if (selected.value && !selected.value.is_mount) {
    emit('confirm', selected.value)
    handleClose()
  }
}
</script>

<style scoped>
.selector-toolbar { display: flex; gap: 8px; margin-bottom: 12px; align-items: center; }
.selector-footer-bar { display: flex; justify-content: space-between; align-items: center; margin-top: 12px; }
.unit-input-row { display: flex; align-items: center; gap: 6px; width: 100%; }
.unit-select { width: 90px; flex-shrink: 0; }
</style>
