<template>
    <div>
        <!-- 计划投入资源情况 -->
        <el-card shadow="never" class="card-section">
            <template #header>
                <div class="card-header">计划投入资源情况</div>
            </template>
            <el-form
                ref="formRef"
                size="large"
                :model="formData"
                label-width="180"
                :disabled="isDetail"
                :rules="!isDetail ? rules : {}"
                :validate-on-rule-change="false"
            >
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="计划工作量" prop="plannedWorkload">
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="请输入计划工作量"
                                :model-value="formData.plannedWorkload"
                                @update:model-value="(val) => updateField('plannedWorkload', val)"
                            >
                                <template #suffix>
                                    <span class="input-suffix">基</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="拟投入高处作业人员" prop="highAltitudePersonnelList">
                            <el-input
                                readonly
                                class="clickable-suffix"
                                @click="onOpenPersonPicker('highAltitude')"
                                placeholder="请选择高处作业人员"
                                :model-value="selectedHighAltitudeNames"
                            >
                                <template #suffix>
                                    <el-icon class="clickable-suffix">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="拟投入地面作业人员" prop="groundPersonnelList">
                            <el-input
                                readonly
                                class="clickable-suffix"
                                @click="onOpenPersonPicker('ground')"
                                placeholder="请选择地面作业人员"
                                :model-value="selectedGroundNames"
                            >
                                <template #suffix>
                                    <el-icon class="clickable-suffix">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="7">
                        <el-form-item prop="proposedProficientPersonnel">
                            <template #label>
                                <div style="display: flex; flex-direction: column">
                                    <span>计划投入熟练工人员数量</span>
                                    <span
                                        style="
                                            font-size: 12px;
                                            color: #999;
                                            transform: translateY(-20px);
                                        "
                                    >
                                        (分包高空作业人员)
                                    </span>
                                </div>
                            </template>
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="熟练工人员数量"
                                :model-value="formData.proposedProficientPersonnel"
                                @update:model-value="
                                    (val) => updateField('proposedProficientPersonnel', val)
                                "
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item
                            label="计划投入工日"
                            prop="proposedProficientDay"
                            label-width="120"
                        >
                            <el-input
                                clearable
                                maxlength="7"
                                placeholder="工日"
                                :model-value="formData.proposedProficientDay"
                                @update:model-value="
                                    (val) => updateField('proposedProficientDay', val)
                                "
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item prop="proposedAssistancePersonnel">
                            <template #label>
                                <div style="display: flex; flex-direction: column">
                                    <span>计划投入辅助工人员数量</span>
                                    <span
                                        style="
                                            font-size: 12px;
                                            color: #999;
                                            transform: translateY(-20px);
                                        "
                                    >
                                        (分包地面作业人员)
                                    </span>
                                </div>
                            </template>
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="辅助工人员数量"
                                :model-value="formData.proposedAssistancePersonnel"
                                @update:model-value="
                                    (val) => updateField('proposedAssistancePersonnel', val)
                                "
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item
                            label="计划投入工日"
                            prop="proposedAssistanceDay"
                            label-width="120"
                        >
                            <el-input
                                clearable
                                maxlength="7"
                                placeholder="工日"
                                :model-value="formData.proposedAssistanceDay"
                                @update:model-value="
                                    (val) => updateField('proposedAssistanceDay', val)
                                "
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="拟投入长租车" prop="proposedLongTimeCar">
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="请输入长租车数量"
                                :model-value="formData.proposedLongTimeCar"
                                @update:model-value="
                                    (val) => updateField('proposedLongTimeCar', val)
                                "
                            >
                                <template #suffix>
                                    <span class="input-suffix">辆</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="拟投入临租车" prop="proposedTemporaryCar">
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="请输入临租车数量"
                                :model-value="formData.proposedTemporaryCar"
                                @update:model-value="
                                    (val) => updateField('proposedTemporaryCar', val)
                                "
                            >
                                <template #suffix>
                                    <span class="input-suffix">辆</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="拟投入分包车" prop="proposedSubCar">
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="请输入分包车数量"
                                :model-value="formData.proposedSubCar"
                                @update:model-value="(val) => updateField('proposedSubCar', val)"
                            >
                                <template #suffix>
                                    <span class="input-suffix">辆</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 实际完成情况（默认隐藏） -->
        <el-card
            v-if="showActualCompletion"
            shadow="never"
            class="card-section"
            style="margin-top: 20px"
        >
            <template #header>
                <div class="card-header">实际完成情况</div>
            </template>
            <el-form
                ref="actualFormRef"
                :model="formData"
                :rules="!isDetail ? actualRules : {}"
                size="large"
                label-width="180"
                :disabled="isDetail"
                :validate-on-rule-change="false"
            >
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item
                            label="实际投入高处作业人员"
                            prop="actualHighAltitudePersonnelList"
                        >
                            <el-input
                                readonly
                                class="clickable-suffix"
                                placeholder="请选择高处作业人员"
                                @click="onOpenActualPersonPicker('highAltitude')"
                                :model-value="selectedActualHighAltitudeNames"
                            >
                                <template #suffix>
                                    <el-icon class="clickable-suffix">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="实际投入地面作业人员" prop="actualGroundPersonnelList">
                            <el-input
                                readonly
                                class="clickable-suffix"
                                @click="onOpenActualPersonPicker('ground')"
                                placeholder="请选择地面作业人员"
                                :model-value="selectedActualGroundNames"
                            >
                                <template #suffix>
                                    <el-icon class="clickable-suffix">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item prop="actualProficientPersonnel">
                            <template #label>
                                <div style="display: flex; flex-direction: column">
                                    <span>实际投入检修熟练工数量</span>
                                    <span
                                        style="
                                            font-size: 12px;
                                            color: #999;
                                            transform: translateY(-20px);
                                        "
                                    >
                                        (分包高空作业人员)
                                    </span>
                                </div>
                            </template>
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="熟练工人员数量"
                                :model-value="formData.actualProficientPersonnel"
                                @update:model-value="
                                    (val) => updateField('actualProficientPersonnel', val)
                                "
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item prop="actualAssistancePersonnel">
                            <template #label>
                                <div style="display: flex; flex-direction: column">
                                    <span>实际投入检修辅助工数量</span>
                                    <span
                                        style="
                                            font-size: 12px;
                                            color: #999;
                                            transform: translateY(-20px);
                                        "
                                    >
                                        (分包地面作业人员)
                                    </span>
                                </div>
                            </template>
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="辅助工人员数量"
                                :model-value="formData.actualAssistancePersonnel"
                                @update:model-value="
                                    (val) => updateField('actualAssistancePersonnel', val)
                                "
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="实际投入长租车" prop="actualLongTimeCar">
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="请输入长租车数量"
                                :model-value="formData.actualLongTimeCar"
                                @update:model-value="(val) => updateField('actualLongTimeCar', val)"
                            >
                                <template #suffix>
                                    <span class="input-suffix">辆</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="实际投入临租车" prop="actualTemporaryCar">
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="请输入临租车数量"
                                :model-value="formData.actualTemporaryCar"
                                @update:model-value="
                                    (val) => updateField('actualTemporaryCar', val)
                                "
                            >
                                <template #suffix>
                                    <span class="input-suffix">辆</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="实际投入分包车" prop="actualSubCar">
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="请输入分包车数量"
                                :model-value="formData.actualSubCar"
                                @update:model-value="(val) => updateField('actualSubCar', val)"
                            >
                                <template #suffix>
                                    <span class="input-suffix">辆</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 实际完成工作内容（动态列表） -->
                <el-row :gutter="24">
                    <template v-for="(item, index) in formData.actualWorkloadList" :key="index">
                        <el-col :span="8">
                            <el-form-item
                                :prop="`actualWorkloadList.${index}.workloadCategoryId`"
                                :class="{ 'hide-required': index !== 0 }"
                            >
                                <template #label>
                                    <span v-if="index == 0">实际完成工作内容</span>
                                    <span v-else style="visibility: hidden">工作量</span>
                                </template>
                                <el-select
                                    clearable
                                    placeholder="请选择工作量类别"
                                    :model-value="item.workloadCategoryId"
                                    @update:model-value="
                                        (val) => onChangeWorkLoadCategory(val, index)
                                    "
                                    style="width: 100%"
                                >
                                    <el-option
                                        v-for="option in planWorkLoadCategoryOptions"
                                        :key="option.workloadCategoryId"
                                        :value="option.workloadCategoryId"
                                        :label="option.workloadCategoryName"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item
                                label-width="0"
                                :prop="`actualWorkloadList.${index}.workloadNum`"
                            >
                                <el-input
                                    clearable
                                    style="width: 100%"
                                    placeholder="输入数量"
                                    show-word-limit
                                    maxlength="7"
                                    :model-value="item.workloadNum"
                                    @update:model-value="
                                        (val) => updateWorkloadItem(index, 'workloadNum', val)
                                    "
                                >
                                    <template #suffix>
                                        <el-button
                                            type="success"
                                            icon="Plus"
                                            size="small"
                                            v-if="index === 0 && !isDetail"
                                            @click="onAddWorkLoad"
                                        />
                                        <el-button
                                            type="danger"
                                            icon="Delete"
                                            size="small"
                                            v-if="index !== 0 && !isDetail"
                                            @click="onDeleteWorkLoad(index)"
                                        />
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </template>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="实际完成工作量" prop="actualWorkload">
                            <el-input
                                clearable
                                maxlength="7"
                                show-word-limit
                                placeholder="请输入实际完成工作量"
                                :model-value="formData.actualWorkload"
                                @update:model-value="(val) => updateField('actualWorkload', val)"
                            >
                                <template #suffix>
                                    <span class="input-suffix">基</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="完成比例" prop="completionPercentage">
                            <el-input
                                :model-value="calculatedCompletionPercentage"
                                placeholder="自动计算"
                                readonly
                                disabled
                            >
                                <template #suffix>
                                    <span class="input-suffix">%</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="作业计划完成情况" prop="planCompletionStatus">
                            <el-select
                                :model-value="formData.planCompletionStatus"
                                @update:model-value="
                                    (val) => updateField('planCompletionStatus', val)
                                "
                                placeholder="请选择作业计划完成情况"
                                clearable
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="item in planCompletionStatusOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="计划变更及未完成情况说明" prop="planChanges">
                            <el-input
                                :model-value="formData.planChanges"
                                @update:model-value="(val) => updateField('planChanges', val)"
                                type="textarea"
                                :autosize="{ minRows: 6, maxRows: 12 }"
                                placeholder="请输入计划变更及未完成情况说明"
                                maxlength="500"
                                show-word-limit
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作按钮 -->
        <div class="form-actions" v-if="!isDetail">
            <ComButton
                v-if="!showActualCompletion"
                type="primary"
                @click="showActualCompletion = true"
            >
                填写实际完成情况
            </ComButton>
            <ComButton v-else plain type="info" @click="onCancelActualCompletion">
                取消实际完成情况
            </ComButton>
        </div>
    </div>
