<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 yes-events">
                    <!-- <div class="top-l yes-events">
                        <div>
                            <el-cascader
                                style="width: 184px"
                                :show-all-levels="false"
                                v-model="areaVal"
                                :props="props1"
                                @change="toggleArea"
                                popper-class="area-cascader"
                            />
                        </div>
                    </div> -->
                    <div class="address-box">海南省-琼山区-三门坡镇</div>
                    <div class="btn-box" @click="handleClick">智慧果园</div>
                </div>
            </div>
            <div class="warning-r right chart-wrap yes-events">
                <chart-list
                    :activeBaseTab="activeBaseTab"
                    :areaCode="selectedAreaCode"
                    :areaName="selectedAreaName"
                ></chart-list>
            </div>
            <!-- 地图图例 -->
            <!-- <map-legend></map-legend> -->
            <land-use-legend @change="handleLegendChange"></land-use-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>
    </div>
    <div ref="mapRef" class="bottom-map"></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 mapLegend from "./components/mapLegend.vue";
import landUseLegend from "./components/landUseLegend.vue";
import WarningMap from "./warningMap";
import AlarmLayer from "./map/alarmLayer";
import DistributionLayer from "./map/distributionLayer";
import BoundaryLayer from "./map/boundaryLayer";
import trackDialog from "./components/trackDialog.vue";
import eventBus from "@/api/eventBus";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import chartList from "./components/chart_components/chartList.vue";

let store = useStore();
const router = useRouter();
let warningMap = new WarningMap();
let alarmLayer = null;
let staticMapLayers = null;
let staticMapPointLayers = null;
let distributionLayer = null;
let boundaryLayer = null;
const areaVal = ref([]);
const mapRef = ref(null);
const treeRef = ref(null);

const treeActionData = ref([]);
// 保存原始数据，用于恢复
const originalTreeData = ref([]);

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

// 当前选中的年份和季度
const currentYear = ref(2025);
const currentQuarter = ref(1);

// 顶部基础 tabs
const activeBaseTab = ref("作物分布");

const warningLayers = ref({});

onMounted(async () => {
    // 使用 nextTick 确保 DOM 已经渲染完成，地图容器有正确的尺寸
    await nextTick();

    warningMap.initMap("POINT(110.5125011950405 19.695262155184544)", mapRef.value);

    // 地图初始化后，更新地图尺寸以确保正确渲染
    if (warningMap.kmap && warningMap.kmap.map) {
        // 使用 setTimeout 确保地图容器尺寸已计算
        setTimeout(() => {
            warningMap.kmap.map.updateSize();
        }, 0);
    }

    alarmLayer = new AlarmLayer(warningMap.kmap);
    staticMapLayers = new StaticMapLayers(warningMap.kmap);
    staticMapPointLayers = new StaticMapPointLayers(warningMap.kmap);
    distributionLayer = new DistributionLayer(warningMap.kmap);
    boundaryLayer = new BoundaryLayer(warningMap.kmap);
    await getSpeciesListData();

    getDistributionData();

    // 数据加载完成后，再次更新地图尺寸以确保正确渲染
    if (warningMap.kmap && warningMap.kmap.map) {
        setTimeout(() => {
            warningMap.kmap.map.updateSize();
        }, 100);
    }

    // 胜华村的村界
    // getVillageBoundary()

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

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

    // 监听图表组件的地图更新事件
    eventBus.on("chartList:updateMap", async ({ statType }) => {
        if (!distributionLayer) return;
        // 使用 statType 参数请求地图数据
        getDistributionData(statType);
    });

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

        if (legendUrl) {
            staticMapLayers && staticMapLayers.showSingle(name, true);
        } else {
            let text = "";
            if (name === "日间温度") {
                text = "从化地块日温";
            } else if (name === "夜间温度") {
                text = "从化地块夜温";
            } else if (name === "土壤水分") {
                text = "从化地块水分";
            }
            if (text !== "") {
                staticMapLayers && staticMapLayers.showSingle(text, true);
            } else {
                staticMapLayers && staticMapLayers.hideAll();
            }
        }
    });
    // 初始化区域选择器的默认值
    initAreaDefaultValue();

    // 窗口大小改变时更新地图尺寸
    const handleResize = () => {
        if (warningMap.kmap && warningMap.kmap.map) {
            warningMap.kmap.map.updateSize();
        }
    };
    window.addEventListener("resize", handleResize);

    // 在组件卸载时清理
    onUnmounted(() => {
        window.removeEventListener("resize", handleResize);
    });
});

