<template>
    <div class="base-container no-events">
        <fnHeader showDate :autoGo="true" hideSwitch></fnHeader>
        <div class="content">
            <div class="warning-l left">
                <div class="warning-top">
                    <div class="top-l yes-events">
                        <div>
                            <el-cascader
                                style="width: 184px"
                                :show-all-levels="false"
                                v-model="areaVal"
                                :props="props1"
                                :options="areaListOptions"
                                @change="toggleArea"
                                popper-class="area-cascader"
                            />
                        </div>
                    </div>
                    <div class="top-r yes-events">
                        <div class="data-box" @click="toggleBox('面积')" :class="{ active: activeBoxName === '面积' }">
                            <div class="data-value">
                                <span>{{ areaVal.includes("3186") ? 31.2 : 419.89 }}</span
                                >万亩
                            </div>
                            <div class="data-name">种植面积</div>
                        </div>
                        <div
                            class="data-box"
                            v-if="areaVal.includes('3186')"
                            @click="toggleBox('从化荔枝')"
                            :class="{ active: activeBoxName === '从化荔枝' }"
                        >
                            <div class="data-value"><span>11.9</span>万亩</div>
                            <div class="data-name">疑似失管面积</div>
                        </div>
                        <div class="data-box" @click="toggleBox('产量')" :class="{ active: activeBoxName === '产量' }">
                            <div class="data-value">
                                <span>{{ areaVal.includes("3186") ? 10.4 : 192.12 }}</span
                                >万吨
                            </div>
                            <div class="data-name">预估产量</div>
                        </div>
                    </div>
                </div>
                <div class="warning-alarm yes-events" v-show="activeBaseTab === '预警分布'">
                    <alarm-list></alarm-list>
                </div>
                <div class="time-wrap yes-events">
                    <time-line></time-line>
                </div>
            </div>
            <div class="action-legend" v-if="activeBaseTab !== '农场分布' && activeBaseTab !== '农服管理'">
                <el-tree
                    ref="treeRef"
                    class="yes-events"
                    style="max-width: 250px"
                    :data="treeActionData"
                    show-checkbox
                    node-key="id"
                    :default-expanded-keys="defaultExpandedKeys"
                    :default-checked-keys="defaultCheckedKeys"
                    :props="defaultProps"
                    @check="getTreeChecks"
                >
                    <template #default="{ node, data }">
                        <div class="custom-tree-node">
                            <span>{{ node.label }}</span>
                            <div v-if="node.level === 1" class="level-legend">
                                <span class="legend-dot" :style="{ backgroundColor: data.color }"></span>
                                <span class="legend-text" :style="{ color: data.color }">图例</span>
                            </div>
                        </div>
                    </template>
                </el-tree>
            </div>
            <div v-if="!showDetail" class="warning-r right chart-wrap yes-events">
                <chart-list :activeBaseTab="activeBaseTab"></chart-list>
                <!-- <farmInfoGroup></farmInfoGroup> -->
            </div>
            <div v-else class="warning-r right yes-events">
                <farmInfoGroup></farmInfoGroup>
            </div>
            <!-- 地图图例 -->
            <map-legend :type="activeBaseTab"></map-legend>
            <!-- 地图搜索 -->
            <div class="warning-search yes-events">
                <el-select
                    v-model="locationVal"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="搜索地区"
                    :remote-method="remoteMethod"
                    :loading="loading"
                    @change="handleSearchRes"
                    class="v-select"
                    popper-class="focus-farm-select"
                    style="width: 375px"
                >
                    <template #prefix>
                        <el-icon class="el-input__icon"><search /></el-icon>
                    </template>
                    <el-option
                        v-for="(item, index) in locationOptions.list"
                        :key="index"
                        :label="item.title"
                        :value="item.point"
                    >
                        <span>{{ item.title }}</span>
                        <span class="sub-title">{{ item.province }}{{ item.city }}{{ item.district }}</span>
                    </el-option>
                </el-select>
            </div>
            <div class="base-tabs yes-events">
                <div
                    v-for="item in baseTabs"
                    :key="item"
                    class="tab-item"
                    :class="{ active: item === activeBaseTab }"
                    @click="handleTabClick(item)"
                >
                    {{ item }}
                </div>
            </div>
        </div>
    </div>
    <div ref="mapRef" class="bottom-map"></div>
    <div id="popup" class="ol-popup-warning">
        <div class="warning-info-title">
            <div class="icon">
                <img src="@/assets/images/common/chart-icon.png" />
            </div>
            <div id="popup-title"></div>
            <div class="close" @click="destroyPopup">
                <img src="@/assets/images/warningHome/close-btn.png" />
            </div>
        </div>
        <div id="popup-content" class="info-content"></div>
    </div>
    <track-dialog></track-dialog>
</template>

