<template>
    <div class="edit-add-detail">
        <div v-loading="detailLoading" class="form-content" element-loading-text="加载中...">
            <div class="page-form">
                <!-- 主要内容区域 -->
                <div class="main-content">
                    <!-- 左侧菜单 -->
                    <div class="sidebar-menu">
                        <div class="menu-section">
                            <div class="menu-section">
                                <el-divider content-position="center">
                                    <div class="menu-title">绩效考核信息</div>
                                </el-divider>
                                <div class="menu-items">
                                    <div
                                        v-for="item in menuItems"
                                        :key="item.id"
                                        class="menu-item"
                                        :class="{ active: activeMenuItem === item.id }"
                                        @click="scrollToSection(item.id)"
                                    >
                                        <span>{{ item.title }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 右侧内容区域 -->
                    <div class="content-area">
                        <el-form
                            ref="addEditFormRef"
                            :model="addEditForm"
                            :rules="addEditFormRules"
                            size="large"
                            label-position="left"
                            label-suffix="："
                        >
                            <el-collapse v-model="activeCollapse">
                                <!-- 绩效考核评分 -->
                                <div
                                    v-if="hasMenuItem('access-score')"
                                    class="content-section"
                                    id="access-score"
                                >
                                    <el-collapse-item name="access-score">
                                        <template #title>
                                            <div class="section-title">
                                                <el-icon><Document /></el-icon>
                                                <span>基本信息</span>
                                            </div>
                                        </template>
                                        <div class="section-content">
                                            <el-descriptions :column="2" border>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        
                                                        供应商
                                                    </template>
                                                    <el-form-item prop="supplierName"
                                                        >{{ addEditForm.supplierName || '-' }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        
                                                        绩效考核体系
                                                    </template>
                                                    <el-form-item prop="valuationConfigurationName">
                                                        {{ addEditForm.valuationConfigurationName }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        
                                                        考核年度
                                                    </template>
                                                    <el-form-item prop="assessmentYear">
                                                        {{ addEditForm.assessmentYear }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        
                                                        周期类型
                                                    </template>
                                                    <el-form-item prop="assessmentType">
                                                        {{
                                                            dictionaryEscape(
                                                                'khpj-khlx',
                                                                addEditForm.assessmentType
                                                            )
                                                        }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        
                                                        考核周期
                                                    </template>
                                                    <el-form-item prop="assessmentYear">
                                                        <div v-if="addEditForm.assessmentQuater">
                                                            <span
                                                                >{{
                                                                    addEditForm.assessmentYear
                                                                }}年</span
                                                            >
                                                            <span
                                                                >{{
                                                                    addEditForm.assessmentQuater
                                                                }}季度</span
                                                            >
                                                        </div>
                                                        <div
                                                            v-else-if="addEditForm.assessmentMonth"
                                                        >
                                                            <span
                                                                >{{
                                                                    addEditForm.assessmentYear
                                                                }}年</span
                                                            >
                                                            <span
                                                                >{{
                                                                    addEditForm.assessmentMonth
                                                                }}月</span
                                                            >
                                                        </div>
                                                        <div v-else>
                                                            {{ addEditForm.assessmentYear }}年
                                                        </div>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        
                                                        发起人
                                                    </template>
                                                    <el-form-item prop="initiatorName">
                                                        {{ addEditForm.initiatorName }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        
                                                        总分值
                                                    </template>
                                                    <el-form-item prop="totalScore">
                                                        {{ addEditForm.totalScore }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        <span class=""></span>
                                                        考核评级
                                                    </template>
                                                    <el-form-item prop="totalScore">
                                                        {{ dictionaryEscape('fzdj',addEditForm.level) }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item :span="2">
                                                    <template #label>
                                                        <span class=""></span>
                                                        评审要求
                                                    </template>
                                                    <el-form-item prop="totalScore">
                                                        {{ addEditForm.desc }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                            </el-descriptions>
                                        </div>
                                    </el-collapse-item>
                                </div>
                                <!-- 绩效考核评价 -->
                                <div
                                    v-if="hasMenuItem('access-evaluate')"
                                    class="content-section"
                                    id="access-evaluate"
                                >
                                    <el-collapse-item name="access-evaluate">
                                        <template #title>
                                            <div class="section-title">
                                                <el-icon><Document /></el-icon>
                                                <span>绩效考核评价</span>
                                            </div>
                                        </template>
                                        <div class="section-content">
                                            <el-descriptions :column="2" border>
                                                <el-descriptions-item :span="2">
                                                    <template #label>
                                                        
                                                        评价结论
                                                    </template>
                                                    <el-radio-group
                                                        v-model="
                                                            addEditForm.notification
                                                                .assessmentResult
                                                        "
                                                        disabled
                                                    >
                                                        <el-radio value="1">合格</el-radio>
                                                        <el-radio value="2">可改善</el-radio>
                                                        <el-radio value="3">不合格</el-radio>
                                                    </el-radio-group>
                                                </el-descriptions-item>
                                                <el-descriptions-item :span="2">
                                                    <template #label>
                                                        
                                                        处置类型
                                                    </template>
                                                    <el-radio-group
                                                        v-model="
                                                            addEditForm.notification.processType
                                                        "
                                                        disabled
                                                    >
                                                        <el-radio value="0">无处置</el-radio>
                                                        <el-radio value="1">发出质量警告</el-radio>
                                                        <el-radio value="2"
                                                            >暂停供货资格/限期整改</el-radio
                                                        >
                                                    </el-radio-group>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.notification.processType == 1"
                                                >
                                                    <template #label>
                                                        
                                                        通知标题
                                                    </template>
                                                    <div>
                                                        {{
                                                            addEditForm.notification
                                                                .notificationTitle
                                                        }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.notification.processType == 1"
                                                >
                                                    <template #label>
                                                        
                                                        通知内容
                                                    </template>
                                                    <div>
                                                        {{
                                                            addEditForm.notification
                                                                .notificationContent
                                                        }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.notification.processType == 2"
                                                >
                                                    <template #label>
                                                        
                                                        通知标题
                                                    </template>
                                                    <div>
                                                        {{
                                                            addEditForm.notification
                                                                .notificationTitle
                                                        }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="
                                                        addEditForm.notification.processType == 2 ||
                                                        addEditForm.notification.processType == 1
                                                    "
                                                >
                                                    <template #label>
                                                        
                                                        通知日期
                                                    </template>
                                                    <div>
                                                        {{ addEditForm.notification.notifyDate }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.notification.processType == 2"
                                                >
                                                    <template #label>
                                                        
                                                        整改期限
                                                    </template>
                                                    <div>
                                                        {{ addEditForm.notification.replyDeadline }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.notification.processType == 2"
                                                >
                                                    <template #label>
                                                        
                                                        通知内容
                                                    </template>
                                                    <div>
                                                        {{
                                                            addEditForm.notification
                                                                .notificationContent
                                                        }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    v-if="addEditForm.notification.processType == 2"
                                                >
                                                    <template #label>
                                                        
                                                        企业联系人
                                                    </template>
                                                    <div>
                                                        {{
                                                            addEditForm.notification
                                                                .enterpriseContact
                                                        }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    v-if="addEditForm.notification.processType == 2"
                                                >
                                                    <template #label>
                                                        
                                                        联系方式
                                                    </template>
                                                    <div>
                                                        {{ addEditForm.notification.enterpriseTel }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.notification.processType == 2"
                                                >
                                                    <template #label>
                                                        
                                                        联系地址
                                                    </template>
                                                    <div>
                                                        {{
                                                            addEditForm.notification
                                                                .enterpriseAddress
                                                        }}
                                                    </div>
                                                </el-descriptions-item>
                                            </el-descriptions>
                                            <!-- <el-table
                                                :data="addEditForm.auditHistoryData"
                                                border
                                                stripe
                                            >
                                                <el-table-column
                                                    label="序号"
                                                    prop="index"
                                                    width="80"
                                                    align="center"
                                                />
                                                <el-table-column
                                                    label="审核环节"
                                                    align="center"
                                                    prop="step"
                                                />
                                                <el-table-column
                                                    label="审批意见"
                                                    align="center"
                                                    prop="comments"
                                                />
                                                <el-table-column
                                                    label="办理人"
                                                    align="center"
                                                    prop="handler"
                                                />
                                                <el-table-column
                                                    label="时间"
                                                    align="center"
                                                    prop="time"
                                                />
                                            </el-table> -->
                                        </div>
                                    </el-collapse-item>
                                </div>
                                <!-- 整改反馈信息 -->
                                <div
                                    v-if="hasMenuItem('access-feedback')"
                                    class="content-section"
                                    id="access-feedback"
                                >
                                    <el-collapse-item
                                        name="access-feedback"
                                        v-if="correctionStatus != 0"
                                    >
                                        <template #title>
                                            <div class="section-title">
                                                <el-icon><Document /></el-icon>
                                                <span>整改反馈信息</span>
                                            </div>
                                        </template>
                                        <div class="section-content">
                                            <el-descriptions :column="2" border>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.report"
                                                >
                                                    <template #label>
                                                        
                                                        根本原因分析
                                                    </template>
                                                    <div>
                                                        {{ addEditForm.report.rootCauseAnalysis }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.report"
                                                >
                                                    <template #label>
                                                        
                                                        临时应急措施
                                                    </template>
                                                    <div>
                                                        {{ addEditForm.report.temporaryMeasure }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.report"
                                                >
                                                    <template #label>
                                                        
                                                        长期纠正措施
                                                    </template>
                                                    <div>
                                                        {{ addEditForm.report.longTermCorrection }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.report"
                                                >
                                                    <template #label>
                                                        
                                                        计划完成日期
                                                    </template>
                                                    <div>
                                                        {{ addEditForm.report.planCompleteDate }}
                                                    </div>
                                                </el-descriptions-item>
                                                <el-descriptions-item :span="2">
                                                    <template #label>
                                                        
                                                        整改反馈内容
                                                    </template>
                                                    <el-form-item prop="resultDescription">
                                                        <el-input
                                                            v-model="addEditForm.resultDescription"
                                                            placeholder="请输入"
                                                            type="textarea"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item :span="2">
                                                    <template #label>
                                                        
                                                        附件
                                                    </template>
                                                    <el-form-item prop="files">
                                                        <ChunkFileUploader
                                                            type="button"
                                                            :fileList="addEditForm.files"
                                                            :previewAndDownload="false"
                                                            :typeRegularArr="typeRegularArr"
                                                            @change="handleFileChange"
                                                            @startUpload="handleStartUpload"
                                                        >
                                                        </ChunkFileUploader>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                            </el-descriptions>
                                        </div>
                                    </el-collapse-item>
                                </div>
                            </el-collapse>
                        </el-form>
                    </div>
                </div>
            </div>
        </div>
        <div class="footer">
            <el-button type="primary" @click="handleSubmit" :loading="submiting"
                >整改确定</el-button
            >
            <el-button @click="handleCancel"> 取 消</el-button>
        </div>
        <!-- 同意弹窗 -->
        <el-dialog
            title="整改确定"
            v-model="dialogVisible"
            width="600"
            header-class="headerDialog"
            :close-on-click-modal="false"
            :before-close="dialogBeforeClose"
        >
            <div style="width: 80%; margin: 0 auto">
                <el-form
                    :model="form"
                    ref="formRef"
                    :rules="rules"
                    label-width="100px"
                    :inline="false"
                >
                    <el-form-item label="根本原因分析" prop="rootCauseAnalysis">
                        <el-input
                            type="textarea"
                            placeholder="请输入"
                            clearable
                            v-model="form.rootCauseAnalysis"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="临时应急措施" prop="temporaryMeasure">
                        <el-input
                            type="textarea"
                            placeholder="请输入"
                            clearable
                            v-model="form.temporaryMeasure"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="长期纠正措施" prop="longTermCorrection">
                        <el-input
                            type="textarea"
                            placeholder="请输入"
                            clearable
                            v-model="form.longTermCorrection"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="计划完成日期" prop="planCompleteDate">
                        <el-date-picker
                            v-model="form.planCompleteDate"
                            value-format="YYYY-MM-DD"
                            type="date"
                            placeholder="请选择"
                        ></el-date-picker>
                    </el-form-item>
                </el-form>
            </div>
            <div class="footer">
                <el-button @click="dialogBeforeClose">关 闭</el-button>
                <el-button type="primary" @click="handleSave" :loading="btnLoading"
                    >确 定</el-button
                >
            </div>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { Document, Tickets, Check, CircleCheck } from '@element-plus/icons-vue'
import ChunkFileUploader from '@/components/ChunkFileUploader/index.vue'
import RejectDialog from '@/components/RejectDialog/index.vue'
import { reactive, ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import {
    dataDetail,
    dataAdd,
    dataNotification
} from '@/api/supplierMonitor/AssessmentEvaluation/ImproveNotification'

interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}

interface MenuItem {
    id: string
    title: string
    saveStatusKey: string
}

interface ReviewItem {
    id?: number
    index?: number
    category: string
    content: string
    score?: number
    maxScore?: number
    reviewers?: string[]
}

interface FileItem {
    id?: string
    fileId?: string
    status: string

    [key: string]: any
}

const route = useRoute()
const router = useRouter()

// 获取路由参数
const editId = ref((route.query.id as string) || '')
const isEdit = computed(() => !!editId.value)
const correctionStatus = ref('')
const currentStep = ref(2) // 步骤条当前步骤
const activeMenuItem = ref('access-score') // 当前激活的菜单项
const detailLoading = ref(false) // 详情加载状态
const submiting = ref(false) // 提交中状态
const dialogVisible = ref(false) // 同意弹窗
const notificationId = ref('')
// 折叠面板激活状态 - 包含供应商信息菜单和评审信息菜单
const activeCollapse = computed(() => {
    const supplierMenuIds = menuItems.value.map((item) => item.id)
    const reviewMenuIds = ['access-score', 'access-evaluate', 'access-feedback']
    return [...supplierMenuIds, ...reviewMenuIds]
})

// ==================== 表单相关 ====================
const addEditFormRef = ref<FormInstance>()
const addEditFormRules = reactive<FormRules>({
    agree: [{ required: true, message: '请选择是否同意', trigger: 'change' }],
    comments: [{ required: true, message: '请输入审核意见', trigger: 'blur' }]
})
const formRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    rootCauseAnalysis: [{ required: true, message: '请输入根本原因分析', trigger: 'blur' }],
    temporaryMeasure: [{ required: true, message: '请输入临时应急措施', trigger: 'blur' }],
    longTermCorrection: [{ required: true, message: '请输入长期纠正措施', trigger: 'blur' }],
    planCompleteDate: [{ required: true, message: '请选择计划完成日期', trigger: 'change' }]
})
const form = reactive<any>({
    planCompleteDate: new Date().toISOString().split('T')[0],
    notificationId: '',
    rootCauseAnalysis: '',
    longTermCorrection: '',
    temporaryMeasure: ''
})
const addEditForm = reactive<AddEditForm>({
    notification: {},
    details: [],
    resultDescription: '',
    files: [],
    report: {}
})

const detailForm = reactive<AddEditForm>({
    auditHistoryData: [],
    scoreData: []
})

// ==================== 菜单配置 ====================
const menuItems = ref<MenuItem[]>([
    {
        id: 'access-score',
        title: '绩效考核评分',
        saveStatusKey: 'accessScore'
    },
    {
        id: 'access-evaluate',
        title: '绩效考核评价',
        saveStatusKey: 'accessEvaluate'
    },
    {
        id: 'access-feedback',
        title: '整改反馈信息',
        saveStatusKey: 'accessFeedback'
    }
])

// ==================== 工具函数 ====================
// 检查菜单项是否存在的辅助函数
const hasMenuItem = (menuId: string) => {
    return menuItems.value.some((item) => item.id === menuId)
}

// ==================== 滚动监听相关 ====================
let scrollContainer: HTMLElement | null = null
let isScrolling = false

// 导航相关
const scrollToSection = (sectionId: string) => {
    // 设置滚动标志，防止滚动监听干扰
    isScrolling = true

    // 更新激活的菜单项
    activeMenuItem.value = sectionId

    const element = document.getElementById(sectionId)
    if (element) {
        element.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })

        // 滚动完成后重置标志
        setTimeout(() => {
            isScrolling = false
        }, 1000)
    } else {
        isScrolling = false
    }
}

// 监听滚动事件，更新激活的菜单项
const handleScroll = () => {
    if (isScrolling) return

    // 获取所有菜单项（包括供应商信息和评审信息）
    const supplierSections = menuItems.value
        .map((item) => ({
            id: item.id,
            element: document.getElementById(item.id)
        }))
        .filter((section) => section.element)

    const sections = [...supplierSections]

    if (sections.length === 0) return

    // 获取滚动容器的滚动位置
    const scrollTop = scrollContainer?.scrollTop || window.pageYOffset
    const containerHeight = scrollContainer?.clientHeight || window.innerHeight
    const scrollHeight = scrollContainer?.scrollHeight || document.documentElement.scrollHeight

    // 检查是否滚动到底部（距离底部100px以内）
    const isNearBottom = scrollTop + containerHeight >= scrollHeight - 100

    // 如果接近底部，直接选中最后一个section
    if (isNearBottom) {
        const lastSection = sections[sections.length - 1]
        if (lastSection && activeMenuItem.value !== lastSection.id) {
            activeMenuItem.value = lastSection.id
        }
        return
    }

    // 找到当前可见的section
    let currentSection = sections[0]

    for (const section of sections) {
        if (!section.element) continue

        const rect = section.element.getBoundingClientRect()
        const elementTop = rect.top + scrollTop
        const elementBottom = elementTop + rect.height

        // 如果section的顶部在视口范围内
        if (elementTop <= scrollTop + containerHeight / 2 && elementBottom > scrollTop) {
            currentSection = section
        }
    }

    // 更新激活的菜单项
    if (currentSection && activeMenuItem.value !== currentSection.id) {
        activeMenuItem.value = currentSection.id
    }
}

// 防抖处理滚动事件
const debouncedHandleScroll = () => {
    if (isScrolling) return
    requestAnimationFrame(() => {
        handleScroll()
    })
}

// ==================== 数据获取 ====================
const getDetail = async (id: string) => {
    // 获取详情逻辑
    detailLoading.value = true
    const data = (await dataDetail(id)) as AddEditForm
    if (data.state) {
        detailLoading.value = false
        Object.assign(addEditForm, data.value)
        const groupedDetails = []
        const codeMap = new Map()
        data.value.details.forEach((item: any) => {
            if (codeMap.has(item.assessmentIndicatorTypeCode)) {
                const parent = codeMap.get(item.assessmentIndicatorTypeCode)
                parent.children.push({ ...item, isParent: false })
            } else {
                const parentItem = { ...item, children: [], isParent: true }
                groupedDetails.push(parentItem)
                codeMap.set(item.assessmentIndicatorTypeCode, parentItem)
            }
        })
        addEditForm.details = groupedDetails
        addEditForm.details.forEach((item) => {
            item.name = item.assessmentIndicatorTypeName
        })
        addEditForm.notification.assessmentResult = data.value.assessmentResult
        if (data.value.processType) {
            addEditForm.notification.processType = data.value.processType
        }
    }
}

//附件上传
const btnLoading = ref<Boolean>(false)
const readyToUpload = ref<Boolean>(false)
const fileList = ref<FileItem[]>([])
const typeRegularArr = [
    'doc',
    'docx',
    'xls',
    'xlsx',
    'ppt',
    'pptx',
    'txt',
    'pdf', // 文档格式
    'jpg',
    'png',
    'gif' // 图像文件
]
const handleStartUpload = () => {
    btnLoading.value = true
}

const handleFileChange = (file: [FileItem]) => {
    fileList.value = file.map((item) => item as FileItem)
    btnLoading.value = !file.every((item: FileItem) => item.status === 'success')
}

// ==================== 表单操作 ====================
const isShowRejectDialog = ref<Boolean>(false)
const rejectDialogRef = ref<InstanceType<typeof RejectDialog> | null>(null)

const handleReject = () => {
    isShowRejectDialog.value = true
}

const handleRejectSuccess = (data: any) => {
    isShowRejectDialog.value = false
    console.log(isShowRejectDialog.value)
}

const handleSubmit = async () => {
    if (correctionStatus.value == '0') {
        dialogVisible.value = true
    } else {
        try {
            submiting.value = true
            const form = {
                files: addEditForm.files,
                resultDescription: addEditForm.resultDescription,
                status: '2',
                reportId: addEditForm.report.id
            }
            const data = await dataAdd(form)
            if (data.state) {
                submiting.value = false
                router.push({ name: 'ImproveNotification' })
            }
        } finally {
            submiting.value = false
        }
    }
}
// 关闭整改弹窗
const dialogBeforeClose = () => {
    dialogVisible.value = false
}
const handleSave = async () => {
    if (!formRef.value) return
    try {
        await formRef.value.validate()
        btnLoading.value = true
        const saveData = {
            ...form,
            notificationId: notificationId.value
        }
        const data = await dataNotification(saveData)
        if (data.state) {
            ElMessage.success('保存成功')
            dialogVisible.value = false
            router.push({ name: 'ImproveNotification' })
        }
    } catch (error) {
        console.error('表单校验失败:', error)
    } finally {
        btnLoading.value = false
    }
}

const handleCancel = () => {
    router.push({ name: 'ImproveNotification' })
}

// ==================== 生命周期 ====================
onMounted(() => {
    readyToUpload.value = true
    correctionStatus.value = route.query.correctionStatus as string
    notificationId.value = route.query.notificationId as string
    getDetail(route.query.id)

    // 设置滚动监听
    setTimeout(() => {
        // 设置滚动标志，防止初始化滚动触发监听
        isScrolling = true

        // 查找滚动容器
        scrollContainer = document.querySelector('.page-form') as HTMLElement

        // 初始化滚动位置（在添加监听器之前）
        const element = document.getElementById(activeMenuItem.value)
        if (element) {
            element.scrollIntoView({
                behavior: 'instant',
                block: 'start'
            })
        }

        // 延迟添加滚动监听器，确保初始滚动完成
        setTimeout(() => {
            // 添加滚动监听器
            if (scrollContainer) {
                scrollContainer.addEventListener('scroll', debouncedHandleScroll)
            } else {
                // 如果没有找到滚动容器，监听window滚动
                window.addEventListener('scroll', debouncedHandleScroll)
            }

            // 重置滚动标志
            isScrolling = false
        }, 200)
    }, 100)
})

onUnmounted(() => {
    // 清理滚动监听器
    if (scrollContainer) {
        scrollContainer.removeEventListener('scroll', debouncedHandleScroll)
    } else {
        window.removeEventListener('scroll', debouncedHandleScroll)
    }
})
</script>

<style lang="scss" scoped>
.edit-add-detail {
    .form-content {
        display: flex;
        flex-direction: column;
        align-items: center;

        .page-form {
            width: 80%;
            overflow-x: hidden;
            overflow-y: auto;
            max-height: 100%;
            padding: 0 20px;

            /* 隐藏滚动条样式 */
            &::-webkit-scrollbar {
                width: 0;
                height: 0;
            }

            &::-webkit-scrollbar-track {
                background: transparent;
            }

            &::-webkit-scrollbar-thumb {
                background: transparent;
            }

            /* Firefox 隐藏滚动条 */
            scrollbar-width: none;
            -ms-overflow-style: none;
        }
        .step-container {
            width: 100%;
            margin-bottom: 20px;
            padding: 20px;
            border-radius: 8px;
        }

        .main-content {
            display: flex;
            gap: 20px;
            width: 100%;
            padding-bottom: 20px;

            .sidebar-menu {
                width: 180px;
                background-color: var(--theme-search-wrapper-bg);
                box-shadow: 0px 0px 20px 0px rgba(0, 36, 65, 0.2);
                border-radius: 16px;
                padding: 10px 20px 20px 20px;
                height: fit-content;
                position: sticky;
                top: 10px;

                .menu-section {
                    margin-bottom: 30px;

                    .menu-title {
                        font-size: 16px;
                        font-weight: bold;
                        color: var(--theme-text-primary);
                        white-space: pre;
                    }

                    .menu-items {
                        .menu-item {
                            font-size: 14px;
                            padding: 10px 15px;
                            margin-bottom: 5px;
                            cursor: pointer;
                            border-radius: 4px;
                            transition: all 0.3s ease;
                            color: var(--theme-text-primary);
                            display: flex;
                            justify-content: space-between;
                            align-items: center;

                            &:hover {
                                background-color: var(--theme-system-module-1);
                                color: var(--theme-primary);
                            }

                            &.active {
                                background-color: var(--theme-primary);
                                color: white;
                            }

                            .save-icon {
                                font-size: 20px;

                                &.saved {
                                    color: #67c23a; /* 绿色 */
                                }

                                &.not-saved {
                                    color: #c0c4cc; /* 灰色 */
                                }
                            }
                        }
                    }
                }
            }

            .content-area {
                width: calc(100% - 180px - 80px);
                background-color: var(--theme-form-content-bg);
                border-radius: 8px;
                padding: 20px 20px 0 20px;

                .content-section {
                    .content-title {
                        margin-bottom: 5px;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        .content-title-left {
                            font-size: 14px;
                            font-weight: bold;
                            color: var(--theme-text-primary);
                            display: flex;
                            align-items: center;
                        }
                        .content-title-left::before {
                            content: '';
                            display: inline-block;
                            width: 4px;
                            height: 18px;
                            background-color: #1a8cff;
                            border-radius: 2px;
                            margin-right: 8px;
                        }
                    }

                    .site-inspection-content {
                        background-color: #f5f8fa;
                        padding: 16px;
                        box-sizing: border-box;
                    }

                    .section-content {
                        color: var(--theme-text-inverse);

                        .review-actions {
                            display: flex;
                            padding: 10px 0 10px 10px;
                        }
                    }
                }
            }
        }
    }
}

</style>