const getVillageBoundary = async () => {
    const res = await VE_API.warning.fetchVillageBoundary();
    if (res.code === 0 && res.data) {
        const villageBoundary = res.data;
        console.log(villageBoundary);
        boundaryLayer.initData(villageBoundary);
    }
};

const handleClick = () => {
    if (window.parent) {
        window.parent.postMessage(
            {
                type: "land-click",
                payload: {
                    source: "warningHome",
                    action: "openSmartGarden",
                },
            },
            "*" // 如果有固定父应用域名，可以替换为 'http://localhost:8080' 等
        );
    }
};

// 时间轴
eventBus.on("weatherTime:changeTime", ({ index, year, quarter }) => {
    handleTimeChange(index, year, quarter);
});

const handleTimeChange = (index, year, quarter) => {
    // 更新当前选中的年份和季度
    currentYear.value = year;
    currentQuarter.value = quarter;

    // 如果当前在作物分布或物候期分布tab，需要重新加载地图数据
    if (activeBaseTab.value === "作物分布" || activeBaseTab.value === "物候期分布") {
        // 重新获取当前选中的节点数据
        if (treeRef.value) {
            const checkedNodes = treeRef.value.getCheckedNodes(false, true);
            if (checkedNodes && checkedNodes.length > 0) {
                getTreeChecks(checkedNodes[0], { checkedNodes });
            }
        }
    }
};

// 初始化区域选择器的默认值
const initAreaDefaultValue = async () => {
    try {
        const res = await VE_API.species.provinceList();
        if (res.code === 0 && res.data && res.data.length > 0) {
            // 设置第一个省为默认值
            const firstProvinceCode = res.data[0].provCode || res.data[0].code;
            const firstProvinceName = res.data[0].provName || res.data[0].name;
            areaVal.value = [firstProvinceCode];
            selectedAreaCode.value = firstProvinceCode;
            selectedAreaName.value = firstProvinceName;
            // 保存到映射中
            areaCodeNameMap.value.set(firstProvinceCode, firstProvinceName);
        }
    } catch (error) {
        console.error("初始化区域默认值失败:", error);
    }
};

sessionStorage.removeItem("farmId");

onUnmounted(() => {
    eventBus.off("alarmList:changeMapLayer");
    eventBus.off("chartList:updateMap");
    // 时间轴
    eventBus.off("weatherTime:changeTime");
});


const getSpeciesListData = async () => {
    const res = await VE_API.species.speciesList();
    treeActionData.value = res.data;
    // 保存原始数据副本（深拷贝）
    originalTreeData.value = JSON.parse(JSON.stringify(res.data));
};

const getDistributionData = async (statType = null) => {
    const { data } = await VE_API.agri_land_crop.queryDistribution({ statType: statType || 0 });
    // 把点位图层去掉：不返回 centerPoint，只保留地块相关信息
    const list = Array.isArray(data)
        ? data.map((item) => {
              const { centerPoint, ...rest } = item || {};
              return rest;
          })
        : [];
    distributionLayer.initData(list);
};
const props1 = {
    checkStrictly: true,
    lazy: true,
    lazyLoad(node, resolve) {
        const { level } = node;

        if (level === 0) {
            // 第一级：获取省级列表
            VE_API.species
                .provinceList()
                .then((res) => {
                    if (res.code === 0 && res.data) {
                        const nodes = res.data.map((item) => {
                            const code = item.provCode || item.code;
                            const name = item.provName || item.name;
                            // 保存 code 到 name 的映射
                            areaCodeNameMap.value.set(code, name);
                            return {
                                value: code, // 使用code，不使用id
                                label: name,
                                leaf: false, // 省级不是叶子节点
                            };
                        });
                        if (nodes.length > 0) {
                            // 设置第一个省的code
                            const firstProvinceCode = nodes[0].value;
                            areaVal.value = [firstProvinceCode];
                            selectedAreaCode.value = firstProvinceCode;
                            selectedAreaName.value = nodes[0].label;
                        }
                        resolve(nodes);
                    } else {
                        resolve([]);
                    }
                })
                .catch(() => {
                    resolve([]);
                });
        } else if (level === 1) {
            // 第二级：获取市级列表，参数 provCode
            const provCode = node.value;
            VE_API.species
                .cityList({ provCode })
                .then((res) => {
                    if (res.code === 0 && res.data) {
                        const nodes = res.data.map((item) => {
                            const code = item.cityCode || item.code;
                            const name = item.cityName || item.name;
                            // 保存 code 到 name 的映射
                            areaCodeNameMap.value.set(code, name);
                            return {
                                value: code,
                                label: name,
                                leaf: false, // 市级不是叶子节点
                            };
                        });
                        resolve(nodes);
                    } else {
                        resolve([]);
                    }
                })
                .catch(() => {
                    resolve([]);
                });
        } else if (level === 2) {
            // 第三级：获取区级列表，参数 cityCode
            const cityCode = node.value;
            VE_API.species
                .districtList({ cityCode })
                .then((res) => {
                    if (res.code === 0 && res.data) {
                        const nodes = res.data.map((item) => {
                            const code = item.districtCode || item.code;
                            const name = item.districtName || item.name;
                            // 保存 code 到 name 的映射
                            areaCodeNameMap.value.set(code, name);
                            return {
                                value: code,
                                label: name,
                                leaf: true, // 区级是叶子节点
                            };
                        });
                        resolve(nodes);
                    } else {
                        resolve([]);
                    }
                })
                .catch(() => {
                    resolve([]);
                });
        } else {
            resolve([]);
        }
    },
};



