<template>
    <popup
        class="active-upload-popup"
        v-model:show="show"
        closeable
        teleport="body"
        :overlay-style="{ 'z-index': 9999 }"
        :close-on-click-overlay="false"
        @closed="handleClosed"
    >
        <div class="header" v-if="selectCurrentPhenology">
            <div class="title">
                <span class="required">*</span>
                当前物候期
            </div>
            <div class="date-input">
                <el-select popper-class="custom-select-dropdown" v-model="currentPhenologyId" size="large" placeholder="请选择当前物候期">
                    <el-option
                        v-for="item in phenologyList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </div>
        </div>
        <div class="header">
            <div class="title">
                <span class="required">*</span>
                {{ problemTitle }}
            </div>
            <div class="date-input">
                <el-date-picker
                    v-model="uploadDate"
                    size="large"
                    popper-class="custom-select-dropdown"
                    style="width: 100%"
                    type="date"
                    placeholder="请选择日期"
                    :editable="false"
                />
            </div>
        </div>
        <div v-if="needExecutor">
            <div class="header">
                <div class="title">
                    <span class="required">*</span>
                    请确认执行人
                </div>
                <div class="date-input">
                    <el-select popper-class="custom-select-dropdown" size="large" v-model="executorId" placeholder="请选择执行人">
                        <el-option
                            v-for="(item, index) in executorList"
                            :key="index"
                            :label="item.name"
                            :value="item.miniUserId"
                        />
                    </el-select>
                </div>
            </div>
            <div class="header flex-header">
                <div class="title">
                    <span class="required">*</span>
                    是否需要复核？
                </div>
                <div class="date-input">
                    <el-radio-group v-model="needReview">
                        <el-radio :value="1">需要</el-radio>
                        <el-radio :value="0">不需要</el-radio>
                    </el-radio-group>
                </div>
            </div>
            <div class="header" v-if="needReview">
                <div class="title">
                    <span class="required">*</span>
                    请选择农事执行后复核时间
                </div>
                <div class="date-input review-day-input">
                    <el-input size="large" v-model="reviewDay" type="number" step="0.01">
                        <template #append>天后</template>
                    </el-input>
                </div>
            </div>
        </div>
        <div class="tips-text img-desc" v-if="imgDesc"><span class="required" v-if="userInfoObj?.agriculturalRole !== 1">*</span>{{ imgDesc }}</div>
        <div class="tips-text" v-else>上传照片，诊断更准确哦~</div>
        <upload :textShow="true" class="upload-wrap" exampleImg>
            <img class="example" src="@/assets/img/home/example-4.png" alt="" />
            <img class="example" src="@/assets/img/home/plus.png" alt="" />
        </upload>
        <div class="btn" :class="{ disabled: isUploading }" @click="handleUpload">
            {{ isUploading ? "提交中..." : "确认" }}
        </div>
    </popup>

    <!-- 上传成功提示弹窗 -->
    <popup class="success-popup" v-model:show="successShow" :close-on-click-overlay="false">
        <div class="success-wrap">
            <img class="success-icon" src="@/assets/img/home/right.png" alt="" />
            <div class="success-title">好的，感谢您的配合</div>
            <div class="success-sub">请您耐心等待农事确认</div>
            <div class="btn" @click="successShow = false">我知道了</div>
        </div>
    </popup>
</template>

<script setup>
import { Popup } from "vant";
import { onMounted, onUnmounted, ref } from "vue";
import upload from "@/components/upload";
import eventBus from "@/api/eventBus";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();
const show = ref(false);
const gardenId = ref(null);
const images = ref([]);
const uploadDate = ref("");
const problemTitle = ref("请选择问题");
const successShow = ref(false);
const isUploading = ref(false); // 标记是否正在上传中
onMounted(() => {
    eventBus.off("upload:changeArr", uploadChange);
    eventBus.on("upload:changeArr", uploadChange);
    eventBus.on("activeUpload:show", handleShow);
    eventBus.on("activeUpload:success", handleSuccess);
});

const userInfo = localStorage.getItem("localUserInfo");
const userInfoObj = userInfo ? JSON.parse(userInfo) : {};

function uploadChange(arr) {
    images.value = arr;
}

