<template>
    <el-form
        size="large"
        label-width="auto"
        :model="formData"
        ref="formRef"
        :rules="rules"
        class="add-and-edit-form"
    >
        <!-- 月份 -->
        <el-form-item label="月份" prop="planManagementMonth">
            <el-date-picker
                type="month"
                style="width: 100%"
                value-format="YYYY-MM"
                placeholder="请选择月份"
                v-model="formData.planManagementMonth"
                @change="handleMonthChange"
            />
        </el-form-item>

        <!-- 项目名称 -->
        <el-form-item label="项目名称" prop="projectName">
            <el-input
                clearable
                maxlength="100"
                show-word-limit
                placeholder="请输入项目名称"
                v-model.trim="formData.projectName"
            />
        </el-form-item>

        <!-- 作业内容 -->
        <el-form-item label="作业内容" prop="workContent">
            <el-input
                type="textarea"
                maxlength="500"
                show-word-limit
                placeholder="请输入作业内容"
                v-model.trim="formData.workContent"
                :autosize="{ minRows: 4, maxRows: 8 }"
            />
        </el-form-item>

        <!-- 实施部门 -->
        <el-form-item label="实施部门" prop="inspectionStationId">
            <el-select
                clearable
                filterable
                style="width: 100%"
                placeholder="请选择实施部门"
                v-model="formData.inspectionStationId"
            >
                <el-option
                    v-for="item in inspectionStationOptions"
                    :key="item.id"
                    :value="item.id"
                    :label="item.value"
                />
            </el-select>
        </el-form-item>

        <!-- 计划开始时间 -->
        <el-form-item label="计划开始时间" prop="stareDate">
            <el-date-picker
                v-model="formData.stareDate"
                type="date"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                :placeholder="!formData.planManagementMonth ? '请先选择月份' : '请选择计划开始时间'"
                :disabled="!formData.planManagementMonth"
                :disabled-date="disabledStartDate"
                :default-value="defaultDateValue"
                @change="handleStartDateChange"
            />
        </el-form-item>

        <!-- 计划结束时间 -->
        <el-form-item label="计划结束时间" prop="endDate">
            <el-date-picker
                type="date"
                style="width: 100%"
                v-model="formData.endDate"
                value-format="YYYY-MM-DD"
                :placeholder="!formData.planManagementMonth ? '请先选择月份' : '请选择计划结束时间'"
                :disabled="!formData.planManagementMonth"
                :disabled-date="disabledEndDate"
                :default-value="defaultDateValue"
                @change="handleEndDateChange"
            />
        </el-form-item>

        <!-- 风险等级 -->
        <el-form-item label="风险等级" prop="riskLevel">
            <el-select
                clearable
                style="width: 100%"
                placeholder="请选择风险等级"
                v-model="formData.riskLevel"
            >
                <el-option
                    v-for="item in plan_risk_level"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                />
            </el-select>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
            <el-input
                type="textarea"
                maxlength="200"
                show-word-limit
                :autosize="{ minRows: 4, maxRows: 8 }"
                placeholder="请输入备注"
                v-model.trim="formData.remark"
            />
        </el-form-item>
    </el-form>
</template>

<script setup name="AddAndEditForm">
import { ref, watch, computed } from 'vue'
const { proxy } = getCurrentInstance()
const { plan_risk_level } = proxy.useDict('plan_risk_level')

const props = defineProps({
    formData: {
        type: Object,
        default: () => ({}),
    },
    inspectionStationOptions: {
        type: Array,
        default: () => [],
    },
})

const formRef = ref(null)

// 计算月份的开始和结束日期
const monthRange = computed(() => {
    if (!props.formData.planManagementMonth) {
        return { start: null, end: null }
    }
    const [year, month] = props.formData.planManagementMonth.split('-')
    const start = new Date(year, parseInt(month) - 1, 1)
    const end = new Date(year, parseInt(month), 0, 23, 59, 59) // 当月最后一天

    return {
        start: start.getTime(),
        end: end.getTime(),
    }
})

// 计算默认日期值（用于日期选择器打开时定位到选定月份）
const defaultDateValue = computed(() => {
    if (!props.formData.planManagementMonth) {
        return new Date() // 如果没有选择月份，使用当前日期
    }
    const [year, month] = props.formData.planManagementMonth.split('-')
    // 返回选定月份的第一天，这样日期选择器打开时会显示该月份
    return new Date(year, parseInt(month) - 1, 1)
})

// 检查日期是否在选定月份内
const isDateInMonth = (dateStr) => {
    if (!dateStr || !monthRange.value.start) return false
    const date = new Date(dateStr)
    const timestamp = date.getTime()
    return timestamp >= monthRange.value.start && timestamp <= monthRange.value.end
}

