<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="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>
                                                        <span class="required-asterisk">*</span>
                                                        供应商
                                                    </template>
                                                    <el-form-item prop="supplierName">
                                                        <el-select
                                                            v-model="addEditForm.supplierId"
                                                            filterable
                                                            clearable
                                                            @change="selectSupplier"
                                                            placeholder="请选择"
                                                        >
                                                            <el-option
                                                                v-for="item in supplierList"
                                                                :key="item.supplierId"
                                                                :label="item.companyName"
                                                                :value="item.supplierId"
                                                            >
                                                            </el-option>
                                                        </el-select>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        预警标题名称
                                                    </template>
                                                    <el-form-item prop="valuationConfigurationName">
                                                        <el-input
                                                            v-model="
                                                                addEditForm.valuationConfigurationName
                                                            "
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        评价年度
                                                    </template>
                                                    <el-form-item prop="assessmentYear">
                                                        <el-date-picker
                                                            v-model="addEditForm.assessmentYear"
                                                            type="year"
                                                            value-format="YYYY"
                                                            placeholder="请选择"
                                                        ></el-date-picker>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item>
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        评价类型
                                                    </template>
                                                    <el-form-item prop="assessmentType">
                                                        <el-select
                                                            v-model="addEditForm.assessmentType"
                                                            placeholder="请选择"
                                                            @change="handleAssessmentTypeChange"
                                                        >
                                                            <el-option
                                                                v-for="(
                                                                    item, i
                                                                ) in getDictionaryByCode(
                                                                    'khpj-khlx'
                                                                )"
                                                                :key="i"
                                                                :label="item.name"
                                                                :value="item.value"
                                                            >
                                                            </el-option>
                                                        </el-select>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item :span="2">
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        评价周期
                                                    </template>
                                                    <el-form-item
                                                        prop="assessmentMonth"
                                                        v-if="addEditForm.assessmentType == 1"
                                                    >
                                                        <el-date-picker
                                                            v-model="addEditForm.assessmentMonth"
                                                            type="month"
                                                            value-format="YYYY-MM"
                                                            :default-value="
                                                                new Date(
                                                                    addEditForm.assessmentYear,
                                                                    0
                                                                )
                                                            "
                                                            :disabled-date="disabledDate"
                                                            placeholder="请选择"
                                                        ></el-date-picker>
                                                    </el-form-item>
                                                    <el-form-item
                                                        prop="assessmentQuater"
                                                        v-if="addEditForm.assessmentType == 2"
                                                    >
                                                        <DatePopover
                                                            format="YYYY年Q季度"
                                                            value-format="YYYY-Q"
                                                            v-model="addEditForm.assessmentQuater"
                                                            placeholder="请选择季度"
                                                            :disabled-date="disabledDate"
                                                        ></DatePopover>
                                                    </el-form-item>
                                                    <el-form-item prop="assessmentYear" v-if="addEditForm.assessmentType == 3">
                                                        <el-date-picker
                                                            v-model="addEditForm.assessmentYear"
                                                            type="year"
                                                            value-format="YYYY"
                                                            placeholder="请选择"
                                                        ></el-date-picker>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                            </el-descriptions>
                                        </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"
                                            >
                                                <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
                                                    v-if="currentStep !== 1"
                                                    prop="operationScore"
                                                    label="评分"
                                                    align="center"
                                                    width="150"
                                                />
                                                <el-table-column
                                                    label="评分人"
                                                    align="center"
                                                    width="150"
                                                >
                                                    <template #default="{ row }">
                                                        <span v-if="row.users && Array.isArray(row.users)">
                                                            {{ row.users.map(user => user.ratingName).join(', ') }}
                                                        </span>
                                                        <span v-else>-</span>
                                                    </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="addEditForm.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="addEditForm.processType"
                                                        >
                                                            <el-radio value="1"
                                                                >发出质量警告</el-radio
                                                            >
                                                        </el-radio-group>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.processType == 1"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        通知标题
                                                    </template>
                                                    <el-form-item prop="notificationTitle">
                                                        <el-input
                                                            v-model="addEditForm.notificationTitle"
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.processType == 1"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        通知内容
                                                    </template>
                                                    <el-form-item prop="notificationContent">
                                                        <el-input
                                                            v-model="
                                                                addEditForm.notificationContent
                                                            "
                                                            type="textarea"
                                                            :rows="4"
                                                            placeholder="请输入"
                                                        ></el-input>
                                                    </el-form-item>
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    :span="2"
                                                    v-if="addEditForm.processType == 1"
                                                >
                                                    <template #label>
                                                        <span class="required-asterisk">*</span>
                                                        通知日期
                                                    </template>
                                                    <el-form-item prop="notifyDate">
                                                        <el-date-picker
                                                            v-model="addEditForm.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>
                                        </div>
                                    </el-collapse-item>
                                </div>
                            </el-collapse>
                        </el-form>
                    </div>
                </div>
            </div>
        </div>
        <div class="footer">
            <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                提 交
            </el-button>
            <el-button @click="handleCancel"> 取 消</el-button>
        </div>
    </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 { reactive, ref, onMounted } from 'vue'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { useRoute, useRouter } from 'vue-router'
