<template>
  <div id="viewDiv">
    <div
      id="line-button"
      class="esri-widget esri-widget--button esri-interactive"
      title="画线"
    >
      <span class="esri-icon-polyline"></span>
    </div>
    <div
      id="area-button"
      class="esri-widget esri-widget--button esri-interactive"
      title="画面"
    >
      <span class="esri-icon-polygon"></span>
    </div>
    <div
      id="point-button"
      class="esri-widget esri-widget--button esri-interactive"
      title="画点"
    >
      <span class="esri-icon-radio-checked"></span>
    </div>
    <div
      id="circle-button"
      class="esri-widget esri-widget--button esri-interactive"
      title="画圆"
    >
      <span class="esri-icon-radio-unchecked"></span>
    </div>
    <div
      id="rectangle-button"
      class="esri-widget esri-widget--button esri-interactive"
      title="画矩形"
    >
      <span class="esri-icon-checkbox-unchecked"></span>
    </div>
  </div>
</template>

<script setup lang="ts">
import Map from "@arcgis/core/Map";
import MapView from "@arcgis/core/views/MapView";
import WebTileLayer from "@arcgis/core/layers/WebTileLayer";
import TileInfo from "@arcgis/core/layers/support/TileInfo";
import SpatialReference from "@arcgis/core/geometry/SpatialReference";
import Basemap from "@arcgis/core/Basemap";
import TileLayer from "@arcgis/core/layers/TileLayer.js";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer.js";
import Zoom from "@arcgis/core/widgets/Zoom.js";
import DistanceMeasurement2D from "@arcgis/core/widgets/DistanceMeasurement2D.js";
import Draw from "@arcgis/core/views/draw/Draw.js";
import BasemapToggle from "@arcgis/core/widgets/BasemapToggle.js";
import PolylineDrawAction from "@arcgis/core/views/draw/PolylineDrawAction.js";
import * as geometryEngine from "@arcgis/core/geometry/geometryEngine.js";
import Polyline from "@arcgis/core/geometry/Polyline.js";
import Polygon from "@arcgis/core/geometry/Polygon.js";
import Graphic from "@arcgis/core/Graphic.js";
import Point from "@arcgis/core/geometry/Point.js";
import Circle from "@arcgis/core/geometry/Circle.js";
import Color from "@arcgis/core/Color.js";
import SimpleMarkerSymbol from "@arcgis/core/symbols/SimpleMarkerSymbol.js";
import BufferParameters from "@arcgis/core/rest/support/BufferParameters.js";
import Sketch from "@arcgis/core/widgets/Sketch.js";
import SketchViewModel from "@arcgis/core/widgets/Sketch/SketchViewModel.js";