<script setup>
import "./map/mockFarmLayer";
import StaticMapLayers from "@/components/static_map_change/Layers.js";
import StaticMapPointLayers from "@/components/static_map_change/pointLayer.js";
import { onMounted, onUnmounted, ref, reactive, nextTick } from "vue";
import fnHeader from "@/components/fnHeader.vue";
import WarningMap from "./warningMap";
import AlarmLayer from "./map/alarmLayer";
import DistributionLayer from "./map/distributionLayer";
import trackDialog from "./components/trackDialog.vue";
import alarmList from "./components/alarmList.vue";
import timeLine from "./components/timeLine.vue";
import eventBus from "@/api/eventBus";
import { areaListOptions } from "./area";
import { useStore } from "vuex";
import farmInfoGroup from "./components/farmInfoGroup.vue";
import mapLegend from "./components/mapLegend.vue";
import chartList from "./components/chart_components/chartList.vue";

let store = useStore();

let warningMap = new WarningMap();
let alarmLayer = null;
let staticMapLayers = null;
let staticMapPointLayers = null;
let distributionLayer = null;
const areaVal = ref(["3"]);
const mapRef = ref(null);
const showDetail = ref(false);
const treeRef = ref(null);
const defaultProps = {
    children: "items",
    label: "name",
};

import lz from "@/assets/images/map/type/荔枝.png";
import ly from "@/assets/images/map/type/龙眼.png";
import sd from "@/assets/images/map/type/水稻.png";
import xm from "@/assets/images/map/type/小麦.png";
import bc from "@/assets/images/map/type/小麦.png";
import lb from "@/assets/images/map/type/小麦.png";
// 冷链冷库、加工厂图标（与图例保持一致）
import coldChainIcon from "@/assets/images/common/legend-icon-1.png";
import factoryIcon from "@/assets/images/common/legend-icon-2.png";

const originTreeData = [
    {
        id: 1,
        label: "果类",
        color: "#51B2FF",
        fillColor: "rgba(5, 49, 84, 0.5)",
        geom: "MULTIPOLYGON (((113.58668302396221 23.244659822289524, 113.32095411231998 23.24298858095617, 112.99338890476295 23.002328435946534, 113.13878785387456 22.604570799124076, 113.59503930394511 22.86862839611681, 113.58668302396221 23.244659822289524)))",
        children: [
            {
                id: 4,
                label: "荔枝",
                color: "#2199F8",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E8%8D%94%E6%9E%9D.png",
                imgName: lz,
                wktArr: [
                    "POINT(113.33722309500006 23.204074978290652)",
                    "POINT(113.53593237057355 23.188789823486065)",
                    "POINT(113.36970447853234 23.064596505297875)",
                ],
            },
            {
                id: 55,
                label: "龙眼",
                color: "#2199F8",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E7%99%BD%E7%B3%96.png",
                imgName: ly,
                wktArr: [
                    "POINT(113.29900983080294 22.949956545068478)",
                    "POINT(113.10412186488536 22.800924630297875)",
                    "POINT(113.32384842738536 22.776086033715462)",
                    "POINT(113.22640444442656 22.90983245840535)",
                ],
            },
        ],
    },
    {
        id: 2,
        label: "粮食",
        color: "#FF8E1C",
        fillColor: "rgba(83, 46, 8, 0.5)",
        geom: "MULTIPOLYGON (((112.42256410334443 23.14863707066071, 112.09584019992684 22.842930537988664, 112.25060416300033 22.62511471413565, 112.80278650958275 22.749307864685775, 112.75119857777094 23.13144100957107, 112.42256410334443 23.14863707066071)))",
        children: [
            {
                id: 5,
                label: "水稻",
                color: "#FAA53D",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E6%8C%82%E7%BB%BF.png",
                imgName: sd,
                wktArr: [
                    "POINT(112.70843577567298 22.969169477864167)",
                    "POINT(112.23636397199755 22.85839626464389)",
                    "POINT(112.35889247053002 23.008153324438585)",
                    "POINT(112.47894566011911 22.9017143340381)",
                ],
            },
            {
                id: 6,
                label: "小麦",
                color: "#FAA53D",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E6%97%A0%E6%A0%B8.png",
                imgName: xm,
                wktArr: [
                    "POINT(112.36777193304151 22.73892833157863)",
                    "POINT(112.26684873669083 22.71150357559281)",
                    "POINT(112.65408646638161 22.84862740364581)",
                ],
            },
        ],
    },
    {
        id: 3,
        label: "蔬菜",
        color: "#25BC07",
        fillColor: "rgba(0, 69, 4, 0.5)",
        children: [
            {
                id: 7,
                label: "白菜",
                color: "#7ABB00",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E7%99%BD%E8%8F%9C.png",
                imgName: bc,
                wktArr: [
                    "POINT(110.34100329503417 21.516399336978793)",
                    "POINT(113.89499662443995 22.653799122199416)",
                    "POINT(113.9329988323152 22.653600638732314)",
                    "POINT(113.94400024786592 22.614900553599)",
                ],
            },
            {
                id: 8,
                label: "萝卜",
                color: "#7ABB00",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E8%90%9D%E8%8F%9C.png",
                imgName: lb,
                wktArr: [
                    "POINT(110.34100329503417 21.516399336978793)",
                    "POINT(113.89499662443995 22.653799122199416)",
                    "POINT(113.9329988323152 22.653600638732314)",
                    "POINT(113.94400024786592 22.614900553599)",
                ],
            },
        ],
    },
];

