<template>
    <div class="pest-interact-page">
        <custom-header :name="t('agriFile.pestInteract')" />
        <div class="pest-interact-content">
            <div class="map-container" ref="mapContainer"></div>
            <div class="search-bar">
                <location-search class="search-bar__search" :user-location="userLocation"
                    @change="handleLocationChange" />
            </div>
            <div class="map-tip">{{ t("agriFile.selectAbnormalPlot") }}</div>
            <div class="locate-btn" @click="handleLocate">
                <img class="locate-btn__icon" src="@/assets/img/map/map-icon.png" alt="" />
            </div>
        </div>
        <div class="custom-bottom-fixed-btns">
            <div class="bottom-btn secondary-btn" @click="handleCancel">{{ t("agriFile.cancel") }}</div>
            <div class="bottom-btn primary-btn" @click="handleConfirm">{{ t("agriFile.confirmPlot") }}</div>
        </div>
        <album-upload-popup v-model:show="showUploadPopup" />
    </div>
</template>

<script setup>
import { nextTick, onActivated, ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import customHeader from "@/components/customHeader.vue";
import locationSearch from "@/components/pageComponents/locationSearch.vue";
import albumUploadPopup from "../components/albumUploadPopup.vue";
import FileMap from "../fileMap";
import * as util from "@/common/ol_common.js";
import { useI18n } from "@/i18n";

const { t } = useI18n();
const router = useRouter();
const store = useStore();
const mapContainer = ref(null);
const fileMap = new FileMap();
const selectedZoneId = ref(null);
const showUploadPopup = ref(false);
let clickBound = false;

const DEFAULT_MAP_LOCATION = "POINT(113.6142086995688 23.585836479509055)";
const userLocation = ref(
    store.state.home.miniUserLocation ||
    localStorage.getItem("MINI_USER_LOCATION") ||
    "113.61702297075017,23.584863449735067"
);

const MOCK_ZONES = [
    { id: 1, nameKey: "agriFile.legendZone", dlng: -0.00115, dlat: 0.00055, delta: 0.00155 },
];

function squarePolygonWkt(lng, lat, delta = 0.0014) {
    const ring = [
        [lng - delta, lat + delta * 0.7],
        [lng + delta * 0.35, lat + delta],
        [lng + delta, lat - delta * 0.2],
        [lng + delta * 0.15, lat - delta],
        [lng - delta * 0.85, lat - delta * 0.45],
        [lng - delta, lat + delta * 0.7],
    ];
    return `POLYGON((${ring.map((point) => point.join(" ")).join(", ")}))`;
}

function getFarmData() {
    try {
        return JSON.parse(localStorage.getItem("selectedFarmData") || "{}");
    } catch {
        return {};
    }
}

function isPointWkt(value) {
    return typeof value === "string" && /^POINT\s*\(/i.test(value.trim());
}

function wkbHexToPointWkt(hex) {
    const text = String(hex || "").trim();
    if (!/^[0-9a-fA-F]+$/.test(text) || text.length < 42) return null;
    const bytes = new Uint8Array(text.length / 2);
    for (let i = 0; i < bytes.length; i++) {
        bytes[i] = parseInt(text.slice(i * 2, i * 2 + 2), 16);
    }
    const view = new DataView(bytes.buffer);
    const little = view.getUint8(0) === 1;
    let type = view.getUint32(1, little);
    const hasSrid = (type & 0x20000000) !== 0;
    type &= 0xff;
    if (type !== 1) return null;
    let offset = 5;
    if (hasSrid) offset += 4;
    if (offset + 16 > bytes.length) return null;
    const lng = view.getFloat64(offset, little);
    const lat = view.getFloat64(offset + 8, little);
    if (!Number.isFinite(lng) || !Number.isFinite(lat)) return null;
    return `POINT(${lng} ${lat})`;
}

function toPointWkt(value) {
    if (!value || typeof value !== "string") return null;
    if (isPointWkt(value)) return value.trim();
    return wkbHexToPointWkt(value);
}

function getFarmMapLocation() {
    const farmData = getFarmData();
    const candidates = [farmData.wkt, farmData.geom_wkt, farmData.farm_location];
    for (const item of candidates) {
        const pointWkt = toPointWkt(item);
        if (pointWkt) return pointWkt;
    }
    return DEFAULT_MAP_LOCATION;
}

function getDefaultMapLocation() {
    return (
        toPointWkt(localStorage.getItem("MINI_USER_LOCATION_POINT")) ||
        toPointWkt(store.state.home.miniUserLocationPoint) ||
        getFarmMapLocation()
    );
}

function getDefaultMapCoordinate() {
    return util.wktCastGeom(getDefaultMapLocation()).getFirstCoordinate();
}

function loadPlotLayers() {
    const [lng, lat] = getDefaultMapCoordinate();
    const labels = MOCK_ZONES.map((item) => ({
        name: t(item.nameKey),
        longitude: lng + item.dlng,
        latitude: lat + item.dlat,
    }));
    const zoneRecords = MOCK_ZONES.map((item) => ({
        id: item.id,
        zone_name: "",
        polygon: squarePolygonWkt(lng + item.dlng, lat + item.dlat, item.delta),
    }));
    fileMap.setRecordPolygons(zoneRecords, "album");
    fileMap.setAlbumMarkers({ labels, photos: [] });
    fileMap.recordPolygonLayer.source.getFeatures().forEach((feature, index) => {
        feature.set("zone_id", MOCK_ZONES[index]?.id);
    });
    selectedZoneId.value = MOCK_ZONES[0]?.id ?? null;
}

function onMapClick(evt) {
    const feature = fileMap.kmap?.map?.forEachFeatureAtPixel(evt.pixel, (hit) => {
        if (hit.get("zone_id")) return hit;
        return undefined;
    });
    if (!feature) return;
    selectedZoneId.value = feature.get("zone_id");
}

function bindMapClick() {
    if (clickBound || !fileMap.kmap?.map) return;
    clickBound = true;
    fileMap.kmap.map.on("singleclick", onMapClick);
}

const initMap = async () => {
    await nextTick();
    if (!mapContainer.value) return;
    fileMap.initMap(getDefaultMapLocation(), mapContainer.value);
    loadPlotLayers();
    fileMap.kmap?.map?.updateSize?.();
    bindMapClick();
};

const handleLocationChange = (payload) => {
    if (!payload?.coordinateArray || !fileMap.kmap) return;
    fileMap.kmap.getView().animate({
        center: payload.coordinateArray,
        zoom: 16,
        duration: 0,
    });
};

const handleLocate = () => {
    if (!fileMap.kmap) return;
    fileMap.kmap.getView().animate({
        center: getDefaultMapCoordinate(),
        zoom: 16,
        duration: 0,
    });
};

const handleCancel = () => {
    router.back();
};

const handleConfirm = () => {
    if (!selectedZoneId.value) {
        ElMessage.warning(t("agriFile.pleaseSelectPlot"));
        return;
    }
    sessionStorage.setItem("SELECTED_ABNORMAL_PLOT", String(selectedZoneId.value));
    showUploadPopup.value = true;
};

onActivated(() => {
    initMap();
});
</script>

<style lang="scss" scoped>
.pest-interact-page {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100vh;
    overflow: hidden;
    background: #fff;
}

.pest-interact-content {
    position: relative;
    flex: 1;
    min-height: 0;
    overflow: hidden;

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

    .search-bar {
        position: absolute;
        top: 12px;
        left: 12px;
        right: 12px;
        z-index: 2;
        display: flex;
        align-items: center;
        height: 40px;
        padding: 0 4px 0 12px;
        border-radius: 20px;
        background: rgba(0, 0, 0, 0.45);
        box-sizing: border-box;

        &__search {
            flex: 1;
            min-width: 0;

            :deep(.el-select__wrapper) {
                background: transparent;
                box-shadow: none;
                border: none;
                min-height: 40px;
                padding-left: 0;
            }

            :deep(.el-select__placeholder),
            :deep(.el-select__input) {
                color: rgba(255, 255, 255, 0.7);
            }

            :deep(.el-icon) {
                color: rgba(255, 255, 255, 0.85);
            }
        }
    }

    .map-tip {
        position: absolute;
        top: 64px;
        left: 50%;
        z-index: 2;
        transform: translateX(-50%);
        padding: 8px 30px;
        border-radius: 25px;
        background: rgba(0, 0, 0, 0.5);
        color: #7CC5FF;
        font-size: 12px;
        white-space: nowrap;
    }

    .locate-btn {
        position: absolute;
        right: 12px;
        bottom: 24px;
        z-index: 2;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 36px;
        height: 36px;
        border-radius: 8px;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);

        &__icon {
            width: 16px;
            height: 18px;
        }
    }
}

.custom-bottom-fixed-btns {
    position: relative;
    justify-content: space-between;

    .bottom-btn {
        padding: 10px 20px;
        border-radius: 25px;
    }

    .secondary-btn {
        color: #666;
        border: 1px solid rgba(153, 153, 153, 0.5);
    }

    .primary-btn {
        background: #2199f8;
    }
}
</style>
