<template>
  <div class="vm-images-container" v-loading="loading">
    <div class="page-header">
      <h2>虚拟机镜像</h2>
      <div class="header-actions">
        <el-button type="primary" @click="toLoad(selectedServer)" :disabled="!selectedServer">
          <el-icon><plus /></el-icon>添加镜像
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <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 />
        </el-form-item>
        <el-form-item label="操作系统">
          <el-select v-model="searchForm.os" placeholder="请选择操作系统" clearable>
            <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>
            <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>
    </el-card>

    <!-- 镜像列表 -->
    <el-card class="table-card" v-if="selectedServer">
      <el-table
        v-loading="tableLoading"
        :data="currentImages"
        border
        style="width: 100%"
        row-key="id"
      >
        <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>

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

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

    <!-- 镜像表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editOr ? '编辑镜像' : '添加镜像'"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form :model="imageForm" label-width="120px" :rules="rules" ref="imageFormRef">
        <el-form-item label="镜像名称" prop="name">
          <el-input v-model="imageForm.name" placeholder="请输入镜像名称" />
        </el-form-item>
        <el-form-item label="文件路径" prop="path" v-if="editOr == true">
          <el-input v-model="imageForm.path" placeholder="请输入镜像文件路径" />
        </el-form-item>
        <el-form-item label="展示名称" prop="show_name">
          <el-input v-model="imageForm.show_name" placeholder="请输入展示名称" />
        </el-form-item>
        <el-form-item label="分类" prop="class_id" v-if="editOr == true">
          <el-select v-model="imageForm.class_id" placeholder="请选择分类" clearable style="width: 100%">
            <el-option v-for="item in categoryList" :key="item.class_id" :label="item.name" :value="item.class_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="图标" prop="image_ico">
          <div class="image-icon-upload">
            <img v-if="imageForm.image_ico" :src="mainUrl + imageForm.image_ico" class="preview-icon" />
            <div class="upload-buttons">
              <el-button type="primary" @click="$refs.fileInput.click()">选择文件</el-button>
              <input ref="fileInput" type="file" style="display: none" @change="onFileSelected" />
              <div class="el-upload__tip" v-if="selectedFileName">
                已选择: {{ selectedFileName }}
              </div>
              <el-button @click="picSwitch = true; getpicList()">从素材库选择</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="套餐" prop="plan_id">
          <el-select v-model="imageForm.plan_id" placeholder="请选择套餐" style="width: 100%">
            <el-option v-for="item in planlist" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="imageForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入镜像描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="getit">一键粘贴内容</el-button>
          <el-button @click="copyit">一键复制内容</el-button>
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 素材库对话框 -->
    <el-dialog v-model="picSwitch" title="素材库" width="70%" :before-close="() => picSwitch = false">
      <div class="pic-search">
        <el-input 
          v-model="picPagin.key" 
          placeholder="请输入搜索内容" 
          style="width: 300px; margin-bottom: 20px"
          @blur="getpicList()"
        >
          <template #append>
            <el-button @click="getpicList()">
              <el-icon><search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      <div class="piclist">
        <div 
          v-for="(item, index) in picList" 
          :key="index" 
          class="icon" 
          :class="{ choose: currentIndex === index }"
          @click="selectImage(index, item)"
        >
          <img :src="`${mainUrl}/v1/attachment/get_attachment?aid=${item.attachment_id}`" />
          <div class="tit">{{ item.title ? item.title.slice(0, 8) : '未命名' }}</div>
        </div>
      </div>
      <div class="pagination-container" style="margin-top: 20px">
        <el-pagination
          background 
          layout="total, sizes, prev, pager, next" 
          :total="total" 
          :current-page="picPagin.page"
          :page-size="picPagin.count" 
          :page-sizes="[10, 20, 50, 100]"
          @current-change="CurrentPageChange" 
          @size-change="PageSizeChange" 
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="picSwitch = false">取消</el-button>
          <el-button type="primary" @click="tochoose">确认选择</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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

// 搜索表单
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 dialogVisible = ref(false)
const editOr = ref(false)
const selectedFileName = ref(null)
const planlist = ref([])
const nowserver_id = ref('')

// 表单对象和规则
const imageFormRef = ref(null)
const imageForm = reactive({
  id: '',
  name: '',
  show_name: '',
  description: '',
  server_type: 'hyperV',
  plan_id: '',
  image_ico: '',
  server_id: '',
  path: '',
  class_id: ''
})

const rules = {
  name: [{ required: true, message: '请输入镜像名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入镜像文件路径', trigger: 'blur' }],
  show_name: [{ required: true, message: '请输入展示名称', trigger: 'blur' }],
  // plan_id: [{ required: true, message: '请选择套餐', trigger: 'change' }]
}

// 素材库相关
const picSwitch = ref(false)
const picPagin = reactive({
  count: 50,
  page: 1,
  key: '',
  user_type: 1
})
const picList = ref([])
const total = ref(10)
const currentIndex = ref(null)
const categoryList = ref([])

// 获取操作系统图标
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 fetchCategoryList = async (serverId) => {
  try {
    const response = await getImageTypeList(serverId)
    if (response.data.code === 200) {
      categoryList.value = response.data.data || []
    } else {
      ElMessage.error('获取镜像分类失败：' + response.data.message)
    }
  } catch (error) {
    console.error('获取镜像分类出错：', error)
    ElMessage.error('获取镜像分类列表失败')
  }
}

