<template>
  <div class="container-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="selectedServerId" placeholder="请选择服务器" @change="handleServerChange" style="width: 200px">
                <el-option 
                  v-for="server in serverList" 
                  :key="server.server_id" 
                  :label="server.name" 
                  :value="server.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>
              <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="handleRefresh">
              <el-icon><refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </div>

      <!-- 当前服务器镜像列表 -->
      <div v-if="currentServer" class="table-section">
        <div class="server-header">
          <h3>{{ currentServer.name }}</h3>
          <div class="server-actions">
            <el-button type="primary" @click="handleAdd(currentServer.server_id)">
              <el-icon><plus /></el-icon>上传镜像
            </el-button>
            <el-button type="success" @click="TosyncMirror(currentServer.server_id)">
              <el-icon><refresh /></el-icon>同步镜像
            </el-button>
          </div>
        </div>

        <el-table
          :data="currentMirrorList"
          style="width: 100%"
          row-key="image_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="scope.row.image_ico ? mainUrl + scope.row.image_ico : '/path/to/default-image.png'" class="table-image-logo" />
                <div class="image-info-content">
                  <div class="image-name-row">
                    <span class="table-image-name">{{ scope.row.name }}</span>
                    <el-tag size="small">{{ scope.row.tag || '无标签' }}</el-tag>
                  </div>
                  <div class="image-desc-row">{{ scope.row.description || '暂无描述' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="show_name" label="展示名称" width="150">
            <template #default="scope">
              {{ scope.row.show_name || '未设置' }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.state == 0 ? 'primary' : scope.row.state == 1 ? 'success' : 'danger'">
                {{ scope.row.state == 0 ? '上传中' : scope.row.state == 1 ? '上传成功' : '上传失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="150" align="center" />
          <el-table-column label="操作" width="280" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleCreateContainer(scope.row)">
                <el-icon><ship /></el-icon>创建容器
              </el-button>
              <el-button type="info" link @click="handleView(scope.row)">
                <el-icon><view /></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
          v-model:current-page="currentPage"
          :page-size="10"
          :total="total"
          layout="prev, pager, next"
          @current-change="handleCurrentPageChange"
          background
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 镜像详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="镜像详情"
      width="800px"
      :before-close="handleDialogClose"
    >
      <div v-if="currentImage.image_id" class="image-detail">
        <div class="detail-header">
          <img :src="currentImage.image_ico ? mainUrl + currentImage.image_ico : '/path/to/default-image.png'" class="detail-logo" />
          <div class="detail-title">
            <h2>{{ currentImage.name }}</h2>
            <el-tag>{{ currentImage.tag || '无标签' }}</el-tag>
          </div>
        </div>
        
        <el-divider />
        
        <div class="detail-info">
          <div class="info-group">
            <div class="info-item">
              <span class="label">镜像ID:</span>
              <span class="value">{{ currentImage.image_id }}</span>
            </div>
            <div class="info-item">
              <span class="label">展示名称:</span>
              <span class="value">{{ currentImage.show_name || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态:</span>
              <span class="value">
                <el-tag :type="currentImage.state == 0 ? 'primary' : currentImage.state == 1 ? 'success' : 'danger'">
                  {{ currentImage.state == 0 ? '上传中' : currentImage.state == 1 ? '上传成功' : '上传失败' }}
                </el-tag>
              </span>
            </div>
          </div>
          <div class="info-group">
            <div class="info-item" v-if="currentImage.proxy">
              <span class="label">网络配置:</span>
              <span class="value">已配置</span>
            </div>
            <div class="info-item" v-if="currentImage.env">
              <span class="label">环境变量:</span>
              <span class="value">已配置</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间:</span>
              <span class="value">{{ currentImage.created_at || '未知' }}</span>
            </div>
          </div>
        </div>
        
        <el-divider content-position="left">描述</el-divider>
        
        <div class="detail-description">
          {{ currentImage.description || '暂无描述信息' }}
        </div>
      </div>
    </el-dialog>

    <!-- 添加/编辑镜像对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="editOr ? '编辑镜像' : '上传镜像'"
      width="45%"
      :before-close="handleDialogClose"
    >
      <el-form :model="form" label-width="120px" :rules="rules" ref="imageFormRef">
        <el-form-item label="镜像名称" prop="name">
          <div style="display: flex">
            <el-input v-model="form.name" placeholder="请输入镜像名称" />
            <span style="margin: 0 10px; line-height: 32px;">:</span>
            <el-input v-model="form.tag" placeholder="请输入镜像版本" />
          </div>
        </el-form-item>
        <el-form-item label="展示名称" prop="show_name">
          <el-input v-model="form.show_name" placeholder="请输入展示名称" />
        </el-form-item>
        <el-form-item label="分类" prop="image_class_id" v-if="editOr == true">
          <el-select v-model="form.image_class_id" placeholder="请选择分类">
              <el-option v-for="item in options" :key="item.class_id" :label="item.name" :value="item.class_id">
              </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图标">
          <div class="image-icon-upload">
            <img v-if="form.image_ico" :src="mainUrl + form.image_ico" class="preview-icon" />
            <el-upload
              ref="uploadRef"
              class="image-upload"
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :limit="1"
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip" v-if="selectedFileName">
                  已选择: {{ selectedFileName }}
                </div>
              </template>
            </el-upload>
            <el-button @click="picSwitch = true; getpicList()">从素材库选择</el-button>
          </div>
        </el-form-item>
        <el-form-item label="套餐" prop="plan_id">
          <el-select v-model="form.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="网络配置">
          <div>
            <el-button type="primary" @click="netVisible = true">
              <el-icon><plus /></el-icon>添加网络
            </el-button>
          </div>
          <el-table :data="prot_data" border style="width: 100%; margin-top: 10px" v-if="prot_data.length > 0">
            <el-table-column label="网络类型" prop="type">
              <template #default="scope">
                {{ scope.row.type === 'nginx' ? '建站服务' : 
                   scope.row.type === 'port_forward' ? '自定义端口' : 
                   scope.row.type === 'floating_ip' ? '独立IP' : scope.row.type }}
              </template>
            </el-table-column>
            <el-table-column label="容器端口" prop="container_port" />
            <el-table-column label="域名" prop="domain" />
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button type="danger" link @click="delProt(scope.$index)">
                  <el-icon><delete /></el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="镜像变量">
          <div>
            <el-button type="primary" @click="envSwitch = true">
              <el-icon><plus /></el-icon>添加环境变量
            </el-button>
          </div>
          <el-table :data="envList" border style="width: 100%; margin-top: 10px" v-if="envList.length > 0">
            <el-table-column label="变量名" prop="key" />
            <el-table-column label="变量值" prop="value" />
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button type="danger" link @click="delenv(scope.$index)">
                  <el-icon><delete /></el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="镜像描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入镜像描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="editOr" type="success" @click="reloadMirror(form)">
            <el-icon><refresh /></el-icon>重新拉取镜像
          </el-button>
 
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 网络配置对话框 -->
    <el-dialog v-model="netVisible" title="网络配置" width="500px">
      <el-form :model="netform" label-width="120px">
        <el-form-item label="网络类型">
          <el-select v-model="netform.type" placeholder="请选择网络类型" style="width: 100%">
            <el-option v-for="item in network_list" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="netform.type == 'port_forward' || netform.type == 'nginx'" label="容器内部端口号">
          <el-input v-model="netform.container_port" type="number" :min="1" :max="65535" placeholder="端口号应在1-65535之间" />
        </el-form-item>
        <el-form-item v-if="netform.type == 'nginx'" label="域名">
          <el-input v-model="netform.domain" placeholder="请输入域名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="netVisible = false">取消</el-button>
          <el-button type="primary" @click="addnet(netform)">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 环境变量对话框 -->
    <el-dialog v-model="envSwitch" title="环境变量" width="500px">
      <el-form :model="envItem" label-width="120px">
        <el-form-item label="变量名">
          <el-input v-model="envItem.key" placeholder="请输入变量名" />
        </el-form-item>
        <el-form-item label="变量值">
          <el-input v-model="envItem.value" placeholder="请输入变量值" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="envSwitch = false">取消</el-button>
          <el-button type="primary" @click="addenv(envItem)">确认</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, computed } from 'vue'
import { 
  Plus, Refresh, Search, View, Download, Delete, 
  Ship, CopyDocument, Edit, DocumentCopy
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getServer } from '@/utils/acs/server'
import { 
  getMirrorList, uploadMirror, editMirror, delMirror, 
  syncMirror, getUserMirrorList, pullMirror, getImageTypeList
} from '@/utils/acs/mirror'
import { uploadFile, getFileList } from '@/utils/acs/message'
// import { message } from '@/utils/acs/message'
import { mainUrl } from '@/utils/request'
import { getServerPlan } from '@/utils/acs/server'

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

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  handleSearch()
}
const options = ref([])

// 表格数据
const loading = ref(false)
const imageData = ref([])

// 服务器和镜像数据
const serverList = ref([])
const selectedServerId = ref(null)
const currentServer = ref(null)
const currentMirrorList = ref([])
const currentPage = ref(1)
const total = ref(0)

// 对话框相关
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const netVisible = ref(false)
const envSwitch = ref(false)
const picSwitch = ref(false)
const currentImage = ref({})
const editOr = ref(false)
const selectedFileName = ref(null)

// 表单对象和规则
const imageFormRef = ref(null)
const uploadRef = ref(null)
const planlist = ref([])

const form = reactive({
  name: '',
  server_type: 'dockerContainer',
  show_name: '',
  description: '',
  plan_id: '',
  proxy: '',
  image_ico: '',
  tag: '',
  server_id: '',
  env: '',
  class_id: '',
  class_name: ''
})

const rules = {
  name: [{ required: true, message: '请输入镜像名称', trigger: 'blur' }],
  show_name: [{ required: true, message: '请输入展示名称', trigger: 'blur' }],
  tag: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  plan_id: [{ required: true, message: '请选择套餐', trigger: 'change' }],
  description: [{ required: true, message: '请输入镜像描述', trigger: 'blur' }],
  class_id: [{ required: false, message: '请输入分类ID', trigger: 'blur' }],
  class_name: [{ required: false, message: '请输入分类名称', trigger: 'blur' }]
}

const netform = reactive({
  type: "",
  container_id: "",
  server_port: "",
  container_port: "",
  domain: "",
  floating_ip: ""
})

const network_list = [
  {
    value: "nginx",
    name: "建站服务"
  },
  {
    value: "port_forward",
    name: "自定义端口"
  },
  {
    value: "floating_ip",
    name: "独立ip"
  }
]

const prot_data = ref([])
const nowserver_id = ref('')

// 镜像类型标签
const getTagType = (type) => {
  const map = {
    application: 'primary',
    base: 'success',
    database: 'danger',
    development: 'warning',
    other: 'info'
  }
  return map[type] || 'info'
}

const getTypeText = (type) => {
  const map = {
    application: '应用镜像',
    base: '基础镜像',
    database: '数据库镜像',
    development: '开发环境',
    other: '其他'
  }
  return map[type] || '未知'
}

// 镜像来源文本
const getSourceText = (source) => {
  const map = {
    official: '官方镜像',
    user: '用户上传',
    thirdparty: '第三方'
  }
  return map[source] || '未知'
}

// 获取服务器列表和默认选中第一个服务器
const fetchServerList = () => {
  loading.value = true
  getServer(1, 100, '').then((res) => {
    if (res.data && res.data.code === 200 && res.data.data && res.data.data.length > 0) {
      serverList.value = res.data.data.map(item => ({ server_id: item.server_id, name: item.name }))
      
      // 默认选中第一个服务器
      if (serverList.value.length > 0) {
        selectedServerId.value = serverList.value[0].server_id
        currentServer.value = serverList.value[0]
        console.log('已选中服务器:', currentServer.value)
        fetchMirrorList(selectedServerId.value)
      } else {
        loading.value = false
        ElMessage.warning('没有可用的服务器')
      }
    } else {
      loading.value = false
      ElMessage.error('获取服务器列表失败或服务器列表为空')
      console.error('服务器列表接口返回:', res.data)
    }
  }).catch((err) => {
    console.error('获取服务器列表失败:', err)
    loading.value = false
    ElMessage.error('获取服务器列表失败')
  })
}

// 获取镜像列表
const fetchMirrorList = (serverId) => {
  if (!serverId) {
    console.error('服务器ID为空，无法获取镜像列表')
    loading.value = false
    return
  }
  
  loading.value = true
  console.log('获取镜像列表，服务器ID:', serverId)
  
  getUserMirrorList({ 
    server_id: serverId, 
    count: 10, 
    page: currentPage.value, 
    key: searchForm.name || '' 
  })
    .then(res => {
      if (res.data && res.data.code === 200 && res.data.data) {
        currentMirrorList.value = res.data.data
        total.value = res.data.count || 0
        console.log('获取到镜像列表:', currentMirrorList.value.length, '条数据')
      } else {
        currentMirrorList.value = []
        total.value = 0
        console.log('获取到空镜像列表或接口返回错误:', res.data)
      }
      loading.value = false
    })
    .catch(err => {
      console.error('获取镜像列表失败:', err)
      currentMirrorList.value = []
      total.value = 0
      loading.value = false
    })
}

// 处理服务器变更
const handleServerChange = (serverId) => {
  console.log('服务器变更为:', serverId)
  currentPage.value = 1
  currentServer.value = serverList.value.find(server => server.server_id === serverId)
  fetchMirrorList(serverId)
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchMirrorList(selectedServerId.value)
}

// 刷新数据
const handleRefresh = () => {
  fetchMirrorList(selectedServerId.value)
}

// 处理页码变化
const handleCurrentPageChange = (newPage) => {
  currentPage.value = newPage
  fetchMirrorList(selectedServerId.value)
}

// 添加镜像
const handleAdd = (serverId) => {
  toLoad(serverId)
}

// 查看镜像详情
const handleView = (row) => {
  currentImage.value = { ...row }
  detailDialogVisible.value = true
}

// 下载镜像
const handleDownload = (row) => {
  ElMessage.success(`开始下载镜像: ${row.name}:${row.tag}`)
}

// 删除镜像
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除镜像"${row.name}"吗？删除后不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    deleteMirror(row)
  }).catch(() => {})
}

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

// 复制命令
const copyCommand = (command) => {
  navigator.clipboard.writeText(command).then(() => {
    ElMessage.success('命令已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 加载编辑数据
const toLoad = async (data) => {
  formDialogVisible.value = true
  editOr.value = false
  prot_data.value = []
  envList.value = []
  Object.keys(form).forEach(key => {
    form[key] = null
  })
  form.server_id = data
  nowserver_id.value = data
  let res = await getServerPlan({server_id:data,count:10})
  planlist.value = res.data.data.map(item => {
    return {
      name: item.name,
      id: item.plan_id,
    }
  })
}

// 处理文件变更
const handleFileChange = (file) => {
  const fileObj = file.raw || file
  if (fileObj) {
    selectedFileName.value = fileObj.name // 显示文件名
    uploadFile({ file: fileObj }).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success('上传成功')
        selectedFileName.value = null
        form.image_ico = '/v1/attachment/get_attachment?aid=' + res.data.data.attachment_id
        // 清空文件列表，允许再次选择文件
        if (uploadRef.value) {
          uploadRef.value.clearFiles()
        }
      } else {
        ElMessage.error(res.data.message || '上传失败')
        // 失败时也清空文件列表
        if (uploadRef.value) {
          uploadRef.value.clearFiles()
        }
        selectedFileName.value = null
      }
    }).catch((error) => {
      console.error('上传文件失败:', error)
      ElMessage.error('上传文件失败，请重试')
      // 异常时也清空文件列表
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
      selectedFileName.value = null
    })
  } else {
    selectedFileName.value = null // 如果用户取消选择，清空文件名
  }
}

// 网络配置
const addnet = (data) => {
  const entries = Object.entries(data)
  // 过滤掉属性值为空字符串的属性
  const filteredEntries = entries.filter(([key, value]) => value !== "")
  // 将过滤后的数组转换回对象
  const filteredObj = Object.fromEntries(filteredEntries)
  prot_data.value.push(filteredObj)
  form.proxy = JSON.stringify(prot_data.value)
  Object.keys(netform).forEach(key => {
    netform[key] = ''
  })
  ElMessage.success('添加成功！')
  netVisible.value = false
}

const delProt = (index) => {
  prot_data.value.splice(index, 1)
}
// 获取镜像分类列表
const fetchCategoryList = async (serverId) => {
  try {
    const response = await getImageTypeList(serverId)
    if (response.data.code === 200) {
      options.value = response.data.data || []
    } else {
      ElMessage.error('获取镜像分类失败：' + response.data.message)
    }
  } catch (error) {
    console.error('获取镜像分类出错：', error)
    ElMessage.error('获取镜像分类列表失败')
  }
}

// 编辑镜像
const handleEdit = async (data) => {
  try {
    let res = await getServerPlan({server_id: data.server_id,count: 10})
    if (res.data && res.data.data) {
      planlist.value = res.data.data.map(item => {
        return {
          name: item.name,
          id: item.plan_id,
        }
      })
      await fetchCategoryList(data.server_id)
      
    } else {
      planlist.value = []
    }
    
    editOr.value = true
    formDialogVisible.value = true
    
    // 清空表单
    Object.keys(form).forEach(key => {
      form[key] = null
    })
    
    // 填充表单数据
    for (const key in data) {
      if (data.hasOwnProperty(key)) {
        form[key] = data[key]
      }
    }
    
    // 处理网络配置
    prot_data.value = []
    if (data.proxy) {
      try {
        prot_data.value = JSON.parse(data.proxy)
      } catch (e) {
        console.error('解析网络配置失败:', e)
        ElMessage.warning('网络配置格式错误')
      }
    }
    
    // 处理环境变量
    envList.value = []
    if (data.env) {
      try {
        let obj = JSON.parse(data.env)
        envList.value = Object.entries(obj).map(([key, value]) => ({ key, value }))
      } catch (e) {
        console.error('解析环境变量失败:', e)
        ElMessage.warning('环境变量格式错误')
      }
    }
  } catch (err) {
    console.error('加载编辑数据失败:', err)
    ElMessage.error('加载数据失败')
  }
}

// 删除镜像
const deleteMirror = (data) => {
  delMirror({ server_id: data.server_id, image_id: data.image_id }).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success('删除成功')
      currentMirrorList.value = []
      fetchMirrorList(selectedServerId.value)
    }
  })
}