const phenologyData = [
    {
        id: 1,
        label: "果类",
        color: "#51B2FF",
        fillColor: "rgba(5, 49, 84, 0.5)",
        geom: "MULTIPOLYGON (((113.58668302396221 23.244659822289524, 113.32095411231998 23.24298858095617, 112.99338890476295 23.002328435946534, 113.13878785387456 22.604570799124076, 113.59503930394511 22.86862839611681, 113.58668302396221 23.244659822289524)))",
        children: [
            {
                id: 4,
                label: "荔枝",
                color: "#2199F8",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E8%8D%94%E6%9E%9D.png",
                imgName: lz,
                children: [
                    {
                        id: 13,
                        label: "秋梢期",
                        color: "#58B5FF",
                        imgName: lz,
                        wktArr: [
                            "POINT(113.33722309500006 23.204074978290652)",
                            "POINT(113.53593237057355 23.188789823486065)",
                        ],
                    },
                    {
                        id: 14,
                        label: "膨果期",
                        color: "#1688E3",
                        imgName: lz,
                        wktArr: [
                            "POINT(113.32095411231998 23.24298858095617)",
                        ],
                    },
                    {
                        id: 15,
                        label: "成熟期",
                        color: "#3D8CCB",
                        imgName: lz,
                        wktArr: [
                            "POINT(113.36970447853234 23.064596505297875)",
                        ],
                    },
                ],
            },
            {
                id: 55,
                label: "龙眼",
                color: "#2199F8",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E7%99%BD%E7%B3%96.png",
                imgName: ly,
                children: [
                    {
                        id: 16,
                        label: "秋梢期",
                        color: "#5986AA",
                        imgName: ly,
                        wktArr: [
                            "POINT(113.29900983080294 22.949956545068478)",
                            "POINT(113.10412186488536 22.800924630297875)",
                        ],
                    },
                    {
                        id: 17,
                        label: "膨果期",
                        color: "#79ABD3",
                        imgName: ly,
                        wktArr: [
                            "POINT(113.32384842738536 22.776086033715462)",
                            "POINT(113.22640444442656 22.90983245840535)",
                        ],
                    },
                ],
            },
        ],
    },
    {
        id: 2,
        label: "粮食",
        color: "#FF8E1C",
        fillColor: "rgba(83, 46, 8, 0.5)",
        geom: "MULTIPOLYGON (((112.42256410334443 23.14863707066071, 112.09584019992684 22.842930537988664, 112.25060416300033 22.62511471413565, 112.80278650958275 22.749307864685775, 112.75119857777094 23.13144100957107, 112.42256410334443 23.14863707066071)))",
        children: [
            {
                id: 5,
                label: "水稻",
                color: "#FAA53D",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E6%8C%82%E7%BB%BF.png",
                imgName: sd,
                children: [
                    {
                        id: 10,
                        label: "拔节期",
                        color: "#985400",
                        imgName: sd,
                        wktArr: [
                            "POINT(112.36777193304151 22.73892833157863)",
                        ],
                    },
                    {
                        id: 11,
                        label: "孕穗期",
                        color: "#512D00",
                        imgName: sd,
                        wktArr: [
                            "POINT(112.26684873669083 22.71150357559281)",
                        ],
                    },
                    {
                        id: 12,
                        label: "抽穗期",
                        color: "#DD871D",
                        imgName: sd,
                        wktArr: [
                            "POINT(112.65408646638161 22.84862740364581)",
                        ],
                    },
                ],
            },
            {
                id: 6,
                label: "小麦",
                color: "#FAA53D",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E6%97%A0%E6%A0%B8.png",
                imgName: xm,
                children: [
                    {
                        id: 18,
                        label: "拔节期",
                        color: "#FAA53D",
                        imgName: xm,
                        wktArr: [
                            "POINT(112.36777193304151 22.73892833157863)",
                        ],
                    },
                ],
            },
        ],
    },
    {
        id: 3,
        label: "蔬菜",
        color: "#25BC07",
        fillColor: "rgba(0, 69, 4, 0.5)",
        children: [
            {
                id: 7,
                label: "白菜",
                color: "#7ABB00",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E7%99%BD%E8%8F%9C.png",
                imgName: bc,
                children: [
                    {
                        id: 19,
                        label: "拔节期",
                        color: "#7ABB00",
                        imgName: bc,
                        wktArr: [
                            "POINT(110.34100329503417 21.516399336978793)",
                            "POINT(113.89499662443995 22.653799122199416)",
                            "POINT(113.9329988323152 22.653600638732314)",
                            "POINT(113.94400024786592 22.614900553599)",
                        ],
                    },
                ],
            },
            {
                id: 8,
                label: "萝卜",
                color: "#7ABB00",
                imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E8%90%9D%E8%8F%9C.png",
                imgName: lb,
                children: [
                    {
                        id: 20,
                        label: "拔节期",
                        color: "#7ABB00",
                        imgName: lb,
                        wktArr: [
                            "POINT(110.34100329503417 21.516399336978793)",
                            "POINT(113.89499662443995 22.653799122199416)",
                            "POINT(113.9329988323152 22.653600638732314)",
                            "POINT(113.94400024786592 22.614900553599)",
                        ],
                    },
                ],
            },
        ],
    },
];

