<template>
    <custom-header v-if="isHeaderShow" name="农场详情"></custom-header>
    <div class="monitor-index" :style="{ height: `calc(100vh - ${tabBarHeight}px)` }">
        <!-- 天气遮罩 -->
        <div class="weather-mask" v-show="isExpanded" @click="handleMaskClick"></div>
        <!-- 天气 -->
        <weather-info ref="weatherInfoRef" from="monitor" class="weather-info" @weatherExpanded="weatherExpanded"
            @changeGarden="changeGarden" @changeGardenTab="changeGardenTab" :isGarden="true"
            :gardenId="defaultGardenId"></weather-info>
        <!-- 农场列表 -->
        <div v-show="activeGardenTab === 'list'">
            <garden-list ref="gardenListRef" :garden-id="selectedGardenId" @loaded="handleGardenLoaded"
                @selectGarden="handleGardenSelected" />
        </div>
        <!-- 作物档案 -->
        <div class="archives-time-line" :class="{ 'no-top': !varietyTabs.length && !gardenId }" v-show="activeGardenTab === 'current'">
            <div class="archives-time-line-header">
                <div class="line-title">农情档案</div>
                <div class="header-right">
                    <div class="add-variety-btn" v-if="varietyTabs.length > 0" @click="handleAddVariety">
                        <span>分区管理</span>
                    </div>
                    <el-date-picker
                        style="width: 100px"
                        :editable="false"
                        v-model="date"
                        type="year"
                        placeholder="全部日期"
                        :disabled-date="disabledYearDate"
                    />
                </div>
            </div>
            <!-- 品种选择 -->
            <div class="category-tabs tabs-list" v-if="farmsCategoryList.length > 0">
                <div v-for="(v, index) in farmsCategoryList" :key="index" class="item-tab"
                    :class="{ 'item-tab--active': activeFarmsCategory === v.speciesId }" @click="handleFarmsCategoryClick(v, index)">
                    {{ v.speciesName }}
                </div>
            </div>
            <div class="variety-tabs tabs-list" v-if="varietyTabs.length > 0">
                <div v-for="(v, index) in varietyTabs" :key="index" class="item-tab"
                    :class="{ 'item-tab--active': activeVariety === index }" @click="handleVarietyClick(v, index)">
                    {{ v.regionName }}
                </div>
            </div>
            <template v-if="!varietyTabs.length">
                <div class="lock-img" @click="handleLockClick">
                    <img src="@/assets/img/home/lock-blue.png" alt="" class="lock-img-item" />
                    <div class="lock-text">
                        专属数字农场，种好卖好
                        <div>点击解锁一键溯源增产</div>
                    </div>
                    <div class="lock-btn">点击解锁</div>
                </div>
                <img class="example-img" src="@/assets/img/monitor/example.png" alt="">
            </template>
            <div class="archives-time-line-content">
                <div class="time-line">
                    <archives-farm-time-line :year="date.getFullYear()" :farmId="farmIdData" :regionId="regionData" @card-click="handleCardClick"></archives-farm-time-line>
                </div>
            </div>
        </div>
    </div>

    <!-- 勾选区域引导弹窗 -->
    <select-region-popup v-model:show="showSelectRegionPopup" :title="titlePopup" @confirm="handleGoSelectRegion"
        @skip="handleSkipSelectRegion" />

    <!-- 农事执行弹窗（勾选区域引导弹窗显示时不展示） -->
    <agri-execute-popup v-if="!showSelectRegionPopup" ref="agriExecutePopupRef" />

    <start-interact-popup ref="startInteractPopupRef" />
</template>

<script setup>
import { ref, computed, onActivated, onDeactivated, onMounted } from "vue";
import customHeader from "@/components/customHeader.vue";
import { useStore } from "vuex";
import wx from "weixin-js-sdk";
import weatherInfo from "@/components/weatherInfo.vue";
import { useRouter, useRoute } from "vue-router";
import selectRegionPopup from "@/components/popup/selectRegionPopup.vue";
import ArchivesFarmTimeLine from "@/components/pageComponents/ArchivesFarmTimeLine.vue";
import agriExecutePopup from "@/components/popup/agriExecutePopup.vue";
import startInteractPopup from "@/components/popup/startInteractPopup.vue";
import gardenList from "@/components/gardenList.vue";

