<template>
    <div class="app-container daily-plan-edit">
        <!-- 顶部返回 + 标题 -->
        <el-page-header @back="onBack" :content="pageTitle" class="page-header" />

        <!-- 基本信息表单（禁用） -->
        <el-card shadow="never" class="card-section">
            <template #header>
                <div class="card-header">基本信息</div>
            </template>

            <el-form
                ref="baseFormRef"
                :model="formData"
                size="large"
                label-width="180"
                :disabled="true"
            >
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="运检站">
                            <el-input v-model="formData.inspectionStationName" disabled />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="专业">
                            <el-input v-model="formData.planMajorName" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="项目名称">
                            <el-input v-model="formData.projectName" disabled />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="日期">
                            <el-input v-model="formData.dayPlan" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 动态表单组件（根据类型切换） -->
        <component
            :is="currentFormComponent"
            :form-data="formData"
            :is-detail="isDetail"
            :selected-manager-names="selectedManagerNames"
            @open-person-picker="onOpenPersonPicker"
            @update:form-data="formData = $event"
            ref="formRef"
        />

        <!-- 底部操作按钮 -->
        <div class="page-footer">
            <ComButton plain type="info" @click="onBack">
                {{ isDetail ? '返回' : '取消' }}
            </ComButton>
            <ComButton v-if="!isDetail" type="primary" @click="onSubmit">保存</ComButton>
        </div>

        <!-- 人员选择弹窗 -->
        <ComDialog :dialog-config="managerDialogConfig" @closeDialogOuter="onCloseDialogOuter">
            <template #outerContent>
                <el-row :gutter="20" style="padding-bottom: 30px">
                    <el-col :span="16">
                        <div class="person-search-bar">
                            <el-input
                                v-model.trim="managerDialog.keyword"
                                placeholder="输入姓名搜索"
                                clearable
                                prefix-icon="Search"
                            />
                        </div>
                        <el-table
                            border
                            ref="personTableRef"
                            :data="filteredPersons"
                            @selection-change="onManagerSelectionChange"
                        >
                            <el-table-column type="selection" width="50" align="center" />
                            <el-table-column
                                show-overflow-tooltip
                                prop="org"
                                label="人员所属单位"
                                align="center"
                            />
                            <el-table-column
                                show-overflow-tooltip
                                prop="name"
                                label="姓名"
                                width="120"
                                align="center"
                            />
                            <el-table-column
                                show-overflow-tooltip
                                prop="gender"
                                label="性别"
                                align="center"
                            />
                            <el-table-column
                                show-overflow-tooltip
                                prop="station"
                                label="岗位"
                                align="center"
                            />
                            <el-table-column
                                show-overflow-tooltip
                                prop="position"
                                label="岗位性质"
                                align="center"
                            />
                            <el-table-column
                                show-overflow-tooltip
                                prop="type"
                                label="人员分类"
                                align="center"
                            />
                        </el-table>
                    </el-col>
                    <el-col :span="8">
                        <div class="selected-panel">
                            <div class="panel-header">
                                <span>已选人员</span>
                                <el-button type="text" @click="onClearManagers">清空</el-button>
                            </div>
                            <div class="selected-list">
                                <div>
                                    <el-tag
                                        :key="item.id"
                                        :closable="!isDetail"
                                        class="selected-tag"
                                        @close="onRemoveManager(item)"
                                        v-for="item in managerDialog.selected"
                                    >
                                        {{ item.name }}
                                    </el-tag>
                                </div>

                                <div v-if="!managerDialog.selected.length" class="empty-tip">
                                    暂未选择人员
                                </div>
                            </div>
                        </div>
                    </el-col>
                </el-row>
                <el-row class="common-btn-row fixed-bottom">
                    <ComButton plain type="info" @click="managerDialogConfig.outerVisible = false">
                        取消
                    </ComButton>
                    <ComButton type="primary" @click="onConfirmManager">确定</ComButton>
                </el-row>
            </template>
        </ComDialog>
    </div>
</template>

<script setup name="DailyPlanEdit">
import {
    ref,
    reactive,
    computed,
    getCurrentInstance,
    nextTick,
    onMounted,
    shallowRef,
    watch,
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getPersonnelCommonListAPI } from '@/api/common.js'
import { updateDailyPlanAPI, getDailyPlanDetailAPI } from '@/api/planMange/dailyPlan.js'
import { Search } from '@element-plus/icons-vue'
import { useOptions } from '@/hooks/useOptions'
import ComButton from '@/components/ComButton/index.vue'
import ComDialog from '@/components/ComDialog/index.vue'
import RunForm from './forms/runForm.vue'
import RepairForm from './forms/repairForm.vue'
import ProjectForm from './forms/projectForm.vue'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