const treeActionData = ref(originTreeData);

// 物候期分布下，当前激活的“二级”节点（只允许一个）
const activePhenologySecondId = ref(null);

// 树的默认展开与默认选中（展开/选中第一个“果类”及其子节点）
const defaultExpandedKeys = ref();
const defaultCheckedKeys = ref();

// 顶部基础 tabs
const baseTabs = ["作物分布", "物候期分布", "预警分布", "农场分布", "农服管理"];
const activeBaseTab = ref("作物分布");

const legendImg = ref("");
const warningLayers = ref({});

onMounted(async () => {
    warningMap.initMap(store.getters.userinfo.location, mapRef.value);
    alarmLayer = new AlarmLayer(warningMap.kmap);
    staticMapLayers = new StaticMapLayers(warningMap.kmap);
    staticMapPointLayers = new StaticMapPointLayers(warningMap.kmap);
    distributionLayer = new DistributionLayer(warningMap.kmap);
    await getSpeciesListData();
    // 作物分布默认选中
    await handleDistributionTreeDefault()
    await handleDistributionLayer();

    eventBus.emit("warningMap:init", warningMap.kmap);

    // 图例数据
    eventBus.on("alarmList:warningLayers", (data) => {
        warningLayers.value = data;
    });

    // 预警分布图层联动：仅在“预警分布”tab 显示时，才在地图上显示对应图层
    eventBus.on("alarmList:changeMapLayer", ({ name, legendUrl }) => {
        // 47 行：只在 activeBaseTab === '预警分布' 时显示预警列表
        // 这里保持一致：只有在该 tab 下才显示地图图层，否则直接隐藏
        if (activeBaseTab.value !== "预警分布") {
            staticMapLayers && staticMapLayers.hideAll();
            legendImg.value = "";
            return;
        }

        if (legendUrl) {
            legendImg.value = legendUrl;
            staticMapLayers && staticMapLayers.showSingle(name, true);
        } else {
            legendImg.value = warningLayers.value[`${name}图例`];
            let text = "";
            if (name === "日间温度") {
                text = "从化地块日温";
            } else if (name === "夜间温度") {
                text = "从化地块夜温";
            } else if (name === "土壤水分") {
                text = "从化地块水分";
            }
            if (text !== "") {
                staticMapLayers && staticMapLayers.showSingle(text, true);
            } else {
                staticMapLayers && staticMapLayers.hideAll();
            }
        }
    });

    // ai与地图交互
    eventBus.off("chat:showMapLayer", handleMapLayer);
    eventBus.on("chat:showMapLayer", handleMapLayer);
});

sessionStorage.removeItem("farmId");

onUnmounted(() => {
    eventBus.off("alarmList:changeMapLayer");
});

// 作物分布默认选中并展开第一个节点，在地图上显示对应分布图层
const handleDistributionLayer = async () => {
    // 默认选中并展开第一个“果类”节点，在地图上显示对应分布图层
    const firstCategory = treeActionData.value[0];
    if (firstCategory) {
        await getDistributionData(firstCategory.id);
    }
};

// 作物分布树形结构默认展开与默认选中
const handleDistributionTreeDefault = () => {
    defaultExpandedKeys.value = [treeActionData.value[0]?.id];
    defaultCheckedKeys.value = [
        treeActionData.value[0]?.id,
        ...(treeActionData.value[0]?.children?.map((c) => c.id) || []),
    ];
};

// 物候期分布默认选中并展开第一个节点，在地图上显示对应分布图层
const handlePhenologyLayer = async () => {
    const firstCategory = treeActionData.value[0].children[0];
    if (firstCategory) {
        // 递归查找最后一层的节点（没有子节点的叶子节点）
        const getLastLevelNodes = (node) => {
            const lastLevelNodes = [];
            if ((!node.items || node.items.length === 0) && (!node.children || node.children.length === 0)) {
                lastLevelNodes.push(node);
            } else {
                const children = node.items || node.children || [];
                children.forEach((child) => {
                    lastLevelNodes.push(...getLastLevelNodes(child));
                });
            }
            return lastLevelNodes;
        };
        
        const lastLevelNodes = getLastLevelNodes(firstCategory);
        const lastLevelIds = lastLevelNodes.map((n) => n.id);
        
        // 并发请求所有数据
        const promises = lastLevelIds.map((id) => getDistributionData(id));
        const results = await Promise.all(promises);
        const finalMapData = results.flat();
        
        distributionLayer.initData(finalMapData);
    }
};

// 物候期分布树形结构默认展开与默认选中
const handlePhenologyTreeDefault = () => {
    defaultCheckedKeys.value = [
        treeActionData.value[0]?.children[0]?.id,
        ...(treeActionData.value[0]?.children[0]?.children?.map((c) => c.id) || []),
    ];
    defaultExpandedKeys.value = [treeActionData.value[0]?.children[0]?.id];
};

