<template>
  <div class="image-categories-container" v-loading="loading">
    <el-card class="main-container" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" 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="searchKey"
                placeholder="搜索分类名称"
                clearable
                @input="handleSearch"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><search /></el-icon>搜索
              </el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button
              type="primary"
              @click="handleAddCategory"
              :disabled="!selectedServer"
            >
              <el-icon><plus /></el-icon>添加分类
            </el-button>
          </div>
        </div>
      </div>

      <!-- 表格 -->
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="filteredCategoryList"
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column type="index" width="60" align="center" label="序号" />
          <el-table-column prop="name" label="分类名称" min-width="150" />
          <el-table-column label="分类图标" align="center" width="100">
            <template #default="scope">
              <el-avatar
                v-if="scope.row.class_ico"
                :size="40"
                :src="scope.row.class_ico"
                fit="cover"
                style="background-color: #f5f7fa; border: 1px solid #ebeef5;"
              />
              <el-icon v-else :size="20" color="#909399"><picture /></el-icon>
            </template>
          </el-table-column>
          <el-table-column label="所属服务器" min-width="150">
            <template #default="scope">
              <el-tag type="info">{{ getServerName(scope.row.server_id) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="180" />
          <el-table-column label="操作" width="200" align="center" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="handleEditCategory(scope.row)"
              >
                <el-icon><edit /></el-icon>编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>

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

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑分类' : '添加分类'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="所属服务器" prop="server_id" v-if="!isEdit">
          <el-select
            v-model="categoryForm.server_id"
            placeholder="请选择服务器"
            style="width: 100%"
          >
            <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="分类名称" prop="class_name">
          <el-input v-model="categoryForm.class_name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类图标" prop="class_icon">
          <div class="image-icon-upload">
            <div class="preview-container">
              <img
                v-if="categoryForm.class_icon"
                :src="categoryForm.class_icon"
                class="preview-icon"
              />
              <div v-else class="empty-preview">
                <el-icon><picture /></el-icon>
              </div>
            </div>
            <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>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCategoryForm" :loading="submitLoading">
            确 定
          </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, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Picture, Edit } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { getServer } from '@/utils/acs/server'
import { getImageTypeList, createImageType, updateImageType } from '@/utils/acs/mirror'
import { uploadFile, getFileList } from '@/utils/acs/message'
import { mainUrl } from '@/utils/request'

// 数据
const loading = ref(false)
const submitLoading = ref(false)
const serverList = ref([])
const categoryList = ref([])
const selectedServer = ref('')
const searchKey = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const dialogVisible = ref(false)
const isEdit = ref(false)
const categoryFormRef = ref(null)
const selectedFileName = ref(null)

const categoryForm = reactive({
  server_id: '',
  class_id: '',
  class_name: '',
  class_icon: ''
})

const categoryRules = {
  server_id: [
    { required: true, message: '请选择所属服务器', trigger: 'change' }
  ],
  class_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

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

// 计算属性：过滤分类列表
const filteredCategoryList = computed(() => {
  if (!searchKey.value) {
    return categoryList.value
  }
  return categoryList.value.filter(item => 
    item.name && item.name.toLowerCase().includes(searchKey.value.toLowerCase())
  )
})

// 生命周期钩子
onMounted(async () => {
  await fetchServerList()
})

// 方法
const fetchServerList = async () => {
  try {
    loading.value = true
    // 获取服务器列表，这里包含了所有类型的服务器
    const response = await getServer(1, 100, '', '')
    if (response.data.code === 200) {
      serverList.value = response.data.data || []
      // 如果没有选择服务器但有服务器列表数据，默认选择第一个服务器
      if (serverList.value.length > 0 && !selectedServer.value) {
        selectedServer.value = serverList.value[0].server_id
        // 获取默认服务器的分类列表
        fetchCategoryList()
      }
    } else {
      ElMessage.error('获取服务器列表失败：' + response.data.message)
    }
  } catch (error) {
    console.error('获取服务器列表出错：', error)
    ElMessage.error('获取服务器列表出错')
  } finally {
    loading.value = false
  }
}

const fetchCategoryList = async () => {
  if (!selectedServer.value) {
    categoryList.value = []
    return
  }
  
  try {
    loading.value = true
    const response = await getImageTypeList(selectedServer.value)
    if (response.data.code === 200) {
      categoryList.value = response.data.data || []
      totalCount.value = categoryList.value.length
    } else {
      ElMessage.error('获取镜像分类失败：' + response.data.message)
    }
  } catch (error) {
    console.error('获取镜像分类出错：', error)
    ElMessage.error('获取镜像分类出错')
  } finally {
    loading.value = false
  }
}

const handleServerChange = () => {
  currentPage.value = 1
  fetchCategoryList()
}

const handleSearch = () => {
  currentPage.value = 1
}

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

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleAddCategory = () => {
  isEdit.value = false
  categoryForm.server_id = selectedServer.value
  categoryForm.class_id = ''
  categoryForm.class_name = ''
  categoryForm.class_icon = ''
  selectedFileName.value = null
  dialogVisible.value = true
}

const handleEditCategory = (row) => {
  isEdit.value = true
  categoryForm.server_id = row.server_id
  categoryForm.class_id = row.class_id
  categoryForm.class_name = row.name
  categoryForm.class_icon = row.class_ico
  selectedFileName.value = null
  dialogVisible.value = true
}


// 处理文件变更
const onFileSelected = (event) => {
  const file = event.target.files[0]
  if (file) {
    selectedFileName.value = file.name
    const isImage = /^image\/(jpeg|png|jpg|gif)$/.test(file.type)
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
      ElMessage.error('上传图标只能是图片格式!')
      return
    }
    if (!isLt2M) {
      ElMessage.error('上传图标大小不能超过 2MB!')
      return
    }

    uploadFile({ file: file }).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success('上传成功')
        categoryForm.class_icon = mainUrl + '/v1/attachment/get_attachment?aid=' + res.data.data.attachment_id
      } else {
        ElMessage.error('上传失败：' + res.data.message)
      }
    }).catch((error) => {
      console.error('上传文件出错：', error)
      ElMessage.error('上传失败')
    })
  } else {
    selectedFileName.value = null
  }
}