// 新增镜像
const toLoad = async (data) => {
  dialogVisible.value = true
  editOr.value = false
  Object.keys(imageForm).forEach(key => {
    imageForm[key] = ''
  })
  imageForm.server_id = data
  nowserver_id.value = data
  try {
    // 获取套餐列表
    let res = await getServerPlan({ server_id: data })
    planlist.value = res.data.data.map(item => {
      return {
        name: item.name,
        id: item.plan_id,
      }
    })
    // 获取分类列表
    await fetchCategoryList(data)
  } catch (error) {
    ElMessage.error('获取数据失败')
  }
}

// 处理文件变更
const onFileSelected = (event) => {
  const file = event.target.files[0]
  if (file) {
    selectedFileName.value = file.name
    uploadFile({ file: file }).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success('上传成功')
        selectedFileName.value = null
        imageForm.image_ico = '/v1/attachment/get_attachment?aid=' + res.data.data.attachment_id
      }
    }).catch(() => {
      ElMessage.error('上传失败')
    })
  } else {
    selectedFileName.value = null
  }
}

// 添加镜像
const handleAdd = () => {
  if (!selectedServer.value) {
    ElMessage.warning('请先选择一个服务器')
    return
  }
  toLoad(selectedServer.value)
}

// 编辑镜像
const handleEdit = async (row) => {
  try {
    let res = await getServerPlan({ server_id: row.server_id })
    planlist.value = res.data.data.map(item => {
      return {
        name: item.name,
        id: item.plan_id,
      }
    })
    // 获取分类列表
    await fetchCategoryList(row.server_id)
    
    editOr.value = true
    dialogVisible.value = true
    for (const key in row) {
      if (row.hasOwnProperty(key)) {
        imageForm[key] = row[key]
      }
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
  }
}

// 删除镜像
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}"创建虚拟机，请前往虚拟机管理页面查看`)
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  if (imageFormRef.value) {
    imageFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!imageFormRef.value) return
  
  await imageFormRef.value.validate((valid) => {
    if (valid) {
      if (editOr.value) {
        imageForm.image_id = imageForm.id
        delete imageForm.id
        editMirror(imageForm).then(res => {
          if (res.data.code == 200) {
            dialogVisible.value = false
            ElMessage.success('编辑成功')
            fetchImageList()
          } else {
            ElMessage.error(res.data.msg || '编辑失败')
          }
        }).catch(() => {
          ElMessage.error('编辑失败')
        })
      } else {
        addVirtualMirror(imageForm).then(res => {
          if (res.data.code == 200) {
            dialogVisible.value = false
            ElMessage.success('添加成功')
            fetchImageList()
          } else {
            ElMessage.error(res.data.msg || '添加失败')
          }
        }).catch((e) => {
          ElMessage.error('添加失败')
        })
      }
    }
  })
}

// 素材库相关
const getpicList = () => {
  getFileList(picPagin).then(res => {
    picList.value = res.data.data
    total.value = res.data.count
  }).catch(() => {
    ElMessage.error('获取图片列表失败')
  })
}

const selectImage = (index, data) => {
  currentIndex.value = index
}

const CurrentPageChange = async newPage => {
  picPagin.page = newPage
  getpicList()
}

const PageSizeChange = async newSize => {
  picPagin.count = newSize
  getpicList()
}

const tochoose = () => {
  if (currentIndex.value != null) {
    imageForm.image_ico = `/v1/attachment/get_attachment?aid=${picList.value[currentIndex.value].attachment_id}`
    picSwitch.value = false
  }
}

// 复制粘贴相关
const copytext = ref({})
const copyit = async () => {
  copytext.value = JSON.parse(JSON.stringify(imageForm))
  ElMessage.success('复制成功')
  await navigator.clipboard.writeText(JSON.stringify(copytext.value))
}

const getit = async () => {
  try {
    const text = await navigator.clipboard.readText()
    Object.keys(JSON.parse(text)).forEach(key => {
      imageForm[key] = JSON.parse(text)[key]
    })
    imageForm.server_id = nowserver_id.value
    ElMessage.success('粘贴成功')
    return text
  } catch (err) {
    ElMessage.error('无法读取剪贴板内容,请检查获取到的格式')
  }
}

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

<style scoped>
.vm-images-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 8px;
}

.table-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.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;
  -webkit-box-orient: vertical;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 0 16px 16px;
}

.empty-tip {
  margin-top: 50px;
}

.image-icon-upload {
  display: flex;
  align-items: center;
  gap: 16px;
}

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

.upload-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.el-upload__tip {
  line-height: 1.5;
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

/* 素材库样式 */
.piclist {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin: 16px 0;
}

.piclist .icon {
  width: 100px;
  height: 110px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  background-color: #fff;
}

.piclist .icon:hover {
  cursor: pointer;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.piclist .icon img {
  width: 60px;
  height: 60px;
  object-fit: contain;
  border-radius: 4px;
}

.piclist .icon .tit {
  margin-top: 10px;
  font-size: 13px;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #606266;
}

.piclist .choose {
  border-color: #409EFF;
  box-shadow: 0 0 12px rgba(64, 158, 255, 0.6);
  background-color: #ecf5ff;
}

/* 对话框样式优化 */
:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 16px 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table__row:hover) {
  background-color: #ecf5ff !important;
}

:deep(.el-button--link) {
  padding: 4px 8px;
}

:deep(.el-button--link):hover {
  background-color: #f0f2f5;
  border-radius: 4px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .image-info-cell {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .image-info-content {
    margin-left: 0;
    margin-top: 12px;
    width: 100%;
  }
  
  .table-image-logo {
    width: 60px;
    height: 60px;
  }
}
</style>