<template>
  <el-container>
    <el-header>
      <h1>回收站</h1>
      <el-button type="danger" @click="handleCleanTrash" :disabled="trashItems.length === 0">清空回收站</el-button>
      <el-button @click="goBack">返回首页</el-button>
    </el-header>
    <el-main>
      <el-table :data="trashItems" style="width: 100%">
        <el-table-column prop="title" label="名称"></el-table-column>
        <el-table-column prop="type" label="类型">
          <template #default="scope">
            <el-tag :type="scope.row.type === 'group' ? 'success' : 'primary'">
              {{ scope.row.type === 'group' ? '分类' : '笔记' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deletedAt" label="删除时间"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleRestore(scope.row)">恢复</el-button>
            <el-button size="small" type="danger" @click="handleDeletePermanently(scope.row)">永久删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="trashItems.length === 0" description="回收站是空的"></el-empty>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getTrash, restoreTrashItem, permanentlyDeleteItem, cleanTrash } from '@/api/CommonApi.js';

const router = useRouter();
const trashItems = ref([]);

const fetchTrashItems = async () => {
  try {
    const response = await getTrash();
    trashItems.value = response.data || [];
  } catch (error) {
    ElMessage.error('获取回收站内容失败');
  }
};

const handleRestore = async (item) => {
  try {
    await restoreTrashItem(item.id);
    ElMessage.success('恢复成功');
    fetchTrashItems();
  } catch (error) {
    ElMessage.error('恢复失败');
  }
};

const handleDeletePermanently = async (item) => {
  await ElMessageBox.confirm('确定要永久删除此项目吗？此操作不可恢复。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });
  try {
    await permanentlyDeleteItem(item.id);
    ElMessage.success('已永久删除');
    fetchTrashItems();
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

const handleCleanTrash = async () => {
  await ElMessageBox.confirm('确定要清空回收站吗？此操作不可恢复。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });
  try {
    await cleanTrash();
    ElMessage.success('回收站已清空');
    fetchTrashItems();
  } catch (error) {
    ElMessage.error('清空失败');
  }
};

const goBack = () => {
  router.push('/home');
};

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

<style scoped>
.el-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>