import {
    dataDetail,
    dataAdd,
    dataUpdate
} from '@/api/supplierMonitor/PerformanceManagement/EvaluationAlertQuery'
import { dataTable } from '@/api/supplierMonitor/SupplyManagement/SupplierQualified'
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 notificationStatus = ref('')
const activeMenuItem = ref('access-score') // 当前激活的菜单项
const detailLoading = ref(false) // 详情加载状态
const submitLoading = 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>({
    supplierName: [{ required: true, message: '请选择供应商', trigger: 'change' }],
    valuationConfigurationName: [
        { required: true, message: '请输入预警标题名称', trigger: 'blur' }
    ],
    assessmentYear: [{ required: true, message: '请选择评价年度', trigger: 'change' }],
    assessmentType: [{ required: true, message: '请选择评价类型', trigger: 'change' }],
    assessmentResult: [{ required: true, message: '请输入原因', trigger: 'blur' }],
    processType: [{ required: true, message: '请选择处置类型', trigger: 'change' }],
    notificationTitle: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
    notificationContent: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
    notifyDate: [{ required: true, message: '请选择通知日期', trigger: 'change' }]
})

const addEditForm = reactive<AddEditForm>({
    notifications : [
        {
            distributeType: 2,
            assessmentResult: '',
            processType: 1,
            notificationTitle: '',
            notificationContent: '',
            notifyDate: new Date().toISOString().replace('T', ' ').split('.')[0],
            supplierName: '',
            supplierId: '',
            supplierCode: ''
        }
    ],
    distributeType: 2,
    assessmentResult: '',
    processType: '1',
    notificationTitle: '',
    notificationContent: '',
    notifyDate: new Date().toISOString().replace('T', ' ').split('.')[0],
    assessmentYear: '',
    assessment: new Date().getFullYear().toString(),
    assessmentType: '3',
    supplierName: '',
    supplierId: '',
    supplierCode: ''
})
const supplierList = ref<any[]>([])

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

// ==================== 工具函数 ====================
// 检查菜单项是否存在的辅助函数
const hasMenuItem = (menuId: string) => {
    return menuItems.value.some((item) => item.id === menuId)
}
// 禁用日期函数
const disabledDate = (time: Date) => {
    if (!addEditForm.assessmentYear) return false
    return time.getFullYear() !== parseInt(addEditForm.assessmentYear)
}
// 评价类型变化处理
const handleAssessmentTypeChange = (value: any) => {
    if (value == 1) {
        addEditForm.assessmentMonth =
            addEditForm.assessmentYear + '-' + String(new Date().getMonth() + 1).padStart(2, '0')
    } else if (value == 2) {
        const currentQuarter = Math.floor((new Date().getMonth() + 3) / 3)
        addEditForm.assessmentQuater = addEditForm.assessmentYear + '-' + currentQuarter
    } else if (value == 3) {
        addEditForm.assessmentYear = addEditForm.assessmentYear
    } else {
        addEditForm.assessmentMonth = ''
        addEditForm.assessmentQuater = ''
    }
}
// 获取供应商列表
const getSupplierList = async () => {
    let params = {
        pageBean: {
            pageSize: -1,
            page: 1
        }
    }
    const data = await dataTable(params, 1)
    supplierList.value = data.rows
}
// ==================== 滚动监听相关 ====================
let scrollContainer: HTMLElement | null = null
let isScrolling = false