const selectedAreaCode = ref(null);
const selectedAreaName = ref(null);

// 保存 code 到 name 的映射关系
const areaCodeNameMap = ref(new Map());

const toggleArea = (v) => {
    // 获取选中的最后一个值（即最终的code）
    const selectedCode = v && v.length > 0 ? v[v.length - 1] : null;
    selectedAreaCode.value = selectedCode;

    // 从映射中获取对应的 name
    if (selectedCode && areaCodeNameMap.value.has(selectedCode)) {
        selectedAreaName.value = areaCodeNameMap.value.get(selectedCode);
    } else {
        selectedAreaName.value = null;
    }
};

// 搜索
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 };
        }
        const rootChildren = root.items || root.children || [];
        for (const second of rootChildren) {
            if (second.id === id) {
                return { level: 2, secondId: second.id };
            }
            const secondChildren = second.items || second.children || [];
            for (const third of secondChildren) {
                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 === "预警分布" ||
            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) => {
                    const rootChildren = root.items || root.children || [];
                    rootChildren.forEach((second) => {
                        if (second.id !== currentSecondId) {
                            // 取消其它二级及其所有子级勾选
                            tree.setChecked(second.id, false, true);
                        }
                        // 对于当前二级节点，不手动设置其选中状态
                        // 让 Element Plus 根据子节点的选中状态自动计算半选中状态
                        // 这样当部分三级节点被选中时，二级节点会自动显示半选中状态
                    });
                });
            } 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 field = activeBaseTab.value === "物候期分布" || activeBaseTab.value === "农场分布" ? "originalId" : "id";
    const lastLevelIds = finalCheckedNodes
        .filter((n) => (!n.items || n.items.length === 0) && (!n.children || n.children.length === 0))
        .map((n) => n[field]);
    if (lastLevelIds && lastLevelIds.length === 0) {
        distributionLayer.initData([]);
        return;
    }
    if (activeBaseTab.value === "物候期分布") {
        const phenologyData = await getDistributionData(null, lastLevelIds);
        distributionLayer.initData(phenologyData, "phenologyName");
        return;
    }
    if (activeBaseTab.value === "农场分布") {
        await fetchFarmList(lastLevelIds);
        return;
    }
    // 并发请求所有数据，等待所有 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);
};

// 处理图例变化
const handleLegendChange = (data) => {
    console.log("图例变化:", data);
    // 通过 eventBus 将选中的类别信息传递给饼图组件
    if (data.checked) {
        eventBus.emit("landUseLegend:change", {
            category: data.category,
            nonGrain: data.nonGrain,
            children: data.children,
        });
    }
};
</script>

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

    .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;
        }
        .warning-search {
            position: fixed;
            right: 207px;
            top: 28px;
            display: flex;
            align-items: center;
            ::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;
            .address-box{
                color: #f7be5a;
                font-size: 20px;
                font-family: "PangMenZhengDao";
                margin-right: 15px;
                border: 2px solid rgba(255, 212, 137, 0.3);
                border-radius: 4px;
                padding: 8px 14px 11px;
                background: rgba(29, 29, 29, 0.54);
            }
            .btn-box {
                cursor: pointer;
                color: #f7be5a;
                font-size: 20px;
                font-family: "PangMenZhengDao";
                border: 2px solid #f7be5a;
                border-radius: 4px;
                padding: 8px 14px 11px;
                background: rgba(29, 29, 29, 0.54);
            }
            .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-input__suffix {
                            color: #f7be5a;
                        }
                    }
                    .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;
                    }
                }
            }
        }
        .time-wrap {
            position: fixed;
            bottom: 20px;
            left: 20px;
            width: 950px;
            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-radio__inner::after {
        background: #000;
    }
    &.el-popper.is-light .el-popper__arrow:before {
        background: #232323;
        border-color: rgba(255, 212, 137, 0.3);
    }
}
</style>
