<template>
    <div class="adopt-map-page">
        <div class="garden-info" v-if="gardenObj && !enterSelectTree">
            <div class="panel-title">
                <div class="title-l">
                    <div class="title-garden-box">
                        <img :src="farmAvatar" class="farm-avatar" alt="" />
                        <span class="title-garden">{{ gardenObj.farmName || "农场名称" }}</span>
                    </div>
                    <div class="btn-switch" @click="onSwitchFarm">切换农场</div>
                </div>
                <div class="title-r" v-if="gardenObj.people != null">
                    <div class="avatar-stack" v-if="adoptAvatars.length">
                        <img
                            v-for="(avatar, idx) in adoptAvatars"
                            :key="idx"
                            :src="avatar"
                            class="stack-avatar"
                            alt=""
                        />
                    </div>
                    <span class="adopt-text">
                        已有 <span class="adopt-val">{{ gardenObj.people }}</span> 人认养
                    </span>
                </div>
            </div>
        </div>

        <div class="select-tips" v-if="enterSelectTree">请选择您要守护的农场区域</div>
        <div class="select-btn" :class="{ active: selectedRegion }" v-if="enterSelectTree" @click="onSelectTree">
            我选好了
        </div>
        <div class="select-btn invite-btn" v-if="!enterSelectTree" @click="onInviteFriend">邀请好友守护</div>

        <div ref="mapRef" class="map"></div>

        <!-- <div class="top-mask"></div> -->

        <BaseFooter v-if="!enterSelectTree" :init-tab="2" />
    </div>
</template>

