<template>
    <div class="pro-form-group-container">
        <!-- 固定头部：锚点导航 -->
        <div class="form-anchor-wrapper">
            <el-anchor
                ref="anchorRef"
                direction="horizontal"
                :offset="70"
                :container="scrollbarRef?.wrapRef"
                select-scroll-top
                class="form-anchor"
            >
                <el-anchor-link v-for="form in formConfigs" :key="form.key" :href="`#${form.id}`">
                    {{ form.title }}
                </el-anchor-link>
            </el-anchor>
        </div>

        <!-- 中间滚动区域 -->
        <el-scrollbar ref="scrollbarRef" class="form-scrollbar">
            <div class="form-group-container">
                <el-card
                    v-for="form in formConfigs"
                    :id="form.id"
                    :key="form.key"
                    v-model:collapsed="cardCollapsed[form.key]"
                    class="form-card"
                    shadow="hover"
                    collapsible
                >
                    <template #header>
                        <div class="form-card-header" @click="toggleCardCollapse(form.key)">
                            <div class="form-card-header-left">
                                <el-icon class="collapse-icon">
                                    <ArrowUp v-if="!cardCollapsed[form.key]" />
                                    <ArrowDown v-else />
                                </el-icon>
                                <span>{{ form.title }}</span>
                            </div>
                            <el-tag
                                v-if="formStatus[form.key]"
                                :type="formStatus[form.key] === 'valid' ? 'success' : 'danger'"
                            >
                                {{ formStatus[form.key] === 'valid' ? '已校验通过' : '校验失败' }}
                            </el-tag>
                        </div>
                    </template>
                    <pro-form
                        :ref="el => (formRefs[form.key] = el)"
                        :columns="form.columns"
                        :initial-values="form.initialValues"
                        :rules="form.rules"
                        :label-width="'120px'"
                        :cols="2"
                        @validate="(prop, isValid) => handleFormValidate(form.key, prop, isValid)"
                    />
                </el-card>
            </div>
        </el-scrollbar>

        <!-- 固定底部：统一操作按钮 -->
        <div class="group-actions-wrapper">
            <div class="group-actions">
                <el-button type="primary" size="large" @click="handleSubmitAll">统一提交</el-button>
                <el-button size="large" @click="handleValidateAll">统一校验</el-button>
                <el-button size="large" @click="handleResetAll">统一重置</el-button>
                <el-button size="large" @click="handleGetAllValues">获取所有表单值</el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
import {
    ElCard,
    ElButton,
    ElTag,
    ElMessage,
    ElMessageBox,
    ElIcon,
    ElAnchor,
    ElAnchorLink,
    ElScrollbar,
    ElAffix,
} from '@deppon/deppon-ui';
import { ArrowUp, ArrowDown } from '@deppon/deppon-ui/icons-vue';
import { ProForm } from '@deppon/deppon-template';

// 所有表单数据
const allFormData = ref({});

// 滚动条引用
const scrollbarRef = ref(null);

// 锚点组件引用
const anchorRef = ref(null);

// 表单引用（动态）
const formRefs = ref({});

// 表单校验状态（动态初始化）
const formStatus = ref({
    basic: null, // null: 未校验, 'valid': 校验通过, 'invalid': 校验失败
    detail: null,
    other: null,
});

// 卡片折叠状态（动态初始化）
const cardCollapsed = ref({
    basic: false,
    detail: false,
    other: false,
});

// 切换卡片折叠状态
const toggleCardCollapse = key => {
    cardCollapsed.value[key] = !cardCollapsed.value[key];
};

// 处理表单校验
const handleFormValidate = (key, prop, isValid) => {
    formStatus.value[key] = isValid ? 'valid' : 'invalid';
};

// 基本信息表单配置
const basicColumns = computed(() => [
    {
        name: 'name',
        label: '姓名',
        valueType: 'text',
        required: true,
        fieldProps: {
            placeholder: '请输入姓名',
        },
    },
    {
        name: 'gender',
        label: '性别',
        valueType: 'select',
        required: true,
        fieldProps: {
            options: [
                { label: '男', value: 'male' },
                { label: '女', value: 'female' },
            ],
            placeholder: '请选择性别',
        },
    },
    {
        name: 'age',
        label: '年龄',
        valueType: 'text',
        required: true,
        fieldProps: {
            placeholder: '请输入年龄',
        },
    },
    {
        name: 'phone',
        label: '手机号',
        valueType: 'text',
        required: true,
        fieldProps: {
            placeholder: '请输入手机号',
        },
    },
    {
        name: 'email',
        label: '邮箱',
        valueType: 'text',
        required: true,
        fieldProps: {
            placeholder: '请输入邮箱',
        },
    },
    {
        name: 'idCard',
        label: '身份证号',
        valueType: 'text',
        fieldProps: {
            placeholder: '请输入身份证号',
        },
    },
]);

const basicInitialValues = {
    name: '',
    gender: '',
    age: '',
    phone: '',
    email: '',
    idCard: '',
};