// 同步镜像
const TosyncMirror = (data) => {
  loading.value = true
  syncMirror(data).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success('同步成功')
      currentMirrorList.value = []
      fetchMirrorList(selectedServerId.value)
    }
  }).finally(() => {
    loading.value = false
  })
}

// 镜像环境
const envItem = reactive({
  key: '',
  value: ''
})
const envList = ref([])

const addenv = (data) => {
  envList.value.push({ ...data })
  ElMessage.success('添加成功')
  envSwitch.value = false
  envItem.key = ''
  envItem.value = ''
}

const delenv = (index) => {
  envList.value.splice(index, 1)
  ElMessage.success('删除成功')
}

// 复制粘贴配置
const copytext = ref({})
const copyit = async () => {
  copytext.value = JSON.parse(JSON.stringify(form))
  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 => {
      form[key] = JSON.parse(text)[key]
    })
    form.server_id = nowserver_id.value
    ElMessage.success('粘贴成功')
    return text
  } catch (err) {
    ElMessage.error('无法读取剪贴板内容,请检查获取到的格式')
  }
}

// 选择图片
const picPagin = reactive({
  count: 10,
  page: 1,
  key: '',
  user_type: 1
})
const picList = ref([])

// 重新拉取镜像
const reloadMirror = (data) => {
  pullMirror({ server_id: data.server_id, image_id: data.image_id }).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg || '重新拉取成功')
      fetchMirrorList(selectedServerId.value)
      formDialogVisible.value = false
    }
  })
}