// 预警分布默认选中并展开第一个节点，在地图上显示对应分布图层
const handleAlarmLayer = async () => {
    const firstCategory = treeActionData.value[0].children[0];
    if (firstCategory) {
        // 递归查找最后一层的节点（没有子节点的叶子节点）
        const getLastLevelNodes = (node) => {
            const lastLevelNodes = [];
            if ((!node.items || node.items.length === 0) && (!node.children || node.children.length === 0)) {
                lastLevelNodes.push(node);
            } else {
                const children = node.items || node.children || [];
                children.forEach((child) => {
                    lastLevelNodes.push(...getLastLevelNodes(child));
                });
            }
            return lastLevelNodes;
        };
        
        const lastLevelNodes = getLastLevelNodes(firstCategory);
        const lastLevelIds = lastLevelNodes.map((n) => n.id);
        
        // 并发请求所有数据
        const promises = lastLevelIds.map((id) => getDistributionData(id));
        const results = await Promise.all(promises);
        const finalMapData = results.flat();
        
        distributionLayer.initData(finalMapData);
    }
};

// 预警分布树形结构默认展开与默认选中
const handleAlarmTreeDefault = () => {
    defaultCheckedKeys.value = [
        treeActionData.value[0]?.children[0]?.id
    ];
    defaultExpandedKeys.value = [treeActionData.value[0]?.id];
};

// ai与地图交互
const hideChatMapLayer = ref(true);
const handleMapLayer = ({ mapName, isHome }) => {
    if (!isHome) {
        hideChatMapLayer.value = false;
    }
    staticMapPointLayers.hidePoint();
    staticMapLayers.hideAll();

    // 重置时间轴
    // eventBus.emit("map_click_alarm")
    if (mapName === "植保机") {
        staticMapLayers.show("分散种植", true);
        staticMapPointLayers.showPoint();
    } else if (mapName) {
        // staticMapLayers.show("作物种类")
        if (isHome) {
            staticMapLayers.show(mapName, true);
        } else {
            staticMapLayers.showSingle(mapName, true);
        }
    }
};

const toggleChatMapLayer = () => {
    hideChatMapLayer.value = true;
    eventBus.emit("chat:hideMapLayer");
    staticMapLayers.hideAll();
};

const destroyPopup = () => {
    eventBus.emit("map:destroyPopup");
};

const handleTabClick = (item) => {
    activeBaseTab.value = item;

    // 切换 Tab 时，先清空农场分布图层上的旧数据
    if (distributionLayer) {
        distributionLayer.clear();
    }
    // 所有操作前，先清空图层和选中项
    legendImg.value = "";
    staticMapLayers && staticMapLayers.hideAll();
    // 通知预警列表组件清空默认选中项
    eventBus.emit("warningHome:clearAlarm");
    treeActionData.value = originTreeData;
    // 使用 nextTick 确保树组件数据更新后再设置选中状态
    nextTick(() => {
        if (treeRef.value) {
            // 先清空所有选中项
            treeRef.value.setCheckedKeys([]);
            // 再设置新的选中项
            treeRef.value.setCheckedKeys(defaultCheckedKeys.value);
        }
    });

    switch (item) {
        case "作物分布":
            handleDistributionTreeDefault();
            handleDistributionLayer();
            break;
        case "物候期分布":
            treeActionData.value = phenologyData;
            handlePhenologyTreeDefault()
            handlePhenologyLayer();
            break;
        case "预警分布":
            handleAlarmTreeDefault()
            handleAlarmLayer();
            // 通知预警列表组件默认选中第一个（因子）项
            eventBus.emit("warningHome:activeFirstAlarmFactor");
            break;
        case "农场分布":
            const cropData = [
                {
                    id: 4,
                    label: "荔枝-物候期",
                    color: "#2199F8",
                    farmName: "荔博园",
                    imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E8%8D%94%E6%9E%9D.png",
                    imgName: lz,
                    wktArr: [
                        "POINT(113.33722309500006 23.204074978290652)",
                        "POINT(113.53593237057355 23.188789823486065)",
                        "POINT(113.36970447853234 23.064596505297875)",
                    ],
                },
                {
                    id: 55,
                    label: "荔枝-秋梢期",
                    color: "#FF8E1C",
                    farmName: "荔博园",
                    imgUrl: "https://birdseye-img.sysuimars.com/temp/pz/%E7%99%BD%E7%B3%96.png",
                    imgName: lz,
                    wktArr: [
                        "POINT(113.29900983080294 22.949956545068478)",
                        "POINT(113.22640444442656 22.90983245840535)",
                    ],
                },
            ];

            // 设施图层测试数据
            const facilityData = [
                {
                    id: 201,
                    label: "冷链冷库",
                    imgName: coldChainIcon,
                    wktArr: ["POINT(113.35 23.10)"],
                },
                {
                    id: 202,
                    label: "加工厂",
                    imgName: factoryIcon,
                    wktArr: ["POINT(113.25 23.02)"],
                },
            ];

            distributionLayer.initData(cropData);
            distributionLayer.initFacilityData(facilityData);
            break;
        default:
            break;
    }
};

