(function (window, mars3d) {
  //创建widget类，需要继承BaseWidget
  class MyWidget extends mars3d.widget.BaseWidget {
    //弹窗配置
    get view() {
      return {
        type: "window",
        url: "view.html",
        windowOptions: {
          width: 350,
        },
      };
    }

    //gaodePOI 通过输入名称选点
    queryPOI(text, type) {
      if (!text || !type) {
        return;
      }

      this.gaodePOI.queryText({
        text: text,
        city: "合肥市",
        success: (res) => {
          this.viewWindow.setHtmlInMCXD(res, type); //展示搜索结果
        },
        error: (msg, error) => {
          window.toastr.error(msg);
          haoutil.loading.close();
        },
      });
    }

    //初始化[仅执行1次]
    create() {
      this.gaodeRoute = new mars3d.query.GaodeRoute({
        // key: ['ae29a37307840c7ae4a785ac905927e0'],
      });
      this.gaodePOI = new mars3d.query.GaodePOI({
        // key: ['ae29a37307840c7ae4a785ac905927e0'],
      });

      //图层管理使用的分组
      this.groupLayer = new mars3d.layer.GroupLayer({
        name: this.config.name,
        pid: 99, //图层管理 中使用，父节点id
      });

      //创建矢量数据图层
      this.pointLayer = new mars3d.layer.GraphicLayer({
        name: this.config.name + "-起止点",
      });
      this.groupLayer.addLayer(this.pointLayer); //加入分组

      this.routeLayer = new mars3d.layer.GraphicLayer({
        name: this.config.name + "-路线",
      });
      this.groupLayer.addLayer(this.routeLayer); //加入分组

      //设置路线随机色
      this.randomColor = ["#eaf731", "#57f72e", "#2effd2", "#cc6e26", "#ff2ec7"];
    }
    //每个窗口创建完成后调用
    winCreateOK(opt, result) {
      this.viewWindow = result;
    }
    //打开激活
    activate() {
      this.map.addLayer(this.groupLayer);
    }
    //关闭释放
    disable() {
      if (this.startGraphic) {
        this.startGraphic.remove();
        this.startGraphic = null;
      }
      if (this.endGraphic) {
        this.endGraphic.remove();
        this.endGraphic = null;
      }
      this.map.removeLayer(this.groupLayer);

      this.clearCoumpute();
    }
    //=======================起点===============================
    //绘制起点
    drawStartPoint(callback) {
      if (this.startGraphic) {
        this.startGraphic.remove();
        this.startGraphic = null;
      }

      this.pointLayer.startDraw({
        type: "billboard",
        style: {
          image: this.path + "img/start.png",
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        },
        success: (graphic) => {
          this.startGraphic = graphic;

          if (callback) {
            var point = graphic.point;
            point.format();
            callback(point.lng + "," + point.lat);
          }

          this.startCompute();
        },
      });
    }
    //输入起点坐标
    inputStartPoint(jd, wd) {
      if (!jd || !wd) {
        return;
      }

      let point = [jd, wd];
      if (this.startGraphic) {
        this.startGraphic.position = point;
      } else {
        this.startGraphic = new mars3d.graphic.BillboardEntity({
          position: point,
          style: {
            image: this.path + "img/start.png",
            scale: 1,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            clampToGround: true,
          },
        });
        this.pointLayer.addGraphic(this.startGraphic);
      }

      this.map.flyToPoint(point, { radius: 2500 });

      this.startCompute();
    }
    //查询起点坐标
    queryStartPoint(text) {
      if (!text) {
        window.toastr.error("请输入查询条件！");
        return;
      }
      this.queryPOI(text, "start");
    }
    //=======================终点===============================
    //绘制终点
    drawEndPoint(callback) {
      if (this.endGraphic) {
        this.endGraphic.remove();
        this.endGraphic = null;
      }

      this.pointLayer.startDraw({
        type: "billboard",
        style: {
          image: this.path + "img/end.png",
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        },
        success: (graphic) => {
          this.endGraphic = graphic;

          if (callback) {
            var point = graphic.point;
            point.format();
            callback(point.lng + "," + point.lat);
          }

          this.startCompute();
        },
      });
    }
    //输入终点坐标
    inputEndPoint(jd, wd) {
      if (!jd || !wd) {
        return;
      }

      let point = [jd, wd];
      if (this.endGraphic) {
        this.endGraphic.position = point;
      } else {
        this.endGraphic = new mars3d.graphic.BillboardEntity({
          position: point,
          style: {
            image: this.path + "img/end.png",
            scale: 1,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            clampToGround: true,
          },
        });
        this.pointLayer.addGraphic(this.endGraphic);
      }

      this.map.flyToPoint(point, { radius: 2500 });

      this.startCompute();
    }
    //查询终点坐标
    queryEndPoint(text) {
      if (!text) {
        window.toastr.error("请输入查询条件！");
        return;
      }
      this.queryPOI(text, "end");
    }
    //===================开始计算路线========================
    //清除计算的结果
    clearCoumpute() {
      //清除路线
      this.routeLayer.clear();
      this.viewWindow.clearRouteContent(); //清除页面搜索结果

      //取消当前的视角跟随
      this.removeTrack();

      $("#mapDH_speed").remove();
    }
    //开始计算
    startCompute() {
      if (!this.startGraphic || !this.endGraphic) {
        return;
      }

      //清除上一次的计算结果
      this.clearCoumpute();

      //当两点存在时 自动计算
      this.gaodeRoute.query({
        points: [this.startGraphic.coordinate, this.endGraphic.coordinate],
        type: 3,
        extensions: "all",
        strategy: 11,
        success: (data) => {
          this.viewWindow.startCompute();
          if (!data || data.paths.length < 1) {
            return;
          }
          this.viewWindow.showRouteBox(true);

          //添加速度控制面板
          for (var i = 0; i < data.paths.length; i++) {
            var path = data.paths[i];
            var points = path.points;
            if (!path.steps || path.steps.length < 1 || !points || points.length < 1) {
              continue;
            }

            let graphic = new mars3d.graphic.PolylineEntity({
              positions: points,
              style: {
                clampToGround: true,
                color: this.randomColor[i % 5],
                opacity: 0.8,
                width: 4,
              },
              attr: path,
            });
            this.routeLayer.addGraphic(graphic);

            //漫游路线
            let flyLine = new mars3d.graphic.RoamLine({
              positions: points,
              speed: 200,
              camera: { type: "" },
              model: {
                uri: "//data.mars3d.cn/gltf/mars/qiche.gltf",
                scale: 0.3,
                minimumPixelSize: 30,
                clampToGround: true,
                show: true,
              },
              attr: {
                lineId: graphic.id,
              },
            });
            this.routeLayer.addGraphic(flyLine);

            //展示路径信息
            this.viewWindow.showRouteInfo(graphic.id, path);
          }

          this.routeLayer.flyTo();
        },
      });
    }

    //============= 计算漫游路线 ======================
    getFlylineById(id) {
      return this.routeLayer.getGraphicByAttr("lineId", id);
    }
    roamOneById(id) {
      this.nowFline = this.getFlylineById(id);
      this.nowFline.show = true;
      this.nowFline.start(() => {
        this.reset();
      });
    }

    //漫游自动结束 或点击 停止导航按钮 后，重置界面和操作
    reset() {
      //漫游结束 重置按钮 取消跟随
      this.resetBtn();
      this.removeTrack();

      if (this.nowFline) {
        this.nowFline.show = false;
        this.nowFline = null;
      }

      //重置速度面板
      this.map.clock.multiplier = 1;

      //还原线的高亮
      this.highLightLine();
    }
    //重置按钮
    resetBtn() {
      this.viewWindow.resetButton();
    }
    //取消当前的视角跟随
    removeTrack() {
      if (this.nowFline) {
        this.nowFline.setCameraOptions({ type: "" });
      }
      this.map.trackedEntity = undefined;
    }
    //==============开始导航===================
    startDH(id, isGS) {
      //导航前释放之前的所有导航操作
      this.reset();

      if (!id) {
        return;
      }
      this.roamOneById(id);

      if (isGS) {
        this.nowFline.setCameraOptions({
          type: "gs",
          heading: 0,
          radius: 2500,
        });
      }
    }
    //============开始视角跟随=============
    startGS(id, ele) {
      //判断当前点击的视角跟随的id 是否是已在导航时的id
      if (this.nowFline) {
        //表示已开始漫游即已点击开始导航
        if (this.nowFline.attr.lineId == id) {
          this.nowFline.setCameraOptions({
            type: "gs",
            heading: 0,
            radius: 2500,
          });
        } else {
          window.toastr.error("当前路径沒有车辆运行！");
          if (ele) {
            ele.prop("checked", false);
          }
          return;
        }
      }
    }
    //==================其它方法=====================
    highLightLine(id) {
      if (this.lastRoute) {
        this.lastRoute.entityGraphic.material = this.lastRoute.entityGraphic.material_old;
        this.lastRoute.entityGraphic.width = this.lastRoute.entityGraphic.width_old;
      }

      if (!id) {
        return;
      }

      //动画线材质
      let graphic = this.routeLayer.getGraphicById(id);
      if (!graphic) {
        return;
      }

      if (!graphic.entityGraphic.material_old) {
        graphic.entityGraphic.material_old = graphic.entityGraphic.material;
      }
      if (!graphic.entityGraphic.width_old) {
        graphic.entityGraphic.width_old = graphic.entityGraphic.width;
      }

      graphic.entityGraphic.width = 10;
      graphic.entityGraphic.material = new mars3d.material.LineFlowMaterialProperty({
        color: Cesium.Color.AQUA,
        image: "./img/textures/arrow2.png",
        repeat: new Cesium.Cartesian2(50, 1),
        speed: 40, //速度，建议取值范围1-100
      });

      graphic.flyTo();

      this.lastRoute = graphic;
    }
    resetSpeed(num) {
      if (num == undefined) {
        return;
      }
      this.map.clock.multiplier = num / 120;
    }
  }

  //注册到widget管理器中。
  mars3d.widget.bindClass(MyWidget);

  //每个widet之间都是直接引入到index.html中，会存在彼此命名冲突，所以闭包处理下。
})(window, mars3d);
