<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"
                                @click="onOpenActualPersonPicker('highAltitude')"
                                placeholder="请选择高处作业人员"
                                :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">
                    <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="24">
                        <el-form-item label="实际完成工作内容" prop="actualWorkContent">
                            <el-input
                                :model-value="formData.actualWorkContent"
                                @update:model-value="(val) => updateField('actualWorkContent', val)"
                                type="textarea"
                                :autosize="{ minRows: 6, maxRows: 12 }"
                                placeholder="请输入实际完成工作内容"
                                maxlength="500"
                                show-word-limit
                            />
                        </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="ProjectForm">
import { ref, computed, nextTick, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import ComButton from '@/components/ComButton/index.vue'

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 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 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*$/
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(() => ({
    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' },
    ],
    actualWorkContent: [{ required: true, 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' }],
}))

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 onCancelActualCompletion = () => {
    showActualCompletion.value = false
    const clearedData = {
        ...props.formData,
        actualHighAltitudePersonnelList: [],
        actualGroundPersonnelList: [],
        actualProficientPersonnel: null,
        actualAssistancePersonnel: null,
        actualLongTimeCar: null,
        actualTemporaryCar: null,
        actualSubCar: null,
        actualWorkContent: '',
        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;
}
</style>
