import ldMap  from "./init";
import Draw from "@arcgis/core/views/draw/Draw.js";
import Graphic from "@arcgis/core/Graphic.js";
import * as geometryEngine from "@arcgis/core/geometry/geometryEngine.js";
import useMapDataStore from "@map/store/modules/mapData"

let selectGraphic
function cut(){
  if(ldMap.sketchLayer.selectGraphic){
    selectGraphic = ldMap.sketchLayer.selectGraphic
    startDrawLine()

    return {flag:true,data:''}
  }else{
    return {flag:false,data:''}
  }
}
function destroyDraw(){
  let mapdata = useMapDataStore()
  let polyline = ldMap.view.graphics.items[0].geometry
  let boundaryPolygon = selectGraphic.geometry

  const geometries = geometryEngine.cut(boundaryPolygon, polyline);
  geometries.forEach(polygon=>{
    let id = selectGraphic.attributes.type + ':' + Date.now()+Math.floor(Math.random() * (1000 -  1) + 0);
    console.log(id)
    let val = {
      geometryId: id,
      action: 2,
      "innerings":polygon.rings.length?polygon.rings.slice(1):[],
      "extend": null,
      type: selectGraphic.attributes.type,
      path: polygon.rings[0],
    }
   let data =    mapdata.addByTypeData(selectGraphic.attributes.type, val)

   const newPolygonGraphic = new Graphic({
    id,
    geometry: polygon,
    symbol: selectGraphic.symbol,
    attributes: {
      ...selectGraphic.attributes,
      data
    }
  });
   ldMap.sketchLayer.polygonLayer.add(newPolygonGraphic)

  })

  ldMap.sketchLayer.polygonLayer.remove(selectGraphic);
  mapdata.delData(selectGraphic.attributes.data)
  ldMap.view.graphics.removeAll();
  ldMap.sketchLayer.polygonLayer.sublayers.items.forEach(item=>{
    item.visible=true
  })
}
function startDrawLine(){
  ldMap.sketchLayer.polygonLayer.sublayers.items.forEach(item=>{
   if(item!=selectGraphic){
    item.visible=false
   }
  })
  ldMap.draw = new Draw({
    view: ldMap.view,
  })
  let action = ldMap.draw.create("polyline", {
    mode: 'click'
  });
  action.on("vertex-add", (event) => creatLineByClick(event));

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

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

}
function creatLineByClick(event){
ldMap.view.graphics.removeAll();
  var vertices = event.vertices;



  let polyline = {
    type: "polyline", // autocasts as new Polyline()
    paths: vertices,
    spatialReference: ldMap.view.spatialReference
  }

  let graphic = new Graphic({
    geometry: polyline,
    symbol: {
      type: "simple-line", // autocasts as new SimpleFillSymbol
      color: [0, 206, 209],
      width: 3,
      cap: "round",
      join: "round"
    }
  })
  ldMap.view.graphics.add(graphic)

}

export default cut