const getSpeciesListData = async () => {
    const res = await VE_API.species.speciesList();
    treeActionData.value = res.data;
};

const getDistributionData = async (speciesId) => {
    const {data} = await VE_API.agri_land_crop.queryDistribution({
        year: 2025,
        quarter: 1,
        speciesId
    });
    return data;
};
const props1 = {
    checkStrictly: true,
};

const toggleArea = (v) => {
    activeBoxName.value = null;
    const val = v[v.length - 1];
    if (val === "3" || val === "3186") {
        eventBus.emit("warningHome:toggleArea", val);
    }
};

const activeBoxName = ref(null);
const toggleBox = (name) => {
    activeBoxName.value = name;
    legendImg.value = warningLayers.value[`${name}图例`];
    eventBus.emit("warningHome:toggleMapLayer", name);
};

// 搜索
const locationVal = ref("");
const loading = ref(false);
const MAP_KEY = "CZLBZ-LJICQ-R4A5J-BN62X-YXCRJ-GNBUT";

const handleSearchRes = (v) => {
    warningMap.setMapCenter(v);
    // onRest();
};

const locationOptions = reactive({
    list: [],
});
const remoteMethod = async (keyword) => {
    if (keyword) {
        locationOptions.list = [];
        loading.value = true;
        const params = {
            key: MAP_KEY,
            keyword,
            //   location: location.value,
            location: "22.574540836684672,113.1093017627431",
        };
        await VE_API.old_mini_map.getCtiyList({ word: keyword }).then(({ data }) => {
            if (data && data.length) {
                data.forEach((item) => {
                    item.point = item.location.lat + "," + item.location.lng;
                    locationOptions.list.push(item);
                });
            }
        });
        VE_API.old_mini_map.search(params).then(({ data }) => {
            loading.value = false;
            data.forEach((item) => {
                item.point = item.location.lat + "," + item.location.lng;
                locationOptions.list.push(item);
            });
        });
    } else {
        locationOptions.list = [];
    }
};

// 根据节点 id 在当前树数据中计算其层级（1/2/3）及所属的二级节点 id
const getNodeLevelInfo = (id) => {
    const roots = treeActionData.value || [];
    for (const root of roots) {
        if (root.id === id) {
            return { level: 1, secondId: null };
        }
        if (root.children) {
            for (const second of root.children) {
                if (second.id === id) {
                    return { level: 2, secondId: second.id };
                }
                if (second.children) {
                    for (const third of second.children) {
                        if (third.id === id) {
                            return { level: 3, secondId: second.id };
                        }
                    }
                }
            }
        }
    }
    return { level: 0, secondId: null };
};

const getTreeChecks = async (nodeData, data) => {
    const { checkedNodes } = data;
    let finalCheckedNodes = checkedNodes;

    // 物候期分布：限制"二级只能选一个，三级不限个数"
    if ((activeBaseTab.value === "物候期分布" || activeBaseTab.value === "预警分布") && treeRef.value) {
        const tree = treeRef.value;
        const { level, secondId } = getNodeLevelInfo(nodeData.id);

        if (level === 2 || level === 3) {
            const currentSecondId = secondId;

            // 判断当前这个二级分支下，是否还有被选中的节点（包含二级自己或其子级）
            const hasAnyCheckedInCurrentSecond = checkedNodes.some((n) => {
                const info = getNodeLevelInfo(n.id);
                return info.secondId === currentSecondId || (info.level === 2 && n.id === currentSecondId);
            });

            if (hasAnyCheckedInCurrentSecond) {
                // 仍有节点被选中 → 保证只有当前这个二级分支被选中，其它分支全部取消
                activePhenologySecondId.value = currentSecondId;

                const roots = treeActionData.value || [];
                roots.forEach((root) => {
                    (root.children || []).forEach((second) => {
                        if (second.id !== currentSecondId) {
                            // 取消其它二级及其所有子级勾选
                            tree.setChecked(second.id, false, true);
                        } else {
                            // 保持当前二级选中，子级按用户选择
                            tree.setChecked(second.id, true, false);
                        }
                    });
                });
            } else {
                // 当前二级分支已经被全部取消勾选 → 清空激活记录，允许"全部不选"
                activePhenologySecondId.value = null;
            }
        }
        // 对树进行了 setChecked 操作后，重新从树组件拿一次最新的选中节点列表
        // 这里只需要最后一层（叶子节点 / 有 wktArr 的节点），不用父级节点
        const allCheckedNodes = treeRef.value.getCheckedNodes(false, true);
        finalCheckedNodes = allCheckedNodes.filter((n) => !n.children || n.children.length === 0 || n.wktArr);
    }

    // 任意 tab 下，最终都用当前选中的节点驱动地图渲染
    // 提取最后一级节点的 id 到数组（没有子节点的叶子节点）
    const lastLevelIds = finalCheckedNodes
        .filter((n) => (!n.items || n.items.length === 0) && (!n.children || n.children.length === 0))
        .map((n) => n.id);
    
    // 并发请求所有数据，等待所有 Promise 完成
    const promises = lastLevelIds.map((id) => {
        const node = finalCheckedNodes.find((n) => n.id === id);
        if (node) {
            return getDistributionData(node.id);
        }
        return Promise.resolve([]);
    });
    
    // 等待所有请求完成，并将结果扁平化
    const results = await Promise.all(promises);
    const finalMapData = results.flat();
    
    distributionLayer.initData(finalMapData);
};
</script>

