<template>
    <div>
        <!-- 计划投入资源情况 -->
        <el-card shadow="never" class="card-section">
            <template #header>
                <div class="card-header">计划投入资源情况</div>
            </template>
            <el-form
                ref="formRef"
                :model="formData"
                :rules="!isDetail ? rules : {}"
                size="large"
                label-width="140"
                :disabled="isDetail"
                :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-col :span="12">
                        <el-form-item label="拟投入作业人员" prop="planPersonnelList">
                            <el-input
                                readonly
                                class="clickable-suffix"
                                @click="onOpenPersonPicker"
                                placeholder="请选择作业人员"
                                :model-value="selectedManagerNames"
                            >
                                <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 label="拟投入长租车" prop="proposedLongTimeCar">
                            <el-input
                                :model-value="formData.proposedLongTimeCar"
                                @update:model-value="
                                    (val) => updateField('proposedLongTimeCar', val)
                                "
                                placeholder="请输入长租车数量"
                                clearable
                                maxlength="7"
                                show-word-limit
                            >
                                <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
                                :model-value="formData.proposedTemporaryCar"
                                @update:model-value="
                                    (val) => updateField('proposedTemporaryCar', val)
                                "
                                placeholder="请输入临租车数量"
                                clearable
                                maxlength="7"
                                show-word-limit
                            >
                                <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="140"
                :disabled="isDetail"
                :validate-on-rule-change="false"
            >
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="实际投入作业人员" prop="actualPersonnelList">
                            <el-input
                                :model-value="selectedActualManagerNames"
                                placeholder="请选择作业人员"
                                readonly
                                @click="onOpenActualPersonPicker"
                                class="clickable-suffix"
                            >
                                <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="actualLongTimeCar">
                            <el-input
                                :model-value="formData.actualLongTimeCar"
                                @update:model-value="(val) => updateField('actualLongTimeCar', val)"
                                placeholder="请输入长租车数量"
                                clearable
                                maxlength="7"
                                show-word-limit
                            >
                                <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="actualTemporaryCar">
                            <el-input
                                :model-value="formData.actualTemporaryCar"
                                @update:model-value="
                                    (val) => updateField('actualTemporaryCar', val)
                                "
                                placeholder="请输入临租车数量"
                                clearable
                                maxlength="7"
                                show-word-limit
                            >
                                <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="actualWorkload">
                            <el-input
                                :model-value="formData.actualWorkload"
                                @update:model-value="(val) => updateField('actualWorkload', val)"
                                placeholder="请输入实际完成工作量"
                                clearable
                                maxlength="7"
                                show-word-limit
                            >
                                <template #suffix>
                                    <span class="input-suffix">基</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

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

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

        // 检查是否为有效数字
        if (isNaN(actual) || isNaN(planned)) {
            return null
        }

        // 检查计划工作量是否为0或负数
        if (planned <= 0) {
            return null
        }

        // 检查实际完成工作量是否为负数
        if (actual < 0) {
            return null
        }

        // 计算完成比例，保留2位小数
        const percentage = (actual / planned) * 100
        const roundedPercentage = Math.round(percentage * 100) / 100

        // 如果超过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 直接更新，避免循环调用
                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*)$/
// 百分比正则校验（0-100）
const percentagePattern = /^(0|[1-9]\d?|100)$/

// 表单校验规则
const rules = computed(() => ({
    plannedWorkload: [
        { required: true, message: '请输入计划工作量', trigger: 'blur' },
        { pattern: positiveIntegerPattern, message: '请输入正整数', trigger: 'blur' },
    ],
    planPersonnelList: [{ required: true, message: '请选择拟投入作业人员', trigger: 'change' }],
    proposedLongTimeCar: [
        { required: true, message: '请输入拟投入长租车数量', trigger: 'blur' },
        { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
    ],
    proposedTemporaryCar: [
        { required: true, message: '请输入拟投入临租车数量', trigger: 'blur' },
        { pattern: nonNegativeIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
    ],
}))

// 实际完成情况校验规则
const actualRules = computed(() => ({
    actualPersonnelList: [{ required: true, message: '请选择实际入作业人员', trigger: 'change' }],
    actualLongTimeCar: [
        { required: true, message: '请输入实际入长租车数量', trigger: 'blur' },
        { pattern: positiveIntegerPattern, message: '请输入非负整数', trigger: 'blur' },
    ],
    actualTemporaryCar: [
        { required: true, message: '请输入实际入临租车数量', trigger: 'blur' },
        { pattern: positiveIntegerPattern, 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 selectedActualManagerNames = computed(() =>
    (props.formData.actualPersonnelList || []).map((item) => item.name).join('、'),
)

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

const onOpenActualPersonPicker = () => {
    emit('open-person-picker', 'actual')
}

// 取消实际完成情况
const onCancelActualCompletion = () => {
    showActualCompletion.value = false
    // 清空实际完成情况的数据
    const clearedData = {
        ...props.formData,
        actualPersonnelList: [],
        actualLongTimeCar: null,
        actualTemporaryCar: 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>
