
/*
TODO 修改完成
*/

import * as geometric from "geometric";
import * as turf from 'turf';
import { LMConfig } from "@zenview/micro-basic-library";

/**
 *  判断一个点是否在多边形内部
 *  @param points 多边形坐标集合
 *  @param testPoint 测试点坐标
 *  返回true为真，false为假
 *  */



export function insidePolygon(testPoint, points) {
  return geometric.pointInPolygon(testPoint, points);
}

/**
 *  判断一个点是否在圆的内部
 *  @param point  测试点坐标
 *  @param circle 圆心坐标
 *  @param r 圆半径
 *  返回true为真，false为假
 *  */

export function pointInsideCircle(point, circle, r) {
  if (r === 0) {
    return false;
  }
  let dx = circle[0] - point[0];
  let dy = circle[1] - point[1];
  return dx * dx + dy * dy <= r * r;
}

export function polygonIntersectsPolygons(polygonA, paths) {
  if (!Array.isArray(paths) || paths.length === 0) {
    return false;
  }
  const polygons =
    paths.length === 1
      ? paths[0].split("|").map(path2 => path2.split(";").map(v => v.split(",").reverse()))
      : paths.reduce((prev, next) => {
          if (!Array.isArray(prev)) {
            return prev.split("|").map(path2 => path2.split(";").map(v => v.split(",")));
          }
          const nextPath = next.split("|").map(path2 => path2.split(";").map(v => v.split(",")));
          return [].concat(prev, ...nextPath);
        });
  const checkeds = polygons.map(v => geometric.polygonIntersectsPolygon(polygonA, v) || geometric.polygonInPolygon(v, polygonA));
  return checkeds.filter(v => v).length > 0;
}

export function polygonInPolygon(polygonB, path) {
  let pathArr = [];
  if (typeof path === "string") {
    pathArr = path.split("|").map(path2 => path2.split(";").map(v => v.split(",").map(v => +v).reverse()));
  }
  return !!pathArr.find(v => geometric.polygonInPolygon(polygonB, v));
}

export function pointInBuffer(point, buffer) {
  const pt = turf.point(point);
  const poly = turf.polygon(buffer);
  return turf.booleanPointInPolygon(pt, poly);
}

/**
 * 判断经纬度是否合理，依据传递过来的bounds，默认读取LMapConfig中的bounds
 * add by zhangyu 2020.06.18  fix bug[8228]
 *
 * @param      {number}   lat     待检测的纬度
 * @param      {number}   lon     待检测的经度
 * @param      {<type>}   bounds  检测范围，读取全局配置的maxBounds，如果没有配置，默认中国范围内
 * @return     {boolean}  是否在这个范围内
 */
export function validLatLon(lat, lon, bounds = LMConfig?.LMapConfig?.maxBounds || [[3.31743, 66.749529], [56.353861, 138.55617]]) {
  return lat >= bounds[0][0] && lat <= bounds[1][0] && lon >= bounds[0][1] && lon <= bounds[1][1];
}