import gcoord from "gcoord";

// 示例 WKT 数据，可以是 POLYGON 或 MULTIPOLYGON
let wktData = "MULTIPOLYGON(((106.67591743605254 38.21012898330025,106.67588081160454 38.21003303839916,106.6755667227518 38.21006159193115,106.67551318487904 38.20994380861134,106.67578087424232 38.20991525507935,106.67573447475257 38.209776056610394,106.67594862624321 38.20973322631232,106.6759771797752 38.20983673286605,106.67621495734579 38.20981715370431,106.6761636759473 38.20962317624071,106.67538440246796 38.209765943901175,106.67538440246796 38.20984050880776,106.67519166939297 38.20987258822527,106.6752925390611 38.2102444053304,106.67591743605254 38.21012898330025)))";

// 从 WKT 字符串解析出坐标数组
function wktToCoordinates(wkt) {
    if (wkt.startsWith("POLYGON")) {
        // 处理 POLYGON 格式
        return [wkt.match(/\(([^()]+)\)/)[1].trim().split(',').map(point => {
            return point.trim().split(' ').map(Number);
        })];
    } else if (wkt.startsWith("MULTIPOLYGON")) {
        // 处理 MULTIPOLYGON 格式
        let polygons = wkt.match(/\(\(\(([^()]+)\)\)\)/g);
        return polygons.map(polygon => {
            return polygon.match(/\(([^()]+)\)/)[1].trim().split(',').map(point => {
                return point.trim().split(' ').map(Number);
            });
        });
    } else {
        throw new Error("Unsupported WKT type");
    }
}

// 将坐标数组转换为火星坐标系（GCJ-02）
function convertToGCJ02(coordinates) {
    return coordinates.map(polygon => {
        return polygon.map(coord => {
            return gcoord.transform(
                coord,    // 源坐标
                gcoord.WGS84,    // 源坐标系
                gcoord.GCJ02     // 目标坐标系（火星坐标系）
            );
        });
    });
}

// 将火星坐标系的坐标转换回 WKT 格式字符串
function coordinatesToWKT(coordinates, isMultiPolygon) {
    if (isMultiPolygon) {
        // MULTIPOLYGON 格式
        let polygons = coordinates.map(polygon => {
            let coordString = polygon.map(coord => coord.join(' ')).join(', ');
            return `((${coordString}))`;
        });
        return `MULTIPOLYGON (${polygons.join(', ')})`;
    } else {
        // POLYGON 格式
        let coordString = coordinates[0].map(coord => coord.join(' ')).join(', ');
        return `POLYGON ((${coordString}))`;
    }
}
// 输入wkt 为84，返回wkt为火星坐标（高德）
export function transform(wktData) {
    if (!wktData) return []
    wktData = wktData.replace("SRID=4490;", '')
    // 判断 WKT 数据是 POLYGON 还是 MULTIPOLYGON
    let isMultiPolygon = wktData.startsWith("MULTIPOLYGON");

    // WGS84 转 火星坐标
    let coordinates = wktToCoordinates(wktData);
    let gcj02Coordinates = convertToGCJ02(coordinates);
    let gcj02Wkt = coordinatesToWKT(gcj02Coordinates, isMultiPolygon);
    return gcj02Wkt;
}