<template>
    <div class="entry-information-page">
        <custom-header name="录入信息" bgColor="#fff"></custom-header>
        <div class="entry-information-body">
            <service-information v-if="currentStep === 1 && isServiceEntry" @next="handleNext" />
            <ba-information v-else-if="currentStep === 1" @next="handleNext" />
            <select-category v-else-if="currentStep === 2" :multiple="isServiceEntry" @prev="handlePrev" @next="handleNext" />
            <select-equipment
                v-else-if="showEquipmentStep"
                :key="equipmentScope || 'farmer'"
                :is-service="isServiceEntry"
                :is-last-step="equipmentIsLastStep"
                :equipment-scope="equipmentScope"
                :total-steps="totalSteps"
                @prev="handlePrev"
                @next="handleNext"
                @confirm="handleConfirm"
            />
            <select-variety
                v-else-if="showVarietyStep"
                :multiple="isServiceEntry"
                @prev="handlePrev"
                @next="handleNext"
            />
            <manual-farming-service
                v-else-if="showManualStep"
                :has-field="hasFieldSelected"
                :has-fruit="hasFruitSelected"
                @prev="handlePrev"
                @next="handleNext"
                @confirm="handleConfirm"
            />
        </div>
    </div>
</template>

<script setup>
import { computed, onActivated, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import customHeader from "@/components/customHeader.vue";
import baInformation from "./components/baInformation.vue";
import serviceInformation from "./components/serviceInformation.vue";
import selectCategory from "./components/selectCategory.vue";
import selectVariety from "./components/selectVariety.vue";
import selectEquipment from "./components/selectEquipment.vue";
import manualFarmingService from "./components/manualFarmingService.vue";

const STEP_KEY = "ENTRY_INFORMATION_STEP";
const INVITE_TYPE_KEY = "ENTRY_INVITE_TYPE";
const CATEGORY_SESSION_KEY = "ENTRY_SELECTED_CATEGORY";

const router = useRouter();
const route = useRoute();

function readStep() {
    const step = Number(sessionStorage.getItem(STEP_KEY));
    return step >= 1 && step <= 5 ? step : 1;
}

function readInviteType() {
    const fromQuery = route.query.inviteType;
    if (fromQuery === "service" || fromQuery === "farmer") {
        sessionStorage.setItem(INVITE_TYPE_KEY, fromQuery);
        return fromQuery;
    }
    return sessionStorage.getItem(INVITE_TYPE_KEY) || "farmer";
}

const currentStep = ref(readStep());
const inviteType = ref(readInviteType());
const isServiceEntry = computed(() => inviteType.value === "service");
const hasFieldSelected = ref(false);
const hasFruitSelected = ref(false);
const isBothCrops = computed(() => hasFieldSelected.value && hasFruitSelected.value);
const totalSteps = computed(() => {
    if (!isServiceEntry.value) return 4;
    return isBothCrops.value ? 6 : 4;
});
const maxStep = computed(() => {
    if (!isServiceEntry.value) return 4;
    return isBothCrops.value ? 5 : 4;
});
const showEquipmentStep = computed(() => {
    if (!isServiceEntry.value) return currentStep.value === 4;
    if (hasFieldSelected.value && currentStep.value === 3) return true;
    if (isBothCrops.value && currentStep.value === 5) return true;
    if (hasFruitSelected.value && !hasFieldSelected.value && currentStep.value === 4) return true;
    return false;
});
const equipmentScope = computed(() => {
    if (!isServiceEntry.value) return "";
    if (!hasFieldSelected.value) return "fruit";
    return currentStep.value === 5 ? "fruit" : "field";
});
const equipmentIsLastStep = computed(() => {
    if (!isServiceEntry.value) return true;
    return equipmentScope.value === "fruit";
});
const showVarietyStep = computed(() => !isServiceEntry.value && currentStep.value === 3);
const showManualStep = computed(() => {
    if (!isServiceEntry.value) return false;
    if (hasFieldSelected.value) return currentStep.value === 4;
    return hasFruitSelected.value && currentStep.value === 3;
});

function refreshHasField() {
    try {
        const list = JSON.parse(sessionStorage.getItem(CATEGORY_SESSION_KEY) || "[]");
        const items = Array.isArray(list) ? list : [];
        hasFieldSelected.value = items.some(
            (item) => item?.firstCrop === "大田" || item?.majorKey === "field"
        );
        hasFruitSelected.value = items.some(
            (item) => item?.firstCrop === "果树" || item?.majorKey === "fruit"
        );
    } catch {
        hasFieldSelected.value = false;
        hasFruitSelected.value = false;
    }
}

function clampStep() {
    if (currentStep.value > maxStep.value) {
        currentStep.value = maxStep.value;
    }
}

function syncEntryState() {
    inviteType.value = readInviteType();
    currentStep.value = readStep();
    refreshHasField();
    clampStep();
}

onMounted(syncEntryState);
onActivated(syncEntryState);

watch(
    currentStep,
    (step) => {
        sessionStorage.setItem(STEP_KEY, String(step));
    },
    { immediate: true }
);

const handleNext = () => {
    refreshHasField();
    if (hasFieldSelected.value && currentStep.value === 3) {
        sessionStorage.removeItem("ENTRY_MANUAL_VIEW");
    }
    if (currentStep.value < maxStep.value) {
        currentStep.value += 1;
    }
};

const handlePrev = () => {
    if (currentStep.value > 1) {
        currentStep.value -= 1;
    }
};

const handleConfirm = () => {
    router.replace("/growth_report");
};
</script>

<style lang="scss" scoped>
.entry-information-page {
    height: 100vh;
    background: linear-gradient(270deg, rgba(218, 195, 255, 0.59) 0%, #E6F2FF 0.01%, #8FC5FE 100%);
    display: flex;
    flex-direction: column;
}

.entry-information-body {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
</style>