</template>

<script setup name="RepairForm">
import { ref, computed, nextTick, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import ComButton from '@/components/ComButton/index.vue'
import { useOptions } from '@/hooks/useOptions'
import { getPlanMajorListSelectAPI } from '@/api/common.js'

const props = defineProps({
    formData: {
        type: Object,
        required: true,
    },
    isDetail: {
        type: Boolean,
        default: false,
    },
    selectedManagerNames: {
        type: String,
        default: '',
    },
})

const emit = defineEmits(['open-person-picker', 'update:formData', 'open-actual-person-picker'])

const formRef = ref(null)
const actualFormRef = ref(null)
const showActualCompletion = ref(false)

// 工作量类别选项
const { options: planWorkLoadCategoryOptions } = useOptions(
    'planWorkLoadCategoryOptions',
    getPlanMajorListSelectAPI,
    {},
)

// 作业计划完成情况选项
const planCompletionStatusOptions = [
    { label: '完成', value: '完成' },
    { label: '进行中', value: '进行中' },
    { label: '未完成', value: '未完成' },
]

// 更新表单字段
const updateField = (field, value) => {
    const newData = {
        ...props.formData,
        [field]: value,
    }
    // 如果更新的是实际完成工作量或计划工作量，自动计算完成比例
    if (field === 'actualWorkload' || field === 'plannedWorkload') {
        newData.completionPercentage = calculateCompletionPercentage(
            newData.actualWorkload,
            newData.plannedWorkload,
        )
    }
    emit('update:formData', newData)
}

// 更新工作量列表项
const updateWorkloadItem = (index, field, value) => {
    const newWorkloadList = [...(props.formData.actualWorkloadList || [])]
    newWorkloadList[index] = {
        ...newWorkloadList[index],
        [field]: value,
    }
    updateField('actualWorkloadList', newWorkloadList)
}

// 计算完成比例：实际完成工作量 ÷ 计划完成工作量 × 100%
const calculateCompletionPercentage = (actualWorkload, plannedWorkload) => {
    try {
        const actual = Number(actualWorkload)
        const planned = Number(plannedWorkload)

        if (isNaN(actual) || isNaN(planned)) {
            return null
        }

        if (planned <= 0) {
            return null
        }

        if (actual < 0) {
            return null
        }

        const percentage = (actual / planned) * 100
        const roundedPercentage = Math.round(percentage * 100) / 100

        return roundedPercentage > 100 ? 100 : roundedPercentage
    } catch (error) {
        console.error('计算完成比例时出错:', error)
        return null
    }
}

// 计算完成比例（用于显示）
const calculatedCompletionPercentage = computed(() => {
    const percentage = calculateCompletionPercentage(
        props.formData.actualWorkload,
        props.formData.plannedWorkload,
    )
    return percentage !== null ? percentage : ''
})

// 监听实际完成工作量和计划工作量的变化，自动计算完成比例
watch(
    () => [props.formData.actualWorkload, props.formData.plannedWorkload],
    ([actualWorkload, plannedWorkload]) => {
        if (showActualCompletion.value) {
            const percentage = calculateCompletionPercentage(actualWorkload, plannedWorkload)
            if (percentage !== null && percentage !== props.formData.completionPercentage) {
                emit('update:formData', {
                    ...props.formData,
                    completionPercentage: percentage,
                })
            }
        }
    },
    { immediate: true },
)

// 监听实际完成情况显示状态，显示时自动计算完成比例
watch(
    () => showActualCompletion.value,
    (isShow) => {
        if (isShow && props.formData.actualWorkload && props.formData.plannedWorkload) {
            const percentage = calculateCompletionPercentage(
                props.formData.actualWorkload,
                props.formData.plannedWorkload,
            )
            if (percentage !== null) {
                emit('update:formData', {
                    ...props.formData,
                    completionPercentage: percentage,
                })
            }
        }
    },
)

// 正整数正则校验
const positiveIntegerPattern = /^[1-9]\d*$/
// 非负整数正则校验（包括0）
const nonNegativeIntegerPattern = /^(0|[1-9]\d*)$/

// 表单校验规则
const rules = computed(() => ({
    plannedWorkload: [
        { required: true, message: '请输入计划工作量', trigger: 'blur' },
        { pattern: positiveIntegerPattern, message: '请输入正整数', trigger: 'blur' },
    ],
    highAltitudePersonnelList: [
        { required: true, message: '请选择拟投入高处作业人员', trigger: 'change' },
    ],
    groundPersonnelList: [
        { required: true, message: '请选择拟投入地面作业人员', trigger: 'change' },
    ],
    proposedProficientPersonnel: [
        { required: true, message: '请输入计划投入熟练工人员数量', trigger: 'blur' },
        { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
    ],
    proposedProficientDay: [
        { required: true, message: '请输入计划投入工日', trigger: 'blur' },
        { pattern: positiveIntegerPattern, message: '请输入正整数', trigger: 'blur' },
    ],
    proposedAssistancePersonnel: [
        { required: true, message: '请输入计划投入辅助工人员数量', trigger: 'blur' },
        { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
    ],
    proposedAssistanceDay: [
        { required: true, message: '请输入计划投入工日', trigger: 'blur' },
        { pattern: positiveIntegerPattern, message: '请输入正整数', trigger: 'blur' },
    ],
    proposedLongTimeCar: [
        { required: true, message: '请输入拟投入长租车数量', trigger: 'blur' },
        { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
    ],
    proposedTemporaryCar: [
        { required: true, message: '请输入拟投入临租车数量', trigger: 'blur' },
        { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
    ],
    proposedSubCar: [
        { required: true, message: '请输入拟投入分包车数量', trigger: 'blur' },
        { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
    ],
}))

// 实际完成情况校验规则
const actualRules = computed(() => {
    const baseRules = {
        actualHighAltitudePersonnelList: [
            { required: true, message: '请选择实际投入高处作业人员', trigger: 'change' },
        ],
        actualGroundPersonnelList: [
            { required: true, message: '请选择实际投入地面作业人员', trigger: 'change' },
        ],
        actualProficientPersonnel: [
            { required: true, message: '请输入实际投入检修熟练工数量', trigger: 'blur' },
            { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
        ],
        actualAssistancePersonnel: [
            { required: true, message: '请输入实际投入检修辅助工数量', trigger: 'blur' },
            { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
        ],
        actualLongTimeCar: [
            { required: true, message: '请输入实际投入长租车数量', trigger: 'blur' },
            { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
        ],
        actualTemporaryCar: [
            { required: true, message: '请输入实际投入临租车数量', trigger: 'blur' },
            { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
        ],
        actualSubCar: [
            { required: true, message: '请输入实际投入分包车数量', trigger: 'blur' },
            { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
        ],
        actualWorkload: [
            { required: true, message: '请输入实际完成工作量', trigger: 'blur' },
            { pattern: positiveIntegerPattern, message: '请输入正整数', trigger: 'blur' },
        ],
        completionPercentage: [
            {
                required: true,
                validator: (rule, value, callback) => {
                    const percentage = calculateCompletionPercentage(
                        props.formData.actualWorkload,
                        props.formData.plannedWorkload,
                    )
                    if (percentage === null || percentage === '') {
                        callback(new Error('请先填写计划工作量和实际完成工作量'))
                    } else {
                        callback()
                    }
                },
                trigger: 'blur',
            },
        ],
        planCompletionStatus: [
            { required: true, message: '请选择作业计划完成情况', trigger: 'change' },
        ],
        planChanges: [
            { required: false, message: '请输入计划变更及未完成情况说明', trigger: 'blur' },
        ],
    }

    // 为 actualWorkloadList 的每一项生成对应的校验规则
    baseRules.actualWorkloadList = (props.formData.actualWorkloadList || []).map(() => ({
        workloadCategoryId: [{ required: true, message: '请选择工作量类别', trigger: 'change' }],
        workloadNum: [
            { required: true, message: '请输入工作量', trigger: 'blur' },
            { pattern: positiveIntegerPattern, message: '请输入正整数', trigger: 'blur' },
        ],
    }))

    return baseRules
})

// 人员名称显示
const selectedHighAltitudeNames = computed(() =>
    (props.formData.highAltitudePersonnelList || []).map((item) => item.name).join('、'),
)

const selectedGroundNames = computed(() =>
    (props.formData.groundPersonnelList || []).map((item) => item.name).join('、'),
)

const selectedActualHighAltitudeNames = computed(() =>
    (props.formData.actualHighAltitudePersonnelList || []).map((item) => item.name).join('、'),
)

const selectedActualGroundNames = computed(() =>
    (props.formData.actualGroundPersonnelList || []).map((item) => item.name).join('、'),
)

const onOpenPersonPicker = (type) => {
    emit('open-person-picker', type)
}

const onOpenActualPersonPicker = (type) => {
    emit('open-person-picker', `actual_${type}`)
}

// 添加工作量项
const onAddWorkLoad = () => {
    const newWorkloadList = [...(props.formData.actualWorkloadList || [])]
    newWorkloadList.push({
        workloadCategoryId: '',
        workloadCategoryName: '',
        unitPrice: '',
        workloadNum: '',
        settlementUnitPrice: '',
    })
    updateField('actualWorkloadList', newWorkloadList)
}

// 删除工作量项
const onDeleteWorkLoad = (index) => {
    const newWorkloadList = [...(props.formData.actualWorkloadList || [])]
    newWorkloadList.splice(index, 1)
    updateField('actualWorkloadList', newWorkloadList)
    // 清除被删除项的校验状态
    nextTick(() => {
        if (actualFormRef.value) {
            newWorkloadList.forEach((item, idx) => {
                actualFormRef.value?.clearValidate([
                    `actualWorkloadList.${idx}.workloadCategoryId`,
                    `actualWorkloadList.${idx}.workloadNum`,
                ])
            })
        }
    })
}

// 工作量类别变化
const onChangeWorkLoadCategory = (workloadCategoryId, index) => {
    const workloadCategory = planWorkLoadCategoryOptions.value.find(
        (item) => item.workloadCategoryId === workloadCategoryId,
    )
    if (workloadCategory) {
        const newWorkloadList = [...(props.formData.actualWorkloadList || [])]
        newWorkloadList[index] = {
            ...newWorkloadList[index],
            workloadCategoryId: workloadCategory.workloadCategoryId,
            workloadCategoryName: workloadCategory.workloadCategoryName,
            unitPrice: workloadCategory.unitPrice || '',
            settlementUnitPrice: workloadCategory.settlementUnitPrice || '',
        }
        updateField('actualWorkloadList', newWorkloadList)
    } else {
        const newWorkloadList = [...(props.formData.actualWorkloadList || [])]
        newWorkloadList[index] = {
            ...newWorkloadList[index],
            workloadCategoryId: '',
            workloadCategoryName: '',
            unitPrice: '',
            settlementUnitPrice: '',
        }
        updateField('actualWorkloadList', newWorkloadList)
    }

    // 手动触发该字段的校验
    nextTick(() => {
        actualFormRef.value?.validateField(`actualWorkloadList.${index}.workloadCategoryId`)
    })
}

// 取消实际完成情况
const onCancelActualCompletion = () => {
    showActualCompletion.value = false
    // 清空实际完成情况的数据
    const clearedData = {
        ...props.formData,
        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: '',
    }
    emit('update:formData', clearedData)
    // 清除校验
    nextTick(() => {
        actualFormRef.value?.clearValidate()
    })
}

// 暴露方法给父组件
defineExpose({
    validate: async () => {
        const results = []
        if (formRef.value) {
            results.push(await formRef.value.validate())
        }
        if (showActualCompletion.value && actualFormRef.value) {
            results.push(await actualFormRef.value.validate())
        }
        return results.every((r) => r !== false)
    },
    clearValidate: () => {
        formRef.value?.clearValidate()
        actualFormRef.value?.clearValidate()
    },
    scrollToField: (prop) => {
        if (formRef.value) {
            formRef.value.scrollToField(prop)
        }
        if (actualFormRef.value) {
            actualFormRef.value.scrollToField(prop)
        }
    },
    showActualCompletionForm: () => {
        showActualCompletion.value = true
    },
})
</script>

<style scoped lang="scss">
.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;
    }
}

.clickable-suffix {
    cursor: pointer;
}

.input-suffix {
    color: #909399;
    font-size: 14px;
    padding-right: 8px;
}

.form-actions {
    margin-top: 20px;
    display: flex;
    justify-content: flex-start;
}

// 隐藏索引不为 0 的工作量项的 required 标记（*号）
:deep(.hide-required) {
    &.is-required .el-form-item__label::before {
        display: none;
    }
}
</style>