const getpicList = () => {
  getFileList(picPagin).then(res => {
    picList.value = res.data.data
    total.value = res.data.count
  })
}

const currentIndex = ref(null)
const selectImage = (index) => {
  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) {
    form.image_ico = `/v1/attachment/get_attachment?aid=${picList.value[currentIndex.value].attachment_id}`
    picSwitch.value = false
  }
}

// 上传镜像
const submitForm = async () => {
  if (!imageFormRef.value) return
  
  await imageFormRef.value.validate(async (valid) => {
    if (valid) {
      await uploadImage()
    }
  })
}

// 上传镜像
const uploadImage = async () => {
  form.proxy = JSON.stringify(prot_data.value)
  let env = envList.value.reduce((acc, cur) => {
    acc[cur.key] = cur.value
    return acc
  }, {})
  form.env = JSON.stringify(env)
  form.class_id = form.image_class_id
  
  if (editOr.value == true) {
    let res = await editMirror(form)
    if (res.data.code == 200) {
      formDialogVisible.value = false
      ElMessage.success('编辑成功')
      currentMirrorList.value = []
      fetchMirrorList(selectedServerId.value)
    }
  } else {
    let res = await uploadMirror(form)
    if (res.data.code == 200) {
      formDialogVisible.value = false
      ElMessage.success('上传成功')
      currentMirrorList.value = []
      fetchMirrorList(selectedServerId.value)
    }
  }
}

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

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

