<template>
    <div class="agri-file-page" :style="{ height: `calc(100vh - ${tabBarHeight}px)` }">
        <!-- 天气遮罩 -->
        <div class="weather-mask" v-show="isExpanded" @click="handleMaskClick"></div>
        <!-- 头部 -->
        <div class="agri-file-header" :style="activeGardenTab === 'current' ? headerMotionStyle : undefined">
            <weather-info ref="weatherInfoRef" :hasWeather="false" from="agri_file" class="weather-info"
                @weatherExpanded="weatherExpanded" @changeGarden="changeGarden" @changeGardenTab="changeGardenTab"
                @reportTabClick="handleReportTabClick" :isGarden="true"
                :gardenId="defaultGardenId" />
        </div>
        <!-- 农场列表 -->
        <div v-show="activeGardenTab === 'list'">
            <garden-list ref="gardenListRef" :garden-id="selectedGardenId" @loaded="handleGardenLoaded"
                @selectGarden="handleGardenSelected" />
        </div>

        <div v-show="activeGardenTab === 'current'" class="tracking-list">
            <div v-for="item in trackingList" :key="item.id" class="tracking-item"
                :class="`tracking-item--${item.theme}`" @click="handleTrackingItemClick(item)">
                <div class="tracking-item__header">
                    <div class="tracking-item__header-row">
                        <div class="tracking-item__header-left">
                            <span class="tracking-item__level" v-show="item.risk_level">{{
                                formatRiskLevel(item.risk_level) }}</span>
                            <span class="tracking-item__title">{{ item.first_work?.work_name }}</span>
                        </div>
                        <div class="tracking-item__tags">
                            <span v-for="(tag, tagIndex) in item.list" :key="tagIndex" class="tracking-item__tag">{{
                                tag?.category_name || tag }}</span>
                        </div>
                    </div>
                </div>
                <div class="tracking-item__body">
                    <div class="tracking-item__action">
                        <div class="tracking-item__action-main">
                            <div class="tracking-item__icon">
                                <img :src="item.icon" alt="" />
                                <div class="tracking-item__reason">{{ item.first_work?.work_reason_short }}</div>
                            </div>
                            <div class="tracking-item__info">
                                <div class="tracking-item__issue">{{ item.first_work?.interaction_issue }}</div>
                            </div>
                        </div>
                        <div class="tracking-item__btn">{{ $t('agriFile.recordNow') }}</div>
                    </div>
                    <div class="tracking-item__history" v-show="false">
                        <div class="tracking-item__history-text">{{ item.historyText }}</div>
                        <div class="tracking-item__images">
                            <img v-for="(image, imageIndex) in item.images" :key="imageIndex"
                                class="tracking-item__thumb" :src="image" alt="" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, onActivated, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { useI18n } from "@/i18n";
import weatherInfo from "@/components/weatherInfo.vue";
import gardenList from "@/components/gardenList.vue";

const { t } = useI18n();

const store = useStore();
const route = useRoute();
const router = useRouter();
const tabBarHeight = computed(() => store.state.home.tabBarHeight);

const isExpanded = ref(false);
const weatherInfoRef = ref(null);
const defaultGardenId = ref(null);
const selectedGardenId = ref(null);
const gardenListRef = ref(null);
const activeGardenTab = ref("current");
const panelExpandProgress = ref(0);
const panelViewType = ref("risk");

const HEADER_FADE_START = 0.68;

const headerMotionStyle = computed(() => {
    const progress = panelExpandProgress.value;
    const fade = progress <= HEADER_FADE_START
        ? 0
        : (progress - HEADER_FADE_START) / (1 - HEADER_FADE_START);
    const opacity = 1 - fade;
    return {
        opacity,
        transform: `translateY(${-14 * fade}px) scale(${1 - fade * 0.04})`,
        pointerEvents: opacity < 0.15 ? "none" : "auto",
    };
});

const currentFarmName = ref("");
const currentFarmVariety = ref(null);

