<template>
    <div class="edit-add-detail" v-loading="detailLoading" element-loading-text="加载中...">
        <div class="form-content">
            <div class="page-form">
                <div class="main-content">
                    <!-- 步骤条 -->
                    <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="content-area">
                        <el-form
                            ref="addEditFormRef"
                            :model="addEditForm"
                            :rules="addEditFormRules"
                            size="large"
                            label-position="left"
                            label-suffix="："
                        >
                            <el-collapse v-model="activeCollapse">
                                <el-collapse-item name="basic-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="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">
                                                    <el-date-picker
                                                        v-model="addEditForm.assessmentYear"
                                                        type="year"
                                                        v-if="addEditForm.assessmentType == 3"
                                                        value-format="YYYY"
                                                        :default-value="
                                                            new Date(addEditForm.assessmentYear, 0)
                                                        "
                                                        :disabled-date="disabledDate"
                                                        placeholder="请选择"
                                                    ></el-date-picker>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    评价体系名称
                                                </template>
                                                <el-form-item prop="valuationConfigurationName">
                                                    <el-checkbox-group
                                                        v-model="
                                                            addEditForm.valuationConfigurationName
                                                        "
                                                        class="evaluation-checkbox-group"
                                                    >
                                                        <el-checkbox
                                                            v-for="item in appraisalList"
                                                            :key="item.id"
                                                            :label="item.id"
                                                            :value="item.id"
                                                            class="evaluation-checkbox"
                                                        >
                                                            {{ item.name }}
                                                        </el-checkbox>
                                                    </el-checkbox-group>
                                                </el-form-item>
                                            </el-descriptions-item>
                                        </el-descriptions>
                                    </div>
                                </el-collapse-item>
                                <el-collapse-item name="review-info">
                                    <template #title>
                                        <div class="section-title">
                                            <el-icon><Document /></el-icon>
                                            <span>评审人分配</span>
                                        </div>
                                    </template>

                                    <el-tabs v-model="activeReviewTab" class="review-tabs">
                                        <el-tab-pane
                                            v-for="item in selectedAppraisalList"
                                            :key="item.id"
                                            :label="item.name"
                                            :name="item.id.toString()"
                                        >
                                            <div class="review-actions">
                                                <el-button
                                                    type="primary"
                                                    @click="assignReviewers(item.id)"
                                                >
                                                    分配评审人
                                                </el-button>
                                                <el-button @click="clearReviewers(item.id)">
                                                    清空评审人
                                                </el-button>
                                                <el-button
                                                    type="primary"
                                                    @click="handleSubmit"
                                                    :loading="btnLoading"
                                                >
                                                    提交
                                                </el-button>
                                            </div>

                                            <el-table
                                                :data="getReviewTableData(item.id)"
                                                border
                                                stripe
                                                row-key="id"
                                                :tree-props="{
                                                    children: 'children',
                                                    hasChildren: 'hasChildren',
                                                    expandColumnKey: 'name'
                                                }"
                                                :default-expand-all="true"
                                                @selection-change="handleSelectionChange"
                                                :ref="`reviewTableRef_${item.id}`"
                                            >
                                                <el-table-column
                                                    type="selection"
                                                    width="55"
                                                    align="center"
                                                />
                                                <el-table-column
                                                    label="序号"
                                                    align="center"
                                                    width="80"
                                                >
                                                    <template #default="{ $index }">
                                                        {{ $index + 1 }}
                                                    </template>
                                                </el-table-column>
                                                <el-table-column
                                                    prop="name"
                                                    align="center"
                                                    label="类别"
                                                    width="180"
                                                >
                                                    <template #default="{ row }">
                                                        <div v-if="row.isParent">
                                                            {{ row.name }}
                                                        </div>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column
                                                    label="评审内容"
                                                    prop="content"
                                                    min-width="300"
                                                />
                                                <el-table-column
                                                    label="评分人"
                                                    width="200"
                                                    align="center"
                                                >
                                                    <template #default="{ row }">
                                                        <el-select
                                                            v-if="!row.isParent"
                                                            v-model="row.usersList"
                                                            placeholder="请选择"
                                                            clearable
                                                            multiple
                                                            @change="changeRatingName(row)"
                                                        >
                                                            <el-option
                                                                v-for="reviewer in reviewerOptions"
                                                                :key="reviewer.userId"
                                                                :label="reviewer.fullname"
                                                                :value="reviewer.userId"
                                                            />
                                                        </el-select>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </el-tab-pane>
                                    </el-tabs>
                                </el-collapse-item>
                            </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>
        <!-- 分配评审人弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            title="分配评审人"
            width="500"
            :before-close="handleClose"
            align-center
            :close-on-click-modal="false"
        >
            <div>
                <el-form ref="formRef" :model="form" label-width="80px">
                    <el-form-item label="评分人">
                        <el-select
                            v-model="form.ratingName"
                            filterable
                            placeholder="请选择"
                            clearable
                            multiple
                        >
                            <el-option
                                v-for="item in reviewerOptions"
                                :key="item.userId"
                                :label="item.fullname"
                                :value="item.userId"
                            />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">关 闭</el-button>
                    <el-button type="primary" @click="saveDialog"> 保 存 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import DatePopover from '@/components/DatePopover/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { type FormRules } from 'element-plus'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { reactive, ref, onMounted, nextTick, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
    getEvaluationConfig,
    dataUpdate,
    dataAdd,
    dataDetail,
    getEvaluationConfigDetail
} from '@/api/supplierMonitor/PerformanceManagement/PerformanceEvaluation'
import { dataTable } from '@/api/supplierMonitor/BasicManagement/AssessmentCategory'
import { getOrgUserList } from '@/api/system/user'
interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}
interface formRef {
    [key: string]: string | number | undefined | null | any
}
interface ScoreItem {
    id: string
    category: string
    reviewContent: string
    defaultReviewer: string
    score: number
    weight: number
    isParent: boolean
    children?: ScoreItem[]
}

