import api from "@/api/menu";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import { transform } from "ol/proj";

function getLayerData(item, extendFunc, loading) {
    return new Promise((resolve, reject) => {
        api.getLayerData({ modelId: item.id, page: 0, pageSize: 1500 })
            .then((result) => {
                if (loading) loading.close();
                if (result.code == 200) {
                    let poiArr = result.content.map(function (oneitem) {
                        oneitem.classify = item.classify;
                        return createPoi(
                            [oneitem.centerLon, oneitem.centerLat],
                            oneitem,
                            extendFunc
                        );
                    });
                    resolve(poiArr);
                } else {
                    reject(result.message)
                }
            })
            .catch((err) => {
                loading.close();
                reject("服务器异常，请稍后重试！")
            });
    });
}

function createPoi(lonlat, properties, extendFunc) {
    let that = this;
    let point = new Point(transform(lonlat, "EPSG:4326", "EPSG:3857"));
    let poi = new Feature({
        geometry: point,
        callback: function (feature, selectSingleClickFeatures) {
            selectSingleClickFeatures.clear();
            let properties = feature.values_.properties;
            extendFunc(properties, feature.values_.geometry.getCoordinates());
        },
        properties: properties,
    });
    return poi;
}

export { getLayerData }