// 使用通用 Hook 获取下拉数据
const { options: personnelCommonOptions } = useOptions(
    'personnelCommonOptions',
    getPersonnelCommonListAPI,
    {},
)

const mode = computed(() => route.query.mode || 'edit')
const isDetail = computed(() => mode.value === 'detail')

// 获取日计划类型：0-运行，1-检修，2-项目部
const dayPlanType = computed(() => {
    // 优先从路由参数获取
    if (route.query.dayPlanType !== undefined) {
        return String(route.query.dayPlanType)
    }
    // 如果没有，默认返回运行类型
    return '0'
})

// 根据类型动态切换表单组件
const formComponents = {
    0: RunForm, // 运行
    1: RepairForm, // 检修
    2: ProjectForm, // 项目部
}

const currentFormComponent = shallowRef(formComponents[dayPlanType.value] || RunForm)

const pageTitle = computed(() => {
    const typeMap = {
        0: '运行',
        1: '检修',
        2: '项目部',
    }
    const typeName = typeMap[dayPlanType.value] || '运行'
    if (mode.value === 'edit') return `编辑日计划（${typeName}）`
    if (mode.value === 'detail') return `日计划详情（${typeName}）`
    return `新增日计划（${typeName}）`
})

const baseFormRef = ref(null)
const formRef = ref(null)

// 从路由参数获取基本信息（禁用字段）
const routeParams = computed(() => ({
    inspectionStationName: route.query.inspectionStationName || '',
    projectName: route.query.projectName || '',
    planMajorName: route.query.planMajorName || '',
    dayPlan: route.query.dayPlan || '',
    dayPlanId: route.query.id || null,
}))

// 运行类型表单数据结构
const getRunFormData = () => ({
    dayPlanId: routeParams.value.dayPlanId,
    // 基本信息（禁用，从路由参数获取，不传给后端）
    inspectionStationName: routeParams.value.inspectionStationName,
    projectName: routeParams.value.projectName,
    planMajorName: routeParams.value.planMajorName,
    dayPlan: routeParams.value.dayPlan,
    // 计划投入资源情况（可编辑，需要传给后端）
    plannedWorkload: null, // 计划工作量
    planPersonnelList: [], // 拟投入作业人员（数组，暂时不确定字段名）
    planPersonnel: '', // 拟投入作业人员（字符串，提交时使用）
    proposedLongTimeCar: null, // 拟投入长租车
    proposedTemporaryCar: null, // 拟投入临租车
    // 实际完成情况
    actualPersonnelList: [], // 实际入作业人员（数组，暂时不确定字段名）
    actualPersonnel: '', // 实际入作业人员（字符串，提交时使用）
    actualLongTimeCar: null, // 实际入长租车
    actualTemporaryCar: null, // 实际入临租车
    actualWorkContent: '', // 实际完成工作内容
    actualWorkload: null, // 实际完成工作量
    completionPercentage: null, // 完成比例
    planCompletionStatus: null, // 作业计划完成情况
    planChanges: '', // 计划变更及未完成情况说明
})