<style scoped>
.container-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;
}

.server-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e1e8ed;
  background: #fff;
}

.server-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.server-header h3::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #409EFF;
  margin-right: 10px;
  border-radius: 2px;
}

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

.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;
}

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

/* 详情对话框样式 */
.image-detail {
  padding: 20px;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.detail-logo {
  width: 80px;
  height: 80px;
  margin-right: 24px;
  border-radius: 8px;
  object-fit: contain;
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  padding: 8px;
}

.detail-title {
  flex: 1;
}

.detail-title h2 {
  margin: 0 0 12px;
  color: #303133;
}

.detail-info {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 24px;
  background-color: #f8f9fc;
  padding: 16px;
  border-radius: 8px;
}

.info-group {
  flex: 1;
  min-width: 280px;
  margin-bottom: 12px;
}

.info-item {
  margin-bottom: 12px;
  display: flex;
}

.info-item .label {
  font-weight: 600;
  margin-right: 12px;
  width: 100px;
  color: #606266;
}

.info-item .value {
  color: #303133;
}

.detail-description {
  margin-bottom: 24px;
  line-height: 1.8;
  color: #606266;
  background-color: #f8f9fc;
  padding: 16px;
  border-radius: 8px;
}

.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;
}

/* 素材库样式 */
.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-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>