const startInteractPopupRef = ref(null);

const agriExecutePopupRef = ref(null);

// 品种选择（作物档案内）- 根据主体ID动态获取分区列表
const varietyTabs = ref([]);
const activeVariety = ref(0);

const getVarietyTabs = async (isShowPopup = true) => {
    if (!gardenId.value) {
        return;
    }
    try {
        const res = await VE_API.basic_farm.fetchProblemZoneList({
            subjectId: gardenId.value,
        });
        varietyTabs.value = res.data?.regionList || []
        if (varietyTabs.value.length > 0) {
            handleVarietyClick(varietyTabs.value[activeVariety.value || 0], activeVariety.value || 0)
            if (isShowPopup && !showSelectRegionPopup.value && agriExecutePopupRef.value) {
                agriExecutePopupRef.value.showPopup(varietyTabs.value[activeVariety.value || 0].farmId);
            }
        }
    } catch (error) {
        console.error("获取主体分区列表失败:", error);
    }
};

const farmIdData = ref(null);
const regionData = ref(null);
const titlePopup = ref("");
const currentVariety = ref({});
const handleVarietyClick = (tab, index) => {
    activeVariety.value = index;
    if(tab.regionId){
        farmIdData.value = tab.farmId;
        regionData.value = tab.regionId;
    }
    currentVariety.value = tab;
    if (tab.lastViewTime == null && tab.regionId) {
        titlePopup.value = `勾选 ${tab.regionName} 区域`;
        showSelectRegionPopup.value = true;
        VE_API.basic_farm.updateLastViewTime({
            regionId: tab.regionId,
        }).then(() => {
            getVarietyTabs(false);
        });
    }
};

const date = ref(new Date());
const disabledYearDate = (time) => {
    const year = time.getFullYear();
    const currentYear = new Date().getFullYear();
    return year !== currentYear && year !== currentYear - 1;
};

const showSelectRegionPopup = ref(false);

const handleAddVariety = () => {
    router.push(`/draw_area?subjectId=${gardenId.value}&type=viewOnly`);
};

const handleSkipSelectRegion = () => {
    showSelectRegionPopup.value = false;
};

const handleGoSelectRegion = () => {
    showSelectRegionPopup.value = false;
    router.push({
        path: "/draw_area",
        query: {
            subjectId: gardenId.value,
            varietyId: currentVariety.value.typeId
        },
    });
};

const defaultGardenId = ref(null);
const selectedGardenId = ref(null);
const gardenListRef = ref(null);
const activeGardenTab = ref('current');
const changeGardenTab = (tab) => {
    activeGardenTab.value = tab;
};

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

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

const isHeaderShow = ref(false);
const weatherInfoRef = ref(null);
onActivated(() => {
    sessionStorage.removeItem('interactionListScrollTop');
    // 用来接收我的农场跳转过来的农场详情逻辑
    if (route.query.isHeaderShow) {
        isHeaderShow.value = true;
        defaultGardenId.value = route.query.farmId;
    }
    const savedFarmId = localStorage.getItem("selectedFarmId");
    selectedGardenId.value = savedFarmId ? Number(savedFarmId) : null;
    gardenListRef.value?.refreshFarmList?.();
});

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

const userInfo = localStorage.getItem("localUserInfo");
const userInfoObj = userInfo ? JSON.parse(userInfo) : {};
const handleLockClick = () => {
    if (gardenId.value) {
        router.push("/interaction?subjectId=" + localStorage.getItem("selectedFarmId"));
        return;
    }
    if (userInfoObj?.tel) {
        router.push(`/create_farm?from=growth_report&isReload=true`);
        return;
    }
    wx.miniProgram.navigateTo({
        url: '/pages/subPages/phone_auth/index',
    });
}


// 组件卸载时停止语音播放
onDeactivated(() => {
    regionData.value = null;
});

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

// 点击遮罩时收起天气
const handleMaskClick = () => {
    if (weatherInfoRef.value && weatherInfoRef.value.toggleExpand) {
        weatherInfoRef.value.toggleExpand();
    }
};

const gardenId = ref(store.state.home.gardenId);