// 检修类型表单数据结构
const getRepairFormData = () => ({
    dayPlanId: routeParams.value.dayPlanId,
    // 基本信息（禁用，从路由参数获取，不传给后端）
    inspectionStationName: routeParams.value.inspectionStationName,
    projectName: routeParams.value.projectName,
    planMajorName: routeParams.value.planMajorName,
    dayPlan: routeParams.value.dayPlan,
    // 计划投入资源情况
    plannedWorkload: null, // 计划工作量
    highAltitudePersonnelList: [], // 拟投入高处作业人员（数组）
    groundPersonnelList: [], // 拟投入地面作业人员（数组）
    proposedProficientPersonnel: null, // 计划投入熟练工人员数量
    proposedProficientDay: null, // 计划投入工日（熟练工）
    proposedAssistancePersonnel: null, // 计划投入辅助工人员数量
    proposedAssistanceDay: null, // 计划投入工日（辅助工）
    proposedLongTimeCar: null, // 拟投入长租车
    proposedTemporaryCar: null, // 拟投入临租车
    proposedSubCar: null, // 拟投入分包车
    // 实际完成情况
    actualHighAltitudePersonnelList: [], // 实际投入高处作业人员（数组）
    actualGroundPersonnelList: [], // 实际投入地面作业人员（数组）
    actualProficientPersonnel: null, // 实际投入检修熟练工数量
    actualAssistancePersonnel: null, // 实际投入检修辅助工数量
    actualLongTimeCar: null, // 实际投入长租车
    actualTemporaryCar: null, // 实际投入临租车
    actualSubCar: null, // 实际投入分包车
    actualWorkloadList: [
        {
            workloadCategoryId: '',
            workloadCategoryName: '',
            unitPrice: '',
            settlementUnitPrice: '',
            workloadNum: '',
        },
    ], // 实际完成工作内容（动态列表）
    actualWorkload: null, // 实际完成工作量
    completionPercentage: null, // 完成比例
    planCompletionStatus: null, // 作业计划完成情况
    planChanges: '', // 计划变更及未完成情况说明
})

// 项目部类型表单数据结构（与检修类型基本一致，但实际完成情况中无工作量字段，改为实际完成工作内容）
const getProjectFormData = () => ({
    dayPlanId: routeParams.value.dayPlanId,
    inspectionStationName: routeParams.value.inspectionStationName,
    projectName: routeParams.value.projectName,
    planMajorName: routeParams.value.planMajorName,
    dayPlan: routeParams.value.dayPlan,
    plannedWorkload: null,
    highAltitudePersonnelList: [],
    groundPersonnelList: [],
    proposedProficientPersonnel: null,
    proposedProficientDay: null,
    proposedAssistancePersonnel: null,
    proposedAssistanceDay: null,
    proposedLongTimeCar: null,
    proposedTemporaryCar: null,
    proposedSubCar: null,
    actualHighAltitudePersonnelList: [],
    actualGroundPersonnelList: [],
    actualProficientPersonnel: null,
    actualAssistancePersonnel: null,
    actualLongTimeCar: null,
    actualTemporaryCar: null,
    actualSubCar: null,
    actualWorkContent: '',
    completionPercentage: null,
    planCompletionStatus: null,
    planChanges: '',
})

// 根据类型获取对应的表单数据结构
const getInitFormData = () => {
    const type = dayPlanType.value
    if (type === '0' || type === 0) {
        return getRunFormData()
    } else if (type === '1' || type === 1) {
        return getRepairFormData()
    } else if (type === '2' || type === 2) {
        return getProjectFormData()
    }
    // 默认返回运行类型
    return getRunFormData()
}

const formData = ref(getInitFormData())

// 表单校验规则（子组件内部处理，这里保留用于兼容）
const rules = computed(() => ({}))

const onBack = () => {
    proxy.$tab.closeOpenPage({
        path: '/plan/dailyPlan',
        query: {
            dayPlanType: dayPlanType.value,
        },
    })
}