const basicRules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
    age: [
        { required: true, message: '请输入年龄', trigger: 'blur' },
        { pattern: /^\d+$/, message: '年龄必须是数字', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    ],
};

// 详细信息表单配置
const detailColumns = computed(() => [
    {
        name: 'address',
        label: '地址',
        valueType: 'textarea',
        required: true,
        colSpan: 24,
        fieldProps: {
            rows: 3,
            placeholder: '请输入详细地址',
        },
    },
    {
        name: 'education',
        label: '学历',
        valueType: 'select',
        required: true,
        fieldProps: {
            options: [
                { label: '小学', value: 'primary' },
                { label: '初中', value: 'junior' },
                { label: '高中', value: 'senior' },
                { label: '大专', value: 'college' },
                { label: '本科', value: 'bachelor' },
                { label: '硕士', value: 'master' },
                { label: '博士', value: 'doctor' },
            ],
            placeholder: '请选择学历',
        },
    },
    {
        name: 'profession',
        label: '职业',
        valueType: 'text',
        required: true,
        fieldProps: {
            placeholder: '请输入职业',
        },
    },
    {
        name: 'company',
        label: '公司',
        valueType: 'text',
        fieldProps: {
            placeholder: '请输入公司名称',
        },
    },
    {
        name: 'salary',
        label: '月薪',
        valueType: 'text',
        fieldProps: {
            placeholder: '请输入月薪',
        },
    },
    {
        name: 'workYears',
        label: '工作年限',
        valueType: 'text',
        fieldProps: {
            placeholder: '请输入工作年限',
        },
    },
]);

const detailInitialValues = {
    address: '',
    education: '',
    profession: '',
    company: '',
    salary: '',
    workYears: '',
};

const detailRules = {
    address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
    education: [{ required: true, message: '请选择学历', trigger: 'change' }],
    profession: [{ required: true, message: '请输入职业', trigger: 'blur' }],
};

// 其他信息表单配置
const otherColumns = computed(() => [
    {
        name: 'hobby',
        label: '兴趣爱好',
        valueType: 'textarea',
        colSpan: 24,
        fieldProps: {
            rows: 3,
            placeholder: '请输入兴趣爱好',
        },
    },
    {
        name: 'emergencyContact',
        label: '紧急联系人',
        valueType: 'text',
        fieldProps: {
            placeholder: '请输入紧急联系人',
        },
    },
    {
        name: 'emergencyPhone',
        label: '紧急联系电话',
        valueType: 'text',
        fieldProps: {
            placeholder: '请输入紧急联系电话',
        },
    },
    {
        name: 'remark',
        label: '备注',
        valueType: 'textarea',
        colSpan: 24,
        fieldProps: {
            rows: 3,
            placeholder: '请输入备注信息',
        },
    },
]);

const otherInitialValues = {
    hobby: '',
    emergencyContact: '',
    emergencyPhone: '',
    remark: '',
};

const otherRules = {
    emergencyPhone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
};

// 表单配置数组
const formConfigs = computed(() => [
    {
        key: 'basic',
        id: 'basic-form',
        title: '基本信息',
        columns: basicColumns.value,
        initialValues: basicInitialValues,
        rules: basicRules,
    },
    {
        key: 'detail',
        id: 'detail-form',
        title: '详细信息',
        columns: detailColumns.value,
        initialValues: detailInitialValues,
        rules: detailRules,
    },
    {
        key: 'other',
        id: 'other-form',
        title: '其他信息',
        columns: otherColumns.value,
        initialValues: otherInitialValues,
        rules: otherRules,
    },
]);

// 统一提交所有表单
const handleSubmitAll = async () => {
    try {
        // 先校验所有表单
        const validatePromises = formConfigs.value.map(form => formRefs.value[form.key]?.validate());
        const validateResults = await Promise.allSettled(validatePromises);

        // 检查是否有校验失败的
        const failedForms = [];
        validateResults.forEach((result, index) => {
            if (result.status === 'rejected' || !result.value) {
                failedForms.push(formConfigs.value[index].title);
            }
        });

        if (failedForms.length > 0) {
            ElMessage.error(`以下表单校验失败，请检查：${failedForms.join('、')}`);
            return;
        }

        // 所有表单校验通过，获取所有表单值并提交
        const formValues = formConfigs.value.reduce((acc, form) => {
            acc[form.key] = formRefs.value[form.key]?.getFieldsValue() || {};
            return acc;
        }, {});

        allFormData.value = formValues;

        ElMessage.success('所有表单校验通过，提交成功！');
        console.log('提交的所有表单数据:', allFormData.value);
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败，请检查表单数据');
    }
};