<style lang="scss" scoped>
.base-container {
    width: 100%;
    height: 100vh;
    color: #fff;
    position: absolute;
    box-sizing: border-box;
    z-index: 1;

    ::v-deep {
        .focus-farm {
            top: 42px;
        }
    }

    .content {
        width: 100%;
        height: calc(100% - 74px - 48px);
        padding: 16px 20px 0 27px;
        display: flex;
        justify-content: space-between;
        box-sizing: border-box;
        position: relative;
        .left,
        .right {
            width: calc(376px + 54px);
            height: 100%;
            box-sizing: border-box;
            // display: flex;
        }
        .right {
            // width: 395px;
            width: 376px;
            overflow: auto;
            position: relative;
            .list {
                width: 100%;
                height: 100%;
            }
        }
        .chart-wrap {
            padding: 8px;
            background: #101010;
            border: 1px solid #444444;
        }
        .action-legend {
            flex: 1;
            padding: 0 13px;
            display: flex;
            justify-content: flex-end;
            align-items: baseline;
            ::v-deep {
                .el-tree {
                    background: #232323;
                    border: 1px solid #444444;
                    border-radius: 5px;
                    padding: 10px 0;
                    --el-tree-node-content-height: 34px;
                    --el-tree-node-hover-bg-color: rgba(255, 212, 137, 0.05);
                    --el-tree-text-color: #ffd489;
                    --el-tree-expand-icon-color: #ffd489;

                    .el-checkbox {
                        --el-checkbox-bg-color: transparent;
                        --el-checkbox-input-border: 1px solid #ffd489;
                        --el-checkbox-checked-input-border-color: #ffd489;
                        --el-checkbox-checked-bg-color: #ffd489;
                        --el-checkbox-checked-icon-color: #000;
                        --el-checkbox-input-border-color-hover: #ffd489;
                    }
                }
                .el-tree-node__content {
                    padding-right: 30px;
                }
            }

            .custom-tree-node {
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 8px;
            }
            .level-legend {
                display: flex;
                align-items: center;
                gap: 4px;
                padding: 0 5px;
                height: 17px;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 2px;
                font-size: 10px;
                .legend-dot {
                    width: 4px;
                    height: 4px;
                    border-radius: 50%;
                }
            }
        }
        .warning-r {
            .map-legend {
                position: absolute;
                bottom: -33px;
                left: -360px;
                width: 340px;
                img {
                    width: 340px;
                    opacity: 0.6;
                }
            }
            .chat-legend {
                bottom: -12px;
            }
        }
        .base-tabs {
            position: fixed;
            top: 32px;
            left: 390px;
            display: flex;
            align-items: center;
            .tab-item {
                padding: 7px 12px 9px;
                margin-right: 28px;
                text-align: center;
                font-family: "PangMenZhengDao";
                font-size: 16px;
                color: #fff;
                background: rgba(28, 36, 41, 0.8);
                border-radius: 4px;
                cursor: pointer;
                border: 1px solid transparent;
                &.active {
                    color: #ffdf9a;
                    background: rgba(19, 22, 16, 0.8);
                    border: 1px solid #ffd489;
                }
            }
        }
        .warning-search {
            position: fixed;
            right: 207px;
            top: 28px;
            display: flex;
            align-items: center;
            .focus-farm {
                padding-left: 15px;
            }
            ::v-deep {
                .el-select__wrapper {
                    background: #1d1d1d;
                    box-shadow: 0 0 0 1px rgba(255, 212, 137, 0.3) inset;
                    height: 50px;
                    line-height: 50px;
                    .el-select__caret,
                    .el-select__prefix {
                        color: rgba(255, 212, 137, 0.6);
                    }
                }
                .el-select__input {
                    color: rgba(255, 212, 137, 0.6);
                }
                .el-select__placeholder {
                    color: rgba(255, 212, 137, 0.6);
                    font-size: 20px;
                    font-family: "PangMenZhengDao";
                    // text-align: center;
                }
            }
        }
        .warning-top {
            display: flex;
            width: max-content;
            align-items: center;
            .top-l {
                display: flex;
                flex-direction: column;
                align-items: center;
                .type-box {
                    margin-top: 10px;
                    background: rgba(29, 29, 29, 0.54);
                    border: 1px solid rgba(255, 212, 137, 0.3);
                    border-radius: 2px;
                    text-align: center;
                    line-height: 48px;
                    height: 48px;
                    width: 184px;
                }

                ::v-deep {
                    .el-input__wrapper {
                        background: rgba(29, 29, 29, 0.54);
                        box-shadow: 0 0 0 1px rgba(255, 212, 137, 0.3) inset;
                        height: 50px;
                        line-height: 50px;
                        padding: 0 10px;
                        .el-input__inner {
                            color: #f7be5a;
                            font-size: 20px;
                            font-family: "PangMenZhengDao";
                            text-align: center;
                        }
                    }
                    .el-select__wrapper {
                        background: rgba(29, 29, 29, 0.54);
                        box-shadow: 0 0 0 1px rgba(255, 212, 137, 0.3) inset;
                        height: 50px;
                        line-height: 50px;
                        .el-select__caret {
                            color: #ffd489;
                        }
                    }
                    .el-select__placeholder {
                        color: #f7be5a;
                        font-size: 20px;
                        font-family: "PangMenZhengDao";
                        text-align: center;
                    }
                }
            }
            .top-r {
                display: flex;
                .data-box {
                    cursor: pointer;
                    margin-left: 20px;
                    width: 200px;
                    height: 104px;
                    background: url("@/assets/images/warningHome/box-bg.png") no-repeat center center / 100% 100%;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    &.active {
                        position: relative;
                        &::before {
                            content: "";
                            position: absolute;
                            bottom: -26px;
                            left: 0;
                            right: 0;
                            width: 35px;
                            height: 17px;
                            margin: 0 auto;
                            background: url("@/assets/images/warningHome/triangle.png") no-repeat center center / cover;
                        }
                    }
                    .data-value {
                        padding-top: 15px;
                        font-size: 20px;
                        color: rgba(255, 212, 137, 0.4);
                        font-family: "PangMenZhengDao";
                        span {
                            font-size: 38px;
                            color: #f7be5a;
                            padding-right: 2px;
                        }
                    }
                    .data-name {
                        color: #cecece;
                        font-size: 16px;
                    }
                }
            }
        }
        .warning-alarm {
            width: 88px;
            padding-top: 14px;
        }
        .time-wrap {
            position: absolute;
            bottom: -20px;
            left: 140px;
            width: 46vw;
            min-width: 700px;
            height: 71px;
        }
    }
}
.bottom-map {
    width: 100%;
    height: 100vh;
    position: absolute;
    z-index: 0;
}
</style>