const onSubmit = async () => {
    try {
        const valid = await formRef.value?.validate()

        if (!valid) {
            return
        }

        // 校验通过，继续执行后续代码
        const proposedPersonnelList = []

        const type = dayPlanType.value

        if (type === '0' || type === 0) {
            // 运行类型：拟投入/实际投入作业人员
            ;(formData.value.planPersonnelList || []).forEach((item) => {
                proposedPersonnelList.push({
                    dayPlanId: route.query.id,
                    inspectionStationName: item.inspectionStationName,
                    personnelId: item.id,
                    name: item.name,
                    dataSource: 0, // 拟投入作业人员
                })
            })
            ;(formData.value.actualPersonnelList || []).forEach((item) => {
                proposedPersonnelList.push({
                    dayPlanId: route.query.id,
                    inspectionStationName: item.inspectionStationName,
                    personnelId: item.id,
                    name: item.name,
                    dataSource: 1, // 实际入作业人员
                })
            })
        } else if (type === '1' || type === 1 || type === '2' || type === 2) {
            // 检修类型和项目部类型：高处/地面，拟投入 & 实际投入
            ;(formData.value.highAltitudePersonnelList || []).forEach((item) => {
                proposedPersonnelList.push({
                    dayPlanId: route.query.id,
                    inspectionStationName: item.inspectionStationName,
                    personnelId: item.id,
                    name: item.name,
                    dataSource: 2, // 拟投入高处作业人员
                })
            })
            ;(formData.value.groundPersonnelList || []).forEach((item) => {
                proposedPersonnelList.push({
                    dayPlanId: route.query.id,
                    inspectionStationName: item.inspectionStationName,
                    personnelId: item.id,
                    name: item.name,
                    dataSource: 3, // 拟投入地面作业人员
                })
            })
            ;(formData.value.actualHighAltitudePersonnelList || []).forEach((item) => {
                proposedPersonnelList.push({
                    dayPlanId: route.query.id,
                    inspectionStationName: item.inspectionStationName,
                    personnelId: item.id,
                    name: item.name,
                    dataSource: 4, // 实际投入高处作业人员
                })
            })
            ;(formData.value.actualGroundPersonnelList || []).forEach((item) => {
                proposedPersonnelList.push({
                    dayPlanId: route.query.id,
                    inspectionStationName: item.inspectionStationName,
                    personnelId: item.id,
                    name: item.name,
                    dataSource: 5, // 实际投入地面作业人员
                })
            })
        }

        // 组装参数：排除基本信息和仅前端使用的字段
        const {
            inspectionStationName,
            projectName,
            planMajorName,
            dayPlan,
            planPersonnelList,
            actualPersonnelList,
            highAltitudePersonnelList,
            groundPersonnelList,
            actualHighAltitudePersonnelList,
            actualGroundPersonnelList,
            actualPersonnel,
            planPersonnel,
            actualWorkloadList,
            ...submitData
        } = formData.value

        submitData.proposedPersonnelList = proposedPersonnelList
        submitData.dayPlanType = type
        if (type === '1' || type === 1) {
            submitData.workloadList = formData.value.actualWorkloadList
        }

        const result = await updateDailyPlanAPI(submitData)
        if (result.code === 200) {
            proxy.$modal.msgSuccess('保存成功')
            onBack()
        }
    } catch (error) {
        return Promise.reject(error)
    }
}

// 人员选择弹窗相关
const personTableRef = ref(null)
const managerDialogConfig = reactive({
    outerVisible: false,
    outerTitle: '选择人员',
    outerWidth: '70%',
    minHeight: '60vh',
    maxHeight: '80vh',
})

const managerDialog = reactive({
    visible: false,
    keyword: '',
    selected: [],
    type: 'plan', // 'plan', 'actual', 'highAltitude', 'ground', 'actual_highAltitude', 'actual_ground'
})

// 将公共人员列表转换为表格展示需要的字段结构
const personList = computed(() => {
    return (personnelCommonOptions.value || []).map((item) => ({
        ...item,
        org: item.inspectionStationName, // 人员所属单位
        gender: item.sex === '1' ? '男' : '女',
        station: item.positionName, // 岗位
        position: item.personnelNatureName, // 岗位性质
        type: item.personnelClassificationName, // 人员分类
    }))
})

const filteredPersons = computed(() => {
    const list = personList.value
    if (!managerDialog.keyword) return list
    const keyword = managerDialog.keyword.toLowerCase()
    return list.filter((item) => {
        const name = (item.name || '').toLowerCase()
        const org = (item.org || '').toLowerCase()
        const station = (item.station || '').toLowerCase()
        return name.includes(keyword) || org.includes(keyword) || station.includes(keyword)
    })
})

const selectedManagerNames = computed(() => {
    if (
        dayPlanType.value === '1' ||
        dayPlanType.value === 1 ||
        dayPlanType.value === '2' ||
        dayPlanType.value === 2
    ) {
        const highAltitude = (formData.value.highAltitudePersonnelList || [])
            .map((item) => item.name)
            .join('、')
        const ground = (formData.value.groundPersonnelList || [])
            .map((item) => item.name)
            .join('、')
        return [highAltitude, ground].filter(Boolean).join('、') || ''
    }
    return (formData.value.planPersonnelList || []).map((item) => item.name).join('、')
})

// 同步表格选中状态：根据 managerDialog.selected 设置表格的选中状态
const syncTableSelection = () => {
    if (!personTableRef.value || !managerDialogConfig.outerVisible) return
    nextTick(() => {
        // 清空当前表格选中状态
        personTableRef.value.clearSelection()
        // 根据 managerDialog.selected 重新设置选中状态
        const selectedIds = new Set(managerDialog.selected.map((item) => item.id))
        filteredPersons.value.forEach((row) => {
            if (selectedIds.has(row.id)) {
                personTableRef.value.toggleRowSelection(row, true)
            }
        })
    })
}

