<template>
  <div class="vm-images-container" v-loading="loading">
    <el-card class="main-container" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="服务器">
              <el-select
                v-model="selectedServer"
                placeholder="请选择服务器"
                clearable
                @change="handleServerChange"
                style="width: 220px"
              >
                <el-option
                  v-for="item in serverList"
                  :key="item.server_id"
                  :label="item.name"
                  :value="item.server_id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="镜像名称">
              <el-input v-model="searchForm.name" placeholder="请输入镜像名称" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item label="操作系统">
              <el-select v-model="searchForm.os" placeholder="请选择操作系统" clearable style="width: 150px">
                <el-option label="Windows" value="windows" />
                <el-option label="Ubuntu" value="ubuntu" />
                <el-option label="CentOS" value="centos" />
                <el-option label="Debian" value="debian" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
                <el-option label="可用" value="available" />
                <el-option label="创建中" value="creating" />
                <el-option label="已禁用" value="disabled" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><search /></el-icon>搜索
              </el-button>
              <el-button @click="resetSearch">
                <el-icon><refresh /></el-icon>重置
              </el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button type="primary" @click="toLoad(selectedServer)" :disabled="!selectedServer">
              <el-icon><plus /></el-icon>添加镜像
            </el-button>
          </div>
        </div>
      </div>

      <!-- 镜像列表 -->
      <div class="table-section" v-if="selectedServer">
        <el-table
          v-loading="tableLoading"
          :data="currentImages"
          style="width: 100%"
          row-key="id"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="镜像信息" min-width="250">
            <template #default="scope">
              <div class="image-info-cell">
                <img :src="mainUrl + scope.row.image_ico" class="table-image-logo" />
                <div class="image-info-content">
                  <div class="image-name-row">
                    <span class="table-image-name">{{ scope.row.name }}</span>
                  </div>
                  <div class="image-desc-row">{{ scope.row.description || '暂无描述' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="show_name" label="展示名称" width="120" show-overflow-tooltip />
          <el-table-column label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.state)">
                {{ getStatusText(scope.row.state) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180" align="center" />
          <el-table-column label="操作" width="250" align="center" fixed="right">
            <template #default="scope">
              <el-button 
                type="primary" 
                link 
                @click="handleCreateVM(scope.row)" 
                v-if="scope.row.state === 1"
              >
                <el-icon><monitor /></el-icon>创建虚拟机
              </el-button>
              <el-button type="success" link @click="handleEdit(scope.row)">
                <el-icon><edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">
                <el-icon><delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @update:current-page="handleCurrentPageChange"
          @update:page-size="handleSizeChange"
          class="pagination"
        />
      </div>

      <!-- 未选择服务器时的提示 -->
      <el-empty 
        v-if="!selectedServer && !loading" 
        description="请选择一个服务器查看镜像列表" 
        class="empty-tip"
      />
    </el-card>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Plus, Search, Refresh, Edit, Delete, TurnOff, Open, Monitor
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getServer } from '@/utils/acs/server'
import { 
  delMirror, getUserMirrorList, getImageTypeList
} from '@/utils/acs/mirror'
import { mainUrl } from '@/utils/request'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  name: '',
  os: '',
  status: ''
})

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.os = ''
  searchForm.status = ''
  handleSearch()
}

// 表格数据
const loading = ref(false)
const tableLoading = ref(false)
const serverList = ref([])
const selectedServer = ref('')
const currentImages = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 获取操作系统图标
const getOsIcon = (os) => {
  const icons = {
    windows: 'https://cdn.jsdelivr.net/gh/devicons/devicon/icons/windows8/windows8-original.svg',
    ubuntu: 'https://cdn.jsdelivr.net/gh/devicons/devicon/icons/ubuntu/ubuntu-plain.svg',
    centos: 'https://cdn.jsdelivr.net/gh/devicons/devicon/icons/redhat/redhat-original.svg',
    debian: 'https://cdn.jsdelivr.net/gh/devicons/devicon/icons/debian/debian-original.svg',
    other: 'https://cdn.jsdelivr.net/gh/devicons/devicon/icons/linux/linux-original.svg'
  }
  return icons[os] || icons.other
}

// 状态标签样式
const getStatusType = (state) => {
  const map = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return map[state] || 'info'
}