<style lang="less">
.ol-scale-line {
    left: auto;
    right: 435px;
    bottom: 13px;
    .ol-scale-line-inner {
        max-width: 80px;
        width: 80px !important;
        color: #fff;
        border-color: #fff;
    }
}
.focus-farm-select {
    &.el-popper.is-light {
        background: #232323;
        border-color: rgba(255, 212, 137, 0.3);
        box-shadow: 0px 0px 12px rgba(255, 212, 137, 0.3);
        .el-select-dropdown__item {
            background: none;
            color: rgba(255, 212, 137, 0.6);
        }
        .el-select-dropdown__item.is-selected {
            background: rgba(255, 212, 137, 0.2);
            color: #ffd489;
        }
    }
    &.el-popper.is-light .el-popper__arrow:before {
        background: #232323;
        border-color: rgba(255, 212, 137, 0.3);
    }
}
.ol-popup-warning {
    position: relative;
    width: 295px;
    background: rgb(35, 35, 35, 0.86);
    color: #fff;
    font-size: 16px;
    border-radius: 4px;
    .warning-info-title {
        display: flex;
        padding: 6px 10px;
        background: rgba(255, 255, 255, 0.05);
        font-size: 18px;
        border-radius: 4px 4px 0 0;
        .icon {
            padding-right: 6px;
        }
        .close {
            position: absolute;
            right: 12px;
            top: 4px;
        }
    }
    .info-content {
        padding: 16px 20px 40px 20px;
        line-height: 26px;
        text-indent: 2em;
    }
}
.area-cascader {
    &.el-popper.is-light {
        background: #232323;
        border-color: rgba(255, 212, 137, 0.3);
        box-shadow: 0px 0px 12px rgba(255, 212, 137, 0.3);
        .el-cascader-menu {
            color: rgba(255, 212, 137, 0.6);
            border-color: rgba(255, 212, 137, 0.3);
        }
        .el-cascader-node.in-active-path,
        .el-cascader-node.is-active,
        .el-cascader-node.is-selectable.in-checked-path {
            color: #f7be5a;
            background: transparent;
        }
        .el-radio__input.is-checked .el-radio__inner {
            background: #f7be5a;
            border-color: #f7be5a;
        }
        .el-cascader-node:not(.is-disabled):hover,
        .el-cascader-node:not(.is-disabled):focus,
        .el-cascader-node:not(.is-disabled):hover {
            background: rgba(255, 212, 137, 0.2);
        }
    }
    .el-radio__inner {
        background-color: rgba(255, 212, 137, 0.3);
        border-color: rgba(255, 212, 137, 0.6);
    }
    &.el-popper.is-light .el-popper__arrow:before {
        background: #232323;
        border-color: rgba(255, 212, 137, 0.3);
    }
}
</style>