// 监听 filteredPersons 变化，重新同步表格选中状态
watch(
    () => filteredPersons.value,
    () => {
        if (managerDialogConfig.outerVisible) {
            syncTableSelection()
        }
    },
)

const onOpenPersonPicker = async (type = 'plan') => {
    managerDialog.type = type
    managerDialogConfig.outerVisible = true

    let currentList = []
    if (type === 'plan') {
        currentList = formData.value.planPersonnelList || []
    } else if (type === 'actual') {
        currentList = formData.value.actualPersonnelList || []
    } else if (type === 'highAltitude') {
        currentList = formData.value.highAltitudePersonnelList || []
    } else if (type === 'ground') {
        currentList = formData.value.groundPersonnelList || []
    } else if (type === 'actual_highAltitude') {
        currentList = formData.value.actualHighAltitudePersonnelList || []
    } else if (type === 'actual_ground') {
        currentList = formData.value.actualGroundPersonnelList || []
    }

    managerDialog.selected = [...currentList]
    await nextTick()
    syncTableSelection()
}

const onManagerSelectionChange = (rows) => {
    // 获取当前过滤结果中所有行的 ID
    const currentFilteredIds = new Set(filteredPersons.value.map((row) => row.id))

    // 保留不在当前过滤结果中的已选人员（这些人员被过滤掉了，但仍然是已选状态）
    const keptSelected = managerDialog.selected.filter(
        (person) => !currentFilteredIds.has(person.id),
    )

    // 获取当前过滤结果中选中的人员对象
    const selectedInFiltered = rows

    // 合并：保留被过滤掉的已选人员 + 当前过滤结果中的选中人员
    managerDialog.selected = [...keptSelected, ...selectedInFiltered]
}

const onRemoveManager = (item) => {
    managerDialog.selected = managerDialog.selected.filter((row) => row.id !== item.id)
    if (personTableRef.value) {
        const target = personList.value.find((row) => row.id === item.id)
        if (target) personTableRef.value.toggleRowSelection(target, false)
    }
}

const onClearManagers = () => {
    managerDialog.selected = []
    if (personTableRef.value) personTableRef.value.clearSelection()
}

const onConfirmManager = () => {
    const type = managerDialog.type
    // 根据类型更新对应的人员列表
    if (type === 'plan') {
        formData.value.planPersonnelList = [...managerDialog.selected]
        nextTick(() => {
            formRef.value?.validateField?.('planPersonnelList')
        })
    } else if (type === 'actual') {
        formData.value.actualPersonnelList = [...managerDialog.selected]
        nextTick(() => {
            formRef.value?.validateField?.('actualPersonnelList')
        })
    } else if (type === 'highAltitude') {
        formData.value.highAltitudePersonnelList = [...managerDialog.selected]
        nextTick(() => {
            formRef.value?.validateField?.('highAltitudePersonnelList')
        })
    } else if (type === 'ground') {
        formData.value.groundPersonnelList = [...managerDialog.selected]
        nextTick(() => {
            formRef.value?.validateField?.('groundPersonnelList')
        })
    } else if (type === 'actual_highAltitude') {
        formData.value.actualHighAltitudePersonnelList = [...managerDialog.selected]
        nextTick(() => {
            formRef.value?.validateField?.('actualHighAltitudePersonnelList')
        })
    } else if (type === 'actual_ground') {
        formData.value.actualGroundPersonnelList = [...managerDialog.selected]
        nextTick(() => {
            formRef.value?.validateField?.('actualGroundPersonnelList')
        })
    }
    managerDialogConfig.outerVisible = false
}

// 关闭弹框统一处理
const onCloseDialogOuter = (visible) => {
    managerDialogConfig.outerVisible = visible
}