interface ReviewerOption {
    value: string
    label: string
    children?: ReviewerOption[]
}

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

// 表单相关
const addEditFormRef = ref()
const detailLoading = ref(false)
const activeCollapse = ref(['basic-info', 'supplier-info', 'review-info'])
const appraisalList = ref<any[]>([])
const enterpriseList = ref<any[]>([])
const supplierLoading = ref(false)
const dialogVisible = ref(false)
const btnLoading = ref(false)
const userDetail = ref<any>({})
const tableData = ref<any[]>([])
const checkList = ref<any[]>([])
const supplierTableRef = ref()
const activeReviewTab = ref('')
const reviewTableData = ref<Record<string, any[]>>({})
const classCatory = ref<any[]>([])
// 编辑相关
const isEdit = computed(() => route.name === 'edit')
const editId = computed(() => route.params.id as string)
getDictionaryByCode
// 表单数据
const currentStep = ref(0)
const form = reactive<formRef>({
    ratingName: [],
    currentAppraisalId: ''
})
const addEditForm = reactive<AddEditForm>({
    valuationConfigurationName: [],
    assessmentYear: new Date().getFullYear().toString(),
    assessment: new Date().getFullYear().toString(),
    assessmentType: '3',
    valuationConfigurationCode: '',
    totalScore: '',
    enterpriseCode: '',
    enterpriseName: '',
    enterpriseId: '',
    valuationConfigurationId: '',
    desc: '',
    details: [],
    assessmentMonth: '',
    assessmentQuater: '',
    initiatorName: '',
    initiatorId: '',
    initiatorAccount: '',
})

