<template>
    <el-scrollbar class="blank-layout-scrollbar">
        <div class="layout-spacer layout-spacer--top">11212</div>
        <pro-table
            :data-source="tableData"
            :columns="columns"
            :show-header="true"
            :show-pagination="true"
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            :loading="loading"
            :editable="editable"
            :height="'480'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            @update="handleUpdate"
            @delete="handleDelete"
        >
            <template #header>
                <div class="table-custom-header">
                    <h3>用户列表</h3>
                    <el-button :type="editable ? 'success' : 'default'" @click="toggleEditable">
                        {{ editable ? '退出编辑' : '进入编辑' }}
                    </el-button>
                </div>
            </template>
            <template #status="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                    {{ row.status === 'active' ? '激活' : '未激活' }}
                </el-tag>
            </template>
        </pro-table>
        <div class="layout-spacer layout-spacer--bottom">11212</div>
    </el-scrollbar>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElTag, ElButton, ElMessage, ElScrollbar } from '@deppon/deppon-ui';
import { ProTable } from '@deppon/deppon-template';
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(50);
const total = ref(0);
const editable = ref(true);

// 基础表格数据
const tableData = ref([]);

// 基础列配置（可编辑）
const columns = ref([
    { prop: 'id', label: 'ID', width: 80, hideInSearch: true },
    {
        prop: 'name',
        label: '姓名',
        width: 120,
        valueType: 'text',
        fieldProps: {
            placeholder: '请输入姓名',
        },
        rules: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        hideInSearch: true,
    },
    {
        prop: 'age',
        label: '年龄',
        width: 100,
        valueType: 'text',
        fieldProps: {
            placeholder: '请输入年龄',
        },
        hideInSearch: true,
    },
    {
        prop: 'email',
        label: '邮箱',
        minWidth: 200,
        valueType: 'text',
        fieldProps: {
            placeholder: '请输入邮箱',
        },
        rules: [
            { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
        ],
        hideInSearch: true,
    },
    {
        prop: 'status',
        label: '状态',
        width: 100,
        valueType: 'select',
        fieldProps: {
            options: [
                { label: '激活', value: 'active' },
                { label: '未激活', value: 'inactive' },
            ],
            placeholder: '请选择状态',
        },
        slots: { default: 'status' },
        hideInSearch: true,
    },
]);

// 模拟数据请求
const fetchData = async () => {
    loading.value = true;
    try {
        // 模拟 API 请求延迟
        await new Promise(resolve => setTimeout(resolve, 500));

        // 模拟数据
        const allData = Array.from({ length: 100 }, (_, index) => ({
            id: index + 1,
            name: `用户${index + 1}`,
            age: 20 + Math.floor(Math.random() * 30),
            email: `user${index + 1}@example.com`,
            status: Math.random() > 0.5 ? 'active' : 'inactive',
        }));

        total.value = allData.length;

        // 模拟分页
        const start = (currentPage.value - 1) * pageSize.value;
        const end = start + pageSize.value;
        tableData.value = allData.slice(start, end);
    } catch (error) {
        ElMessage.error('数据加载失败');
        console.error(error);
    } finally {
        loading.value = false;
    }
};

// 分页大小改变
const handleSizeChange = val => {
    pageSize.value = val;
    currentPage.value = 1; // 重置到第一页
    fetchData();
};

// 当前页改变
const handleCurrentChange = val => {
    currentPage.value = val;
    fetchData();
};

const handleUpdate = (updatedRow, index) => {
    tableData.value[index] = { ...updatedRow };
    ElMessage.success(`已更新: ${updatedRow.name || '未命名'}`);
    console.log('更新行:', updatedRow, '索引:', index);
};

const handleDelete = (row, index) => {
    tableData.value.splice(index, 1);
    ElMessage.success(`已删除: ${row.name || '未命名'}`);
    console.log('删除行:', row, '索引:', index);
};

// 切换编辑模式
const toggleEditable = () => {
    editable.value = !editable.value;
    ElMessage.success(editable.value ? '已进入编辑模式' : '已退出编辑模式');
};

// 初始化加载数据
onMounted(() => {
    fetchData();
});
</script>

<style scoped lang="less">
.blank-layout-scrollbar {
    width: 100%;
    height: 100%;
    padding: 15px 0 0 15px;
    box-sizing: border-box;
    position: relative;
    z-index: 1;
    overflow-x: hidden;

    :deep(.el-scrollbar__wrap) {
        overflow-x: hidden;
    }

    :deep(.el-scrollbar__view) {
        height: 100%;
    }

    :deep(.el-scrollbar__bar) {
        z-index: 10;
    }
}

.layout-spacer {
    background-color: var(--el-fill-color-light, #f5f7fa);
    color: var(--el-text-color-secondary, #909399);

    &--top {
        height: 200px;
    }

    &--bottom {
        height: 30px;
    }
}

.table-custom-header {
    padding: 16px;
    background-color: var(--el-fill-color-light, #f5f7fa);
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    h3 {
        margin: 0;
        color: var(--el-text-color-primary, #303133);
        font-size: 16px;
        font-weight: 600;
    }
}
</style>