// 获取详情（如果需要从后端获取数据）
const getDetail = async () => {
    try {
        const result = await getDailyPlanDetailAPI({ dayPlanId: route.query.id })
        if (result.code === 200 && result.data) {
            const data = result.data
            const type = dayPlanType.value

            // 基础字段回显
            const baseFields = {
                dayPlanId: data.dayPlanId,
                plannedWorkload: data.plannedWorkload,
                proposedLongTimeCar: data.proposedLongTimeCar,
                proposedTemporaryCar: data.proposedTemporaryCar,
                actualLongTimeCar: data.actualLongTimeCar,
                actualTemporaryCar: data.actualTemporaryCar,
                actualWorkContent: data.actualWorkContent,
                actualWorkload: data.actualWorkload,
                completionPercentage: data.completionPercentage,
                planCompletionStatus: data.planCompletionStatus,
                planChanges: data.planChanges,
            }

            // 处理人员数据：从 proposedPersonnelList 中按照 dataSource 区分获取并重新组装
            const proposedPersonnelList = data.proposedPersonnelList || []

            if (type === '0' || type === 0) {
                // 运行类型：使用 planPersonnelList 和 actualPersonnelList
                baseFields.planPersonnelList = proposedPersonnelList
                    .filter((item) => item.dataSource === 0 || item.dataSource === '0')
                    .map((item) => ({
                        id: item.personnelId,
                        name: item.name || '',
                        inspectionStationName: item.inspectionStationName || '',
                    }))

                baseFields.actualPersonnelList = proposedPersonnelList
                    .filter((item) => item.dataSource === 1 || item.dataSource === '1')
                    .map((item) => ({
                        id: item.personnelId,
                        name: item.name || '',
                        inspectionStationName: item.inspectionStationName || '',
                    }))
            } else if (type === '1' || type === 1 || type === '2' || type === 2) {
                // 检修类型和项目部类型：使用 highAltitudePersonnelList、groundPersonnelList、actualHighAltitudePersonnelList、actualGroundPersonnelList
                baseFields.highAltitudePersonnelList = proposedPersonnelList
                    .filter((item) => item.dataSource === 2 || item.dataSource === '2')
                    .map((item) => ({
                        id: item.personnelId,
                        name: item.name || '',
                        inspectionStationName: item.inspectionStationName || '',
                    }))

                baseFields.groundPersonnelList = proposedPersonnelList
                    .filter((item) => item.dataSource === 3 || item.dataSource === '3')
                    .map((item) => ({
                        id: item.personnelId,
                        name: item.name || '',
                        inspectionStationName: item.inspectionStationName || '',
                    }))

                baseFields.actualHighAltitudePersonnelList = proposedPersonnelList
                    .filter((item) => item.dataSource === 4 || item.dataSource === '4')
                    .map((item) => ({
                        id: item.personnelId,
                        name: item.name || '',
                        inspectionStationName: item.inspectionStationName || '',
                    }))

                baseFields.actualGroundPersonnelList = proposedPersonnelList
                    .filter((item) => item.dataSource === 5 || item.dataSource === '5')
                    .map((item) => ({
                        id: item.personnelId,
                        name: item.name || '',
                        inspectionStationName: item.inspectionStationName || '',
                    }))

                // 检修和项目部共有的字段
                baseFields.proposedProficientPersonnel = data.proposedProficientPersonnel
                baseFields.proposedProficientDay = data.proposedProficientDay
                baseFields.proposedAssistancePersonnel = data.proposedAssistancePersonnel
                baseFields.proposedAssistanceDay = data.proposedAssistanceDay
                baseFields.proposedSubCar = data.proposedSubCar
                baseFields.actualProficientPersonnel = data.actualProficientPersonnel
                baseFields.actualAssistancePersonnel = data.actualAssistancePersonnel
                baseFields.actualSubCar = data.actualSubCar

                // 检修类型：工作内容从 workloadList 取值
                if (type === '1' || type === 1) {
                    baseFields.actualWorkloadList =
                        data.workloadList && data.workloadList.length > 0
                            ? data.workloadList.map((item) => ({
                                  workloadCategoryId: item.workloadCategoryId || '',
                                  workloadCategoryName: item.workloadCategoryName || '',
                                  unitPrice: item.unitPrice || '',
                                  settlementUnitPrice: item.settlementUnitPrice || '',
                                  workloadNum: item.workloadNum || '',
                              }))
                            : [
                                  {
                                      workloadCategoryId: '',
                                      workloadCategoryName: '',
                                      unitPrice: '',
                                      settlementUnitPrice: '',
                                      workloadNum: '',
                                  },
                              ]
                }
            }

            // 合并到表单数据
            formData.value = {
                ...formData.value,
                ...baseFields,
            }

            // 如果有实际完成情况的数据，自动显示实际完成情况表单
            let hasActualData = false
            if (type === '0' || type === 0) {
                // 运行类型：检查实际入作业人员、实际完成工作量等
                hasActualData =
                    baseFields.actualPersonnelList?.length > 0 ||
                    baseFields.actualWorkload ||
                    baseFields.actualWorkContent ||
                    baseFields.actualLongTimeCar ||
                    baseFields.actualTemporaryCar ||
                    baseFields.planCompletionStatus
            } else if (type === '1' || type === 1) {
                // 检修类型：检查实际投入人员、工作量列表、实际完成工作量等
                hasActualData =
                    baseFields.actualHighAltitudePersonnelList?.length > 0 ||
                    baseFields.actualGroundPersonnelList?.length > 0 ||
                    (baseFields.actualWorkloadList?.length > 0 &&
                        baseFields.actualWorkloadList[0]?.workloadCategoryId) ||
                    baseFields.actualWorkload ||
                    baseFields.actualProficientPersonnel ||
                    baseFields.actualAssistancePersonnel ||
                    baseFields.actualLongTimeCar ||
                    baseFields.actualTemporaryCar ||
                    baseFields.actualSubCar ||
                    baseFields.planCompletionStatus
            } else if (type === '2' || type === 2) {
                // 项目部类型：检查实际投入人员、实际完成工作内容等
                hasActualData =
                    baseFields.actualHighAltitudePersonnelList?.length > 0 ||
                    baseFields.actualGroundPersonnelList?.length > 0 ||
                    baseFields.actualWorkContent ||
                    baseFields.actualWorkload ||
                    baseFields.actualProficientPersonnel ||
                    baseFields.actualAssistancePersonnel ||
                    baseFields.actualLongTimeCar ||
                    baseFields.actualTemporaryCar ||
                    baseFields.actualSubCar ||
                    baseFields.planCompletionStatus
            }

            if (hasActualData) {
                nextTick(() => {
                    formRef.value?.showActualCompletionForm?.()
                })
            }
        }
    } catch (error) {
        console.error('获取详情失败:', error)
    }
}