// 月份变化处理
const handleMonthChange = (value) => {
    // value 是新的月份值（格式：YYYY-MM）
    if (!value) {
        // 如果月份被清空，清空开始和结束时间
        props.formData.stareDate = ''
        props.formData.endDate = ''
        formRef.value?.clearValidate(['stareDate', 'endDate'])
        return
    }

    // 计算新月份的范围
    const [year, month] = value.split('-')
    const monthStart = new Date(year, parseInt(month) - 1, 1).getTime()
    const monthEnd = new Date(year, parseInt(month), 0, 23, 59, 59).getTime()

    // 检查开始时间是否在新月份内
    if (props.formData.stareDate) {
        const stareTimestamp = new Date(props.formData.stareDate).getTime()
        if (stareTimestamp < monthStart || stareTimestamp > monthEnd) {
            props.formData.stareDate = ''
            formRef.value?.clearValidate('stareDate')
        }
    }

    // 检查结束时间是否在新月份内
    if (props.formData.endDate) {
        const endTimestamp = new Date(props.formData.endDate).getTime()
        if (endTimestamp < monthStart || endTimestamp > monthEnd) {
            props.formData.endDate = ''
            formRef.value?.clearValidate('endDate')
        }
    }
}

// 禁用开始日期的逻辑（只能选择选定月份内的日期）
const disabledStartDate = (time) => {
    if (!monthRange.value.start || !monthRange.value.end) {
        return true
    }
    const timestamp = time.getTime()
    return timestamp < monthRange.value.start || timestamp > monthRange.value.end
}

// 禁用结束日期的逻辑（只能选择选定月份内的日期，且不能早于开始时间）
const disabledEndDate = (time) => {
    if (!monthRange.value.start || !monthRange.value.end) {
        return true
    }
    const timestamp = time.getTime()

    // 不能选择月份范围外的日期
    if (timestamp < monthRange.value.start || timestamp > monthRange.value.end) {
        return true
    }

    // 如果已选择开始时间，结束时间不能早于开始时间
    if (props.formData.stareDate) {
        const startTimestamp = new Date(props.formData.stareDate).getTime()
        return timestamp < startTimestamp
    }

    return false
}

// 开始时间变化处理
const handleStartDateChange = (value) => {
    // 如果开始时间改变，且结束时间早于开始时间，清空结束时间
    if (value && props.formData.endDate) {
        const startTimestamp = new Date(value).getTime()
        const endTimestamp = new Date(props.formData.endDate).getTime()
        if (endTimestamp < startTimestamp) {
            props.formData.endDate = ''
            formRef.value?.clearValidate('endDate')
        }
    }
}

// 结束时间变化处理
const handleEndDateChange = (value) => {
    // 验证结束时间必须晚于或等于开始时间
    if (value && props.formData.stareDate) {
        const startTimestamp = new Date(props.formData.stareDate).getTime()
        const endTimestamp = new Date(value).getTime()
        if (endTimestamp < startTimestamp) {
            proxy.$modal.msgError('结束时间不能早于开始时间')
            props.formData.endDate = ''
            formRef.value?.clearValidate('endDate')
        }
    }
}

const rules = {
    planManagementMonth: [{ required: true, message: '请选择月份', trigger: 'change' }],
    projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
    workContent: [{ required: true, message: '请输入作业内容', trigger: 'blur' }],
    inspectionStationId: [{ required: true, message: '请选择实施部门', trigger: 'change' }],
    stareDate: [
        { required: true, message: '请选择计划开始时间', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback()
                    return
                }
                if (!props.formData.planManagementMonth) {
                    callback(new Error('请先选择月份'))
                    return
                }
                if (!isDateInMonth(value)) {
                    callback(new Error('开始时间必须在选定的月份内'))
                    return
                }
                callback()
            },
            trigger: 'change',
        },
    ],
    endDate: [
        { required: true, message: '请选择计划结束时间', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback()
                    return
                }
                if (!props.formData.planManagementMonth) {
                    callback(new Error('请先选择月份'))
                    return
                }
                if (!isDateInMonth(value)) {
                    callback(new Error('结束时间必须在选定的月份内'))
                    return
                }
                if (props.formData.stareDate) {
                    const startTimestamp = new Date(props.formData.stareDate).getTime()
                    const endTimestamp = new Date(value).getTime()
                    if (endTimestamp < startTimestamp) {
                        callback(new Error('结束时间不能早于开始时间'))
                        return
                    }
                }
                callback()
            },
            trigger: 'change',
        },
    ],
    riskLevel: [{ required: true, message: '请选择风险等级', trigger: 'change' }],
}

// 暴露校验方法和重置方法给父组件
defineExpose({
    validate: () => formRef.value.validate(),
    resetFields: () => formRef.value.resetFields(),
    clearValidate: () => formRef.value.clearValidate(),
})
</script>

<style lang="scss" scoped>
.add-and-edit-form {
    padding: 10px 20px;
    :deep(.el-radio-button__inner) {
        border-radius: 20px;
        margin-right: 10px;
        border: 1px solid #dcdfe6 !important;
        box-shadow: none !important;
    }
    :deep(.el-radio-button:first-child .el-radio-button__inner) {
        border-left: 1px solid #dcdfe6 !important;
    }
    :deep(.el-radio-button.is-active .el-radio-button__inner) {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
        border-color: var(--el-color-primary) !important;
    }
}
</style>