// 表单验证规则
const addEditFormRules = reactive<FormRules>({
    valuationConfigurationName: [{ required: true, message: '请选择评价体系', trigger: 'change' }],
    assessmentYear: [{ required: true, message: '请选择评价年度', trigger: 'change' }],
    valuationConfigurationCode: [{ required: true, message: '请选择周期类型', trigger: 'change' }],
    valuationConfigurationId: [{ required: true, message: '请选择评价时间', trigger: 'change' }],
    assessmentQuater: [{ required: true, message: '请选择评价时间', trigger: 'change' }],
    assessmentMonth: [{ required: true, message: '请选择评价时间', trigger: 'change' }]
})

// 表格相关
const selectedRows = ref<ScoreItem[]>([])

// 评审人选项
const reviewerOptions = ref<ReviewerOption[]>([])

// 获取评审人
const getReviewerOptions = async () => {
    const params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: [
            {
                group: 'orgTree',
                operation: 'IN',
                property: 'ORG_ID_',
                relation: 'AND',
                value: userDetail.value.userDetail.org[0].orgId
            }
        ]
    }
    const { total = 0, rows = [] } = await getOrgUserList(params)
    reviewerOptions.value = rows
}

// 表格选择变化
const handleSelectionChange = (selection: ScoreItem[]) => {
    selectedRows.value = selection
}

// 禁用日期函数
const disabledDate = (time: Date) => {
    if (!addEditForm.assessmentYear) return false
    return time.getFullYear() !== parseInt(addEditForm.assessmentYear)
}

// 取消
const handleCancel = () => {
    router.push({ name: 'PerformanceEvaluation' })
}
// 计算属性：获取已选择的评价体系列表
const selectedAppraisalList = computed(() => {
    return appraisalList.value.filter((item) =>
        addEditForm.valuationConfigurationName.includes(item.id)
    )
})

// 获取指定评价体系的表格数据
const getReviewTableData = (appraisalId: string) => {
    return reviewTableData.value[appraisalId] || []
}

// 分配评审人
const assignReviewers = (appraisalId?: string) => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要分配评审人的项目')
        return
    }
    // 记录当前操作的评价体系ID
    form.currentAppraisalId = appraisalId
    dialogVisible.value = true
}

// 清空评审人
const clearReviewers = (appraisalId?: string) => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要清空评审人的项目')
        return
    }

    const currentData = appraisalId ? reviewTableData.value[appraisalId] : addEditForm.details

    // 递归清空评审人
    const clearReviewer = (data, selectedId) => {
        for (let item of data) {
            if (item.id === selectedId) {
                item.users = []
                item.usersList = []
                return true
            }
            if (item.children && item.children.length > 0) {
                if (clearReviewer(item.children, selectedId)) {
                    return true
                }
            }
        }
        return false
    }

    selectedRows.value.forEach((selectedRow) => {
        clearReviewer(currentData, selectedRow.id)
    })

    ElMessage.success(`已清空${selectedRows.value.length}个项目的评审人`)
}
// 批量保存评审人
const saveDialog = () => {
    if (!form.ratingName || form.ratingName.length === 0) {
        ElMessage.warning('请选择评审人')
        return
    }

    // 获取所有选中的评审人信息
    const selectedReviewers = []
    form.ratingName.forEach((userId) => {
        const reviewer = reviewerOptions.value.find((item) => item.userId === userId)
        if (reviewer) {
            selectedReviewers.push({
                ratingId: reviewer.userId,
                ratingName: reviewer.fullname,
                ratingAccount: reviewer.account
            })
        }
    })

    if (selectedReviewers.length === 0) {
        ElMessage.warning('评审人信息不存在')
        return
    }

    // 递归查找并更新评审人
    const updateReviewer = (data, selectedId) => {
        for (let item of data) {
            if (item.id === selectedId) {
                item.usersList = [...form.ratingName]
                item.users = [...selectedReviewers]
                return true
            }
            if (item.children && item.children.length > 0) {
                if (updateReviewer(item.children, selectedId)) {
                    return true
                }
            }
        }
        return false
    }

    // 获取当前操作的数据源
    const currentData = form.currentAppraisalId
        ? reviewTableData.value[form.currentAppraisalId]
        : addEditForm.details

    selectedRows.value.forEach((selectedRow) => {
        updateReviewer(currentData, selectedRow.id)
    })

    const reviewerNames = selectedReviewers.map((r) => r.ratingName).join('、')
    ElMessage.success(`已分配评审人：${reviewerNames}`)
    handleClose()
}
// 关闭分配评审人弹窗
const handleClose = () => {
    form.ratingName = []
    form.currentAppraisalId = ''
    dialogVisible.value = false
}
const changeRatingName = (row: ScoreItem) => {
    row.users = []
    if (row.usersList && row.usersList.length > 0) {
        row.usersList.forEach((userId) => {
            const selectedReviewer = reviewerOptions.value.find(
                (reviewer) => reviewer.userId === userId
            )
            if (selectedReviewer) {
                row.users.push({
                    ratingId: selectedReviewer.userId,
                    ratingName: selectedReviewer.fullname,
                    ratingAccount: selectedReviewer.account
                })
            }
        })
    }
}
// 获取评价体系配置
const getEvaluationConfigData = async () => {
    try {
        let params = {
            pageBean: {
                page: -1,
                pageSize: -1
            },
            querys: [
                {
                    group: 'main',
                    operation: 'EQUAL',
                    property: 'status',
                    relation: 'AND',
                    value: '1'
                }
            ],
            sorter: []
        }
        const { total = 0, rows = [] } = await getEvaluationConfig(params)
        appraisalList.value = rows
    } catch (error) {
        console.error('获取评价体系配置失败:', error)
    }
}

