import Map from "@arcgis/core/Map";
import MapView from "@arcgis/core/views/MapView";
import TianData from './Tmap'
import TileInfo from "@arcgis/core/layers/support/TileInfo";
import WebTileLayer from "@arcgis/core/layers/WebTileLayer";
import TileLayer from "@arcgis/core/layers/TileLayer.js";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer.js";
import Draw from "@arcgis/core/views/draw/Draw.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 GraphicsLayer from "@arcgis/core/layers/GraphicsLayer.js";
import SketchViewModel from "@arcgis/core/widgets/Sketch/SketchViewModel.js";
import useMapDataStore from "@map/store/modules/mapData"
import useMapLogStore from "@map/store/modules/mapLog"
import * as webMercatorUtils from "@arcgis/core/geometry/support/webMercatorUtils.js";
import * as geometryEngine from "@arcgis/core/geometry/geometryEngine.js";
import CIMSymbol from "@arcgis/core/symbols/CIMSymbol.js";
import * as geodesicUtils from "@arcgis/core/geometry/support/geodesicUtils.js";
import MapNotesLayer from "@arcgis/core/layers/MapNotesLayer.js";
import DistanceMeasurement2D from "@arcgis/core/widgets/DistanceMeasurement2D.js";
import * as print from "@arcgis/core/rest/print.js";
import PrintTemplate from "@arcgis/core/rest/support/PrintTemplate.js";
import PrintParameters from "@arcgis/core/rest/support/PrintParameters.js";
import * as turf from '@turf/turf'

import emitter from "../emitter";

const symbolData = {
  House: [255, 0, 0, 0.6],
  Road: [118, 116, 218, 0.9],
  River: [94, 208, 81, 0.9]
}

let mapLog = ''
let logOldGeometry = []