// 监听类型变化，切换组件并重新初始化表单数据
watch(
    () => dayPlanType.value,
    (newType) => {
        currentFormComponent.value = formComponents[newType] || RunForm
        // 类型切换时重新初始化表单数据
        formData.value = getInitFormData()
    },
    { immediate: true },
)

onMounted(() => {
    if (route.query.id) {
        getDetail()
    }
})
</script>

<style scoped lang="scss">
.daily-plan-edit {
    .page-header {
        margin-bottom: 20px;
        padding: 16px 20px;
        background: linear-gradient(135deg, #f5f7fa 0%, #ffffff 100%);
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);

        :deep(.el-page-header__left) {
            .el-page-header__back {
                padding: 8px;
                border-radius: 6px;
                transition: all 0.3s ease;
                background-color: transparent;

                &:hover {
                    background-color: #f0f2f5;
                    color: #1677ff;
                    transform: translateX(-2px);
                }

                &::before {
                    font-size: 16px;
                    font-weight: 600;
                }
            }
        }

        :deep(.el-page-header__content) {
            font-size: 18px;
            font-weight: 600;
            color: #1f2937;
            margin-left: 12px;
        }
    }

    .card-section {
        margin-bottom: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        overflow: hidden;
        transition: box-shadow 0.3s ease;

        &:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        :deep(.el-card__header) {
            padding: 16px 20px;
            background-color: #fafbfc;
            border-bottom: 1px solid #f0f2f5;
        }

        :deep(.el-card__body) {
            padding: 24px 20px;
        }
    }

    .card-header {
        font-weight: 600;
        font-size: 15px;
        color: #1f2937;
        position: relative;
        padding-left: 12px;
        display: flex;
        align-items: center;

        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 16px;
            background: linear-gradient(180deg, #1677ff 0%, #4096ff 100%);
            border-radius: 2px;
        }
    }

    .page-footer {
        margin-top: 12px;
        display: flex;
        justify-content: flex-end;
        gap: 12px;
    }

    .clickable-suffix {
        cursor: pointer;
    }
}

.person-search-bar {
    margin-bottom: 8px;
}

.selected-panel {
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 12px;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.selected-list {
    flex: 1;
    overflow: auto;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.selected-tag {
    margin-left: 6px;
    margin-bottom: 10px;
}

.empty-tip {
    color: #9ca3af;
}
</style>
