<template>
  <el-dialog v-model="visible" title="选择镜像" width="700px" 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="filterOsType" placeholder="系统类型" clearable style="width: 120px" @change="handleSearch">
          <el-option label="Linux" value="linux" />
          <el-option label="Windows" value="windows" />
        </el-select>
        <el-button :icon="Refresh" @click="loadList">刷新</el-button>
      </div>
      <el-table v-loading="loading" :data="list" highlight-current-row @current-change="handleCurrentChange" :height="300" :row-class-name="rowClassName">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="名称" min-width="200" show-overflow-tooltip />
        <el-table-column label="系统" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.os_type === 'linux' ? 'success' : 'primary'" size="small">{{ row.os_type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="70" align="center">
          <template #default="{ row }">
            <el-tag :type="row.type === 'system' ? '' : 'warning'" size="small">{{ row.type === 'system' ? '系统' : '数据' }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper" v-if="total > pageSize">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev,pager,next" small @current-change="loadList" />
      </div>
    </div>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :disabled="!selectedItem" @click="handleConfirm">确认选择</el-button>
    </template>
  </el-dialog>
</template>

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

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

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

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

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

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

const loadList = async () => {
  loading.value = true
  try {
    let res
    if (props.goodId > 0) {
      const params = { good_id: props.goodId, page: page.value, count: pageSize }
      if (keyword.value) params.keyword = keyword.value
      if (filterOsType.value) params.os_type = filterOsType.value
      res = await getGoodHostGroupImages(params)
    } else if (props.useUserVmApi) {
      const params = { service_id: props.serviceId, page: page.value, count: pageSize }
      if (keyword.value) params.keyword = keyword.value
      if (filterOsType.value) params.os_type = filterOsType.value
      res = await getUserVmHostImages(params)
    } else {
      const params = { service_id: props.serviceId, page: page.value, count: pageSize }
      if (keyword.value) params.keyword = keyword.value
      if (filterOsType.value) params.os_type = filterOsType.value
      res = await getImageList(params)
    }
    const body = res?.data
    if (body?.code === 200 && body?.data) {
      const inner = body.data
      let items = inner.data || inner.list || (Array.isArray(inner) ? inner : [])
      if (props.useUserVmApi || props.goodId > 0) {
        items = items.map(item => item.image || item).filter(Boolean)
      }
      list.value = items
      total.value = inner.total ?? inner.all_count ?? list.value.length
    }
  } catch { /* ignore */ }
  finally { loading.value = false }
}

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

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