<script setup>
import IndexMap from "./map/index.js";
import RegionLayer from "./map/regionLayer.js";
import ClusterPointsLayer from "./map/clusterPointsLayer.js";
import { onMounted, onUnmounted, ref, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { SET_TOKEN } from "@/store/modules/app/type.js";
import { _checkImgUrl } from "@/utils";
import wx from "weixin-js-sdk";
import BaseFooter from "@/components/BaseFooter.vue";

const store = useStore();
const route = useRoute();
const router = useRouter();
const mapRef = ref(null);
const indexMap = new IndexMap();
let regionLayer = null;
let clusterPointsLayer = null;

const enterSelectTree = ref(false);
const selectedRegion = ref(null);
const gardenObj = ref(null);
const currenFarmId = ref(null);

const defaultCenter = "POINT(111.0105596 21.77287165)";
const DEFAULT_AVATAR = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";

const farmAvatar = computed(() => {
    const obj = gardenObj.value || {};
    return _checkImgUrl(obj.farmImg || obj.farmPic || obj.cover || obj.pic) || DEFAULT_AVATAR;
});

const adoptAvatars = computed(() => {
    const obj = gardenObj.value || {};
    const list = obj.userList || obj.avatarList || obj.buyUserList || obj.userAvatarList || [];
    if (Array.isArray(list) && list.length) {
        return list.slice(0, 3).map((item) => {
            if (typeof item === "string") return _checkImgUrl(item) || DEFAULT_AVATAR;
            return _checkImgUrl(item.avatar || item.headImg || item.userAvatar) || DEFAULT_AVATAR;
        });
    }
    if (obj.people > 0) {
        return [DEFAULT_AVATAR, DEFAULT_AVATAR, DEFAULT_AVATAR];
    }
    return [];
});

function onSelectTree() {
    router.push({
        path: "/my-guard",
        query: { showGuardSucessPopup: true },
    });
}

function onSwitchFarm() {
    router.push({
        path: "/farm-select",
        query: { ...route.query },
    });
}

function onInviteFriend() {
    const query = {
        askInfo: { title: "邀请好友", content: "是否邀请好友守护农场" },
        shareText: "中大诚邀师长校友，同心共守佳木，长念中大温情",
        targetUrl: `/`,
        paramsPage: JSON.stringify({ farmId: currenFarmId.value }),
        imageUrl: "https://birdseye-img.sysuimars.com/birdseye-look-mini/invite_bg.png",
    };
    wx.miniProgram.navigateTo({
        url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=sharePage`,
    });
}

async function reloadMapData() {
    await Promise.all([getGardenInfo(), getBlueRegionList(), getPointList()]);
}

function isEnterSelectTreeQuery(val) {
    if (val === undefined || val === null || val === "") return false;
    if (val === "0" || val === "false") return false;
    return true;
}

async function initAuth() {
    const userId = route.query.userId;
    if (!userId) return;
    const token = route.query.token;
    if (!token) {
        const { data } = await VE_API.system.devLogin({ userId });
        store.dispatch(`app/${SET_TOKEN}`, data.token);
    } else {
        store.dispatch(`app/${SET_TOKEN}`, token);
    }
    localStorage.setItem("MINI_USER_ID", userId);
    store.commit("home/SET_MINI_USER_ID");
}

function getGardenInfo() {
    return VE_API.lj_home.farmBuyInfo({ farmId: currenFarmId.value }).then(({ data }) => {
        gardenObj.value = data || {};
    });
}

function getBlueRegionList() {
    return VE_API.region
        .list({ farmId: currenFarmId.value })
        .then((res) => {
            //   const list = Array.isArray(res?.data) ? res.data : []
            const list = [
                {
                    areaMu: null,
                    farmCode: "LBY",
                    farmId: 766,
                    id: 2,
                    isGenerateReport: 1,
                    lastViewTime: null,
                    name: "分区2",
                    pointCount: 131,
                    pointWkt: "POINT (113.6142086995688 23.585836479509055)",
                    regionAreaId: null,
                    regionCode: "LBY-MR-2",
                    schemeId: null,
                    typeId: null,
                    wkt: "MULTIPOLYGON (((113.61348988377155 23.58617369800422, 113.61395837633405 23.58622555407246, 113.61414076654707 23.58622555407246, 113.61436964832843 23.5862774101407, 113.61478628474084 23.586468741036786, 113.61491681896747 23.58652417337007, 113.61512424307672 23.586449071517652, 113.61491503077356 23.585742756367924, 113.61479880177082 23.585596129050916, 113.61473800497858 23.585451289764112, 113.61438931780664 23.585286780835393, 113.61410858003889 23.585299297865365, 113.61385645239149 23.585249229909184, 113.61378135053907 23.585288569029306, 113.61357571446003 23.585283204611276, 113.61347200232355 23.585342213209604, 113.61338080721704 23.585506721974614, 113.61335934954492 23.585665866485304, 113.61342193444922 23.58616296916816, 113.61348988377155 23.58617369800422)))",
                },
                {
                    areaMu: null,
                    farmCode: "LBY",
                    farmId: 766,
                    id: 9,
                    isGenerateReport: 1,
                    lastViewTime: null,
                    name: "分区9",
                    pointCount: 63,
                    pointWkt: "POINT (113.61725048541882 23.585262743588892)",
                    regionAreaId: null,
                    regionCode: "LBY-MR-9",
                    schemeId: null,
                    typeId: null,
                    wkt: "MULTIPOLYGON (((113.61697301904715 23.585749021838886, 113.617320420354 23.585742359348075, 113.61752600578478 23.585708095109652, 113.61772112158744 23.5856785897931, 113.61789720170187 23.58559102562808, 113.61787340709186 23.585330236701996, 113.61793812843106 23.58526932250014, 113.61795526055036 23.585167481569073, 113.61793146594025 23.585022810339957, 113.61790671954574 23.58491525870246, 113.61779345720193 23.58473346788171, 113.61779821612386 23.584601169849783, 113.61771921801855 23.584509798547092, 113.61763260563801 23.584517412822354, 113.61755741467023 23.584640193010298, 113.61736515422085 23.584823887399946, 113.61726902399624 23.58487623554194, 113.61709484745067 23.584864814129187, 113.61707105284067 23.584962847922696, 113.61699586187265 23.585023762124397, 113.61689877986377 23.585071351344393, 113.61675981934107 23.58515796372515, 113.61663132844662 23.585192227963518, 113.61646000725422 23.58524076896813, 113.61634484134152 23.585320718857897, 113.61628392713976 23.585360693802862, 113.6162163504473 23.585397813394497, 113.61601552393823 23.585480618637533, 113.61596127222741 23.585499654325552, 113.61597174185577 23.585538677485918, 113.61598125969975 23.585561520311693, 113.61608690776846 23.585591025628073, 113.61610689524092 23.585611013100582, 113.61619350762157 23.58557960421532, 113.6162886860618 23.58552820785755, 113.61632104673151 23.585492040050294, 113.61638196093314 23.585453968674216, 113.61646095903859 23.585480618637543, 113.6164771393734 23.585505365031985, 113.61649617506146 23.585564375664962, 113.61648760900198 23.58561006131614, 113.61645048941011 23.58567192730245, 113.61649807863034 23.585676686224392, 113.61662466595578 23.585595784550236, 113.61671698904298 23.585495847187836, 113.61676553004737 23.585587218490588, 113.61681787818966 23.585559616742817, 113.61689211737293 23.5854558722431, 113.61695588692798 23.585499654325556, 113.61697301904715 23.585749021838886)))",
                },
                {
                    areaMu: null,
                    farmCode: "LBY",
                    farmId: 766,
                    id: 29,
                    isGenerateReport: 1,
                    lastViewTime: null,
                    name: "分区8",
                    pointCount: 40,
                    pointWkt: "POINT (113.61587084394066 23.58618878122994)",
                    regionAreaId: null,
                    regionCode: "LBY-MR-8",
                    schemeId: null,
                    typeId: null,
                    wkt: "MULTIPOLYGON (((113.61516876894466 23.58617727723074, 113.6153952936325 23.58616014511155, 113.61551426668275 23.586215348606817, 113.61564275757719 23.586290539574595, 113.61565798612749 23.58640951262483, 113.61577695917796 23.58637905552401, 113.61584168051715 23.586392380505654, 113.615912112563 23.58637048946448, 113.61613483011318 23.586200120056528, 113.6162547549478 23.586365730542376, 113.61623762282863 23.586448535785365, 113.61615196223237 23.586476137533136, 113.61634435485792 23.586946782901485, 113.61654695275945 23.586932042261843, 113.61651364030526 23.58667220511998, 113.61648127963554 23.586552280285296, 113.61640894402115 23.58641903046899, 113.61636135480092 23.586292443143435, 113.6163308977001 23.586121121951034, 113.61631471736528 23.58605735239606, 113.61618622647107 23.586071629162152, 113.61612911940675 23.58603260600161, 113.61610342122786 23.58595265611185, 113.61601109814079 23.585864140162432, 113.61585310193013 23.585803225960632, 113.61557898802205 23.585730890346124, 113.6153714990225 23.585723276070855, 113.61520493675204 23.585882224066058, 113.61516591359151 23.586056400611785, 113.61516876894466 23.58617727723074)))",
                },
                {
                    areaMu: null,
                    farmCode: "LBY",
                    farmId: 766,
                    id: 12828,
                    isGenerateReport: 1,
                    lastViewTime: null,
                    name: "分区5",
                    pointCount: 45,
                    pointWkt: "POINT (113.61692837797158 23.58435388968608)",
                    regionAreaId: null,
                    regionCode: "LBY-MR-5",
                    schemeId: null,
                    typeId: null,
                    wkt: "MULTIPOLYGON (((113.61726902399624 23.584875938109313, 113.61732981922493 23.584649032707855, 113.61741785928217 23.58458954618279, 113.6176284415812 23.584287354634938, 113.61761892373723 23.584146966435544, 113.61762249292879 23.584041080420736, 113.61758442155264 23.584010147427676, 113.61752374529698 23.583939953328095, 113.6174499820059 23.583857861923292, 113.61723702024568 23.5839113997961, 113.61706331959229 23.583947091711153, 113.61689794705232 23.583967317129648, 113.61673019505157 23.58399468093132, 113.61659218631306 23.584025613924393, 113.61641848565968 23.584054167456387, 113.61624716446725 23.584093428562902, 113.61621623147425 23.584286164904498, 113.61622218012678 23.584531249388036, 113.6162186109351 23.58466211974327, 113.61629713314835 23.584684724622857, 113.6166052733487 23.58470970896351, 113.61669926205845 23.584731124112597, 113.61678016373266 23.584778713332653, 113.61680276861217 23.584819164169826, 113.61683846052725 23.58481916416982, 113.61689080866942 23.584775144141148, 113.61697884872665 23.58482035390024, 113.61709484745067 23.584864516696555, 113.61726902399624 23.584875938109313)))",
                },
                {
                    areaMu: null,
                    farmCode: "LBY",
                    farmId: 766,
                    id: 172047,
                    isGenerateReport: 1,
                    lastViewTime: null,
                    name: "认养分区",
                    pointCount: null,
                    pointWkt: "POINT (113.61573550741103 23.586606696698798)",
                    regionAreaId: null,
                    regionCode: "LBY认养分区",
                    schemeId: null,
                    typeId: null,
                    wkt: "MULTIPOLYGON (((113.61553138381385 23.586555391814727, 113.61578836560238 23.586770495089638, 113.61593018147823 23.586692924660838, 113.61571507820327 23.5864349910878, 113.61553138381385 23.586555391814727)))",
                },
                {
                    areaMu: null,
                    farmCode: "LBY",
                    farmId: 766,
                    id: 175094,
                    isGenerateReport: 1,
                    lastViewTime: null,
                    name: "12",
                    pointCount: null,
                    pointWkt: "POINT (113.61860504330416 23.583859757151316)",
                    regionAreaId: null,
                    regionCode: "LBY-MR-12",
                    schemeId: null,
                    typeId: null,
                    wkt: "MULTIPOLYGON (((113.61790764544605 23.58437349638575, 113.61810434755591 23.58448136528483, 113.61834039008784 23.58457781277093, 113.61887973458238 23.58461715319288, 113.61901298439875 23.584476289101246, 113.61925029597637 23.584407760624345, 113.61937973865497 23.58437349638575, 113.61932390063691 23.584164103817216, 113.61923506742585 23.5838836446801, 113.61920587937084 23.583660292607078, 113.61927060071025 23.58345216908441, 113.61940004338908 23.5832846550295, 113.6191449651692 23.58325927411221, 113.61896095351813 23.583223740827805, 113.61884166320624 23.58314759807564, 113.61873379430745 23.58305115058954, 113.6185180565094 23.583087952919755, 113.61840257333529 23.58318947658927, 113.61825028783096 23.583260543158076, 113.61815510939073 23.583216126552543, 113.61807262140928 23.583183131360045, 113.61779216227194 23.583299883580025, 113.61792541208831 23.58360953077215, 113.61817668317042 23.583615876001545, 113.61831374012445 23.583843035212283, 113.61829216634476 23.583925523193727, 113.61821348550086 23.5839014113223, 113.6179825191524 23.583770699597665, 113.6178530764738 23.583793542423393, 113.61783784792328 23.583905218459847, 113.617946985868 23.58400166594589, 113.61795713823494 23.584085422973374, 113.61786703597829 23.58419963710162, 113.61785815265716 23.58428847031246, 113.61790764544605 23.58437349638575)))",
                },
                {
                    areaMu: null,
                    farmCode: "LBY",
                    farmId: 766,
                    id: 175095,
                    isGenerateReport: 1,
                    lastViewTime: null,
                    name: "13",
                    pointCount: null,
                    pointWkt: "POINT (113.61907779775447 23.582774628335315)",
                    regionAreaId: null,
                    regionCode: "LBY-MR-13",
                    schemeId: null,
                    typeId: null,
                    wkt: "MULTIPOLYGON (((113.6185180565094 23.583087952919755, 113.61873379430756 23.58305115058954, 113.61884166320624 23.58314759807564, 113.61896095351813 23.583223740827805, 113.6191449651692 23.58325927411221, 113.61940004338908 23.5832846550295, 113.61952853428329 23.58303148037845, 113.61974554112703 23.582682175502953, 113.61942574156774 23.58233191884284, 113.61909737594897 23.58227005285653, 113.61872713181651 23.58242614549863, 113.61843207865172 23.58267265765886, 113.61843112686734 23.583051467850964, 113.6185180565094 23.583087952919755)))",
                },
                {
                    areaMu: null,
                    farmCode: "LBY",
                    farmId: 766,
                    id: 175096,
                    isGenerateReport: 1,
                    lastViewTime: null,
                    name: "15",
                    pointCount: null,
                    pointWkt: "POINT (113.61729343325402 23.581078231145653)",
                    regionAreaId: null,
                    regionCode: "LBY-MR-15",
                    schemeId: null,
                    typeId: null,
                    wkt: "MULTIPOLYGON (((113.61579634969576 23.580895993441118, 113.61623258421344 23.58139885286704, 113.61657522659812 23.581547965756727, 113.61743341886756 23.5818731587608, 113.61737155288142 23.58216345300349, 113.61798704012836 23.582252286214498, 113.61852479831566 23.58088806190449, 113.61799973058703 23.58035347633188, 113.61769991850042 23.580115530231183, 113.61644039047451 23.580399479244647, 113.61574558786083 23.580797642386187, 113.61579634969576 23.580895993441118)))",
                },
            ];
            if (!list.length) {
                console.warn("[adopt_map] 分区列表为空", res);
            }
            regionLayer.initData(list);
        })
        .catch((err) => {
            console.error("[adopt_map] region/list 请求失败", err);
        });
}

function getPointList() {
    if (enterSelectTree.value || !clusterPointsLayer) {
        return Promise.resolve();
    }
    return VE_API.variety.getBuyTreeList({ farmId: currenFarmId.value }).then(({ data }) => {
        clusterPointsLayer.setData(data, false);
    });
}

onMounted(async () => {
    currenFarmId.value = route.query.farmId || 766;

    await initAuth();

    console.log("route", route, router);

    // URL 带 enterSelectTree 即进入选分区模式（不再依赖 getLightTree 是否有 id）
    if (isEnterSelectTreeQuery(route.meta.selectMode)) {
        enterSelectTree.value = true;
        try {
            const { data } = await VE_API.lj_home.getLightTree({ speciesId: "1" });
            if (data?.id) {
                // 已有分配的树时可在此扩展其它逻辑，选分区 UI 仍保持开启
                console.log("[adopt_map] 用户已有点亮树", data.id);
            }
        } catch (e) {
            console.warn("[adopt_map] getLightTree", e);
        }
    }

    indexMap.initMap(defaultCenter, mapRef.value);
    regionLayer = new RegionLayer(indexMap.kmap, {
        enterSelectTree: enterSelectTree.value,
        onRegionSelect: (region) => {
            selectedRegion.value = region;
        },
    });
    if (!enterSelectTree.value) {
        clusterPointsLayer = new ClusterPointsLayer(indexMap.kmap);
    }

    await reloadMapData();

    regionLayer.setEnterSelectTree(enterSelectTree.value);
});

watch(
    () => route.query.farmId,
    async (newId, oldId) => {
        if (!newId || String(newId) === String(oldId)) return;
        currenFarmId.value = newId;
        await reloadMapData();
    },
);
</script>

<style scoped lang="less">
.adopt-map-page {
    width: 100%;
    height: 100vh;
    background: #fff;
    position: relative;
    overflow: hidden;

    .map {
        width: 100%;
        height: 100%;
    }

    .select-tips {
        position: absolute;
        z-index: 3;
        top: 10px;
        left: 50%;
        transform: translateX(-50%);
        pointer-events: none;
        background: rgba(0, 0, 0, 0.5);
        color: #ffffff;
        font-size: 12px;
        padding: 7px 20px;
        border-radius: 30px;
    }

    .select-btn {
        position: absolute;
        z-index: 3;
        bottom: 60px;
        left: 50%;
        transform: translateX(-50%);
        background: linear-gradient(141.52deg, #ffe6b2 7.21%, #ffa617 95.86%);
        color: #000000;
        font-size: 16px;
        width: 152px;
        text-align: center;
        line-height: 40px;
        border: 1px solid #ffffff;
        box-sizing: border-box;
        height: 40px;
        border-radius: 20px;
        font-family: "PangMenZhengDao";
        opacity: 0.4;

        &.active,
        &.invite-btn {
            opacity: 1;
        }
        &.invite-btn {
            box-shadow: 0px 0px 8px 0px #f3ca88;
            bottom: 120px;
        }
    }

    .garden-info {
        position: absolute;
        z-index: 3;
        top: 10px;
        left: 12px;
        right: 0;
        width: auto;

        .panel-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            min-width: 0;
            gap: 8px;

            .title-l {
                display: flex;
                align-items: center;
                gap: 2px;
                min-width: 0;
                flex: 1;
                overflow: hidden;
                background: rgba(0, 0, 0, 0.5);
                padding: 4px;
                border-radius: 20px;
                border: 0.5px solid rgba(255, 255, 255, 0.5);

                .title-garden-box {
                    display: flex;
                    align-items: center;
                    gap: 4px;
                    min-width: 0;
                    flex: 1;
                    overflow: hidden;
                }

                .farm-avatar {
                    width: 32px;
                    height: 32px;
                    border-radius: 50%;
                    object-fit: cover;
                    flex-shrink: 0;
                }

                .title-garden {
                    color: #fff;
                    font-size: 14px;
                    min-width: 0;
                    flex: 1;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
            }

            .btn-switch {
                flex-shrink: 0;
                width: 68px;
                text-align: center;
                height: 28px;
                line-height: 28px;
                background: #ffa617;
                border-radius: 20px;
                color: #fff;
                font-size: 12px;
                cursor: pointer;
            }

            .title-r {
                background: rgba(0, 0, 0, 0.6);
                padding: 4px;
                border-radius: 20px 0 0 20px;
                display: flex;
                align-items: center;
                gap: 5px;
                flex-shrink: 0;
                margin-left: auto;

                .avatar-stack {
                    display: flex;
                    align-items: center;

                    .stack-avatar {
                        width: 22px;
                        height: 22px;
                        border-radius: 50%;
                        border: 1px solid #fff;
                        object-fit: cover;
                        margin-left: -8px;

                        &:first-child {
                            margin-left: 0;
                        }
                    }
                }

                .adopt-text {
                    font-size: 12px;
                    color: #fff;
                    white-space: nowrap;

                    .adopt-val {
                        color: #f9be00;
                        font-weight: 500;
                    }
                }
            }
        }
    }

    .top-mask {
        position: absolute;
        z-index: 2;
        top: 0;
        left: 0;
        width: 100%;
        height: 120px;
        pointer-events: none;
        background: linear-gradient(0deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.8) 100%);
    }

    .bottom-mask {
        position: absolute;
        z-index: 2;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 80px;
        pointer-events: none;
        background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.7) 100%);
    }
}
</style>

<style lang="less">
/* 仅压暗底图瓦片，避免 .ol-layer 把分区和点位一起压到看不见 */
// .dark .ol-map-clearness {
//   filter: brightness(0.35);
// }
</style>