const getStatusText = (state) => {
  const map = {
    0: '上传中',
    1: '可用',
    2: '上传失败'
  }
  return map[state] || '未知'
}

// 处理搜索
const handleSearch = () => {
  if (selectedServer.value) {
    fetchImageList()
  }
}

// 处理服务器变更
const handleServerChange = () => {
  currentPage.value = 1
  if (selectedServer.value) {
    fetchImageList()
  } else {
    currentImages.value = []
    totalCount.value = 0
  }
}

// 获取服务器列表
const fetchServerList = async () => {
  try {
    loading.value = true
    const response = await getServer(1, 100, '', 'hyperV')
    if (response.data.code === 200) {
      serverList.value = response.data.data || []
      // 如果有服务器列表且没有选择服务器，默认选择第一个
      if (serverList.value.length > 0 && !selectedServer.value) {
        selectedServer.value = serverList.value[0].server_id
        await fetchImageList()
      }
    } else {
      ElMessage.error('获取服务器列表失败：' + response.data.message)
    }
  } catch (error) {
    console.error('获取服务器列表出错：', error)
    ElMessage.error('获取服务器列表出错')
  } finally {
    loading.value = false
  }
}

// 获取镜像列表
const fetchImageList = async () => {
  if (!selectedServer.value) return
  
  try {
    tableLoading.value = true
    const response = await getUserMirrorList({
      server_id: selectedServer.value,
      count: pageSize.value,
      page: currentPage.value,
      key: searchForm.name || ''
    })
    
    if (response.data.code === 200) {
      currentImages.value = response.data.data || []
      totalCount.value = response.data.count || 0
    } else {
      ElMessage.error('获取镜像列表失败：' + response.data.message)
    }
  } catch (error) {
    console.error('获取镜像列表出错：', error)
    ElMessage.error('获取镜像列表出错')
  } finally {
    tableLoading.value = false
  }
}

// 分页相关
const handleCurrentPageChange = (newPage) => {
  currentPage.value = newPage
  fetchImageList()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchImageList()
}

// 新增镜像
const toLoad = (serverId) => {
  router.push({
    path: '/acs/images/form',
    query: { server_id: serverId }
  })
}

// 编辑镜像
const handleEdit = (row) => {
  router.push({
    path: '/acs/images/form',
    query: { id: row.id, server_id: row.server_id },
    state: { params: JSON.parse(JSON.stringify(row)) }
  })
}

// 删除镜像
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除镜像"${row.name}"吗？删除后不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    delMirror({ server_id: row.server_id, image_id: row.id }).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success('删除成功')
        fetchImageList()
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    }).catch(() => {
      ElMessage.error('删除失败')
    })
  }).catch(() => {})
}

// 创建虚拟机
const handleCreateVM = (row) => {
  ElMessage.success(`正在使用镜像"${row.name}"创建虚拟机，请前往虚拟机管理页面查看`)
}

// 初始加载
onMounted(() => {
  fetchServerList()
})
</script>

<style scoped>
.vm-images-container {
  padding: 0;
}

.main-container {
  border: 1px solid #e1e8ed;
  background: #ffffff;
}

.filter-section {
  padding: 0;
  border-bottom: 1px solid #e1e8ed;
  background: #fafbfc;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form {
  margin: 0;
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 12px;
}

.action-bar {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.table-section {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  border-top: 1px solid #e1e8ed;
  background: #fafbfc;
  justify-content: flex-end;
}

.image-info-cell {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.table-image-logo {
  width: 48px;
  height: 48px;
  border-radius: 6px;
  object-fit: contain;
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  padding: 4px;
}

.image-info-content {
  flex: 1;
  margin-left: 15px;
}

.image-name-row {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.table-image-name {
  font-weight: 600;
  margin-right: 12px;
  color: #303133;
  font-size: 15px;
}

.image-desc-row {
  color: #909399;
  font-size: 13px;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}



/* 表格样式优化 */
:deep(.el-table) {
  border: none;
  color: #2c3e50;
}

:deep(.el-table__header) {
  background: #f8f9fa;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  border-bottom: 2px solid #e1e8ed;
  color: #2c3e50;
  font-weight: 600;
  font-size: 13px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  color: #34495e;
}

:deep(.el-table tr:hover > td) {
  background-color: #f8f9fa !important;
}

:deep(.el-card__body) {
  padding: 0;
}
</style>