import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer.js";
import { ref, onMounted } from "vue";
const splitvalue = ref(0.2);
let tileInfo = new TileInfo({
  dpi: 90.71428571427429, // 切片方案的每英寸点数（即像素）。
  size: 256, // 设置每个瓷砖的高度和宽度为[256, 256]像素。
  origin: {
    // 切片方案的原点。
    type: "point",
    x: -180,
    y: 90,
    spatialReference: { wkid: 4326 },
  },
  spatialReference: { wkid: 4326 },
  lods: [
    // 定义平铺方案的详细级别数组。
    {
      level: 2,
      levelValue: 2,
      resolution: 0.3515625,
      scale: 147748796.52937502,
    },
    {
      level: 3,
      levelValue: 3,
      resolution: 0.17578125,
      scale: 73874398.264687508,
    },
    {
      level: 4,
      levelValue: 4,
      resolution: 0.087890625,
      scale: 36937199.132343754,
    },
    {
      level: 5,
      levelValue: 5,
      resolution: 0.0439453125,
      scale: 18468599.566171877,
    },
    {
      level: 6,
      levelValue: 6,
      resolution: 0.02197265625,
      scale: 9234299.7830859385,
    },
    {
      level: 7,
      levelValue: 7,
      resolution: 0.010986328125,
      scale: 4617149.8915429693,
    },
    {
      level: 8,
      levelValue: 8,
      resolution: 0.0054931640625,
      scale: 2308574.9457714846,
    },
    {
      level: 9,
      levelValue: 9,
      resolution: 0.00274658203125,
      scale: 1154287.4728857423,
    },
    {
      level: 10,
      levelValue: 10,
      resolution: 0.001373291015625,
      scale: 577143.73644287116,
    },
    {
      level: 11,
      levelValue: 11,
      resolution: 0.0006866455078125,
      scale: 288571.86822143558,
    },
    {
      level: 12,
      levelValue: 12,
      resolution: 0.00034332275390625,
      scale: 144285.93411071779,
    },
    {
      level: 13,
      levelValue: 13,
      resolution: 0.000171661376953125,
      scale: 72142.967055358895,
    },
    {
      level: 14,
      levelValue: 14,
      resolution: 8.58306884765625e-5,
      scale: 36071.483527679447,
    },
    {
      level: 15,
      levelValue: 15,
      resolution: 4.291534423828125e-5,
      scale: 18035.741763839724,
    },
    {
      level: 16,
      levelValue: 16,
      resolution: 2.1457672119140625e-5,
      scale: 9017.8708819198619,
    },
    {
      level: 17,
      levelValue: 17,
      resolution: 1.0728836059570313e-5,
      scale: 4508.9354409599309,
    },
    {
      level: 18,
      levelValue: 18,
      resolution: 5.3644180297851563e-6,
      scale: 2254.4677204799655,
    },
    {
      level: 19,
      levelValue: 19,
      resolution: 2.68220901489257815e-6,
      scale: 1127.23386023998275,
    },
    {
      level: 20,
      levelValue: 20,
      resolution: 1.341104507446289075e-6,
      scale: 563.616930119991375,
    },
  ],
});
let tk = "0eab750b26cdeee155e8c4f2310b53ef";
// 1.矢量底图(T=vec_c) vectorBasemap
let vectorBasemapLayer = new WebTileLayer({
  id: "vectorBasemapMap",
  title: "vectorBasemapMap",
  spatialReference: {
    wkid: 4326,
  },
  urlTemplate:
    "http://{subDomain}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=" +
    tk,
  subDomains: ["t0"],
  tileInfo: tileInfo,
});
// 2.矢量注记(T=cva_c) vectorNote
let vectorNoteLayer = new WebTileLayer({
  id: "vectorNoteMap",
  title: "vectorNoteMap",
  spatialReference: {
    wkid: 4326,
  },
  urlTemplate:
    "http://{subDomain}.tianditu.gov.cn/cva_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=" +
    tk,
  subDomains: ["t0"],
  tileInfo: tileInfo,
});

// 3.影像底图(T=img_c) imageBasemap
let imageBasemapLayer = new WebTileLayer({
  urlTemplate:
    "http://{subDomain}.tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=" +
    tk,
  subDomains: ["t0"],
  spatialReference: {
    wkid: 4326,
  },
  tileInfo: tileInfo,
});
// 4.影像注记(T=cia_c) imageNote
let imageNoteLayer = new WebTileLayer({
  id: "imageNoteMap",
  title: "imageNoteMap",
  urlTemplate:
    "http://{subDomain}.tianditu.gov.cn/cia_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=" +
    tk,
  subDomains: ["t0"],
  spatialReference: {
    wkid: 4326,
  },
  tileInfo: tileInfo,
});

// 5.地形晕渲(T=ter_c) terrainShading。
let terrainShadingLayer = new WebTileLayer({
  urlTemplate:
    "http://{subDomain}.tianditu.gov.cn/ter_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=" +
    tk,
  subDomains: ["t0"],
  spatialReference: {
    wkid: 4326,
  },
  // 该层的平铺方案信息。
  tileInfo: tileInfo,
});
// 6.地形注记(T=cta_c) terrainNote
let terrainNoteLayer = new WebTileLayer({
  id: "terrainNoteMap",
  title: "terrainNoteMap",
  urlTemplate:
    "http://{subDomain}.tianditu.com/DataServer?T=cta_c&x={col}&y={row}&l={level}&tk=" +
    tk,
  subDomains: ["t0"],
  spatialReference: {
    wkid: 4326,
  },
  tileInfo: tileInfo,
});