const defaultThumb = require("@/assets/img/home/banner.png");
const trackingList = ref([]);
// const trackingList = ref([
//     {
//         id: "phenology",
//         theme: "blue",
//         level: "二级",
//         title: "物候跟踪记录",
//         tags: ["物候", "物候", "物候"],
//         icon: require("@/assets/img/report/wh-icon.png"),
//         reason: "某某原因",
//         issue: "互动问题互动问题互动问题互动问题互",
//         recordText: "立即记录",
//         historyText: "2026.06.07 某某区发生的事情",
//         images: Array.from({ length: 5 }, () => defaultThumb),
//     },
//     {
//         id: "pest",
//         theme: "red",
//         level: "二级",
//         title: "病虫害态势监控",
//         tags: ["真菌类", "真菌类", "真菌类"],
//         icon: require("@/assets/img/report/bh-icon.png"),
//         reason: "某某原因",
//         issue: "互动问题互动问题互动问题互动问题互",
//         recordText: "立即记录",
//         historyText: "2026.06.07 某某区发生的事情",
//         images: Array.from({ length: 5 }, () => defaultThumb),
//     },
//     {
//         id: "growth",
//         theme: "orange",
//         level: "二级",
//         title: "长势异常态势跟踪",
//         tags: ["真菌类", "真菌类", "真菌类"],
//         icon: require("@/assets/img/report/yc-icon.png"),
//         reason: "某某原因",
//         issue: "互动问题互动问题互动问题互动问题互",
//         recordText: "立即记录",
//         historyText: "2026.06.07 某某区发生的事情",
//         images: Array.from({ length: 5 }, () => defaultThumb),
//     },
// ]);

const handleReportTabClick = (item) => {
    panelViewType.value = "plot";
};

const weatherExpanded = (isExpandedValue) => {
    isExpanded.value = isExpandedValue;
};

const handleMaskClick = () => {
    if (weatherInfoRef.value?.toggleExpand) {
        weatherInfoRef.value.toggleExpand();
    }
};

const changeGardenTab = (tab) => {
    activeGardenTab.value = tab;
    if (tab !== "current") {
        panelExpandProgress.value = 0;
        panelViewType.value = "risk";
    }
};

const handleGardenLoaded = ({ hasFarm }) => {
    weatherInfoRef.value?.setGardenLoaded?.(hasFarm);
};

const handleGardenSelected = (garden) => {
    selectedGardenId.value = garden?.id ?? null;
    weatherInfoRef.value?.setSelectedGarden?.(garden);
};

const changeGarden = (data) => {
    if (!data?.id) return;
    store.commit("home/SET_GARDEN_ID", data.id);
    selectedGardenId.value = data.id;
    currentFarmName.value = data.name ?? "";
    currentFarmVariety.value = data.farm_variety ?? null;
    getFarmRiskAndTracking();
};

onActivated(() => {
    if (route.query?.farmId) {
        defaultGardenId.value = route.query.farmId;
    }
    const savedFarmId = localStorage.getItem("selectedFarmId");
    selectedGardenId.value = savedFarmId ? Number(savedFarmId) : null;
    gardenListRef.value?.refreshFarmList?.();
});

const RISK_LEVEL_KEYS = { 1: "agriFile.riskLevel1", 2: "agriFile.riskLevel2", 3: "agriFile.riskLevel3" };
const formatRiskLevel = (level) => {
    const key = RISK_LEVEL_KEYS[Number(level)];
    return key ? t(key) : "";
};

const currentPheCode = ref('');
let fetchRequestId = 0;
const getFarmRiskAndTracking = async () => {
    const requestId = ++fetchRequestId;
    trackingList.value = [];
    const selectedFarmData = JSON.parse(localStorage.getItem("selectedFarmData") || "{}");
    const res = await VE_API.monitor.getFarmRiskAndTracking({
        farm_id: selectedGardenId.value,
        crop_type: selectedFarmData.farm_variety,
        category_code: selectedFarmData.farm_category
    });
    if (requestId !== fetchRequestId) return;
    if (res.code === 200) {
        currentPheCode.value = res.data.current_phe_code;
        trackingList.value = [
            { ...res.data.phenology_tracking, theme: "blue", icon: require("@/assets/img/report/wh-icon.png"), workType: 'phenology' },
            { ...res.data.growth_abnormal_tracking, theme: "orange", icon: require("@/assets/img/report/yc-icon.png"), workType: 'growth' },
            { ...res.data.pest_risk_assessment, theme: "red", icon: require("@/assets/img/report/bh-icon.png"), workType: 'pest' },
        ];
    }
};

const handleTrackingItemClick = (item) => {
    router.push({
        path: "/record_details",
        query: { workId: item?.first_work?.work_id, type: item?.workType, curCode: currentPheCode.value },
    });
};
</script>