// 获取评价详情
const getAppraisalDetail = async (id: string) => {
    try {
        detailLoading.value = true
        const data = await getEvaluationConfigDetail(id)
        addEditForm.desc = data.value.desc
        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, users: [], usersList: [] })
            } else {
                const parentItem = {
                    ...item,
                    children: [],
                    isParent: true,
                    users: [],
                    usersList: []
                }
                groupedDetails.push(parentItem)
                codeMap.set(item.assessmentIndicatorTypeCode, parentItem)
            }
        })

        // 将获取的详情数据赋值给 addEditForm.details 用于比较
        addEditForm.details = data.value.details

        // 调用 initScoreDetails 进行数据匹配和重新赋值
        initScoreDetails()

        // 使用 initScoreDetails 返回的优化数据构建表格数据
        const optimizedData = addEditForm.details.map(category => ({
            ...category,
            name: category.name,
            isParent: true,
            users: [],
            usersList: [],
            children: category.children?.map(child => ({
                ...child,
                isParent: false,
                users: [],
                usersList: []
            })) || []
        }))
        
        // 为每个评价体系单独存储数据
        reviewTableData.value[id] = optimizedData

        // 如果是第一个评价体系，设置总分
        if (Object.keys(reviewTableData.value).length === 1) {
            addEditForm.totalScore = data.value.totalScore
        }
    } finally {
        detailLoading.value = false
    }
}
// 监听评价体系选择变化
watch(
    () => addEditForm.valuationConfigurationName,
    (newValues, oldValues) => {
        if (!newValues || newValues.length === 0) {
            reviewTableData.value = {}
            activeReviewTab.value = ''
            return
        }

        // 处理移除的评价体系
        const removedIds = oldValues?.filter((id) => !newValues.includes(id)) || []
        removedIds.forEach((id) => {
            delete reviewTableData.value[id]
        })

        // 设置默认激活的标签页
        if (newValues.length > 0 && !activeReviewTab.value) {
            activeReviewTab.value = newValues[0].toString()
        }
    },
    { deep: true }
)

// 监听tabs页签切换
watch(
    () => activeReviewTab.value,
    async (newTabId) => {
        if (newTabId && !reviewTableData.value[newTabId]) {
            await getAppraisalDetail(newTabId)
        }
    }
)