function formatDate(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}`;
}

const type = ref(null);
const arrangeId = ref(null);
// 选择执行人
const needExecutor = ref(false);
const executorList = ref([]);
const executorId = ref(null);
const needReview = ref(false);
const reviewDay = ref(null);
// 选择当前物候期
const currentPhenologyId = ref(null);
const phenologyList = ref([]);
const selectCurrentPhenology = ref(false);

// 图片上传标题描述
const imgDesc = ref(null);
function handleShow({
    gardenIdVal,
    problemTitleVal,
    typeVal,
    arrangeIdVal,
    executorListVal,
    imgDescVal,
    needExecutorVal,
    selectCurrentPhenologyVal,
    phenologyListVal,
    farmWorkIdVal,
    schemeIdVal,
}) {
    images.value = [];
    gardenId.value = gardenIdVal;
    problemTitle.value = problemTitleVal || "请选择问题";
    uploadDate.value = new Date();
    show.value = true;
    type.value = typeVal;
    arrangeId.value = arrangeIdVal;
    executorList.value = executorListVal;
    imgDesc.value = imgDescVal;
    needExecutor.value = needExecutorVal;
    selectCurrentPhenology.value = selectCurrentPhenologyVal ? true : false;
    phenologyList.value = phenologyListVal;
    // 重置上传状态
    isUploading.value = false;
    if(typeVal !== "question"){
        // 如果没有报价信息，则跳转去完善报价信息
        VE_API.monitor.validatePesticideFertilizerQuotes({ id: farmWorkIdVal, schemeId: schemeIdVal }).then((res) => {
            if (res.data === false) {
                ElMessage.warning("请先完善报价信息");
                setTimeout(() => {
                    router.push(`/modify?farmWorkId=${farmWorkIdVal}&schemeId=${schemeIdVal}&farmId=${gardenIdVal}&onlyPrice=true&isEdit=true`);
                }, 1000);
            }
        });
    }
}

function handleSuccess() {
    successShow.value = true;
}

const emit = defineEmits(["handleUploadSuccess"]);

const handleUpload = () => {
    // 如果正在上传中，直接返回，防止重复调用
    if (isUploading.value) return;

    if (userInfoObj?.agriculturalRole !== 1 && images.value.length === 0) return ElMessage.warning("请上传图片");
    let paramsObj = {
        farmId: gardenId.value,
        arrangeId: arrangeId.value,
        executeDate: formatDate(uploadDate.value),
        imagePaths: images.value,
    };
    if (needExecutor.value) {
        paramsObj = {
            ...paramsObj,
            executeDeadlineDate: formatDate(uploadDate.value),
            executeDate: null,
            executorUserId: executorId.value,
            needReview: needReview.value,
            reviewIntervalDays: reviewDay.value,
        };
    }
    if (type.value === "question") {
        show.value = false;
        emit("handleUploadSuccess", paramsObj);
        return;
    }
    triggerFarmWork(paramsObj, true);
};

function triggerFarmWork(paramsObj, showSuccess) {
    // 如果正在上传中，直接返回，防止重复调用
    if (isUploading.value) return;

    // 设置上传状态为 true
    isUploading.value = true;

    VE_API.monitor
        .triggerFarmWork(paramsObj)
        .then((res) => {
            if (res.code === 0) {
                if (showSuccess) {
                    show.value = false;
                    // successShow.value = true;
                    ElMessage.success("农事已转入成功");
                    emit("handleUploadSuccess", paramsObj);
                }
            }
        })
        .catch((error) => {
            console.error("触发农事失败:", error);
        })
        .finally(() => {
            // 无论成功或失败，都重置上传状态
            isUploading.value = false;
        });
}

function showPopup(data) {
    handleShow(data);
}

defineExpose({
    triggerFarmWork,
    showPopup,
});

function handleClosed() {
    eventBus.emit("upload:reset");
}

onUnmounted(() => {
    eventBus.off("activeUpload:show", handleShow);
    eventBus.off("activeUpload:success", handleSuccess);
    eventBus.off("upload:changeArr", uploadChange);
    show.value = false;
});
</script>

<style lang="scss" scoped>
.active-upload-popup {
    z-index: 9999 !important;
    width: 90%;
    box-sizing: border-box;
    padding: 24px 18px 20px;
    background: linear-gradient(0deg, #ffffff 70%, #d1ebff 100%);
    border-radius: 10px;
    ::v-deep {
        .van-popup__close-icon {
            color: #000;
        }
    }
    .header {
        .title {
            font-size: 16px;
            font-weight: 500;
            display: flex;
        }
        align-items: center;
        .date-input {
            margin: 12px 0;
            ::v-deep {
                .el-input__inner {
                    caret-color: transparent;
                }
            }
        }
        .review-day-input {
            border: 1px solid #dcdcdc;
            border-radius: 3px;
            ::v-deep {
                .el-input__wrapper {
                    width: 40px;
                    flex: none;
                    box-shadow: none;
                }
                .el-input-group__append {
                    box-shadow: none;
                    background: none;
                }
            }
        }
    }
    .flex-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12px;
        .date-input {
            margin: 0;
        }
    }
    .required {
        color: #ff4d4f;
        margin-right: 4px;
    }
    .tips-text {
        font-weight: 500;
        &.img-desc {
            font-size: 16px;
        }
    }
    .upload-wrap {
        margin: 12px 0 24px;
    }
    .example {
        width: 80px;
        height: 80px;
    }
    .example + .example {
        margin-left: 12px;
    }
}

.btn {
    padding: 8px;
    background: #2199f8;
    border-radius: 25px;
    color: #fff;
    font-size: 16px;
    text-align: center;
    cursor: pointer;
    transition: opacity 0.3s;
    &.disabled {
        opacity: 0.6;
        cursor: not-allowed;
        pointer-events: none;
    }
}

.success-popup {
    width: 300px;
    border-radius: 14px;
    padding: 28px 15px 20px;
    box-sizing: border-box;
    .success-wrap {
        text-align: center;
    }
    .success-icon {
        width: 68px;
        height: 68px;
    }
    .success-title {
        font-size: 24px;
        margin-top: 12px;
    }
    .success-sub {
        margin: 8px 0 32px;
    }
}
</style>

<style lang="scss">
// 全局样式，用于设置下拉框的 z-index（不受 scoped 限制）
.custom-select-dropdown {
    z-index: 10000 !important;
}
</style>