<style lang="scss" scoped>
.agri-file-page {
    width: 100%;
    height: 100%;
    background: #D0E6FC;

    .weather-mask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.52);
        z-index: 11;
    }

    .agri-file-header {
        position: absolute;
        z-index: 12;
        left: 10px;
        top: 12px;
        width: calc(100% - 20px);
        will-change: transform, opacity;
        transform-origin: center top;

        .weather-info {
            width: 100%;
            position: relative;
            left: auto;
            top: auto;

            :deep(.garden-tabs) {
                .garden-item.left-item.active .current-name {
                    color: #2199F8;
                    font-weight: 600;
                }
            }
        }
    }

    .tracking-list {
        height: 100%;
        padding: 65px 10px 12px;
        // padding: 105px 10px 12px;
        box-sizing: border-box;
        overflow-y: auto;
        display: flex;
        flex-direction: column;
        gap: 12px;

        &::-webkit-scrollbar {
            display: none;
        }
    }

    .tracking-item {
        width: 100%;
        box-shadow: 0px 4px 4px 0px var(--tracking-shadow);
        border: 1px solid #fff;
        border-radius: 10px;

        &--blue {
            --tracking-header-bg: linear-gradient(0deg, #A6D8FF 0%, #39A7FF 100%);
            --tracking-primary: #2199f8;
            --tracking-action-border: rgba(33, 153, 248, 0.2);
            --tracking-shadow: #2199f81a;
        }

        &--red {
            --tracking-header-bg: linear-gradient(0deg, #FD9D9D 0%, #FF6A6A 100%);
            --tracking-primary: #FF6A6A;
            --tracking-action-border: rgba(255, 173, 173, 0.2);
            --tracking-shadow: #ff6b6b1a;
        }

        &--orange {
            --tracking-header-bg: linear-gradient(0deg, #FCB981 0%, #FF953D 100%);
            --tracking-primary: #FA8D39;
            --tracking-action-border: rgba(255, 173, 173, 0.2);
            --tracking-shadow: #f593421a;
        }

        &__header {
            position: relative;
            padding: 10px 10px 20px;
            border-radius: 10px 10px 0 0;
            background: var(--tracking-header-bg);
        }

        &__header-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        &__header-left {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        &__level {
            padding: 1px 6px;
            border-radius: 2px;
            background: #fff;
            color: #FF6A6A;
            font-size: 12px;
            min-width: fit-content;
        }

        &__title {
            color: #fff;
            font-size: 16px;
            font-weight: 500;
        }

        &__tags {
            display: flex;
            align-items: center;
            gap: 4px;
        }

        &__tag {
            padding: 1px 5px;
            border-radius: 2px;
            background: #fff;
            color: var(--tracking-primary);
            font-size: 12px;
            border: .5px solid var(--tracking-primary);
            min-width: max-content;
        }

        &__body {
            position: relative;
            padding: 10px;
            background: #fff;
            border-radius: 10px;
            margin-top: -8px;

            &::before {
                content: "";
                position: absolute;
                top: -7px;
                left: 60px;
                width: 0;
                height: 0;
                border-left: 7px solid transparent;
                border-right: 7px solid transparent;
                border-bottom: 7px solid #fff;
            }
        }

        &__action {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 8px;
            padding: 10px 8px;
            border: 1px solid var(--tracking-action-border);
            border-radius: 6px;
            box-sizing: border-box;
        }

        &__icon {
            display: flex;
            align-items: center;
            gap: 4px;

            img {
                width: 18px;
                height: 16px;
            }
        }

        &__reason {
            color: var(--tracking-primary);
            font-weight: 500;
        }

        &__issue {
            margin-top: 3px;
            color: var(--tracking-primary);
            font-size: 12px;
        }

        &__btn {
            padding: 5px 7px;
            border-radius: 5px;
            background: var(--tracking-primary);
            color: #fff;
            font-size: 12px;
            min-width: fit-content;
        }

        &__history {
            margin-top: 10px;
            padding: 6px 8px;
            border-radius: 6px;
            background: rgba(168, 168, 168, 0.1);
        }

        &__history-text {
            color: rgba(31, 31, 31, 0.5);
            font-size: 12px;
        }

        &__images {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 6px;
            margin-top: 6px;
        }

        &__thumb {
            width: 100%;
            aspect-ratio: 1;
            border-radius: 8px;
            object-fit: cover;
        }
    }
}
</style>
