<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>单页管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddOnePage">
          <el-icon>
            <Plus />
          </el-icon>
          添加单页
        </el-button>
        <el-button @click="refresh" :loading="loading">
          <el-icon>
            <Refresh />
          </el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-divider></el-divider>

    <!-- 表格 -->
    <el-table
      :data="onePageList"
      style="width: 100%"
      border
      v-loading="loading"
      element-loading-text="正在加载..."
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      
      <el-table-column prop="title" label="标题" min-width="150" />
      
      <el-table-column prop="path" label="路由" width="200">
        <template #default="scope">
          <el-tag type="info">{{ scope.row.path }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          <div style="font-family: 'Courier New', monospace; white-space: pre-wrap;">{{ getContentPreview(scope.row.content) }}</div>
        </template>
      </el-table-column>

      <el-table-column
        prop="status"
        label="状态"
        width="100"
        align="center"
      >
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="sort"
        label="排序"
        width="100"
        align="center"
        sortable
      >
        <template #default="scope">
          <el-tag>{{ scope.row.sort || 0 }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="scope">
          <el-button size="small" text @click="handleEditOnePage(scope.row)">
            <el-icon>
              <Edit />
            </el-icon>
            <span>编辑</span>
          </el-button>

          <el-button
            size="small"
            text
            type="danger"
            @click="handleDeleteOnePage(scope.row)"
          >
            <el-icon>
              <Delete />
            </el-icon>
            <span>删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 引入编辑组件 -->
    <OnePageEdit
      v-model:visible="dialogVisible"
      :onepage="dialogOnePage"
      @save="handleOnePageSave"
      @cancel="handleOnePageCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete, Refresh } from "@element-plus/icons-vue";
import {
  getOnePages,
  createOnePage,
  editOnePage,
  deleteOnePage,
} from "@/api/onepage";
import OnePageEdit from "./components/edit.vue";

// 定义单页数据类型
interface OnePage {
  id: number;
  title: string;
  content: string;
  path: string;
  sort: number;
  status: 0 | 1;
  create_time?: string;
  update_time?: string;
  delete_time?: string;
}

// 单页列表
const onePageList = ref<OnePage[]>([]);
const loading = ref(false);

// 对话框相关变量
const dialogVisible = ref(false);
const dialogOnePage = ref<Partial<OnePage> | null>(null);

// 获取单页列表
const fetchOnePages = async () => {
  loading.value = true;
  try {
    const result = await getOnePages();
    if (result.code === 200) {
      onePageList.value = result.data || [];
    } else {
      ElMessage.error("获取单页列表失败: " + result.message);
    }
  } catch (error) {
    ElMessage.error("获取单页列表失败: " + (error as Error).message);
  } finally {
    loading.value = false;
  }
};

// 刷新界面
async function refresh() {
  loading.value = true;
  try {
    await fetchOnePages();
    ElMessage.success("刷新成功");
  } catch (error) {
    ElMessage.error("刷新失败");
  } finally {
    loading.value = false;
  }
}

// 获取内容预览
const getContentPreview = (content: string) => {
  if (!content) return '-';
  // 限制长度，保留原始格式
  return content.length > 100 ? content.substring(0, 100) + '...' : content;
};

// 添加单页
const handleAddOnePage = () => {
  dialogOnePage.value = {
    id: 0,
    title: "",
    content: "",
    path: "",
    sort: 0,
    status: 1,
  };
  dialogVisible.value = true;
};

// 编辑单页
const handleEditOnePage = (onePage: OnePage) => {
  dialogOnePage.value = { ...onePage };
  dialogVisible.value = true;
};

// 删除单页
const handleDeleteOnePage = (onePage: OnePage) => {
  ElMessageBox.confirm(
    `确定要删除单页 "${onePage.title}" 吗？`,
    "确认删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    try {
      const result = await deleteOnePage(onePage.id);
      if (result.code === 200) {
        ElMessage.success("删除成功");
        fetchOnePages();
      } else {
        ElMessage.error("删除失败: " + result.message);
      }
    } catch (error) {
      ElMessage.error("删除失败: " + (error as Error).message);
    }
  });
};

// 处理单页保存
const handleOnePageSave = async (onePage: Partial<OnePage>) => {
  try {
    const payload = { ...onePage };

    // 判断是新增还是编辑
    if (!onePage.id || onePage.id === 0) {
      // 新增单页
      const result = await createOnePage(payload as OnePage);
      if (result.code === 200) {
        ElMessage.success(result.msg || "单页添加成功");
        dialogVisible.value = false;
        await fetchOnePages();
      } else {
        ElMessage.error(result.msg || "添加失败");
      }
    } else {
      // 编辑已存在的单页
      const result = await editOnePage(onePage.id!, payload as OnePage);
      if (result.code === 200) {
        ElMessage.success(result.msg || "更新成功");
        dialogVisible.value = false;
        await fetchOnePages();
      } else {
        ElMessage.error(result.msg || "更新失败");
      }
    }
  } catch (error) {
    ElMessage.error("操作失败: " + (error as Error).message);
  }
};

// 处理单页取消
const handleOnePageCancel = () => {
  dialogVisible.value = false;
};

// 组件挂载时加载单页列表
onMounted(() => {
  fetchOnePages();
});
</script>

<style lang="less" scoped>
.container-box {
  padding: 24px;
  background-color: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
}

.header-bar h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

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

/* 表格样式 */
:deep(.el-table) {
  border-radius: 0;
  width: 100% !important;
}

:deep(.el-table__body td) {
  padding: 12px 0;
  vertical-align: middle;
}
</style>