let self = '';
const ldMap = {
  map: '',
  view: '',
  nowlayer: '',
  sketchLayer: {
    pointLayer: '',
    polylineLayer: '',
    polygonLayer: '',
    selectGraphic: null
  },
  pointSketchViewModel: '',
  polygonSketchViewModel: '',
  polylineSketchViewModel: '',
  addGraphicType: '',
  lineLayer: '',
  count: 0,
  lighHight: null,
  selectLine: null,
  draw: null,
  DrawstartPoint: [],
  DrawenedPoint: [],
  DrawDregType: null,
  textLayer: null,
  loadelevationLayer: null,
  ldMapActionType: '',
  printExcent: '',
  pointSketchType: 'Station',
  drawTypeLine: '',// 划线是一条还是多条
  newDrawLineByClick: '',
  pointMaxIndex: -1,
  hightlayer: '',
  pngLayer: null,
  selectPng: '',
  wkid: null,
  //初始化地图
  initMap: function (wkid) {

    self = this;
    return new Promise((resolve, reject) => {

      if(wkid==self.wkid){
        resolve()

      }else{
        let tileInfo = new TileInfo(TianData.infoData(wkid));
        self.wkid = wkid
        let defaultInfo = {
          subDomains: ["t1"],
          spatialReference: {
            wkid: wkid,
          },
          tileInfo: tileInfo,
        }
        let imageBasemapLayer = new WebTileLayer({
          ...defaultInfo,
          urlTemplate: TianData.img_c
        })
        let imageNoteLayer = new WebTileLayer({
          ...defaultInfo,
          urlTemplate: TianData.cia_c
        })


        this.map = new Map({
          basemap: {
            baseLayers: [imageBasemapLayer, imageNoteLayer],
          },
          slider: false
        });


        let lodsView = [
          { level: 0, resolution: 156543.033928, scale: 591657527.591555 },
          { level: 1, resolution: 78271.5169639999, scale: 295828763.795777 },
          { level: 2, resolution: 39135.7584820001, scale: 147914381.897889 },
          { level: 3, resolution: 19567.8792409999, scale: 73957190.948944 },
          { level: 4, resolution: 9783.93962049996, scale: 36978595.474472 },
          { level: 5, resolution: 4891.96981024998, scale: 18489297.737236 },
          { level: 6, resolution: 2445.98490512499, scale: 9244648.868618 },
          { level: 7, resolution: 1222.99245256249, scale: 4622324.434309 },
          { level: 8, resolution: 611.49622628138, scale: 2311162.217155 },
          { level: 9, resolution: 305.748113140558, scale: 1155581.108577 },
          { level: 10, resolution: 152.874056570411, scale: 577790.554289 },
          { level: 11, resolution: 76.4370282850732, scale: 288895.277144 },
          { level: 12, resolution: 38.2185141425366, scale: 144447.638572 },
          { level: 13, resolution: 19.1092570712683, scale: 72223.819286 },
          { level: 14, resolution: 9.55462853563415, scale: 36111.909643 },
          { level: 15, resolution: 4.77731426794937, scale: 18055.954822 },
          { level: 16, resolution: 2.38865713397468, scale: 9027.977411 },
          { level: 17, resolution: 1.19432856685505, scale: 4513.988705 },
          { level: 18, resolution: 0.597164283559817, scale: 2256.994353 },
          { level: 19, resolution: 0.298582141647617, scale: 1128.497176 },
          { level: 20, resolution: 0.14929107082380833, scale: 564.248588 },
          { level: 21, resolution: 0.07464553541190416, scale: 282.124294 },
          { level: 22, resolution: 0.03732276770595208, scale: 141.062147 },
          { level: 23, resolution: 0.01866138385297604, scale: 70.5310735 },
        ]







        this.view = new MapView({
          container: "viewDiv",
          map: this.map,
          spatialReference: {
            wkid: wkid,
          },
          constraints: {
            lods: lodsView,
            rotationEnabled: false,
            minZoom: 0,
            maxZoom: 50
          },
          center: [116.85722842688202, 39.26485279059861],
          zoom: 15,
        });
        let measurementWidget = new DistanceMeasurement2D({
          view: this.view
        });
        // this.view.ui.add(measurementWidget, "bottom-right");

        self.view.on("drag", function (event) {
          if (event.button == 2 && self.DrawDregType && self.ldMapActionType == 'regectionAction') {
            console.log(event)
            let point = self.view.toMap({ x: event.x, y: event.y });
            if (event.action == 'start') {
              // self.DrawLine()
              self.DrawstartPoint = [point.x, point.y];
            }
            if (event.action == 'end') {
              self.Bindpolygon()
              self.view.graphics.removeAll();
            }
            if (event.action == 'update') {
              // self.destroyDraw()
              self.DrawenedPoint = [point.x, point.y];
              let data = {
                vertices: [self.DrawstartPoint, self.DrawenedPoint]
              }
              self.createPolygon(data)
            }

          }


        });
        mapLog = useMapLogStore()
        self.view.ui.remove("zoom"); //移除
        self.view.ui.remove("attribution"); //移除底部ESRI logo bb

        self.view.on("click", (event) => {

          console.log(event)
          if (self.popup) {
            self.popup.remove()
          }
          if (self.hightlayer) {

            self.hightlayer.removeAll()
          }

          self.view.hitTest(event).then((response) => {

            self.lighHight?.remove();
            self.selectLine = ''
            self.selectPng = ''
            if (response.results && response.results[0]) {
              var graphic = response.results[0].graphic;
              console.log(graphic)
              if (self.ldMapActionType == 'lineAction') {
                if (graphic.geometry.type == "polyline") {
                  self.view.whenLayerView(graphic.layer).then((layerView) => {

                    emitter.emit('line', graphic.attributes.data)
                    self.selectLine = graphic
                    self.lighHight = layerView.highlight(graphic)

                  })

                }




              }
              if (graphic.attributes?.type == 'qdf') {
                self.view.whenLayerView(graphic.layer).then((layerView) => {
                  self.selectPng = graphic
                  self.lighHight = layerView.highlight(graphic)
                })

              }
            }


          });
        });
        self.view.watch("zoom", function (newValue, oldValue, propertyName, target) {

          if (Number.isInteger(newValue)) {
            console.info(newValue);
            self.showeleByzoom(newValue)
          }
        });
        //文字

        self.view.when(e => {
          // const print = new Print({
          //   view: self.view,
          //   // specify your own print service
          //   printServiceUrl:
          //   "http://139.224.252.239:6080/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task"
          // });

          // // Add widget to the top right corner of the view
          // self.view.ui.add(print, "top-right");
          resolve()
        })


      }


    })

  },
  async arcgisPrint() {

    const url = "http://139.224.252.239:6080/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task"
    await self.setCenter(self.nowlayer.fullExtent.center.x, self.nowlayer.fullExtent.center.y, 18)

    let { width, height } = self.nowlayer.fullExtent
    let { metersPerUnit } = self.nowlayer.fullExtent.spatialReference
    width = width * metersPerUnit * 3
    height = height * metersPerUnit * 3
    const template = new PrintTemplate({
      format: 'PNG32',
      exportOptions: {
        width,
        height,
        dpi: 180,
      },
      layout: "map-only",
    })
    const params = new PrintParameters({
      view: self.view,
      template: template,
    })
    print.execute(url, params).then(result => {
      console.log(result.url);
      window.open(result.url);
    }).catch(err => {
      console.log("Something broke: ", err);
    });
  },
  noteSlayerInit() {


    self.sketchLayer = new MapNotesLayer();
    self.sketchLayer.isCreate = true
    self.view.map.add(self.sketchLayer, 1)
    self.textLayer = new GraphicsLayer()

    self.pngLayer = new GraphicsLayer()
    self.loadelevationLayer = new GraphicsLayer()
    self.map.add(self.textLayer, 10)
    self.map.add(self.pngLayer, 11)
    self.map.add(self.loadelevationLayer, 10)
    self.initSketch()
  },
  removeAll() {
    self.view.map.removeAll();
  },
  addLayer: function (e) {

    self.removeAll();
    let data = {
      id: "layerName",
      url: '',
      ...e,
      spatialReference: {
        wkid: self.wkid,
      },
    }
    var imgLayer = new TileLayer(data);

    this.map.add(imgLayer);

    imgLayer.when((e) => {
      self.nowlayer = e
      self.setCenter(e.fullExtent.center.x, e.fullExtent.center.y)
    })
    self.view.whenLayerView(imgLayer).then(function (layerView) {
      // self.nowlayer = layerView
    })

    self.noteSlayerInit()
    return data.id;
  },
  removeLayer: function (e) {
    this.map.remove(this.map.findLayerById(e))
  },
  setCenter: function (x, y, zoom) {
    if (!zoom) {
      zoom = this.view.zoom > 18 ? this.view.zoom : 18
    }
    return new Promise((resolve, reject) => {
      this.view.goTo({
        center: [x, y],
        zoom,
      }).then(res => {

        resolve()
      });
    })

  },
  //添加文字标注
  addTextFeature(text, id,) {
    const textSymbol = {
      type: "text", // autocasts as new TextSymbol()
      angle: 90,
      color: "green",
      font: {
        // autocast as new Font()
        family: "Just Another Hand",
        size: 12
      },
      haloColor: "black",
      haloSize: 1,
      horizontalAlignment: "right",
      verticalAlignment: "bottom"
    };

  },
  //高亮某个数据（未到终点的线）
  hightLineLayer(data) {

    let path = []
    if (!self.hightlayer) {
      self.hightlayer = new GraphicsLayer();
      self.map.add(self.hightlayer)
    }

    data.forEach(item => {

      return path.push([item[0], item[1]])
    })

    let linelayer = new Polyline({
      paths: path,
    })

    const graphic = new Graphic({
      geometry: linelayer,

      symbol: {
        type: "simple-line",
        width: 5,
        color: "red",
      },

    });
    self.hightlayer.add(graphic)



    // console.log(newPointGraphic)
  },
  //计算两点之间的距离
  distance: function (p1, p2) {

    let polyline = new Polyline({
      paths: [[p1[0], p1[1]], [p2[0], p2[1]]],
    })
    length = geometryEngine.geodesicLength(polyline, "meters");

    return length.toFixed(2)
  },

  initSketch() {

    let count = 0;
    const pointLayer = self.sketchLayer.pointLayer;
    const polylineLayer = self.sketchLayer.polylineLayer;
    const polygonLayer = self.sketchLayer.polygonLayer;
    self.pointSketchViewModel = createSketchSketchViewModelPoint(pointLayer)
    self.polygonSketchViewModel = createSketchSketchViewModel(polygonLayer)
    self.polylineSketchViewModel = createSketchSketchViewModel(polylineLayer);
    function createSketchSketchViewModel(layer) {

      const sketchVM = new SketchViewModel({
        view: self.view,
        layer,
        updateOnGraphicClick: true,
        defaultStyle: {
          point: {
            type: "simple-marker",
            color: "[0, 0, 0, 1]",
            outline: {
              color: "[255, 255, 255, 1]",
              width: 1
            },
            size: "5px"
          },
        },
        defaultUpdateOptions: {


          highlightOptions: {
            enabled: false,
          },
          enableScaling: false,

          tool: 'reshape',
          reshapeOptions: {
            edgeOperation: 'none',
            shapeOperation: 'none'
          }
        },
      });

      sketchVM.on("create", addGraphic);
      sketchVM.on("update", selectData)


      return sketchVM;
    }
    function createSketchSketchViewModelPoint(layer) {

      const sketchVM = new SketchViewModel({
        view: self.view,
        layer,
        updateOnGraphicClick: true,
        defaultStyle: {
          point: {
            type: "simple-marker",
            color: "[0, 0, 0, 1]",
            outline: {
              color: "[255, 255, 255, 1]",
              width: 1
            },
            size: "5px"
          },
        },
        defaultUpdateOptions: {


          highlightOptions: {
            enabled: true,
          },

          toggleToolOnClick: false,
          tool: 'move',
          reshapeOptions: {
            edgeOperation: 'none',
            shapeOperation: 'move-xy'
          }
        },
      });
      sketchVM.on("create", addGraphic);
      sketchVM.on("update", selectData);
      sketchVM.on("delete", selectRemove)
      return sketchVM;
    }
    function selectData(e) {
      if (e.graphics[0].attributes.data?.pointType == 'Station' || e.graphics[0].attributes.data?.type == 'Station') {
        return
      }
      let graphic = e.graphics[0]
      console.log(e)
      if (e.tool == "move") {
        self.movePointBy(graphic)
        //移动点位，边线跟随移动
      }
      if (e.state == 'start') {
        logOldGeometry = graphic.geometry
        if (graphic.attributes.type == "House") {

          emitter.emit('polyon', graphic.attributes.data)
        }

        self.sketchLayer.selectGraphic = graphic

        // polygonLayer.remove(e.graphics[0])
      }
      if (e.state == 'active') {

        //记录操作过的特征物
        if (graphic.attributes.type) {
          //更改经纬度范围
          if (graphic.attributes.data && graphic.attributes.data.action == undefined) {
            graphic.attributes.data.action = 1
          }
          if (graphic.attributes.type == "House") {

            //更改文字显示位置
            if (graphic.attributes.data.isExit) {
              self.setLabelByPolygon(graphic.geometry.centroid, 'text' + graphic.id, (graphic.attributes.data.houseMaterial || '') + (graphic.attributes.data.houseFloors || ''))
            }

          }

        }





      }

      if (e.state == 'complete') {
        self.sketchLayer.selectGraphic = null
        if (self.ldMapActionType != 'lineAction') {

          const areas = geodesicUtils.geodesicAreas([graphic.geometry], "square-meters");
          const area = Math.abs(areas[0]).toFixed(2)
          graphic.attributes.data.area = area
        }


        if (logOldGeometry != graphic.geometry) {
          mapLog.addContent({
            mapType: self.ldMapActionType != 'lineAction' ? 'regon' : 'line',
            actionType: 'edit',
            isrevoke: true,
            tips: self.ldMapActionType != 'lineAction' ? graphic.attributes.type : graphic.attributes.data.pointType,
            oldGeometry: [logOldGeometry],
            oldAttributes: [graphic.geometry],
            id: graphic.id,
          })
        }
      }

    }
    function addGraphic(event) {

      let mapdata = useMapDataStore()

      let id
      if (event.state === "complete") {
        switch (event.tool) {
          case "point":
            pointLayer.remove(event.graphic);
            if (self.pointSketchType == 'png') {
              mapdata.addPngStyle(event.graphic.geometry).then(res => {

                self.addsepticBygeomery(event.graphic.geometry, self.pointMaxIndex, res)

              })
            } else {

              console.log(self.pointSketchType)
              let symbol = {
                type: "simple-marker",
                style: "circle",
                size: self.pointSketchType == 'Station' ? '18px' : self.pointSketchType == 'x' ? '14px' : '10px',
                color: self.pointSketchType == 'Station' ? [8, 240, 36, 255] : self.pointSketchType == 'x' ? [7, 253, 253, 255] : [223, 3, 2, 255],
                outline: {
                  width: 0
                }
              }


              id = self.pointSketchType == 'Station' ? ('station:' + Date.now()) : self.pointMaxIndex
              const newPointGraphic = new Graphic({
                geometry: event.graphic.geometry,
                symbol: symbol,
                id,
                attributes: {
                  data: { pointType: self.pointSketchType },
                  startIndex: null,
                  endIndex: null,
                }
              });
              pointLayer.add(newPointGraphic);
              mapLog.addContent({
                mapType: self.ldMapActionType != 'lineAction' ? 'regon' : 'line',
                actionType: 'add',
                isrevoke: self.ldMapActionType != 'lineAction' ? false : true,
                tips: self.pointSketchType,
                oldGeometry: [],
                oldAttributes: [event.graphic.geometry],
                id,
              })


            }

            break;

          case "polyline":
            count++;
            polylineLayer.remove(event.graphic);
            const newPolylineGraphic = new Graphic({
              geometry: event.graphic.geometry,
              symbol: {
                type: "simple-line",
                color: [245, 66, 155, 0.8],
                width: 6
              },
              attributes: {
                type: "polyline",
                title: "polyline#" + count
              }
            });
            polylineLayer.add(newPolylineGraphic);

            break;

          case "polygon":
            count++;
            polygonLayer.remove(event.graphic);
            var polygon = event.graphic.geometry;
            id = self.addGraphicType + ':' + Date.now()
            let val = {
              geometryId: id,
              action: 2,
              "innerings": [],
              "extend": null,
              type: self.addGraphicType,
              path: polygon.rings[0]
            }

            const newPolygonGraphic = new Graphic({
              id: id,
              geometry: event.graphic.geometry,
              symbol: {
                type: "simple-fill", // autocasts as new SimpleFillSymbol()
                color: symbolData[self.addGraphicType],
                outline: {
                  // autocasts as new SimpleLineSymbol()
                  color: [255, 255, 255, 0.4],
                  width: 2
                }
              },
              attributes: {
                data: val,
                type: self.addGraphicType,

                sketchType: 'polygon'
              }
            });
            polygonLayer.add(newPolygonGraphic);
            mapdata.addByTypeData(self.addGraphicType, val)
            mapLog.addContent({
              mapType: 'regon',
              actionType: 'add',
              isrevoke: true,
              tips: self.addGraphicType,
              oldGeometry: [],
              oldAttributes: [event.graphic.geometry],
              id,
            })


            break;

          default:
            console.log("geometry type not found: ", event);
        }
      }
    }
    function selectRemove(e) {

      let selectData = e.graphics[0]
      if (self.ldMapActionType == 'lineAction') {

        let attributes = selectData.attributes
        let allPolyline = self.lineLayer.graphics

        if (!(attributes.endIndex && attributes.startIndex)) {
          let PolyLine = [];
          if (allPolyline) {
            allPolyline.forEach(item => {
              if (item.attributes.leftId == selectData.id || item.attributes.nextId == selectData.id) {
                PolyLine.push(item)
              }
            })
            PolyLine.forEach(item => {
              let point = self.getSketchDataByType("point").filter(data => {
                return data.id == item.attributes.leftId
              })?.[0];
              point && (point.attributes.endIndex = null)

              self.lineLayer.remove(item)
            })
          }

        } else {

          let leftGra = [], rightGra
          allPolyline.forEach(item => {
            if (item.attributes.nextId == selectData.id) {
              leftGra.push(item)
            }
            if (item.attributes.leftId == selectData.id) {
              rightGra = item
            }
          })
          leftGra.forEach((Leftitem) => {
            let leftPoint
            let rightPoint
            self.sketchLayer.pointLayer.graphics.items.forEach(item => {
              if (item.id == rightGra.attributes.nextId) {
                rightPoint = item
              }
              if (item.id == Leftitem.attributes.leftId) {
                leftPoint = item
              }

            })
            let polyline = new Polyline({
              paths: [
                [leftPoint.geometry.x, leftPoint.geometry.y],
                [rightPoint.geometry.x, rightPoint.geometry.y]

              ],
            })
            Leftitem.set({
              geometry: polyline,
              attributes: {
                ...Leftitem.attributes,
                nextId: rightPoint.id,
                endIndex: rightPoint.id
              }
            })


          })

          self.lineLayer.remove(rightGra)


        }
      }
      mapLog.addContent({
        mapType: self.ldMapActionType != 'lineAction' ? 'regon' : 'line',
        actionType: 'delete',
        isrevoke: true,
        tips: self.ldMapActionType != 'lineAction' ? 'Station' : selectData.attributes.data.pointType,
        oldGeometry: [selectData.geometry],
        oldAttributes: [selectData.attributes],
        id: selectData.id,
      })
    }


  },
  //验证新增的面是否有重叠
  addPolygonCheck(newPolygonGraphic, val) {

    let polygonLayer = self.sketchLayer.polygonLayer
    let polygon1 = new Polygon({
      rings: val.path
    })
    let alllayer = self.getSketchDataByType('polygon');
    let arr = []
    alllayer.map(item => {
      let polygon2 = new Polygon({
        rings: item.geometry.rings
      })
      const intersection = geometryEngine.intersect(polygon1, polygon2);
      if (intersection) {
        console.log(intersection)
        console.log(item)
        arr.push(intersection)
      }

      //  return intersection
    })
    if (arr.length) {
      // let  unionPolygon =''
      // arr.forEach(item=>{
      //   let polygon2  = new Polygon({
      //     rings:item.geometry.rings
      //   })
      //   unionPolygon = polygon2
      // })
      // console.log(unionPolygon)
      polygonLayer.removeAll()
      const newGraphic = new Graphic({
        geometry: arr[0],
        id: '11',
        symbol: {
          type: "simple-fill", // autocasts as new SimpleFillSymbol()
          color: [255, 0, 0, 0.6],
          outline: {
            // autocasts as new SimpleLineSymbol()
            color: [255, 255, 255, 0.4],
            width: 2
          }
        },
        attributes: {
          type: self.addGraphicType,
        }
      });
      polygonLayer.add(newGraphic)

    } else {
      //新增
      polygonLayer.add(newPolygonGraphic);
      mapdata.addByTypeData(self.addGraphicType, val)
    }


  },
  //切换线的状态
  getPoylineLayer(id, visible) {
    let p6 = this.lineLayer.graphics.items.filter(item => {
      return item.attributes.id == id
    })
    p6.forEach(item => item.visible = visible)

  },
  //智能合并
  MergeOptimization(long = 1) {
    let p6 = this.lineLayer.graphics.items.filter(item => {
      const length = geometryEngine.geodesicLength(polyline, "meters");
      return length < long
    })
  },
  //新增检修井
  addOpionPoint(type, pointId) {
    console.log(pointId)
    self.pointMaxIndex = pointId
    self.pointSketchType = type
    self.pointSketchViewModel.create("point");
  },
  //移动点位，边线跟随
  movePointBy(e) {

    let nowXy = [e.geometry.longitude, e.geometry.latitude]

    // let polylineLayer = self.sketchLayer.polylineLayer
    // let allPolyline = polylineLayer.graphics.items;

    let allPolyline = self.lineLayer.graphics
    let PolyLine = [];
    if (allPolyline) {
      allPolyline.forEach(item => {
        if (item.attributes.leftId == e.id) {

          PolyLine.push({
            val: item,
            type: 'left'
          })

        }
        if (item.attributes.nextId == e.id) {
          PolyLine.push({
            val: item,
            type: 'right'
          })
        }
      })
      PolyLine.forEach(item => {
        //可编辑线
        self.polylineSet(item.val, item.type, nowXy)

      })



    }










  },

  // 移动后替换原始线路
  polylineSet(polylineVal, type, nowXy) {

    let paths = polylineVal.geometry.paths
    type == 'left' ? paths[0][0] = nowXy : paths[0][paths[0].length - 1] = nowXy
    const polyline = new Polyline({
      paths: paths,

    })
    const length = geometryEngine.geodesicLength(polyline, "meters");
    console.log(length.toFixed(2))
    if (length) {
      polylineVal.set({
        geometry: polyline,
      })
    }


  },
  DrawSketch(type, addType) {


    self.addGraphicType = addType
    switch (type) {
      case 'point': self.pointSketchViewModel.create("point"); break;
      case 'polyline': self.polylineSketchViewModel.create("polyline"); break;
      case 'polygon': self.polygonSketchViewModel.create("polygon"); break;
    }

  },
  //清空图层数据
  removeAllLayer() {

    self.sketchLayer.polygonLayer.removeAll();
    self.sketchLayer.pointLayer.removeAll();
    self.lineLayer && self.lineLayer.removeAll()
    self.loadelevationLayer.removeAll()
    self.hightlayer &&self.hightlayer.removeAll()
    self.textLayer&&self.textLayer.removeAll()
  },
  //清除点位
  removePoint() {
    this.sketchLayer.pointLayer.removeAll();
  },
  removeLine() {
    self.view.graphics.removeAll();
  },
  //布线识别的数据加载
  addDefaultByline(data) {

    self.ldMapActionType = 'lineAction'
    self.DrawDregType = false
    self.textLayer.removeAll()
    return new Promise((resolve, reject) => {
      // let polylineLayer =  self.sketchLayer.polylineLayer;
      self.sketchLayer.polygonLayer.removeAll();
      self.lineLayer && self.lineLayer.removeAll()
      let polylineLayer = new GraphicsLayer()




      data.forEach(item => {
        const polyline = new Polyline({
          paths: item.path,


        })
        const lineSymbol = self.returnLineSymbole(item.width, item.color)
        //  const length = geometryEngine.geodesicLength(polyline, "meters");
        //  console.log(length.toFixed(2))
        //  item.distance = length.toFixed(2)
        const newPolygonGraphic = new Graphic({
          geometry: polyline,
          id: item.id,
          attributes: {
            leftId: item.startIndex,
            nextId: item.endIndex,
            id: item.id,
            data: item,
          },
          symbol: lineSymbol
        })


        polylineLayer.graphics.add(newPolygonGraphic)

      })



      self.map.add(polylineLayer, 1)
      self.lineLayer = polylineLayer
      resolve(data)

    })


  },
  //获取管线起点数据
  getpointByStart() {

    let point = self.getSketchDataByType("point");
    let linelayer = self.lineLayer.graphics.items
    let returnObj = {
      line: [],
      point: [],
      lineAttribute: {},
    }
    point.forEach(item => {
      if (!item.attributes.startIndex && item.attributes.endIndex) {
        try {
          returnObj.line.push(self.getMapByPoint(item, []))
        } catch (error) {
          console.log(error)
          debugger
        }

      }
      if (!item.attributes.startIndex && !item.attributes.endIndex) {
        returnObj.point.push([[item.geometry.x, item.geometry.y, item.attributes.data.pointType, parseInt(item.attributes.data.styleVal) || 200, item.id]])
      }
    })
    linelayer.forEach(item => {
      let { endAltitude = null, endElevation = null, material = null, pipelineType = null, startAltitude = null, startElevation = null } = item.attributes.data
      let length = parseFloat(geometryEngine.geodesicLength(item.geometry, "meters").toFixed(2));
      returnObj.lineAttribute[item.attributes.leftId + ',' + item.attributes.nextId] =
        { endAltitude, endElevation, length, material, pipelineType, startAltitude, startElevation }
    })

    return returnObj

  },
  //根据起点找终点返回数据
  getMapByPoint(item, data) {
    let linelayer = self.lineLayer.graphics.items
    let point = self.getSketchDataByType("point");

    let nowPointId = item.id
    let lineId = item.attributes.endIndex

    //当前的元素数据
    let geometry = item.geometry
    let attributes = item.attributes

    if (lineId && lineId != nowPointId) {
      let linedata = linelayer.filter(item => item.id == lineId)[0]
      if (!linedata) { return data }
      let val = [geometry.x, geometry.y, attributes.data.pointType, parseInt(linedata.attributes.data.styleId), nowPointId]
      data.push(val)
      let nextPointId = linedata.attributes.nextId

      let nextItem = point.filter(item => item.id == nextPointId)[0]
      if (!nextItem) { debugger }
      return this.getMapByPoint(nextItem, data)
    } else {
      //到终点
      let val = [geometry.x, geometry.y, attributes.data.pointType, parseInt(data[data.length - 1][3]), nowPointId]
      data.push(val)
      return data
    }

  },

  //线数据定位
  chooseLineByid(id) {

    let p6 = this.lineLayer.graphics.items.filter(item => {
      return item.attributes.id == id
    })[0]
    self.lighHight?.remove();
    self.view.whenLayerView(p6.layer).then((layerView) => {
      self.lighHight = layerView.highlight(p6)
    })
    self.setCenter(p6.geometry.extent.center.x, p6.geometry.extent.center.y, 22)
  },
  //根据类型获取总skech要素
  getSketchDataByType(type) {
    let sketch = []
    switch (type) {
      case 'polygon': sketch = this.sketchLayer.polygonLayer.graphics.items; break;
      case 'point': sketch = this.sketchLayer.pointLayer.graphics.items; break;
      case 'polyline': sketch = this.sketchLayer.pointLayer.graphics.items; break;
    }
    return sketch
  },
  //线条样式
  returnLineSymbole(width, color) {
    return new CIMSymbol({
      data: {
        type: "CIMSymbolReference",
        symbol: {
          type: "CIMLineSymbol",
          symbolLayers: [{
            type: "CIMSolidStroke",

            enable: "true",
            capStyle: "Butt",
            joinStyle: "Round",
            width,
            color
          },
          {
            // arrow symbol
            type: "CIMVectorMarker",
            enable: true,
            size: 5,
            markerPlacement: {
              type: "CIMMarkerPlacementAlongLineSameSize", // places same size markers along the line
              endings: "WithMarkers",
              placementTemplate: [19.5], // determines space between each arrow
              angleToLine: true // symbol will maintain its angle to the line when map is rotated
            },
            frame: {
              xmin: -5,
              ymin: -5,
              xmax: 5,
              ymax: 5
            },
            markerGraphics: [{
              type: "CIMMarkerGraphic",
              geometry: {
                rings: [
                  [
                    [
                      -8,
                      -5.47
                    ],
                    [
                      -8,
                      5.6
                    ],
                    [
                      1.96,
                      -0.03
                    ],
                    [
                      -8,
                      -5.47
                    ]
                  ]
                ]
              },
              symbol: {
                // black fill for the arrow symbol
                type: "CIMPolygonSymbol",
                symbolLayers: [{
                  type: "CIMSolidFill",
                  enable: true,
                  color: [
                    255, 255, 255, 255

                  ]
                }]
              }
            }]
          }]
        }
      }
    });
  },
  //线添加点位数据
  addDefaultByPoint(data) {

    let pointLayer = self.sketchLayer.pointLayer;
    let id = data.pointId


    // if (data.pointType != 'y') {

    let point = new Point({
      x: data.point[0],
      y: data.point[1]
    })
    // Create a graphic and add the geometry and symbol to it
    let pointGraphic = new Graphic({
      id: id,
      geometry: point,
      attributes: {
        data: data,
        startIndex: data.startIndex,
        endIndex: data.endIndex,
      },
      symbol: {
        // type: "picture-marker",  // autocasts as new PictureMarkerSymbol()
        // url: data.jpg,
        // width: data.width,
        // height: data.height
        type: "simple-marker",  // autocasts as new SimpleMarkerSymbol()
        color: data.color,
        size: data.size,  // pixels
        outline: {
          width: 0
        }
      },

    });

    if (data.pointType == 'y') {
      pointGraphic.visible = false
    }

    pointLayer.add(pointGraphic, 10)
    // return id;

    // }

  },
  addsepticBygeomery(geometry, img, id) {
    let pointGraphic = new Graphic({
      id,
      geometry: geometry,
      attributes: {
        type: 'qdf',
      },
      symbol: {
        type: "picture-marker",  // autocasts as new PictureMarkerSymbol()
        url: img,
        height: 20,
        width: 20,

        outline: {
          width: 10
        }
      },

    });
    self.pngLayer.add(pointGraphic, 10)
  },
  //新增图片点位
  addsepticTank(e) {
    let { data: arr, img } = e
    self.pngLayer.removeAll()
    arr.forEach(data => {
      let point = new Point({
        x: data.point[0],
        y: data.point[1]
      })
      // Create a graphic and add the geometry and symbol to it
      let pointGraphic = new Graphic({
        id: data.id,
        geometry: point,
        attributes: { type: 'qdf' },
        symbol: {
          type: "picture-marker",  // autocasts as new PictureMarkerSymbol()
          url: img,
          height: 20,
          width: 20,
        },

      });
      self.pngLayer.add(pointGraphic, 10)
    })
  },
  //隐藏图片点位
  setPngPoint(visible) {
    self.pngLayer.visible = visible

  },
  //根据管径信息修改管道
  exitLineByVal(data) {

    let polylineLayer = self.lineLayer

    let p6 = this.lineLayer.graphics.items.filter(item => {
      return item.id == data.id || item.id == data.lineId
    })[0]
    p6.set({
      symbol: self.returnLineSymbole(data.width, data.color)
    })


  },

  //切割面
  cutPolygon() {
    self.startDrawLine()
  },
  getCIMSymbolData(rings) {
    return {
      type: "CIMSymbolReference",
      primitiveOverrides: [
        {
          type: "CIMPrimitiveOverride",
          primitiveName: "textGraphic",
          propertyName: "TextString",
          valueExpressionInfo: {
            type: "CIMExpressionInfo",
            title: "Custom",
            expression: "$feature.text",
            returnType: "Default"
          }
        }
      ],
      symbol: {
        type: "CIMPolygonSymbol",
        symbolLayers: [

          {
            type: "CIMSolidFill", // autocasts as new SimpleFillSymbol()
            "enable": true,
            "color": [255, 0, 0, 153]
          },
          {
            type: "CIMVectorMarker",
            enable: true,
            size: 32,
            colorLocked: true,
            anchorPointUnits: "Relative",
            frame: { xmin: -5, ymin: -5, xmax: 5, ymax: 5 },
            markerGraphics: [
              {
                type: "CIMMarkerGraphic",
                primitiveName: "textGraphic",
                geometry: { x: 0, y: 0 },
                symbol: {
                  type: "CIMTextSymbol",
                  fontFamilyName: "Arial",
                  fontStyleName: "Bold",
                  height: 4,
                  horizontalAlignment: "Center",
                  offsetX: 0,
                  offsetY: 0,
                  symbol: {
                    type: "CIMPolygonSymbol",
                    symbolLayers: [
                      {
                        type: "CIMSolidFill",
                        enable: true,
                        color: [255, 255, 255, 255]
                      }
                    ]
                  },
                  verticalAlignment: "Center"
                },
                textString: ""
              }
            ],
            scaleSymbolsProportionally: true,
            respectFrame: true
          },


        ]
      }
    };
  },
  //根据缩放显示高程数据
  showeleByzoom(zoom = self.view.zoom) {
    console.log(zoom)
    if (!self.loadelevationLayer) return;

    if (zoom >= 22) {
      self.loadelevationLayer.graphics.items.forEach(item => {
        item.visible = true
      })
    } else {
      let level = (22 - zoom) * 3
      self.loadelevationLayer.graphics.items.forEach((item, index) => {
        if (!(index % level)) {
          item.visible = true
        } else {
          item.visible = false
        }

      })
    }
  },
  //是否有相近的点位
  isNearbypoint(point) {
    let items = self.loadelevationLayer.graphics.items
    let flag = true
    for (let i = 0; i < items.length; i++) {

      let distance = self.distance(point, [items[i].geometry.x, items[i].geometry.y])
      console.log(distance)
      if (distance < 10) {
        flag = false;
        break;
      }
    }
    return flag

  },
  //道路高程数据展示
  elevationData(flag,data) {
    if (flag) {

      data.forEach((item, index) => {
          let point = new Point({ x: item[0], y: item[1] })
          let text = item[2].toFixed(2)
          const graphic = new Graphic({
            geometry: point,
            visible: !(index % ((22 - self.view.zoom) * 2)),
            symbol: {
              type: "text",  // autocasts as new TextSymbol()
              text: text,
              color: [255, 255, 255, 255],
              font: {
                weight: "bold"
              }
            }
          });

          self.loadelevationLayer.add(graphic)
      })

    } else {
      self.loadelevationLayer.removeAll()
    }


  },
  //特征物的站点数据
  addDefaultPoint(data) {

    let pointLayer = self.sketchLayer.pointLayer
    const point = new Point({
      x: data.path[0],
      y: data.path[1],

    })

    const newPointGraphic = new Graphic({

      geometry: point,
      symbol: {
        type: "simple-marker",
        style: "circle",
        size: '18px',
        color: [8, 240, 36, 255],
        outline: {
          width: 0
        }
      },
      attributes: {
        data,
      }
    });
    pointLayer.add(newPointGraphic);
  },
  //站点数据
  addDeviceData(data, type) {

    self.pointSketchType = type
    let pointLayer = self.sketchLayer.pointLayer;
    data.forEach(item => {
      let xy = item.path[0]
      let point = new Point({
        x: xy[0],
        y: xy[1],
      })
      const newPointGraphic = new Graphic({
        id: item.geometryId,
        geometry: point,
        symbol: {
          type: "simple-marker",
          style: "circle",
          size: '18px',
          color: [8, 240, 36, 255],
          outline: {
            width: 0
          }
        },
        attributes: {
          data: item
        }
      });
      pointLayer.add(newPointGraphic);

    })

  },
  //特征物识别数据
  addDefaultData(data, type) {

    let SymbolColor = symbolData[type]
    let symbol = ''


    self.ldMapActionType = 'regectionAction'

    let polygonLayer = self.sketchLayer.polygonLayer

    const num = 3
    const maxNumber = 15000
    const flag = false;
    self.DrawDregType = true
    data.forEach((res) => {

      let maxNum = 0
      res.innerings = res.innerings
      res.path = res.path
      new Promise((resolve, reject) => {
        maxNum += res.path.length

        res.innerings.forEach(res => {
          maxNum += res.length
        })
        // if(maxNum>1000)
        console.log(maxNum + ":" + res.geometryId)

        let path, innerings



        if (maxNum > maxNumber && flag) {


          path = res.path.filter((item, index) => {
            return index % num == 0
          })
          innerings = res.innerings.map(element => {

            data = element.filter((item, index) => {
              return index % num == 0
            })
            return data
          })
        } else {
          path = res.path
          innerings = res.innerings
        }
        const polygon = new Polygon({
          rings: path,
          //
        })


        if (innerings.length) {
          innerings.forEach(element => {
            polygon.addRing(element)
          });
        }

        //  symbol={
        //    type: "cim",
        //    data:this.getCIMSymbolData()
        //  }
        symbol = {
          type: "simple-fill", // autocasts as new SimpleFillSymbol()
          color: SymbolColor,
          outline: {
            // autocasts as new SimpleLineSymbol()
            color: [255, 255, 255, 0.4],
            width: 0.5
          }
        }

        if (res.type == "House") {
          try{
            const areas = geodesicUtils.geodesicAreas([polygon], "square-meters");
            const area = Math.abs(areas[0]).toFixed(2)
            res.area = res.area || area
          }catch{

          }

        }
        const newPolygonGraphic = new Graphic({
          geometry: polygon,
          id: res.geometryId,
          symbol: symbol,
          attributes: {
            type: type,
            sketchType: 'polygon',
            data: res,
          }
        });


        res.isExit && self.setLabelByPolygon(polygon.centroid, 'text' + res.geometryId, (res.houseMaterial || '') + (res.houseFloors || ''))
        polygonLayer.add(newPolygonGraphic)
        resolve()

      }).then(e => {

      })



    })




  },
  setReconLabel(geometryId, text) {

    let graphic = self.sketchLayer.polygonLayer.graphics.items.filter(item => {
      return item.id == geometryId
    })
    if (graphic.length) {
      self.setLabelByPolygon(graphic[0].geometry.centroid, 'text' + geometryId, text)
    }


  },
  //显示图层中间文字
  setLabelByPolygon(center, id, text) {

    if (!text) return
    let point = new Point({ x: center.x, y: center.y })

    let selectGraphic = self.textLayer.graphics.items.filter(item => {
      return item.id == id
    })
    if (selectGraphic.length) {
      selectGraphic.forEach(p6 => {
        p6.set({
          geometry: point,
          symbol: {
            type: "text",  // autocasts as new TextSymbol()
            text: text,
            color: [255, 255, 255, 255],
            font: {  // autocasts as new Font()
              size: 12,
              weight: "bold"
            }
          }
        })
      })
    } else {

      const graphic = new Graphic({
        geometry: point,
        id: id,
        symbol: {
          type: "text",  // autocasts as new TextSymbol()
          text: text,
          color: [255, 255, 255, 255],
          font: {
            // autocasts as new Font()
            // size: 12,

            weight: "bold"
          }
        }
      });

      self.textLayer.add(graphic)

    }




  },
  //高亮面图层
  lighHightLayer(id) {

    let graphic = self.sketchLayer.polygonLayer.graphics.items.filter(item => {
      return item.id == id
    })

    self.polygonSketchViewModel.update(graphic, {
      tool: "reshape",
      enableMoveAllGraphics: false,
      reshapeOptions: {
        edgeOperation: "none",
        shapeOperation: "none",
        vertexOperation: "none"
      }
    })

    graphic && self.setCenter(graphic[0].geometry.extent.center.x, graphic[0].geometry.extent.center.y)



  },
  //像素转经纬度
  pxMapToLatlon(x, y) {


    let view = self.view
    let zoom = view.zoom
    let tileLayer = self.nowlayer
    let imgwidth = tileLayer.sourceJSON.maxImageWidth
    let imgHeight = tileLayer.sourceJSON.maxImageHeight

    let fullExtent = {
      xmax: 118.86371824235101,
      ymax: 33.26729051757083,
      xmin: 118.85818229653573,
      ymin: 33.26307467082115
    }

    let lngLatToXYmax = webMercatorUtils.lngLatToXY(fullExtent.xmax, fullExtent.ymax)
    let lngLatToXYmin = webMercatorUtils.lngLatToXY(fullExtent.xmin, fullExtent.ymin)

    let nowWith = lngLatToXYmax[0] - lngLatToXYmin[0]
    let nowheight = lngLatToXYmax[1] - lngLatToXYmin[1]

    let nowX = Math.floor(lngLatToXYmin[0] + (x * 4096 / 256) / 125)

    let nowY = Math.floor(lngLatToXYmax[1] - (y * 4096 / 256) / 125)




    let lat = webMercatorUtils.xyToLngLat(nowX, nowY)
    return lat
  },
  getTileExtent(layer) {

  },
  //获取总数居
  getAllData() {

    self.sketchLayer.polygonLayer.removeAll()

  },
  //数据恢复
  recoveryData(data) {
    return new Promise((resolve, reject) => {

      console.log(data)
      switch (data.actionType) {
        case 'add':
          if (data.mapType == 'regon') {
            self.sketchLayer.polygonLayer.graphics.items.forEach(item => {
              if (item.id == data.id) {
                self.sketchLayer.polygonLayer.remove(item)
              }
            })
            resolve()
          }

          break
        case 'delete':
          if (data.mapType == 'regon') {
            let graphicData = JSON.parse(data.oldAttributes[0])
            let polygon = new Polygon(JSON.parse(data.oldGeometry[0]))
            let symbol = {
              type: "simple-fill", // autocasts as new SimpleFillSymbol()
              color: symbolData[data.tips],
              outline: {
                // autocasts as new SimpleLineSymbol()
                color: [255, 255, 255, 0.4],
                width: 0.5
              }
            }
            const newPolygonGraphic = new Graphic({
              geometry: polygon,
              id: data.id,
              symbol: symbol,
              attributes: graphicData.attributes,
            });
            self.sketchLayer.polygonLayer.add(newPolygonGraphic)
            resolve()
          }

          break
        case 'edit':
          console.log(data)

          if (data.mapType == 'regon') {
            self.sketchLayer.polygonLayer.graphics.items.forEach(item => {
              if (item.id == data.id) {
                let geometry = new Polygon(JSON.parse(data.oldGeometry[0]))
                item.set({
                  geometry
                })
              }
            })
            resolve()
          }




          break

      }

    })


  },

  //删除数据
  delSketch() {


    if (self.sketchLayer.selectGraphic) {

      let val = self.sketchLayer.selectGraphic.attributes.data
      let layer = ""
      let selectData = self.sketchLayer.selectGraphic
      switch (selectData.attributes.sketchType) {
        case "polygon": layer = self.sketchLayer.polygonLayer.remove(selectData); break;
        case "polyline": layer = self.sketchLayer.polylineLayer.remove(selectData); break;
      }


      mapLog.addContent({
        mapType: self.ldMapActionType != 'lineAction' ? 'regon' : 'line',
        actionType: 'delete',
        isrevoke: true,
        tips: val.type,
        oldGeometry: [self.sketchLayer.selectGraphic.geometry],
        oldAttributes: [self.sketchLayer.selectGraphic],
        id: self.sketchLayer.selectGraphic.id,
      })
      self.sketchLayer.selectGraphic = null
      return self.ldMapActionType == 'lineAction' ? null : val;


    }
    if (self.lighHight) {
      if (self.selectLine) {
        self.lineLayer.remove(self.selectLine)
        self.sketchLayer.pointLayer.sublayers.items.forEach(item => {
          if (item.id == self.selectLine.attributes.leftId) {
            item.attributes.endIndex = null
          }
          if (item.id == self.selectLine.attributes.nextId) {
            item.attributes.startIndex = null
          }
        })
      }
      if (self.selectPng) {
        let mapdata = useMapDataStore()
        mapdata.delPngTyle(self.selectPng.id).then(() => {
          self.pngLayer.remove(self.selectPng)
        })

      }
    }

  },
  destroyDraw() {
    this.draw.destroy()
    if (this.ldMapActionType == 'lineAction') {
      this.drawTypeLine == 'once' ? this.pointLayerBind() : this.pointManyBind()
    }
  },
  startDrawLine(type) {

    self.drawTypeLine = type
    this.draw && this.draw.destroy()
    self.draw = new Draw({
      view: this.view,
    })
    let action = self.draw.create("polyline", {
      mode: 'click'
    });

    // self.view.focus()
    // 顶点添加事件
    action.on("vertex-add", (event) => self.creatLineByClick(event));

    // 鼠标移动事件
    action.on("cursor-update", (event) => self.creatLineByClick(event));

    // 绘制完成事件
    action.on("draw-complete", (e) => {
      self.destroyDraw()
    });

  },
  //根据画的线合并到最近的点位并找出中间点位相连
  pointManyBind() {

    let polylineLayer = self.lineLayer

    let startItem = null, startMax = 30;
    let endItem = null, endMax = 30;

    let point = self.getSketchDataByType("point");
    let line
    try {
      line = turf.lineString(self.newDrawLineByClick.geometry.paths[0]);
    } catch (error) {
      console.log(self.newDrawLineByClick.geometry.paths)
    }

    let options = { units: 'meters' };
    let pointList = []


    point.forEach(item => {
      let polyline
      let length
      polyline = new Polyline({
        paths: [self.newDrawLineByClick.geometry.paths[0][0], [item.geometry.x, item.geometry.y,]],
      })

      length = geometryEngine.geodesicLength(polyline, "meters");
      if (length < startMax) {
        startMax = length;
        startItem = item
      }
      polyline = new Polyline({
        paths: [self.newDrawLineByClick.geometry.paths[0][1], [item.geometry.x, item.geometry.y]],
      })
      length = geometryEngine.geodesicLength(polyline, "meters");
      if (length < endMax) {
        endMax = length;
        endItem = item
      }

      let point = turf.point([item.geometry.x, item.geometry.y]);

      if (line && turf.pointToLineDistance(point, line, options) < 10) {
        pointList.push(item)
      }




    })
    if (endItem && startItem) {

      let list = pointList.filter(item => {
        return item != startItem
      })
      console.log(list)
      drawByStartItem(startItem)

      function drawByStartItem(startItem) {
        let Minlength = 999;
        let endItem = ''
        list.forEach(item => {

          let polyline = new Polyline({
            paths: [[startItem.geometry.x, startItem.geometry.y], [item.geometry.x, item.geometry.y]],
          })
          length = geometryEngine.geodesicLength(polyline, "meters");
          if (length < Minlength) {
            endItem = item
            Minlength = length
          }
        })
        if (endItem) {
          let lineValue = [[startItem.geometry.x, startItem.geometry.y], [endItem.geometry.x, endItem.geometry.y]]
          let lineValueResve = [[endItem.geometry.x, endItem.geometry.y], [startItem.geometry.x, startItem.geometry.y]]
          let polyline = new Polyline({
            paths: lineValue,
          })
          let flag = polylineLayer.graphics.items.filter(data => {
            return JSON.stringify(lineValue) == JSON.stringify(data.geometry.paths[0]) || JSON.stringify(lineValueResve) == JSON.stringify(data.geometry.paths[0])
          })


          if (!flag.length) {

            let newId = parseInt(startItem.id + '1')
            startItem.attributes.endIndex = newId
            endItem.attributes.startIndex = newId
            const lineSymbol = self.returnLineSymbole(3, [0, 255, 255, 255])
            let graphic = new Graphic({
              geometry: polyline,
              id: newId,
              attributes: {
                leftId: startItem.id,
                nextId: endItem.id,
                data: {
                  lineId: newId,
                  styleId: 400,
                  length: geometryEngine.geodesicLength(polyline, "meters").toFixed(2),
                  path: polyline.paths[0],
                  startIndex: startItem.id,
                  endIndex: endItem.id,
                }
              },
              symbol: lineSymbol
            })

            polylineLayer.add(graphic)
          }
          list = list.filter(item => item != endItem)
          if (list.length != 0)
            drawByStartItem(endItem)
        }




      }
    }

    self.view.graphics.removeAll();

  },
  //根据画的线合并到最近的点位
  pointLayerBind() {


    let polylineLayer = self.lineLayer

    let startItem = null, startMax = 30;
    let endItem = null, endMax = 30;

    let point = self.getSketchDataByType("point");
    point.forEach(item => {
      let polyline
      let length
      polyline = new Polyline({
        paths: [self.newDrawLineByClick.geometry.paths[0][0], [item.geometry.x, item.geometry.y,]],
      })
      length = geometryEngine.geodesicLength(polyline, "meters");
      if (length < startMax) {
        startMax = length;
        startItem = item
      }

      polyline = new Polyline({
        paths: [self.newDrawLineByClick.geometry.paths[0][1], [item.geometry.x, item.geometry.y]],
      })
      length = geometryEngine.geodesicLength(polyline, "meters");
      if (length < endMax) {
        endMax = length;
        endItem = item
      }
    })
    if (endItem && startItem) {

      let polyline = new Polyline({
        paths: [[startItem.geometry.x, startItem.geometry.y], [endItem.geometry.x, endItem.geometry.y]],

      })
      let newId = parseInt(startItem.id + '1')
      startItem.attributes.endIndex = newId
      endItem.attributes.startIndex = newId
      const lineSymbol = self.returnLineSymbole(3, [0, 255, 255, 255])
      let graphic = new Graphic({
        geometry: polyline,
        id: newId,
        attributes: {
          leftId: startItem.id,
          nextId: endItem.id,
          data: {
            styleId: 400,

            lineId: newId,
            length: geometryEngine.geodesicLength(polyline, "meters").toFixed(2),
            path: polyline.paths[0],
            startIndex: startItem.id,
            endIndex: endItem.id,
          }
        },
        symbol: lineSymbol
      })

      polylineLayer.add(graphic)
    }

    self.view.graphics.removeAll();







  },
  creatLineByClick(event) {


    self.view.graphics.removeAll();

    var vertices = event.vertices;

    let falg = false
    if (vertices.length > 2) {
      vertices = vertices.slice(0, 2)
      falg = true
    }

    let polyline = {
      type: "polyline", // autocasts as new Polyline()
      paths: vertices,

    }
    const lineSymbol = self.returnLineSymbole(3, [0, 255, 255, 255])
    let graphic = new Graphic({
      geometry: polyline,
      attributes: {
        data: '1111'
      },
      symbol: lineSymbol
    })
    self.view.graphics.add(graphic)
    if (falg) this.destroyDraw()
    self.newDrawLineByClick = graphic
  },


  //处理合并的经纬度
  Bindpolygon() {

    let polygonLayer = self.sketchLayer.polygonLayer
    let graphic = self.view.graphics.items[0]


    if (!graphic || !self.sketchLayer.selectGraphic) { return }
    let polygon1 = new Polygon({
      rings: graphic.geometry.rings
    })
    let item = self.sketchLayer.selectGraphic
    let rings = item.geometry.rings
    let newRings = []
    let deletFlag = false;
    rings.forEach(ring => {
      let newRing = []
      ring.forEach(p => {
        let point = new Point({ x: p[0], y: p[1] })
        const pointFlag = geometryEngine.intersect(polygon1, point);
        if (!pointFlag) {
          newRing.push(p)
        } else {
          deletFlag = true
        }
      })
      newRing.length && newRings.push(newRing)
    })
    console.log(newRings)
    if (deletFlag) {
      if (newRings.length) {

        if (!item.attributes.data.action) {
          item.attributes.data.action = 1
        }

        item.geometry.set({
          rings: newRings
        })
        item.notifyGeometryChanged()
        self.polygonSketchViewModel.update(item, { tool: "reshape" })
      } else {
        polygonLayer.remove(item)
        let mapdata = useMapDataStore()
        mapdata.delData(item.attributes.data);
      }
    }






    self.view.graphics.removeAll()


  },
  createPolygon(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]]];
    self.view.graphics.removeAll();


    const polygon = new Polygon({
      hasZ: false,
      hasM: false,
      rings: [rings],

    })
    let graphic = new Graphic({
      geometry: polygon,
      symbol: {
        type: "simple-fill",  // autocasts as new SimpleFillSymbol()
        color: [234, 191, 13, 0.6],
        style: "solid",
        outline: {  // autocasts as new SimpleLineSymbol()
          color: "white",
          width: 1
        }


      }
    })

    self.view.graphics.add(graphic)
  },
  addImgbyLine(points, x, y, imgPoint) {

    if (imgPoint) {

      self.view.graphics.remove(imgPoint)
    }

    var x1 = points[0][0]
    var y1 = points[0][1]
    var x2 = points[1][0]
    var y2 = points[1][1]
    let p = (y2 - y1) / (x2 - x1)// 斜率

    let angle = self.calcAngle(x1, y1, x2, y2) //朝向
    let point = {
      type: "point",
      longitude: x,
      latitude: y,
    }
    let graphic = new Graphic({
      geometry: point,
      symbol: {
        type: "picture-marker",
        url: "http://localhost/src/ldmap/assets/tool/icon.png",
        width: 20,
        height: 20,
        angle: angle
      }
    })
    self.view.graphics.add(graphic)
    return graphic
  },
  calcAngle(x1, y1, x2, y2) {
    let tan = (Math.atan(Math.abs((y2 - y1) / (x2 - x1))) * 180) / Math.PI + 90
    if (x2 > x1 && y2 > y1) {
      return -tan + 180
    } else if (x2 > x1 && y2 < y1) {
      return tan
    } else if (x2 < x1 && y2 > y1) {
      return tan - 180
    } else {
      return -tan
    }
  },
  drawPoint(data) {

    let position = {
      type: "point",
      longitude: data[0],
      latitude: data[1]
    }
    let graphic = new Graphic({
      geometry: position,
      symbol: {
        type: "simple-marker",  // autocasts as new SimpleMarkerSymbol()

        color: 'yello',
        size: "8px",
        outline: {  // autocasts as new SimpleLineSymbol()
          color: [255, 255, 0],
          width: 3  // points
        }
      }
    })
    self.view.graphics.add(graphic)

  },
  //优化管线数据（大于50）
  ponitBindByFivety(MAXLENGTH = 50) {

    let pointAll = self.getSketchDataByType("point");
    let linelayer = self.lineLayer.graphics.items
    pointAll.forEach(item => {
      if (!item.attributes.startIndex && item.attributes.endIndex) {
        try {

          //从头开始找
          getpointByStart(item, null, [], [])

        } catch (error) {
        }

      }
    })
    function getpointByStart(leftPoint, leftLIne, arrPoint, arrline) {
      if (leftPoint.attributes.data.pointType == 'x') {
        if (arrPoint.length) {
          arrPoint.push(leftPoint)
          arrline.push(leftLIne)
          isArrPointMax50(arrPoint, arrline)
          arrPoint = [];
          arrline = []
          //597 595 596
        } else {
          arrPoint.push(leftPoint)


        }


      } else {
        if (arrPoint.length) {
          arrPoint.push(leftPoint)
          arrline.push(leftLIne)
        }

      }
      let nextPoint, pointLine
      for (let i = 0; i < linelayer.length; i++) {
        if (linelayer[i].id == leftPoint.attributes.endIndex) {
          pointLine = linelayer[i]
          nextPoint = pointAll.filter(item => {
            return item.id == pointLine.attributes.nextId
          })[0]
          break
        }

      }
      if (nextPoint) {
        getpointByStart(nextPoint, pointLine, arrPoint, arrline)
      }


    }

    function isArrPointMax50(arrPoint, arrLine) {

      let paths = []
      arrPoint.forEach(item => {
        paths.push([item.geometry.x, item.geometry.y])
      })
      let polyline = new Polyline({
        paths: paths

      })
      let length = parseFloat(geometryEngine.geodesicLength(polyline, "meters"));

      if (length >= MAXLENGTH) {

        console.log(length)



        length = length / 2
        //判断中心点位再哪条线上
        let centerLine
        for (let i = 0; i < arrLine.length; i++) {
          let item = arrLine[i]
          let desic = parseFloat(geometryEngine.geodesicLength(item.geometry, "meters"))
          length = length - desic
          if (length <= 0) {
            centerLine = item;
            break;
          }
        }
        //获取中心点位
        let centerPoint = new Point({
          x: centerLine.geometry.extent.center.x,
          y: centerLine.geometry.extent.center.y
        })




        //新增中心点位
        let mapdata = useMapDataStore()
        let id = mapdata.setMaxPointIndex(1);
        let symbol = {
          type: "simple-marker",
          style: "circle",
          size: '14px',
          color: [7, 253, 253, 255],
          outline: {
            width: 0
          }
        }
        const newPointGraphic = new Graphic({
          geometry: centerPoint,
          symbol: symbol,
          id,
          attributes: {
            data: { pointType: 'h' },
            startIndex: centerLine.id,
            endIndex: id + '1',
          }
        });

        self.sketchLayer.pointLayer.add(newPointGraphic);

        //clone 一条线，开始和结尾改为连接到中心点位



        let centerlineClone = centerLine.clone()

        centerLine.set({
          geometry: new Polyline({
            paths: [
              [centerPoint.x, centerPoint.y],
              centerLine.geometry.paths[0][1],
            ]
          })
        })
        centerLine.attributes.leftId = id





        let newPolygon = new Polyline({
          paths: [
            centerlineClone.geometry.paths[0][0],
            [centerPoint.x, centerPoint.y],
          ]
        })
        let LineGraphic = new Graphic({
          geometry: newPolygon,
          id: id * 10 + 1,
          attributes: {
            leftId: centerlineClone.attributes.leftId,
            nextId: id,
            data: centerlineClone.attributes.data
          },
          symbol: centerlineClone.symbol
        })

        self.lineLaye.add(LineGraphic)





















        if (!self.hightlayer) {
          self.hightlayer = new GraphicsLayer();
          self.map.add(self.hightlayer)
        }



        const graphic = new Graphic({
          geometry: polyline,

          symbol: {
            type: "simple-line",
            width: 5,
            color: "red",
          },

        });
        self.hightlayer.add(graphic)
      }







    }



  },

  //优化检修井数据点位
  pointBindByLength(minlength = 5) {
    let pointAll = self.getSketchDataByType("point");
    let linelayer = self.lineLayer.graphics.items
    let index
    let sum
    let num
    let allSum = 0
    do {
      console.log('--------------------------------')
      sum = 0
      index = 1
      pointAll.forEach((item) => {

        if (!item.attributes.startIndex && item.attributes.endIndex) {
          try {
            num = 0
            //从头开始找
            num = getpointBytype(item, num)
            // console.log(`查找中:${index++}条,优化点位${num}个`)
            sum += num
          } catch (error) {
            console.log(error)

          }

        }

      })
      allSum += sum
      console.log(sum)
    } while (sum)

    return allSum





    //找到相邻的点位并且是检修井
    function getpointBytype(leftPoint, num) {

      let nextPoint, p1Top2Line
      for (let i = 0; i < linelayer.length; i++) {
        if (linelayer[i].id == leftPoint.attributes.endIndex) {
          p1Top2Line = linelayer[i]
          nextPoint = pointAll.filter(item => {
            return item.id == p1Top2Line.attributes.nextId
          })[0]
          break
        }

      }
      if (nextPoint) {
        if (leftPoint.attributes.data.pointType == 'x' && nextPoint.attributes.data.pointType == 'x') {
          nextPoint = setLinelength(leftPoint, nextPoint, p1Top2Line)
        }
        num = nextPoint == leftPoint ? num + 1 : num

        return getpointBytype(nextPoint, num)

      } else {
        return num
      }





    }
    function setLinelength(point1, point2, p1Top2Line) {

      let length = parseFloat(geometryEngine.geodesicLength(p1Top2Line.geometry, "meters").toFixed(2));
      // console.log(length)
      if (length >= 50) {
        console.log('50米', length, p1Top2Line)
      }
      if (length < minlength) {

        let p3, p2top3line

        //所有连接到p2的点位都替换到p1，并且连接线都改成连接p1（除了p1本身）
        linelayer.forEach(item => {
          if (item.attributes.nextId == point2.id && item.attributes.leftId != point1.id) {
            item.attributes.nextId = point1.id;
            let polyline = new Polyline({
              paths: [item.geometry.paths[0][0], [point1.geometry.x, point1.geometry.y]],

            })
            item.set({
              geometry: polyline,
            })
          }

          if (item.attributes.leftId == point2.id) {
            p3 = pointAll.filter(val => val.id == item.attributes.nextId)[0]
            p2top3line = item
          }
        })

        //p1到p2的线修改成p1到p3

        let polyline = new Polyline({
          paths: [p1Top2Line.geometry.paths[0][0], [p3.geometry.x, p3.geometry.y]],

        })
        p1Top2Line.set({
          geometry: polyline,
          attributes: {
            ...p1Top2Line.attributes,
            nextId: p3.id
          }
        })


        //p2连接到p3的线删除

        self.lineLayer.remove(p2top3line)
        //p2删除
        self.sketchLayer.pointLayer.remove(point2)




        return point1
      } else {
        return point2
      }


    }




  },
  drawPolygon(data) {


    const polygon = new Polygon({
      rings: data.path,


    })
    let graphic = new Graphic({
      geometry: polygon,
      attributes: data,
      symbol: {
        type: "simple-fill",
        color: [226, 119, 40],

      }

    })
    let editPolygonLayer = new GraphicsLayer({
      graphics: [graphic],
      id: 'editPolygonLayer',
      fullExtent: {
        spatialReference: 4326
      }
    })
    self.map.add(editPolygonLayer)
    const sketchViewModel = new SketchViewModel({
      view: self.view,
      layer: editPolygonLayer,
      defaultUpdateOptions: {
        highlightOptions: {
          enabled: false,
        },
        enableScaling: false,
        tool: 'reshape',
        reshapeOptions: {
          // edgeOperation :'none',
          shapeOperation: 'none'
        }
      },
    });

  },
  drawLine(data) {

    let graphics = []
    data.forEach(item => {
      let line = new Polyline({
        paths: item.path,
        "spatialReference": self.view.spatialReference
      })
      let graphic = new Graphic({
        geometry: line,
        attributes: item,
        symbol: {
          type: "simple-line",  // autocasts as new SimpleMarkerSymbol()
          color: item.color,
          width: item.width,  // pixels
          outline: {  // autocasts as new SimpleLineSymbol()
            color: [255, 255, 0],
            width: 3  // points
          }
        },
        // popupTemplate:{
        //   title: '管道'
        // },
      })
      graphic.attributes.imgPoint = self.addImgbyLine(
        item.path,
        graphic.geometry.extent.center.x,
        graphic.geometry.extent.center.y
      )
      graphics.push(graphic)
    });
    let editPolygonLayer = new GraphicsLayer({
      graphics: graphics,
      id: 'editPolygonLayer',
      fullExtent: {
        spatialReference: 4326
      }
    })

    self.map.add(editPolygonLayer)
    // const sketchViewModel = new SketchViewModel({
    //   view: self.view,
    //   layer: editPolygonLayer,
    //   defaultUpdateOptions: {
    //     highlightOptions: {
    //       enabled: false,
    //     },
    //     enableScaling: false,
    //     tool: 'reshape',
    //     reshapeOptions: {
    //       // edgeOperation :'none',
    //       shapeOperation: 'none'
    //     }
    //   },


    // });
    // sketchViewModel.on("update", onGraphicUpdate);
    // function onGraphicUpdate(event) {
    //   // get the graphic as it is being updated
    //   const graphic = event.graphics[0];

    //   let extent = graphic.geometry.extent
    //   graphic.attributes.imgPoint = self.addImgbyLine(
    //     [[extent.xmax, extent.ymax], [extent.xmin, extent.ymin],],
    //     graphic.geometry.extent.center.x,
    //     graphic.geometry.extent.center.y,
    //     graphic.attributes.imgPoint

    //   )

    // }



  },
}

export default ldMap
