<template>
    <div class="edit-add-detail">
        <div v-loading="detailLoading" class="form-content" element-loading-text="加载中...">
            <div class="page-form">
                <!-- 步骤条 -->
                <div class="step-container">
                    <el-steps
                        :active="currentStep"
                        align-center
                        finish-status="success"
                        process-status="finish"
                    >
                        <el-step title="1 评价创建"></el-step>
                        <el-step title="2 绩效评价评分"></el-step>
                        <el-step title="3 绩效评价评价"></el-step>
                        <el-step title="4 完成"></el-step>
                    </el-steps>
                </div>

                <!-- 主要内容区域 -->
                <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="detailForm"
                            :rules="addEditFormRules"
                            size="large"
                            label-position="left"
                            label-suffix="："
                        >
                            <el-collapse v-model="activeCollapse">
                                <!-- 绩效评价评分 -->
                                <div
                                    v-if="hasMenuItem('base-info')"
                                    class="content-section"
                                    id="base-info"
                                >
                                    <el-collapse-item name="base-info">
                                        <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>
                                                        <span class="required-asterisk">*</span>
                                                        供应商
                                                    </template>
                                                    <el-form-item prop="supplierName"
                                                        >{{ addEditForm.supplierName || '-' }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        评价体系名称
                                                    </template>
                                                    <el-form-item prop="valuationConfigurationName">
                                                        {{ addEditForm.valuationConfigurationName }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        评价年度
                                                    </template>
                                                    <el-form-item prop="assessmentYear">
                                                        {{ addEditForm.assessmentYear }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        评价类型
                                                    </template>
                                                    <el-form-item prop="assessmentType">
                                                        {{
                                                            dictionaryEscape(
                                                                'khpj-khlx',
                                                                addEditForm.assessmentType
                                                            )
                                                        }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        评价周期
                                                    </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>
                                                        <span class="required-asterisk">*</span>
                                                        评价等级
                                                    </template>
                                                    <el-form-item prop="totalScore">
                                                        {{
                                                            dictionaryEscape(
                                                                'fzdj',
                                                                addEditForm.level
                                                            )
                                                        }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        总分值
                                                    </template>
                                                    <el-form-item prop="totalScore">
                                                        {{ addEditForm.totalScore }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        累计订单金额(万元)
                                                    </template>
                                                    <el-form-item prop="totalPrice">
                                                        {{ addEditForm.totalPrice }}
                                                    </el-form-item>
                                                </el-descriptions-item>

                                                <el-descriptions-item :span="2">
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        评审要求
                                                    </template>
                                                    <el-form-item prop="totalScore">
                                                        {{ addEditForm.desc }}
                                                    </el-form-item>
                                                </el-descriptions-item>
                                            </el-descriptions>
                                            <div>
                                                <div
                                                    style="
                                                        display: flex;
                                                        align-items: center;
                                                        justify-content: space-between;
                                                    "
                                                >
                                                    <div
                                                        style="
                                                            box-sizing: border-box;
                                                            font-size: 12px;
                                                            padding: 10px;
                                                            text-align: left;
                                                            font-weight: bold;
                                                        "
                                                    >
                                                        近三年度销售额(万元)
                                                    </div>
                                                    <div class="base-more" @click="openSalesDialog">
                                                        <span>查看更多</span>
                                                        <el-icon><DArrowRight /></el-icon>
                                                    </div>
                                                </div>
                                                <el-table :data="orderSales" border stripe>
                                                    <el-table-column
                                                        type="index"
                                                        label="序号"
                                                        width="80px"
                                                        align="center"
                                                    />
                                                    <el-table-column
                                                        prop="year"
                                                        label="年份"
                                                        align="center"
                                                    />
                                                    <el-table-column
                                                        prop="annualTransAmount"
                                                        label="销售额(万元)"
                                                        align="center"
                                                    />
                                                </el-table>
                                            </div>
                                        </div>
                                    </el-collapse-item>
                                </div>

                                <!-- 评分项 -->
                                <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-table
                                                :data="addEditForm.details"
                                                border
                                                stripe
                                                row-key="id"
                                                :tree-props="{
                                                    children: 'children',
                                                    hasChildren: 'hasChildren',
                                                    expandColumnKey: 'name'
                                                }"
                                                :default-expand-all="true"
                                                show-summary
                                                :summary-method="getSummaries"
                                            >
                                                <el-table-column
                                                    type="index"
                                                    label="序号"
                                                    width="80"
                                                    align="center"
                                                />
                                                <el-table-column
                                                    prop="name"
                                                    label="类别"
                                                    align="center"
                                                    width="150"
                                                />
                                                <el-table-column
                                                    prop="performanceEvaluationDetailsName"
                                                    label="评审内容"
                                                    align="center"
                                                />
                                                <el-table-column
                                                    prop="score"
                                                    label="分值"
                                                    align="center"
                                                    width="120"
                                                />
                                                <el-table-column
                                                    prop="operationScore"
                                                    label="评分"
                                                    align="center"
                                                    width="120"
                                                />
                                                <el-table-column
                                                    prop="users"
                                                    label="评分人"
                                                    align="center"
                                                    width="150"
                                                >
                                                    <template v-slot="{ row }">
                                                        <div
                                                            v-if="row.users && row.users.length > 0"
                                                        >
                                                            {{
                                                                row.users
                                                                    .map((user) => user.ratingName)
                                                                    .join(', ')
                                                            }}
                                                        </div>
                                                        <div v-else>-</div>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </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-table
                                                :data="hisToryList"
                                                border
                                                stripe
                                                row-key="id"
                                            >
                                                <el-table-column
                                                    type="index"
                                                    label="序号"
                                                    width="80"
                                                    align="center"
                                                />
                                                <el-table-column
                                                    prop="assessmentYear"
                                                    label="评价年度"
                                                    align="center"
                                                />
                                                <el-table-column
                                                    prop="assessmentType"
                                                    label="周期类型"
                                                    align="center"
                                                >
                                                    <template v-slot="{ row }">
                                                        <div>
                                                            {{
                                                                dictionaryEscape(
                                                                    'khpj-khlx',
                                                                    row.assessmentType
                                                                )
                                                            }}
                                                        </div>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column
                                                    prop="assessmentQuater"
                                                    label="评价时间"
                                                    align="center"
                                                >
                                                    <template v-slot="{ row }">
                                                        <div v-if="row.assessmentQuater">
                                                            <span>{{ row.assessmentYear }}年</span>
                                                            <span
                                                                >{{
                                                                    row.assessmentQuater
                                                                }}季度</span
                                                            >
                                                        </div>
                                                        <div v-else-if="row.assessmentMonth">
                                                            <span>{{ row.assessmentYear }}年</span>
                                                            <span>{{ row.assessmentMonth }}月</span>
                                                        </div>
                                                        <div v-else>{{ row.assessmentYear }}年</div>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column
                                                    prop="operationScore"
                                                    label="评价得分"
                                                    align="center"
                                                />
                                                <el-table-column
                                                    prop="level"
                                                    label="评价等级"
                                                    align="center"
                                                >
                                                    <template v-slot="{ row }">
                                                        <div>
                                                            {{
                                                                dictionaryEscape('fzdj', row.level)
                                                            }}
                                                        </div>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </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>
                                                        <span class="required-asterisk">*</span>
                                                        原因
                                                    </template>
                                                    <el-form-item prop="assessmentResult">
                                                        <el-input
                                                            v-model="detailForm.assessmentResult"
                                                            :rows="4"
                                                            type="textarea"
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item :span="2">
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        处置类型
                                                    </template>
                                                    <el-form-item prop="processType">
                                                        <el-radio-group
                                                            @change="changeProcessType"
                                                            v-model="detailForm.processType"
                                                        >
                                                            <el-radio value="1"
                                                                >发出质量警告</el-radio
                                                            >
                                                            <el-radio value="2"
                                                                >暂停供货资格/限期整改</el-radio
                                                            >
                                                            <el-radio value="3">淘汰</el-radio>
                                                        </el-radio-group>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <!-- <el-descriptions-item v-if="addEditForm.processType === 1">
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        供应商分类
                                                    </template>
                                                    <el-form-item prop="c">
                                                        <el-select
                                                            v-model="addEditForm.c"
                                                            placeholder="请选择"
                                                            style="width: 100%"
                                                        >
                                                            <el-option
                                                                v-for="item in []"
                                                                :key="item.value"
                                                                :label="item.label"
                                                                :value="item.value"
                                                            />
                                                        </el-select>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item v-if="addEditForm.processType === 1">
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        供应商分级
                                                    </template>
                                                    <el-form-item prop="d">
                                                        <el-select
                                                            v-model="addEditForm.d"
                                                            placeholder="请选择"
                                                            style="width: 100%"
                                                        >
                                                            <el-option
                                                                v-for="item in []"
                                                                :key="item.value"
                                                                :label="item.label"
                                                                :value="item.value"
                                                            />
                                                        </el-select>
                                                    </el-form-item>
                                                </el-descriptions-item> -->
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="detailForm.processType == 1"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        通知标题
                                                    </template>
                                                    <el-form-item prop="notificationTitle">
                                                        <el-input
                                                            v-model="detailForm.notificationTitle"
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="detailForm.processType == 1"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        通知内容
                                                    </template>
                                                    <el-form-item prop="notificationContent">
                                                        <el-input
                                                            v-model="detailForm.notificationContent"
                                                            type="textarea"
                                                            :rows="4"
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="detailForm.processType == 2"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        通知标题
                                                    </template>
                                                    <el-form-item prop="notificationTitle">
                                                        <el-input
                                                            v-model="detailForm.notificationTitle"
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="
                                                        detailForm.processType == 2 ||
                                                        detailForm.processType == 1
                                                    "
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        通知日期
                                                    </template>
                                                    <el-form-item prop="notifyDate">
                                                        <el-date-picker
                                                            v-model="detailForm.notifyDate"
                                                            placeholder="请选择"
                                                            type="datetime"
                                                            :default-value="new Date()"
                                                            style="width: 100%"
                                                            format="YYYY-MM-DD HH:mm:ss"
                                                            value-format="YYYY-MM-DD HH:mm:ss"
                                                        />
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="detailForm.processType == 2"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        整改期限
                                                    </template>
                                                    <el-form-item prop="replyDeadline">
                                                        <el-date-picker
                                                            v-model="detailForm.replyDeadline"
                                                            placeholder="请选择"
                                                            type="datetime"
                                                            :default-value="new Date()"
                                                            style="width: 100%"
                                                            format="YYYY-MM-DD HH:mm:ss"
                                                            value-format="YYYY-MM-DD HH:mm:ss"
                                                        />
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="detailForm.processType == 2"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        整改内容
                                                    </template>
                                                    <el-form-item prop="notificationContent">
                                                        <el-input
                                                            v-model="detailForm.notificationContent"
                                                            type="textarea"
                                                            :rows="4"
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    v-if="detailForm.processType == 2"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        企业联系人
                                                    </template>
                                                    <el-form-item prop="enterpriseContact">
                                                        <el-input
                                                            v-model="detailForm.enterpriseContact"
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    v-if="detailForm.processType == 2"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        联系方式
                                                    </template>
                                                    <el-form-item prop="enterpriseTel">
                                                        <el-input
                                                            v-model="detailForm.enterpriseTel"
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="detailForm.processType == 2"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        联系地址
                                                    </template>
                                                    <el-form-item prop="enterpriseAddress">
                                                        <el-input
                                                            v-model="detailForm.enterpriseAddress"
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </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="btnLoading">确 定</el-button>
            <el-button @click="handleCancel"> 取 消</el-button>
        </div>
        <sales-dialog
            v-model:isShowAdd="salesDialogVisible"
            v-model:info="info"
            title="年度销售额"
        ></sales-dialog>
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import salesDialog from './salesDialog.vue'
import { Document, Tickets, Check, CircleCheck } from '@element-plus/icons-vue'
import CustomUploader from '@/components/CustomUploader/index.vue'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { reactive, ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
    dataDetail,
    saveEvaluation,
    getEvaluationHistory,
    getorderData
} from '@/api/supplierMonitor/PerformanceManagement/PerformanceEvaluation'
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 hisToryList = ref([])
const currentStep = ref(2) // 步骤条当前步骤
const activeMenuItem = ref('base-info') // 当前激活的菜单项
const detailLoading = ref(false) // 详情加载状态
const orderSales = ref([]) // 订单信息
const info = ref<any>({})
const salesDialogVisible = ref(false) // 销售额弹窗显示状态
// 折叠面板激活状态 - 包含供应商信息菜单和评审信息菜单
const activeCollapse = computed(() => {
    const supplierMenuIds = menuItems.value.map((item) => item.id)
    const reviewMenuIds = ['base-info', 'access-score', 'access-evaluate']
    return [...supplierMenuIds, ...reviewMenuIds]
})

// ==================== 表单相关 ====================
const addEditFormRef = ref<FormInstance>()
const addEditFormRules = reactive<FormRules>({
    assessmentResult: [{ required: true, message: '请选择评价结论', trigger: 'change' }],
    processType: [{ required: true, message: '请选择处置类型', trigger: 'change' }],
    notificationTitle: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
    notificationContent: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
    notifyDate: [{ required: true, message: '请选择通知日期', trigger: 'change' }],
    replyDeadline: [{ required: true, message: '请选择整改期限', trigger: 'change' }],
    enterpriseContact: [{ required: true, message: '请输入企业联系人', trigger: 'blur' }],
    enterpriseTel: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
    enterpriseAddress: [{ required: true, message: '请输入联系地址', trigger: 'blur' }]
})

const addEditForm = reactive<AddEditForm>({})
const detailForm = reactive<AddEditForm>({
    assessmentResult: '',
    replyDeadline: '',
    notifyDate: '',
    notificationContent: '',
    notificationTitle: '',
    performanceEvaluationId: '',
    processType: '1',
    remarks: '',
    enterpriseContact: '',
    enterpriseTel: '',
    enterpriseAddress: ''
})

// ==================== 菜单配置 ====================
const menuItems = ref<MenuItem[]>([
    {
        id: 'base-info',
        title: '基本信息',
        saveStatusKey: 'baseInfo'
    },
    {
        id: 'access-score',
        title: '绩效评价评分',
        saveStatusKey: 'accessScore'
    },
    {
        id: 'access-evaluate',
        title: '绩效评价评价',
        saveStatusKey: 'accessEvaluate'
    }
])

// ==================== 工具函数 ====================
// 检查菜单项是否存在的辅助函数
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 | number) => {
    try {
        detailLoading.value = true
        const data = await dataDetail(id)
        Object.assign(addEditForm, data.value)
        getHistoryScore()
        getOrderSales()
        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
        })
        if (addEditForm.status == 2 || addEditForm.status == 3) {
            currentStep.value = 1
        }
        if (addEditForm.status == 4) {
            currentStep.value = 2
        }
        if (addEditForm.status == 5) {
            currentStep.value = 3
        }
        if (addEditForm.status == 1) {
            currentStep.value = 4
        }
        if (data.value.notification) {
            Object.assign(detailForm, data.value.notification)
            detailForm.assessmentResult = data.value.assessmentResult
        }
    } finally {
        detailLoading.value = false // 无论成功或失败，都关闭加载状态
    }
}

//附件上传
const btnLoading = ref<Boolean>(false)
const readyToUpload = ref<Boolean>(false)
const fileList = ref<FileItem[]>([])
const typeRegularArr = [
    'mp4',
    'mov',
    'avi',
    'mkv',
    'wmv',
    'flv',
    'mpeg',
    'mpg',
    '3gp',
    'webm', // 视频格式
    'doc',
    'docx',
    'xls',
    'xlsx',
    'ppt',
    'pptx',
    'txt',
    'rtf',
    'pdf', // 文档格式
    'jpg',
    'png',
    'bmp',
    '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 changeProcessType = (value: string) => {
    if (value == 0) {
        detailForm.replyDeadline = ''
        detailForm.notifyDate = ''
        detailForm.notificationContent = ''
        detailForm.notificationTitle = ''
        detailForm.performanceEvaluationId = ''
        detailForm.enterpriseContact = ''
        detailForm.enterpriseTel = ''
        detailForm.enterpriseAddress = ''
    }
    if (value == 1) {
        detailForm.notifyDate = new Date().toISOString().replace('T', ' ').split('.')[0]
    }
    if (value == 2) {
        detailForm.notifyDate = new Date().toISOString().replace('T', ' ').split('.')[0]
        detailForm.replyDeadline = new Date().toISOString().replace('T', ' ').split('.')[0]
    }
}

const openSalesDialog = () => {
    info.value = addEditForm
    salesDialogVisible.value = true
}

const handleSubmit = () => {
    // 校验processType
   
    addEditFormRef.value?.validate(async (valid, object) => {
        if (valid) {
            try {
                btnLoading.value = true
                detailForm.performanceEvaluationId = addEditForm.id
                const value = await saveEvaluation({ ...detailForm })
                if (value.state) {
                    ElMessage.success('保存成功')
                    router.push({ name: 'PerformanceEvaluation' })
                }
            } finally {
                btnLoading.value = false
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}

// 表格合计方法
const getSummaries = (param: any) => {
    const { columns, data } = param
    const sums: string[] = []

    // 获取所有项数据（包括父级和子级）
    const getAllItems = (items: any[]) => {
        let allItems: any[] = []
        items.forEach((item) => {
            allItems.push(item)
            if (item.children && item.children.length > 0) {
                allItems = allItems.concat(getAllItems(item.children))
            }
        })
        return allItems
    }

    const allItems = getAllItems(data)

    columns.forEach((column: any, index: number) => {
        if (index === 0) {
            sums[index] = ''
            return
        }
        if (index === 1) {
            sums[index] = '合计'
            return
        }

        // 为分值和评分列计算合计
        if (column.property === 'score') {
            const values = allItems.map((item: any) => Number(item[column.property]) || 0)
            sums[index] = values.reduce((prev: number, curr: number) => prev + curr, 0).toString()
        } else if (column.property === 'operationScore') {
            const values = allItems.map((item: any) => Number(item[column.property]) || 0)
            sums[index] =
                values.reduce((prev: number, curr: number) => prev + curr, 0).toString() +
                `(${dictionaryEscape('fzdj', addEditForm.level)})`
        } else {
            sums[index] = '-'
        }
    })
    return sums
}

const handleCancel = () => {
    router.push({ name: 'PerformanceEvaluation' })
}
// 获取订单销售额
const getOrderSales = async () => {
    const params = {
        pageBean: {
            page: 1,
            pageSize: 3
        },
        querys: [],
        sorter: [{ direction: 'DESC', property: 'year' }]
    }
    const res = await getorderData(addEditForm.supplierId, params)
    orderSales.value = res.value.data.rows
    addEditForm.totalPrice = res.value.totalPrice
}

// 查询历史评分项
const getHistoryScore = async () => {
    let params = {
        pageBean: {
            page: 1,
            pageSize: 3
        },
        querys: [
            {
                operation: 'EQUAL',
                property: 'result.SUPPLIER_ID_',
                value: addEditForm.supplierId
            }
        ]
    }
    const data = await getEvaluationHistory(params)
    hisToryList.value = data.rows
}
// ==================== 生命周期 ====================
onMounted(() => {
    readyToUpload.value = true
    if (route.query.id) {
        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;
                        }
                    }
                }
            }
        }
    }
}
.base-more {
    display: flex;
    align-items: center;
    margin-right: 10px;
    cursor: pointer;
    color: #1a8cff;
}
// 表格合计行样式
:deep(.el-table__footer-wrapper .el-table__footer tbody tr td .el-table__cell) {
    background-color: var(--theme-form-content-bg) !important;
    color: var(--theme-text-primary) !important;
    font-weight: 600 !important;
    border-color: var(--el-table-border-color) !important;
}
</style>