// 7.全球境界(T=ibo_c) globalRealm。
let globalRealmLayer = new WebTileLayer({
  urlTemplate:
    "http://{subDomain}.tianditu.com/DataServer?T=ibo_c&X={col}&Y={row}&L={level}&tk=" +
    tk,
  subDomains: ["t0"],
  spatialReference: {
    wkid: 4326,
  },
  // 该层的平铺方案信息。
  tileInfo: tileInfo,
});

onMounted(() => {
  let map = new Map({
    basemap: {
      baseLayers: [imageBasemapLayer,imageNoteLayer, ],

    },
    slider:false
  });
  //匹配一个验证手机的正则



  let view = new MapView({
    container: "viewDiv",
    map: map,
    spatialReference: {
      wkid: 4326,
    },

    center: [118.85722842688202, 33.26485279059861],
    zoom: 15,
  });
  view.ui.add("line-button", "top-right"); //添加绘制线按钮，自定义UI
  view.ui.add("area-button", "top-right"); //添加绘制面按钮，自定义UI
  view.ui.add("point-button", "top-right"); //添加绘制面按钮，自定义UI
  view.ui.add("circle-button", "top-right"); //添加绘制面按钮，自定义UI
  view.ui.add("rectangle-button", "top-right"); //添加绘制面按钮，自定义UI
  view.ui.remove("attribution"); //移除底部ESRI logo
view.ui.remove("zoom"); //移除

  var imgLayer = new TileLayer({
    id: "11",
    url: "http://139.224.252.239:6080/arcgis/rest/services/MyMapService1/MapServer",
  });

  map.add(imgLayer);
  let zoom = new Zoom({
    view: view,
  });

  let draw = new Draw({
    view: view,
  });
  // var basemapToggle = new BasemapToggle({
  //   view: view,
  //   nextBasemap: "streets",
  // });
  // view.ui.add(basemapToggle, "bottom-right");

  //设置图层标注
  let image = {
    type: "picture-marker",
    url: "http://localhost:5173/src/assets/logo.png",
    width: 32,
    height: 32,
  };
  //设置点的位置
  let position = {
    type: "point",
    longitude: "118.8561031602072",
    latitude: "33.26579051282762",
  };
  //将点的样式和位置放到Graphic里面
  let Graphic1 = new Graphic({
    geometry: position,
    symbol: image,
  });

  let highlight;
  view.on("click", function (event) {
    console.log(event);
    if (highlight) {
      height.remove();
    }
    view.hitTest(event).then(function (response) {
      if (response.result && response.result[0]) {
        var graphic = response.result[0].graphic;
        console.log(graphic);
        view.whenLayerView(graphic.layer).then(function (lyrView) {
          highlight = lyrView.highlight(graphic);
        });
      }
    });
  });
  var polySym = {
    type: "simple-fill", // autocasts as new SimpleFillSymbol()
    color: [140, 140, 222, 0.5],
    outline: {
      color: [0, 0, 0, 0.5],
      width: 2,
    },
  };
  view.when(function () {
    var draw = new Draw({
      view: view,
    });
    //绑定线按钮绘制事件
    var drawLineButton = document.getElementById("line-button");
    drawLineButton.onclick = function () {
      // view.graphics.removeAll(); //清楚之前的绘制
      enableCreateLine(draw, view);
    };
    //绑定面按钮绘制事件
    var drawAreaButton = document.getElementById("area-button");
    drawAreaButton.onclick = function () {
      view.graphics.removeAll(); //清楚之前的绘制
      enableCreateArea(draw, view);
    };
    //绑定面按钮绘制事件
    var drawPointButton = document.getElementById("point-button");
    drawPointButton.onclick = function () {
      enableCreatePoint(draw, view);
    };
    //绑定面按钮绘制事件
    var drawCircleButton = document.getElementById("circle-button");
    drawCircleButton.onclick = function () {
      enableCreateCircle(draw, view);
    };
    //绑定面按钮绘制事件
    var drawRectangleButton = document.getElementById("rectangle-button");
    drawRectangleButton.onclick = function () {
      enableCreateRectangle(draw, view);
    };
  });
  //开始监听画线
  function enableCreateLine(draw, view) {
    var action = draw.create("polyline", {
      mode: "click",
    });
    // 获取焦点
    view.focus();

    // 顶点添加事件
    action.on("vertex-add", createPolyline);

    //顶点移除事件
    action.on("vertex-remove", createPolyline);

    // 鼠标移动事件
    action.on("cursor-update", createPolyline);

    // 绘制完成事件
    action.on("draw-complete", createPolyline);
  }
  //开始监听画面
  function enableCreateArea(draw, view) {
    var action = draw.create("polygon", {
      mode: "click", //点击方式加点
    });
    // 获取焦点
    view.focus();

    // 顶点添加事件
    action.on("vertex-add", createPolygon);

    //顶点移除事件
    action.on("vertex-remove", createPolygon);

    // 鼠标移动事件
    action.on("cursor-update", createPolygon);

    // 绘制完成事件
    action.on("draw-complete", createPolygon);
  }
  //开始监听画点
  function enableCreatePoint(draw, view) {
    var action = draw.create("point", {
      mode: "click", //点击方式加点
    });
    // 获取焦点
    view.focus();

    // 顶点添加事件
    action.on("vertex-add", createPoint);

    //顶点移除事件
    action.on("vertex-remove", createPoint);

    // 绘制完成事件
    action.on("draw-complete", createPoint);
  }
  //开始监听画圆
  function enableCreateCircle(draw, view) {
    var action = draw.create("circle", {
      mode: "click", //点击方式加点
    });
    // 获取焦点
    view.focus();
    //顶点移除事件
    action.on("vertex-remove", createCircle);
    // 鼠标移动事件
    action.on("cursor-update", createCircle);
    // 绘制完成事件
    action.on("draw-complete", createCircle);
  }
  //开始监听画矩形
  function enableCreateRectangle(draw, view) {
    var action = draw.create("rectangle", {
      mode: "click", //点击方式加点
    });
    // 获取焦点
    view.focus();

    //顶点移除事件
    action.on("vertex-remove", createRectangle);
    // 鼠标移动事件
    action.on("cursor-update", createRectangle);
    // 绘制完成事件
    action.on("draw-complete", createRectangle);
  }
  let graphic111=null
  //根据点坐标生成新的线
  function createPolyline(event) {
    //获取所有顶点
    var vertices = event.vertices;
    //清除之前绘制
   view.graphics.remove(graphic111);
    var line = new Polyline({
      paths: vertices,
      spatialReference: view.spatialReference,
    });
    // 生成绘制的图形
    graphic111 = new Graphic({
      geometry: line,
      attributes:{
         name: "line"
      },
      symbol: {
        type: "simple-line", // autocasts as new SimpleFillSymbol
        color: [4, 90, 141],
        width: 10,
        cap: "round",
        join: "round",
      },
    });
    // 将绘制的图形添加到view
    view.graphics.add(graphic111);
    if (event.type == "draw-complete") {
      createBuffer(line);
    }
  }
  //根据点坐标生成新的线
  function createPolygon(event) {
    //获取所有顶点
    var vertices = event.vertices;
    //清除之前绘制
    view.graphics.removeAll();
    var polygon = new Polygon({
      hasZ: false,
      hasM: false,
      rings: [vertices],
      spatialReference: view.spatialReference,
    });
    // 生成绘制的图形
    var graphic = new Graphic({
      geometry: polygon,
      symbol: {
        type: "simple-fill", // autocasts as new SimpleFillSymbol()
        color: [51, 51, 204, 0.9],
        style: "solid",
        outline: {
          // autocasts as new SimpleLineSymbol()
          color: "white",
          width: 1,
        },
      },
    });
    // 将绘制的图形添加到view
    view.graphics.add(graphic);
    if (event.type == "draw-complete") {
      createBuffer(polygon);
    }
  }

  //根据点坐标生成新的线
  function createPoint(event) {
    //获取所有顶点
    var coordinates = event.coordinates;
    var point = new Point({
      hasZ: false,
      hasM: false,
      x: coordinates[0],
      y: coordinates[1],
      spatialReference: view.spatialReference,
    });
    //生成绘制的图形
    var graphic = new Graphic({
      geometry: point,
      symbol: {
        type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
        style: "square",
        color: "blue",
        size: "8px", // pixels
        outline: {
          // autocasts as new SimpleLineSymbol()
          color: [255, 255, 0],
          width: 3, // points
        },
      },
    });
    // 将绘制的图形添加到view
    view.graphics.add(graphic);
    if (event.type == "draw-complete") {
      createBuffer(point);
    }
  }
  //根据点坐标生成新的线
  function createCircle(event) {
    //获取所有顶点
    var vertices = event.vertices;
    //少于一个点无法展示圆
    if (vertices.length < 2) {
      return;
    }
    //清除之前绘制
    view.graphics.removeAll();
    //生成绘制的图形,两点画圆
    var center = new Point({
      hasZ: false,
      hasM: false,
      x: vertices[0][0],
      y: vertices[0][1],
      spatialReference: view.spatialReference,
    });
    var dis = center.distance(
      new Point({
        hasZ: false,
        hasM: false,
        x: vertices[1][0],
        y: vertices[1][1],
        spatialReference: view.spatialReference,
      })
    );
    var circle = new Circle({
      hasZ: false,
      hasM: false,
      center: center,
      radius: dis,
      spatialReference: view.spatialReference,
    });
    var graphic = new Graphic({
      geometry: circle,
      symbol: {
        type: "simple-fill", // autocasts as new SimpleFillSymbol()
        color: [51, 51, 204, 0.9],
        style: "solid",
        outline: {
          // autocasts as new SimpleLineSymbol()
          color: "white",
          width: 1,
        },
      },
    });
    // 将绘制的图形添加到view
    view.graphics.add(graphic);
    if (event.type == "draw-complete") {
      createBuffer(circle);
    }
  }
  function createRectangle(event) {
    //获取所有顶点
    var vertices = event.vertices;

    //两点画矩形
    if (vertices.length < 2) {
      return;
    }
    var rings = [
      vertices[0],
      [vertices[0][0], vertices[1][1]],
      vertices[1],
      [vertices[1][0], vertices[0][1]],
    ];
    //清除之前绘制
    view.graphics.removeAll();
    var polygon = new Polygon({
      hasZ: false,
      hasM: false,
      rings: [rings],
      spatialReference: view.spatialReference,
    });
    // 生成绘制的图形
    var graphic = new Graphic({
      geometry: polygon,
      symbol: {
        type: "simple-fill", // autocasts as new SimpleFillSymbol()
        color: [51, 51, 204, 0.9],
        style: "solid",
        outline: {
          // autocasts as new SimpleLineSymbol()
          color: "white",
          width: 1,
        },
      },
    });
    // 将绘制的图形添加到view
    view.graphics.add(graphic);
    console.log(event);
    if (event.type == "draw-complete") {
      createBuffer(polygon);
    }
  }
  function createBuffer(geometry) {
    // var buffer=geometryEngine.geodesicBuffer(geometry,150,"kilometers",false);
    // var buffer = geometryEngine.buffer(geometry, 150, "kilometers", false);
    // view.graphics.add(
    //   new Graphic({
    //     geometry: buffer,
    //     symbol: polySym,
    //   })
    // );
  }
const polygonSymbol = {
  type: "simple-fill", // autocasts as new SimpleFillSymbol()
  color: "#F2BC94",
  outline: {
    // autocasts as new SimpleLineSymbol()
    color: "#722620",
    width: 3
  }
};
let graphicsLayer = new GraphicsLayer()
  const sketch = new SketchViewModel({
          layer: graphicsLayer,
          view: view,
          polygonSymbol: polygonSymbol,
          // graphic will be selected as soon as it is created
          creationMode: "update"
        });

let path =[[118.8558727484595,33.26739267823606],[118.85748027228067,33.265345764570434]]
  createPolylineGraphic(path)
  function createPolylineGraphic(vertices){
    console.log(JSON.stringify(vertices))
    view.graphics.removeAll();
    let polyline = {
      type: "polyline", // autocasts as Polyline
      paths: vertices,
      spatialReference: view.spatialReference
    };

  //   let graphic = new Graphic({
  //     geometry: polyline,
  //     attributes:{
  //        name: "polyline"
  //     },
  //     symbol: symbol
  //  });
  	var _sr4326 = new SpatialReference({wkid: 4326 });


  }
});
</script>

<style scoped lang="scss">
#viewDiv {
  width: 100%;
  height: 100%;
}

:deep(.esri-view .esri-view-surface:focus::after){
  outline: none !important;
}


</style>
