import { Dict, LMConfig } from '@zenview/micro-basic-library';

export const searchRouteByMultiPoints = ({ points, map, successCallBack, errorCallback, lineCallBack }) => {
  const { ZenMap, WKT } = window;
  var service = new ZenMap.Services.RouteService(map, ZenMap.MAPTYPE_GEOSERVER);
  var params = new ZenMap.Services.routeParams();
  let routeMultiService = null;
  const CustomConfig = LMConfig.CustomConfig?.ZenMap || null;
  // let url = CustomConfig?.vectorLayer[0].layerOpt.url[0].split('mapbox')[0];
  var stops = '';
  for (var i = 0; i < points.length; i++) {
    stops += points[i].lon + ',' + points[i].lat + ';';
  }
  stops = stops.substr(0, stops.length - 1);
  params.stops = stops;
  if (routeMultiService) {
    routeMultiService.abort();
    routeMultiService = null;
  }
  routeMultiService = service.routeByMultPoints(
   "/zenmapdataservice/gis/routing",
    params,
    function (infos) {
      if (infos && infos instanceof Array) {
        var myPoints = [];
        var t = new ZenMap.GisToolKit();
        for (var i = 0; i < infos.length; i++) {
          let haveData = true;
          if (+infos[i].length === 0) {
            haveData = false;
          }
          var pstr = infos[i].expend.split(';');
          var tempPoints = []; //参与抽稀
          for (var j = 0; j < pstr.length; j++) {
            var xy = haveData ? pstr[j].split(',') : pstr[j].slice(6, -1).split(' ');
            var x = parseFloat(xy[0]);
            var y = parseFloat(xy[1]);
            tempPoints.push(new ZenMap.Geometry.Point(x, y));
          }
          //抽稀后
          tempPoints = t.covertLine(tempPoints, 175);

          for (var j = 0; j < tempPoints.length; j++) {
            let pointItem = tempPoints[j];
            if (j === 0) {
              // 每段起始点
              pointItem.imageUrl = points[i].imageUrl;
              pointItem.topIndex = points[i].topIndex;
            }

            if (points.length > 2) {
              if (i === infos.length - 1 && j === tempPoints.length - 1) {
                pointItem.imageUrl = points[i + 1].imageUrl;
                pointItem.topIndex = points[i + 1].topIndex;
              }
            } else {
              pointItem.imageUrl = points[i].imageUrl;
              pointItem.topIndex = points[i].topIndex;
            }

            myPoints.push(pointItem);
          }
        }
        successCallBack && successCallBack(myPoints);
        if (lineCallBack) {
          var polyline = new ZenMap.Geometry.Polyline(myPoints, {
            color: 'blue', //颜色
            weight: 5, //宽度，以像素为单位
            opacity: 2, //透明度，取值范围0 - 1
            lineStyle: ZenMap.LINE_TYPE_SOLID, //样式
          });
          lineCallBack && lineCallBack(polyline);
        } else {
          return;
        }
      }
    },
    errorCallback
  );
};