// 评价类型变化处理
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 getDetail = async (id: string) => {
    try {
        detailLoading.value = true
        const data = await dataDetail(id)
        Object.assign(addEditForm, data.value)

        // 处理评审人回显
        if (addEditForm.details && addEditForm.details.length > 0) {
            addEditForm.details.forEach((item) => {
                if (item.users && item.users.length > 0) {
                    item.usersList = item.users.map((user) => user.ratingId || user.userId)
                } else {
                    item.usersList = []
                    item.users = []
                }

                if (item.children && item.children.length > 0) {
                    item.children.forEach((child) => {
                        if (child.users && child.users.length > 0) {
                            child.usersList = child.users.map(
                                (user) => user.ratingId || user.userId
                            )
                        } else {
                            child.usersList = []
                            child.users = []
                        }
                    })
                }
            })
        }
    } finally {
        detailLoading.value = false
    }
}

// 检查评审人是否完整
const checkReviewers = () => {
    const missingReviewers = []

    const checkItem = (item, parentName = '', appraisalName = '') => {
        const itemName = appraisalName
            ? `${appraisalName} - ${parentName ? `${parentName} - ${item.name}` : item.name}`
            : parentName
              ? `${parentName} - ${item.name}`
              : item.name

        if (!item.users || item.users.length === 0) {
            missingReviewers.push(itemName)
        }

        if (item.children && item.children.length > 0) {
            item.children.forEach((child) => {
                checkItem(child, item.name || item.assessmentIndicatorTypeName, appraisalName)
            })
        }
    }

    // 检查所有选中的评价体系
    selectedAppraisalList.value.forEach((appraisal) => {
        const tableData = reviewTableData.value[appraisal.id] || []
        tableData.forEach((item) => {
            checkItem(item, '', appraisal.name)
        })
    })

    return missingReviewers
}
// 获取评价类别分类
const getCategory = async () => {
    try {
        let params = {
            pageBean: {
                page: -1,
                pageSize: -1
            },
            querys: []
        }
        const data = await dataTable(params)
        classCatory.value = data.rows
    } finally {
    }
}
const initScoreDetails = () => {
    classCatory.value.forEach((category) => {
        category.children = []
        category.grade = '1'
    })

    // 重新构建 addEditForm.details
    addEditForm.details.forEach((item) => {
        classCatory.value.forEach((category) => {
            if (category.code === item.assessmentIndicatorTypeCode) {
                category.children.push({
                    ...item,
                    name: item.performanceEvaluationDetailsName,
                    grade: '2',
                    isParent: true
                })
            }
        })
    })

    // 重新赋值给 addEditForm.details
    addEditForm.details = classCatory.value
}
// 提交
const handleSubmit = () => {
    if (!activeReviewTab.value) {
        ElMessage.warning('请选择要提交的评价体系')
        return
    }

    // 只检查当前页签的评审人
    const currentTabData = reviewTableData.value[activeReviewTab.value] || []
    const missingReviewers = []

    const checkItem = (item, parentName = '') => {
        const itemName = parentName ? `${parentName} - ${item.name}` : item.name
        if (!item.users || item.users.length === 0) {
            missingReviewers.push(itemName)
        }
        if (item.children && item.children.length > 0) {
            item.children.forEach((child) => {
                checkItem(child, item.name || item.assessmentIndicatorTypeName)
            })
        }
    }

    currentTabData.forEach((item) => {
        checkItem(item)
    })

    if (missingReviewers.length > 0) {
        ElMessage.warning(`当前页签项目存在未分配评审人`)
        return
    }

    // 只处理当前页签的子级数据
    const newDetails = []
    currentTabData.forEach((item) => {
        if (item.children && item.children.length > 0) {
            item.children.forEach((child) => {
                const { children: _, ...childWithoutChildren } = child
                newDetails.push(childWithoutChildren)
            })
        }
    })

    // 获取当前评价体系信息
    const currentAppraisal = appraisalList.value.find((item) => item.id === activeReviewTab.value)

    // 构建提交数据，只包含基础信息和当前页签数据
    const submitData = {
        ...addEditForm,
        details: newDetails,
        valuationConfigurationName: currentAppraisal?.name || '',
        valuationConfigurationId: activeReviewTab.value,
        valuationConfigurationCode: currentAppraisal?.code || ''
    }

    submitData.details.forEach((item) => {
        item.performanceEvaluationDetailsId = item.id
        item.performanceEvaluationDetailsName = item.content
        item.performanceEvaluationDetailsCode = item.code
    })

    // 从 assessmentMonth 中提取月份
    if (submitData.assessmentMonth) {
        submitData.assessmentMonth = parseInt(submitData.assessmentMonth.split('-')[1]).toString()
    }

    // 从 assessmentQuater 中提取季度
    if (submitData.assessmentQuater) {
        submitData.assessmentQuater = submitData.assessmentQuater.split('-')[1]
    }

    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                btnLoading.value = true
                const value = submitData.id
                    ? await dataUpdate({ ...submitData })
                    : await dataAdd({ ...submitData })
                if (value.state) {
                    ElMessage.success('保存成功')
                }
            } finally {
                btnLoading.value = false
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}