const changeProcessType = (value: string) => {
    const notifications  = addEditForm.notifications [0]
    const currentDateTime = new Date().toISOString().replace('T', ' ').split('.')[0]

    // 清空相关字段
    notifications .notificationTitle = ''
    notifications .notificationContent = ''

    // 设置通知日期默认值
    if (value === '1') {
        notifications .notifyDate = currentDateTime
    }
}
// 监听滚动事件，更新激活的菜单项
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) => {
    if (!id) return
    
    detailLoading.value = true
    try {
        const data = (await dataDetail(id)) as AddEditForm
        Object.assign(addEditForm, data)
        addEditForm.assessmentYear = addEditForm.assessmentYear.toString()
    } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败，请重试')
    } finally {
        detailLoading.value = false
    }
}

//附件上传
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 selectSupplier = (value) => {
    const supplier = supplierList.value.find((item) => item.supplierId === value)
    if (supplier) {
        addEditForm.supplierId = supplier.supplierId
        addEditForm.supplierName = supplier.companyName
        addEditForm.supplierCode = supplier.supplierCode

        if (addEditForm.notifications  && addEditForm.notifications [0]) {
            addEditForm.notifications [0].supplierId = supplier.supplierId
            addEditForm.notifications [0].supplierName = supplier.companyName
            addEditForm.notifications [0].supplierCode = supplier.supplierCode
        }
    }
}
// ==================== 表单操作 ====================

const handleSubmit = async () => {
    if (!addEditFormRef.value) return

    try {
        await addEditFormRef.value.validate()
        submitLoading.value = true

        // 构建提交数据，将绩效评价数据推送到notification数组
        const submitData = {
            ...addEditForm,
            notifications : [
                {
                    distributeType: 2,
                    assessmentResult: addEditForm.assessmentResult,
                    processType: addEditForm.processType,
                    notificationTitle: addEditForm.notificationTitle,
                    notificationContent: addEditForm.notificationContent,
                    notifyDate: addEditForm.notifyDate,
                    supplierId: addEditForm.supplierId,
                    supplierName: addEditForm.supplierName,
                    supplierCode: addEditForm.supplierCode
                }
            ]
        }

        const { state, message } = await dataAdd(submitData)
        if (state) {
            ElMessage.success(message || '操作成功')
            router.push({ name: 'EvaluationAlertQuery' })
        } else {
            ElMessage.error(message || '操作失败')
        }
    } catch (error) {
        console.error('表单验证失败:', error)
    } finally {
        submitLoading.value = false
    }
}

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

// ==================== 生命周期 ====================
onMounted(() => {
    getSupplierList()
    if (route.query.id) {
        getDetail(route.query.id)
    } else {
        addEditForm.assessmentYear = new Date().getFullYear().toString()
    }
    readyToUpload.value = true
    // 设置滚动监听
    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;
            .content-area {
                width: calc(100%);
                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;
                        .review-requirements {
                            margin-bottom: 10px;
                            .review-requirements-title {
                                color: var(--theme-text-primary);
                                margin-bottom: 5px;
                                font-size: 14px;
                                font-weight: bold;
                            }
                            ul {
                                list-style: none;
                                li {
                                    color: var(--theme-text-primary);
                                    line-height: 25px;
                                    font-size: 14px;
                                }
                            }
                        }
                    }

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

                        .review-actions {
                            display: flex;
                            padding: 10px 0 10px 10px;
                        }
                    }
                }
            }
        }
    }
}
.review-requirements {
    padding: 10px;
    .review-requirements-title {
        color: var(--theme-text-primary);
        font-size: 14px;
        font-weight: bold;
    }
    ul {
        list-style: none;
        li {
            color: var(--theme-text-primary);
            line-height: 25px;
            font-size: 14px;
        }
    }
}
</style>