const farmsCategoryList = ref([]);
const activeFarmsCategory = ref(null);
const getListFarmsBySubjectId = async () => {
    const res = await VE_API.monitor.listFarmsBySubjectId({
        subjectId: gardenId.value,
    });
    farmsCategoryList.value = res.data || [];
    if(farmsCategoryList.value.length > 0){
        activeFarmsCategory.value = res.data[0].speciesId;
    }
}

const handleFarmsCategoryClick = (tab, index) => {
    activeFarmsCategory.value = tab.speciesId;
}

const changeGarden = ({ id }) => {
    gardenId.value = id;
    if(sessionStorage.getItem('activeVariety')){
        activeVariety.value = Number(sessionStorage.getItem('activeVariety'));
        sessionStorage.removeItem('activeVariety');
    } else {
        activeVariety.value = 0;
    }
    // 更新 store 中的状态
    store.commit("home/SET_GARDEN_ID", id);
    getVarietyTabs();
    getListFarmsBySubjectId(); 

    startInteractPopupRef.value.getPhenologyInitOrConfirmStatus();
};

const handleCardClick = () => {
    sessionStorage.setItem('activeVariety', activeVariety.value);
}

</script>

<style scoped lang="scss">
.monitor-index {
    width: 100%;
    height: 100%;
    // padding: 13px 10px;
    box-sizing: border-box;
    background: linear-gradient(180deg, #2199F8 6%, #F5F5F5 19%, #F5F5F5 73%, #F5F5F5 100%);
    .weather-mask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.52);
        z-index: 11;
    }

    .lock-img {
        position: fixed;
        z-index: 10;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -20%);
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        gap: 16px;

        .lock-img-item {
            width: 57px;
        }

        .lock-text {
            font-size: 14px;
            color: #000;
            padding: 5px 64px;
            line-height: 21px;
            background: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, #FFFFFF 50%, rgba(255, 255, 255, 0) 100%);
        }

        .lock-btn {
            width: 140px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            background: linear-gradient(180deg, #76C3FF 0%, #2199F8 100%);
            border-radius: 25px;
            color: #fff;
            font-size: 16px;
        }
    }

    .example-img {
        width: 100%;
        height: 100%;
        object-fit: inherit;
    }

    .weather-info {
        width: calc(100% - 20px);
        position: absolute;
        top: 10px;
        left: 10px;
        z-index: 12;
    }

    .archives-time-line {
        position: relative;
        padding: 150px 12px 12px 12px;
        height: calc(100% - 158px);
        display: flex;
        flex-direction: column;
        min-height: 0;
        &.no-top {
            padding: 96px 12px 12px 12px;
        }

        .archives-time-line-header {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .line-title {
                position: relative;
                padding-left: 14px;
                font-size: 16px;

                &::before {
                    content: "";
                    position: absolute;
                    left: 5px;
                    top: 50%;
                    transform: translateY(-50%);
                    width: 4px;
                    height: 15px;
                    background: #2199f8;
                    border-radius: 20px;
                }
            }

            .header-right {
                display: flex;
                align-items: center;
                gap: 12px;

                .add-variety-btn {
                    display: flex;
                    align-items: center;
                    gap: 3px;
                    padding: 4px 10px;
                    border: 1px solid #2199F8;
                    border-radius: 2px;
                    color: #2199F8;
                    background: rgba(33, 153, 248, 0.1);
                }
            }
        }

        .category-tabs{
            margin: 10px 0 6px 0;
        }

        .tabs-list {
            flex-shrink: 0;
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 8px;

            .item-tab {
                box-sizing: border-box;
                padding: 4px;
                border-radius: 2px;
                color: #767676;
                background: #fff;
                display: flex;
                align-items: center;
                justify-content: center;
                text-align: center;
                word-break: break-word;
                overflow-wrap: anywhere;
            }

            .item-tab--active {
                background: #2199F8;
                color: #ffffff;
            }

            &.variety-tabs{
                padding: 5px 6px;
                background: #ffffff;
                .item-tab{
                    background: #F6F6F6;
                }
                .item-tab--active {
                    background: rgba(33, 153, 248, 0.1);
                    color: #2199F8;
                }
            }        
        }

        .archives-time-line-content {
            margin-top: 10px;
            flex: 1;
            min-height: 0;
            background: #fff;
            border-radius: 8px;
            padding: 10px;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;

            .time-line {
                flex: 1;
                min-height: 0;
            }
        }
    }
}
</style>