const submitCategoryForm = () => {
  categoryFormRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      submitLoading.value = true
      let response
      
      if (isEdit.value) {
        // 编辑分类
        response = await updateImageType(
          categoryForm.class_id,
          categoryForm.class_name,
          categoryForm.class_icon
        )
      } else {
        // 添加分类
        response = await createImageType(
          categoryForm.server_id,
          categoryForm.class_name,
          categoryForm.class_icon
        )
      }
      
      if (response.data.code === 200) {
        ElMessage.success(isEdit.value ? '更新分类成功' : '添加分类成功')
        dialogVisible.value = false
        fetchCategoryList()
      } else {
        ElMessage.error((isEdit.value ? '更新分类失败：' : '添加分类失败：') + response.data.message)
      }
    } catch (error) {
      console.error(isEdit.value ? '更新分类出错：' : '添加分类出错：', error)
      ElMessage.error(isEdit.value ? '更新分类出错' : '添加分类出错')
    } finally {
      submitLoading.value = false
    }
  })
}

// 素材库相关方法
const getpicList = () => {
  getFileList(picPagin).then(res => {
    if (res.data.code === 200) {
      picList.value = res.data.data || []
      total.value = res.data.count || 0
    } else {
      ElMessage.error('获取图片列表失败：' + res.data.message)
    }
  }).catch((error) => {
    console.error('获取图片列表出错：', error)
    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) {
    categoryForm.class_icon = `${mainUrl}/v1/attachment/get_attachment?aid=${picList.value[currentIndex.value].attachment_id}`
    picSwitch.value = false
    ElMessage.success('已选择图标')
  } else {
    ElMessage.warning('请先选择一个图标')
  }
}

const getServerName = (serverId) => {
  const server = serverList.value.find(item => item.server_id === serverId)
  return server ? server.name : '--'
}
</script>

<style scoped>
.image-categories-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-icon-upload {
  display: flex;
  align-items: center;
  gap: 16px;
}

.preview-container {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background-color: #f5f7fa;
}

.preview-icon {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.empty-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
}

.empty-preview .el-icon {
  font-size: 28px;
}

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

.el-upload__tip {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
}

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