<template>
  <div class="gallery-page">
    <div class="gallery-container">
      <!-- 搜索区域 -->
      <div class="search-card">
        <el-form :model="queryParams" :inline="true">
          <el-form-item label="图片名称:">
            <el-input v-model="queryParams.imageName" placeholder="请输入图片名称" clearable style="width: 240px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" icon="Upload" @click="handleUpload">上传图片</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-card">
        <div class="table-header">
          <span class="table-title">图片库</span>
          <el-button icon="Refresh" circle size="small" @click="getList" />
        </div>

        <el-table v-loading="loading" :data="imageList" border>
          <el-table-column label="序号" align="center" type="index" width="80" />
          <el-table-column label="图片" align="center" width="120">
            <template #default="scope">
              <el-image
                v-if="scope.row.ossUrl"
                :src="scope.row.ossUrl"
                :preview-src-list="[scope.row.ossUrl]"
                fit="contain"
                style="width: 80px; height: 60px"
                preview-teleported
              >
                <template #error>
                  <div class="image-error">
                    <span class="error-text">加载失败</span>
                  </div>
                </template>
              </el-image>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="图片名称" align="center" prop="imageName" min-width="200" show-overflow-tooltip />
          <el-table-column label="图片地址" align="center" prop="ossUrl" min-width="300">
            <template #default="scope">
              <el-link v-if="scope.row.ossUrl" type="primary" :href="scope.row.ossUrl" target="_blank" :underline="false">
                {{ scope.row.ossUrl }}
              </el-link>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-link type="primary" @click="handleEdit(scope.row)">编辑</el-link>
              <el-link type="danger" @click="handleDelete(scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="handlePagination"
        />
      </div>
    </div>

    <!-- 上传图片对话框 -->
    <el-dialog v-model="uploadDialog.visible" title="上传图片" width="500px" append-to-body>
      <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="100px">
        <el-form-item label="图片名称" prop="imageName">
          <el-input v-model="uploadForm.imageName" placeholder="请输入图片名称" />
        </el-form-item>
        <el-form-item label="图片" prop="ossId">
          <upload-image v-model="uploadForm.ossId" :limit="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitUpload">确 认</el-button>
        <el-button @click="uploadDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialog.visible" title="编辑图片" width="500px" append-to-body>
      <div class="edit-image-container">
        <upload-image v-model="editForm.ossId" :limit="1" />
      </div>
      <template #footer>
        <el-button type="primary" @click="submitEdit">确 认</el-button>
        <el-button @click="editDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OperationGallery" lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import type { FormInstance } from 'element-plus';
import { listUploadImgLib, getUploadImgLib, addUploadImgLib, updateUploadImgLib, delUploadImgLib } from '@/api/system/uploadImgLib';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 查询参数
const queryParams = reactive({
  imageName: '',
  platformCode: 'opm',
  pageNum: 1,
  pageSize: 10
});

// 列表数据
const imageList = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);

// 上传对话框
const uploadDialog = reactive({
  visible: false
});
const uploadFormRef = ref<FormInstance>();
const uploadForm = ref({
  imageName: '',
  ossId: '',
  platformCode: 'opm'
});
const uploadRules = {
  imageName: [{ required: true, message: '请输入图片名称', trigger: 'blur' }],
  ossId: [{ required: true, message: '请上传图片', trigger: 'change' }]
};

// 编辑对话框
const editDialog = reactive({
  visible: false
});
const editForm = ref({
  id: undefined as number | undefined,
  ossId: '',
  platformCode: 'opm'
});

// 查询列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await listUploadImgLib(queryParams);
    imageList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('加载列表失败', error);
    proxy?.$modal.msgError('加载列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 分页
const handlePagination = (paging: { page: number; limit: number }) => {
  queryParams.pageNum = paging.page;
  queryParams.pageSize = paging.limit;
  getList();
};

// 重置
const resetQuery = () => {
  queryParams.imageName = '';
  handleQuery();
};

// 上传图片
const handleUpload = () => {
  uploadForm.value = {
    imageName: '',
    ossId: '',
    platformCode: 'opm'
  };
  uploadFormRef.value?.resetFields();
  uploadDialog.visible = true;
};

// 提交上传
const submitUpload = async () => {
  const valid = await uploadFormRef.value?.validate();
  if (!valid) return;

  try {
    await addUploadImgLib(uploadForm.value);
    proxy?.$modal.msgSuccess('上传成功');
    uploadDialog.visible = false;
    getList();
  } catch (error) {
    console.error('上传失败', error);
    proxy?.$modal.msgError('上传失败');
  }
};

// 编辑
const handleEdit = async (row: any) => {
  editForm.value = {
    id: row.id,
    ossId: row.ossId || '',
    platformCode: 'opm'
  };
  editDialog.visible = true;
};

// 提交编辑
const submitEdit = async () => {
  if (!editForm.value.ossId) {
    proxy?.$modal.msgWarning('请上传图片');
    return;
  }
  try {
    await updateUploadImgLib(editForm.value);
    proxy?.$modal.msgSuccess('修改成功');
    editDialog.visible = false;
    getList();
  } catch (error) {
    console.error('修改失败', error);
    proxy?.$modal.msgError('修改失败');
  }
};

// 删除
const handleDelete = (row: any) => {
  proxy?.$modal.confirm(`是否确认删除图片"${row.imageName}"？`).then(async () => {
    try {
      await delUploadImgLib(row.id);
      proxy?.$modal.msgSuccess('删除成功');
      getList();
    } catch (error) {
      console.error('删除失败', error);
      proxy?.$modal.msgError('删除失败');
    }
  });
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.gallery-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.gallery-container {
  max-width: 1200px;
  margin: 0 auto;
}

.search-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 12px;
}

.table-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.image-error {
  width: 80px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border: 1px solid #eee;

  .error-text {
    font-size: 12px;
    color: #f56c6c;
  }
}

:deep(.el-link) {
  margin: 0 8px;
}

.edit-image-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}
</style>