onMounted(async () => {
    detailLoading.value = true
    try {
        await getCategory()
        const storedData = sessionStorage.getItem('user')
        if (storedData) {
            userDetail.value = JSON.parse(storedData)
        }
        addEditForm.enterpriseCode = userDetail.value.userDetail.org[0].orgCode
        addEditForm.enterpriseId = userDetail.value.userDetail.org[0].orgId
        addEditForm.enterpriseName = userDetail.value.userDetail.org[0].orgName
        addEditForm.initiatorName = userDetail.value.userInfo.username
        addEditForm.initiatorId = userDetail.value.userInfo.userId
        addEditForm.initiatorAccount = userDetail.value.userInfo.account

        await getEvaluationConfigData()
        await getReviewerOptions()

        // 如果是编辑模式，获取详情数据
        if (isEdit.value) {
            await getDetail(editId.value)
        }
    } finally {
        detailLoading.value = false
    }
})
</script>

<style lang="scss" scoped>
.review-requirements {
    margin-bottom: 10px;
    .review-requirements-title {
        color: var(--theme-text-primary);
        margin-bottom: 5px;
        font-size: 15px;
        font-weight: bold;
    }
    ul {
        list-style: none;
        li {
            color: var(--theme-text-primary);
            line-height: 25px;
            font-size: 15px;
        }
    }
}
.form-content {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start !important;

    .page-form {
        overflow-y: hidden;
        overflow-y: auto;
        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;
    }
}

.review-actions {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);
}

.step-container {
    width: 100%;
    margin-bottom: 20px;
}

.content-area {
    /* 确保容器的高度计算正确 */
    box-sizing: border-box;

    :deep(.el-collapse) {
        /* 通过添加 1px 来补偿 border 导致的 1px 高度差 */
        margin-bottom: 1px;
    }
}

.evaluation-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;

    .evaluation-checkbox {
        margin-right: 0;
        margin-bottom: 8px;

        :deep(.el-checkbox__label) {
            font-size: 14px;
            color: var(--el-text-color-regular);
        }

        :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
            background-color: var(--el-color-primary);
            border-color: var(--el-color-primary);
        }
    }
}

.review-tabs {
    :deep(.el-tabs__header) {
        margin-bottom: 16px;
    }

    :deep(.el-tabs__nav-wrap) {
        padding: 0 10px;
    }

    :deep(.el-tabs__item) {
        font-size: 14px;
        padding: 0 16px;
        color: #000000 !important;

        &.is-active {
            color: var(--el-color-primary) !important;
        }
    }

    :deep(.el-tabs__content) {
        padding: 0;
    }
}
</style>