// 统一校验所有表单
const handleValidateAll = async () => {
    try {
        const validatePromises = formConfigs.value.map(form => formRefs.value[form.key]?.validate());
        const validateResults = await Promise.allSettled(validatePromises);

        const results = formConfigs.value.reduce((acc, form, index) => {
            acc[form.key] = validateResults[index].status === 'fulfilled' && validateResults[index].value;
            return acc;
        }, {});

        formStatus.value = formConfigs.value.reduce((acc, form) => {
            acc[form.key] = results[form.key] ? 'valid' : 'invalid';
            return acc;
        }, {});

        const allValid = Object.values(results).every(v => v);
        if (allValid) {
            ElMessage.success('所有表单校验通过！');
        } else {
            const failedForms = formConfigs.value.filter(form => !results[form.key]).map(form => form.title);
            ElMessage.warning(`以下表单校验失败：${failedForms.join('、')}`);
        }
    } catch (error) {
        console.error('校验失败:', error);
        ElMessage.error('校验失败，请检查表单数据');
    }
};

// 统一重置所有表单
const handleResetAll = async () => {
    try {
        await ElMessageBox.confirm('确定要重置所有表单吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });

        formConfigs.value.forEach(form => {
            formRefs.value[form.key]?.reset();
        });

        // 重置状态
        formStatus.value = formConfigs.value.reduce((acc, form) => {
            acc[form.key] = null;
            return acc;
        }, {});

        // 清空数据
        allFormData.value = {};

        ElMessage.success('所有表单已重置');
    } catch {
        // 用户取消
    }
};

// 获取所有表单值
const handleGetAllValues = () => {
    const formValues = formConfigs.value.reduce((acc, form) => {
        acc[form.key] = formRefs.value[form.key]?.getFieldsValue() || {};
        return acc;
    }, {});

    allFormData.value = formValues;

    ElMessage.info('已获取所有表单值，请查看下方数据展示区域');
    console.log('所有表单值:', allFormData.value);
};

onMounted(() => {
    // 检查 URL 中的 hash，如果有则自动滚动到对应位置
    nextTick(() => {
        const hash = window.location.hash;
        if (hash && scrollbarRef.value) {
            // 移除 # 号
            const id = hash.substring(1);
            const targetElement = document.getElementById(id);
            if (targetElement) {
                // 延迟一下确保 DOM 已经渲染完成
                setTimeout(() => {
                    // 使用 el-scrollbar 的 scrollTo 方法
                    scrollbarRef.value.scrollTo({
                        top: targetElement.offsetTop,
                    });
                }, 100);
            }
        }
    });
});
</script>

<style scoped lang="less">
.pro-form-group-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 15px 0 0 15px;
    box-sizing: border-box;
    overflow: hidden;

    // 固定头部：锚点导航
    .form-anchor-wrapper {
        flex-shrink: 0;
        padding: 10px 0;
        background: #fff;
        z-index: 10;
    }

    .form-anchor-wrapper {
        // 去掉 el-anchor 底部边框
        :deep(.el-anchor.el-anchor--horizontal.el-anchor--underline::before) {
            display: none !important;
            content: none !important;
            height: 0 !important;
            width: 0 !important;
            background: none !important;
            opacity: 0 !important;
            visibility: hidden !important;
        }
    }

    .form-anchor {
        padding: 10px 0;
    }

    // 中间滚动区域
    .form-scrollbar {
        flex: 1;
        min-height: 0;
        overflow: hidden;

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

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

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

    // 固定底部：操作按钮
    .group-actions-wrapper {
        flex-shrink: 0;
        position: relative;
        z-index: 99;
        display: flex;
        align-items: center;
        width: 100%;
        padding-inline: 24px;
        padding-block: 0;
        box-sizing: border-box;
        line-height: 56px;
        height: 56px;
        background-color: rgba(255, 255, 255, 0.6);
        border-block-start: 1px solid rgba(5, 5, 5, 0.06);
        -webkit-backdrop-filter: blur(8px);
        backdrop-filter: blur(8px);
        color: rgba(0, 0, 0, 0.88);
        transition: all 0.2s ease 0s;
    }
    .form-scrollbar {
        margin: 20px 0;
    }

    .form-group-container {
        display: flex;
        flex-direction: column;
        gap: 20px;
        // padding: 20px 0;

        .form-card {
            // 去掉边框
            :deep(.el-card) {
                border: none;
            }

            .form-card-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-weight: 600;
                cursor: pointer;
                user-select: none;

                .form-card-header-left {
                    display: flex;
                    align-items: center;
                    gap: 8px;

                    .collapse-icon {
                        font-size: 14px;
                        transition: none;
                        color: var(--el-text-color-secondary);
                    }
                }

                &:hover {
                    .collapse-icon {
                        color: var(--el-color-primary);
                    }
                }
            }
        }
    }

    .group-actions {
        width: 100%;
        display: flex;
        gap: 12px;
        justify-content: center;
        align-items: center;
    }

    .data-card {
        pre {
            margin: 0;
            padding: 16px;
            background: #f5f7fa;
            border-radius: 4px;
            font-size: 12px;
            line-height: 1.6;
            overflow-x: auto;
            max-height: 400px;
            overflow-y: auto;
        }
    }
}
</style>
