<template>
    <popup class="interact-popup" v-model:show="show" closeable :close-on-click-overlay="false" @closed="handleClosed">
        <div class="interact-header">
            <div class="interact-title">{{ currentData.farmWorkName || currentData.name }}</div>
        </div>
        <div class="interact-form">
            <div class="form-item">
                <div class="form-label">
                    <span class="required">*</span>
                    请选择互动阶段
                </div>
                <div class="form-input-wrapper">
                    <el-select v-model="formData.phenologyId" size="large" placeholder="请选择物候期" :editable="false">
                        <el-option
                            v-for="item in phenologyList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </div>
            </div>
            <div class="form-item">
                <div class="form-label">
                    <span class="required">*</span>
                    请选择互动时间
                </div>
                <div class="form-input-wrapper">
                    <el-date-picker
                        v-model="formData.interactionTime"
                        size="large"
                        style="width: 100%"
                        type="date"
                        placeholder="请选择日期"
                        :editable="false"
                    />
                </div>
            </div>
            <div class="form-item">
                <div class="form-label">
                    <span class="required">*</span>
                    请设置互动问题
                </div>
                <el-input
                    v-model="formData.interactionQuestion"
                    type="textarea"
                    :rows="3"
                    maxlength="35"
                    show-word-limit
                    placeholder="请设置互动问题"
                    class="question-textarea"
                />
            </div>
        </div>
        <div class="interact-buttons">
            <div class="btn-delete" @click="handleCancelInteract">取消修改</div>
            <div class="btn-save" :class="{ disabled: isSaving }" @click="handleSaveInteract">
                {{ saveButtonText }}
            </div>
        </div>
    </popup>
</template>

<script setup>
import { Popup } from "vant";
import { ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// Emits
const emit = defineEmits(["handleSaveSuccess"]);

// 响应式数据
const show = ref(false);
const arrangeId = ref(null);
const isSaving = ref(false);

const formData = ref({
    phenologyId: "",
    interactionTime: "",
    interactionQuestion: "",
});

// 计算属性
const saveButtonText = computed(() => (isSaving.value ? "保存中..." : "保存修改"));

// 工具函数
const resetInteractData = () => {
    formData.value = {
        phenologyId: "",
        interactionTime: "",
        interactionQuestion: "",
    };
};

// 验证函数
const validateInteractForm = () => {
    if (!formData.value.phenologyId) {
        ElMessage.warning("请选择互动时间");
        return false;
    }
    if (!formData.value.interactionTime) {
        ElMessage.warning("请选择强制触发互动时间");
        return false;
    }
    if (!formData.value.interactionQuestion?.trim()) {
        ElMessage.warning("请设置互动问题");
        return false;
    }
    return true;
};

const phenologyList = ref(null);
const getPhenologyList = async (containerSpaceTimeId) => {
    if (!containerSpaceTimeId) {
        phenologyList.value = [];
        return;
    }
    const res = await VE_API.monitor.listPhenology({ containerSpaceTimeId });
    if (res.code === 0) {
        phenologyList.value = res.data || [];
    }
};

const getFarmWorkArrangeDetail = async (id) => {
    const { data, code } = await VE_API.farm.getFarmWorkArrangeDetail({ id });
    if(code === 0) {
        formData.value = {
            phenologyId: data.phenologyId,
            interactionTime: data.interactionTime,
            interactionQuestion: data.interactionQuestion || "",
        };
    }
};

const currentData = ref(null);
// 显示弹窗方法
const showPopup = async (data) => {
    // 重置数据
    resetInteractData();
    await getPhenologyList(data.containerSpaceTimeId);
    await getFarmWorkArrangeDetail(data.id);
    // 设置数据
    currentData.value = data;

    isSaving.value = false;

    show.value = true;
};

// 事件处理函数
const handleCancelInteract = () => {
    show.value = false;
};

function formatDate(date) {
    // 如果已经是字符串格式 YYYY-MM-DD，直接返回
    if (typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)) {
        return date;
    }
    // 如果是 Date 对象，进行转换
    if (date instanceof Date) {
        let year = date.getFullYear();
        let month = String(date.getMonth() + 1).padStart(2, "0");
        let day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
    }
    // 其他情况返回原值
    return date;
}

const handleSaveInteract = () => {
    if (isSaving.value || !validateInteractForm()) return;

    isSaving.value = true;

    const paramsObj = {
        id: currentData.value.id,
        ...formData.value,
        interactionTime: formatDate(formData.value.interactionTime),
    };

    VE_API.monitor
        .updateFarmWorkArrange(paramsObj)
        .then((res) => {
            if (res.code === 0) {
                ElMessage.success("保存成功");
                show.value = false;
                emit("handleSaveSuccess", paramsObj);
            } else {
                ElMessage.error(res.message || "保存失败");
            }
        })
        .catch((error) => {
            console.error("保存互动设置失败:", error);
            ElMessage.error("保存失败，请重试");
        })
        .finally(() => {
            isSaving.value = false;
        });
};

const handleClosed = () => {
    resetInteractData();
};

// 暴露方法
defineExpose({
    showPopup,
});
</script>

<style lang="scss" scoped>
.interact-popup {
    width: 90%;
    box-sizing: border-box;
    background: #ffffff;
    padding: 0;
    border-radius: 10px;

    ::v-deep {
        .van-popup__close-icon {
            color: #000;
        }
    }

    .interact-header {
        background: linear-gradient(180deg, #d1ebff 0%, #ffffff 100%);
        padding: 20px 18px;
        text-align: center;
        border-radius: 10px 10px 0 0;

        .interact-title {
            font-size: 18px;
            font-weight: 600;
            color: #000;
        }
    }

    .interact-form {
        padding: 0 18px 20px;

        .form-item {
            margin-bottom: 16px;

            &:last-child {
                margin-bottom: 0;
            }

            .form-label {
                color: #000;
                font-weight: 500;
                margin-bottom: 12px;
                display: flex;
                align-items: center;

                .required {
                    color: #ff4d4f;
                    margin-right: 4px;
                }
            }

            .form-input-wrapper {
                position: relative;

                ::v-deep {
                    .el-input__inner {
                        caret-color: transparent;
                        padding-right: 40px;
                    }

                    .el-input__suffix {
                        display: none;
                    }
                }

                .time-icon {
                    position: absolute;
                    right: 12px;
                    top: 50%;
                    transform: translateY(-50%);
                    color: #909399;
                    pointer-events: none;
                    z-index: 1;
                    font-size: 16px;
                }
            }

            .question-textarea {
                ::v-deep {
                    .el-textarea__inner {
                        resize: none;
                        line-height: 1.5;
                        min-height: 80px;
                    }
                }
            }
        }
    }

    .interact-buttons {
        display: flex;
        gap: 12px;
        padding: 0 18px 20px;

        .btn-delete,
        .btn-save {
            flex: 1;
            padding: 8px;
            border-radius: 25px;
            font-size: 16px;
            text-align: center;
        }

        .btn-delete {
            background: #ffffff;
            border: 1px solid rgba(153, 153, 153, 0.5);
            color: #666666;
        }

        .btn-save {
            background: #2199f8;
            color: #fff;
            border: none;

            &:hover:not(.disabled) {
                background: #1a8ae6;
            }

            &:active:not(.disabled) {
                opacity: 0.9;
                transform: scale(0.98);
            }

            &.disabled {
                opacity: 0.6;
                cursor: not-allowed;
                pointer-events: none;
            }
        }
    }
}
</style>
