import * as THREE from "three";

import FloorplanControls from "../controls/FloorplanControls.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

import { TrackballControls } from "three/examples/jsm/controls/TrackballControls.js";
import Line from "../box/object/Line";
import LinePoints from "../box/object/LinePoints.js";
import Marker from "../box/object/marker.js";
import CircleTextLabel from "../box/object/CircleTextLabel.js";
import PureTextLabel from "../box/object/PureTextLabel.js";
import { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js";

const convertScreenToNDC = function (event, domElement) {
  let x = (event.offsetX / domElement.clientWidth) * 2 - 1;
  let y = -(event.offsetY / domElement.clientHeight) * 2 + 1;
  return new THREE.Vector2(x, y);
};
export default class Player {
  constructor(scene) {
    this.scene = scene;
    this.orthCamera = scene.orthCamera;

    this.floorplanControls = null;
    this.raycaster = null;

    this.position = new THREE.Vector3();

    this.pointerdown = new THREE.Vector2();
    this.pointerup = new THREE.Vector2();
    this.pointer = new THREE.Vector2();
    this.markPosition = new THREE.Vector3();

    this.touchImg = null;
    this.activeEdge = null;
    this.drawLine = null;
    this.startObj = null;
    this.marker = null;
    this.symbol = null;
    this.symbolIndex = 0;
    this.text = null;
    this.showText = "文本";
    this.selectItem = null;

    this.drawing = false;
    this.inited = false;
    this.renderLines = [];
    this.renderMarkers = [];
    this.activeEdges = [];
    this.renderSymbols = [];
    this.renderTexts = [];

    this.matLine = null;
    this.lineColor = 0xe44d54;
    // 1是画线，2是标方向, 3符号, 4文本
    this.mode = 0;
    this.init();
  }

  setMode(mode) {
    this.mode = mode;

    if (mode !== 0) {
      this.reset();
      this.setEditMode();
    }
    // 2方向
    if (mode === 2) {
      let pos = new THREE.Vector3(0, 0, -1);
      pos.unproject(this.orthCamera);
      pos.y = 5;

      this.marker = new Marker(pos);
      this.marker.visible = false;
      this.scene.scene.add(this.marker);
      this.drawing = true;
    }
    //符号
    if (mode === 3) {
      console.log("this.orthCamera", this.orthCamera);
      let pos = new THREE.Vector3(0, 0, -1);
      pos.unproject(this.orthCamera);
      pos.y = 5;
      const lastIndex = this.getLaSybIndex();
      this.symbolIndex = lastIndex + 1;
      console.log("this.symbolIndex", this.symbolIndex);
      this.symbol = new CircleTextLabel(this.symbolIndex, pos);
      this.symbol.visible = false;
      this.scene.scene.add(this.symbol);
      console.log("this.symbol", this.symbol);
      this.drawing = true;
    }

    if (mode === 4) {
      let pos = new THREE.Vector3(0, 0, -1);
      pos.unproject(this.orthCamera);
      pos.y = 5;
      this.text = new PureTextLabel(this.showText, pos);
      this.text.visible = false;
      this.showText = "文本";
      this.scene.scene.add(this.text);
      this.drawing = true;
    }

    if (mode === 0) {
      this.setFreeMode();
    }
    this.scene.emit("mode", this.mode);
  }
  getLaSybIndex() {
    const maxIndexObject = this.renderSymbols.reduce(
      (max, current) => {
        return current.index > max.index ? current : max;
      },
      { index: 0, point: [] }
    );
    console.log("maxIndexObject", this.renderSymbols);
    return maxIndexObject.index;
  }

  setFreeMode() {
    this.floorplanControls.enablePan = true;
    this.floorplanControls.mouseButtons = {
      LEFT: THREE.MOUSE.PAN,
      MIDDLE: THREE.MOUSE.DOLLY,
      RIGHT: THREE.MOUSE.PAN,
    };
    this.reset();
  }

  setEditMode() {
    this.floorplanControls.enablePan = true;
    this.floorplanControls.mouseButtons = {
      LEFT: THREE.MOUSE.ROTATE,
      MIDDLE: THREE.MOUSE.DOLLY,
      RIGHT: THREE.MOUSE.PAN,
    };
  }

  setRotateMode() {
    this.floorplanControls.enableRotate = true;
    this.floorplanControls.mouseButtons = {
      LEFT: THREE.MOUSE.ROTATE,
      MIDDLE: THREE.MOUSE.DOLLY,
      RIGHT: THREE.MOUSE.PAN,
    };
  }
  init = () => {
    // //floorplanControls
    // this.floorplanControls = new FloorplanControls(
    //   this.orthCamera,
    //   this.scene.domElement,
    //   this
    // );
    this.floorplanControls = new OrbitControls(
      this.orthCamera,
      this.scene.domElement
    );

    this.floorplanControls.enablePan = true;
    // this.floorplanControls.target.set(0, 1, 0);
    // this.floorplanControls.rotateSpeed = 0.5;
    // this.floorplanControls.panSpeed = 0.75

    this.floorplanControls.maxDistance = 100;
    this.floorplanControls.minDistance = 3.5;
    this.floorplanControls.maxZoom = 500;
    this.floorplanControls.minZoom = 100;

    // this.floorplanControls.mouseButtons = {
    //   LEFT: THREE.MOUSE.PAN,
    //   MIDDLE: THREE.MOUSE.DOLLY,
    //   RIGHT: THREE.MOUSE.PAN
    // }
    this.setMode(0);
    this.floorplanControls.enableRotate = false;
    this.raycaster = new THREE.Raycaster();
    this.onBindEvent();
    this.inited = true;
    this.matLine = new LineMaterial({
      color: this.lineColor,
      linewidth: 4, // in world units with size attenuation, pixels otherwise
      dashed: false,
      alphaToCoverage: true,
    });
    this.matLine.resolution = new THREE.Vector2(
      this.scene.width,
      this.scene.height
    );
  };

  onPointerMove = (e) => {
    // console.log("intersects", intersects);
    // if (this.mode === 0) {
    //   const intersects = this.raycaster.intersectObjects(
    //     this.scene.scene.children,
    //     true
    //   );
    //   intersects.forEach((i) => {
    //     if (String(i.object.name).includes("marker")) {
    //       // console.log("i.object.name", i.object);
    //       // debugger
    //     }
    //   });
    // }
    this.pointermove = convertScreenToNDC(e, this.scene.domElement);
    this.raycaster.setFromCamera(this.pointermove, this.orthCamera);

    if (!this.drawing) return;

    if (this.mode === 1) {
      let intersectArr = this.scene.boxManager.imgList;
      // if(this.startObj) {
      //   let i = intersectArr.indexOf(this.startObj)
      //   intersectArr.splice(i, 1)
      // }
      const intersects = this.raycaster.intersectObjects(intersectArr, false);
      if (intersects[0] && intersects[0].object !== this.startObj) {
        this.touchImg = intersects[0];
        this.setActiveLine(this.touchImg);
      }
    }
    if (this.mode === 2) {
      if (this.marker) {
        this.marker.visible = true;
        let pos = new THREE.Vector3(this.pointermove.x, this.pointermove.y, -1);
        pos.unproject(this.orthCamera);
        pos.y = 5;
        this.marker.position.copy(pos);
      }
    }

    if (this.mode === 3) {
      if (this.symbol) {
        this.symbol.visible = true;
        let pos = new THREE.Vector3(this.pointermove.x, this.pointermove.y, -1);
        pos.unproject(this.orthCamera);
        pos.y = 5;
        const clamp = new THREE.Vector3();
        this.scene.boxManager.obb.clampPoint(pos, clamp);
        clamp.y = 5;
        this.symbol.position.copy(clamp);
      }
    }

    if (this.mode === 4) {
      if (this.text) {
        this.text.visible = true;
        let pos = new THREE.Vector3(this.pointermove.x, this.pointermove.y, -1);
        pos.unproject(this.orthCamera);
        pos.y = 5;

        const clamp = new THREE.Vector3();
        this.scene.boxManager.obb.clampPoint(pos, clamp);
        clamp.y = 5;
        this.text.position.copy(clamp);
        this.text.userData.pos = clamp.toArray();
      }
    }
  };

  onPointerDown = (e) => {
    console.log("start draw");

    this.pointerdown = convertScreenToNDC(e, this.scene.domElement);

    if (this.mode === 0) {
      const intersects = this.raycaster.intersectObjects(
        this.scene.scene.children,
        true
      );
      intersects.forEach((i) => {
        if (
          String(i.object.name).includes("marker") ||
          String(i.object.name).includes("line") ||
          String(i.object.name).includes("circle") ||
          String(i.object.name).includes("pureText")
        ) {
          let type;
          switch (true) {
            case String(i.object.name).includes("marker"):
              type = 1;
              break;
            case String(i.object.name).includes("line"):
              type = 2;
              break;
            case String(i.object.name).includes("circle"):
              type = 3;
              break;
            case String(i.object.name).includes("pureText"):
              type = 4;
              break;
          }

          this.selectItem = i.object;
          this.scene.emit("confirmDelete", {
            id: i.object.uuid,
            type,
          });
        }
      });
    }

    if (this.mode === 1) {
      this.raycaster.setFromCamera(this.pointerdown, this.orthCamera);
      let intersectArr = this.scene.boxManager.imgList;
      const intersects = this.raycaster.intersectObjects(intersectArr, false);
      console.log("intersects", intersects);
      if (intersects[0]) {
        this.startObj = intersects[0].object;
        this.drawing = true;
      } else {
        this.startObj = null;
        this.drawing = false;
      }
    }

    if (this.mode === 2) {
      if (this.marker) {
        this.raycaster.setFromCamera(this.pointerdown, this.orthCamera);
        let intersectArr = this.scene.boxManager.imgList;
        const intersects = this.raycaster.intersectObjects(intersectArr, false);

        if (intersects[0]) {
          // this.drawing = false;
          const imageId = intersects[0].object.userData;
          let lasPos = new THREE.Vector3(
            this.pointerdown.x,
            this.pointerdown.y,
            -1
          );
          lasPos.unproject(this.orthCamera);
          lasPos.y = 5;
          const marker = new Marker(lasPos, imageId);

          const activeMarkeritem = {
            id: imageId,
            point: lasPos.toArray(),
          };
          const exist = this.renderMarkers.find((item) => item.id === imageId);

          if (!exist) {
            this.scene.scene.add(marker);
            this.renderMarkers.push(activeMarkeritem);
            this.scene.scene.remove(this.marker);
            this.marker = null;
          } else {
            this.scene.emit("markerExist");
          }

          console.log("activeMarkeritem", activeMarkeritem);
          this.setMode(0);
        }
      }
    }

    if (this.mode === 3) {
      if (this.symbol) {
        let lasPos = new THREE.Vector3(
          this.pointerdown.x,
          this.pointerdown.y,
          -1
        );
        lasPos.unproject(this.orthCamera);
        lasPos.y = 5;

        const activeSymbolItem = {
          index: this.symbolIndex,
          point: lasPos.toArray(),
        };
        this.renderSymbols.push(activeSymbolItem);
        console.log("activeSymbolItem", activeSymbolItem);
        this.setMode(0);
      }
    }
    if (this.mode === 4) {
      if (this.text) {
        let lasPos = new THREE.Vector3(
          this.pointerdown.x,
          this.pointerdown.y,
          -1
        );
        this.scene.emit("edit", {
          type: 4,
          text: this.showText,
          id: this.text.uuid,
          ...this.text.userData,
        });
        this.drawing = true;
        // const activeSymbolItem = {
        //   id: this.symbolIndex,
        //   point: lasPos.toArray(),
        // };

        // this.setMode(0);
      }
    }
  };
  onPointerUp = (e) => {
    this.pointerup = convertScreenToNDC(e, this.scene.domElement);
    // console.log("onPointerUp", this.pointerup);
    if (this.mode === 1) {
      this.drawing = false;
      this.floorplanControls.enabled = true;

      if (this.drawLine) {
        const points = this.drawLine.userData.points;
        const dir = this.drawLine.userData.dir;
        const imageId = this.touchImg.object.userData;
        const finishLine = new LinePoints(points, this.matLine, dir, imageId);
        // console.log("startObj", this.startObj);
        this.scene.scene.add(finishLine);
        const activeLineItem = {
          id: finishLine.uuid,
          imgId: imageId,
          startId: this.startObj.userData,
          dir: dir,
          points: points,
        };
        const activeEdgeItem = {
          id: imageId,
          startId: this.startObj.userData,
          dir: [dir],
        };

        this.renderLines.push(activeLineItem);
        // console.log("this.touchImg", activeLineItem, points);
        this.insertActiveEdge(activeEdgeItem);
        this.scene.scene.remove(this.drawLine);
        this.drawLine = null;
        this.startObj = null;
      }
    }
    if (this.mode === 2) {
      // this.drawing = false;
    }
    if (this.mode === 4) {
      if (this.text) {
        let pos = new THREE.Vector3(this.pointerup.x, this.pointerup.y, -1);
        pos.unproject(this.orthCamera);
        pos.y = 5;
        const clamp = new THREE.Vector3();
        this.scene.boxManager.obb.clampPoint(pos, clamp);
        clamp.y = 5;
        console.log("pos", pos);
        console.log("clamp", clamp);
        this.text.position.copy(clamp);
        this.text.userData.pos = clamp.toArray();
        const activeTextItem = this.text.userData;
        this.drawing = false;
        console.log("activeTextItem", activeTextItem);
        this.insertrenderTexts(activeTextItem);
      }
    }
    this.syncDrawData();
  };

  Listener = {
    onPointerDown: this.onPointerDown.bind(this),
    onPointerMove: this.onPointerMove.bind(this),
    onPointerUp: this.onPointerUp.bind(this),
  };

  onBindEvent = () => {
    this.scene.domElement.addEventListener(
      "pointerdown",
      this.Listener.onPointerDown
    );
    this.scene.domElement.addEventListener(
      "pointermove",
      this.Listener.onPointerMove,
      false
    );
    this.scene.domElement.addEventListener(
      "pointerup",
      this.Listener.onPointerUp
    );
  };
  unbindEvent = () => {
    this.scene.domElement.removeEventListener(
      "pointerdown",
      this.Listener.onPointerDown
    );
    this.scene.domElement.removeEventListener(
      "pointermove",
      this.Listener.onPointerMove
    );
    this.scene.domElement.removeEventListener(
      "pointerup",
      this.Listener.onPointerUp
    );
  };

  buildLine = () => {
    if (this.drawLine) {
      this.drawLine.removeFromParent();
    }
    let s = new THREE.Vector3(this.pointerdown.x, this.pointerdown.y, -1);
    let e = new THREE.Vector3(this.pointermove.x, this.pointermove.y, -1);
    s.unproject(this.orthCamera);
    e.unproject(this.orthCamera);
    s.y = 5;
    e.y = 5;
    const matLine = new LineMaterial({
      color: this.lineColor,
      linewidth: 4, // in world units with size attenuation, pixels otherwise
      dashed: false,
      alphaToCoverage: true,
    });
    matLine.resolution = new THREE.Vector2(this.scene.width, this.scene.height);
    this.drawLine = new Line(s, e, this.activeEdge, matLine);
    this.scene.scene.add(this.drawLine);
  };

  setActiveLine = (obj) => {
    function getTouchLine(x, y) {
      // [0 - 1]
      x -= 0.5;
      y -= 0.5;
      // console.log(x, y);
      if (x >= 0 && y >= 0) {
        if (x > y) {
          return 3;
        } else {
          return 0;
        }
      } else if (x >= 0 && y <= 0) {
        if (x > Math.abs(y)) {
          return 3;
        } else {
          return 2;
        }
      } else if (x <= 0 && y >= 0) {
        if (Math.abs(x) > y) {
          return 1;
        } else {
          return 0;
        }
      } else if (x <= 0 && y <= 0) {
        if (-x > -y) {
          return 1;
        } else {
          return 2;
        }
      }
    }

    if (this.activeEdge) {
      this.activeEdge.visible = false;
      this.activeEdge = null;
    }

    let num = getTouchLine(obj.uv.x, obj.uv.y);
    this.activeEdge = obj.object.touchLines.getObjectByName(num);
    this.activeEdge.visible = true;
    this.buildLine();
  };

  insertActiveEdge(item) {
    const exist = this.activeEdges.find((s) => item.id === s.id);
    if (exist) {
      exist.dir = [...new Set([...exist.dir, ...item.dir])];
    } else {
      this.activeEdges.push(item);
    }
  }

  // insertActiveMarker(item) {
  //   const exist = this.activeEdges.find((s) => item.id === s.id);
  //   if (exist) {
  //     exist.dir = [...new Set([...exist.dir, ...item.dir])];
  //   } else {
  //     this.activeEdges.push(item);
  //   }
  // }

  insertrenderTexts(item) {
    const index = this.renderTexts.findIndex((s) => item.id === s.id);
    if (index > -1) {
      this.renderTexts[index] = item;
    } else {
      this.renderTexts.push(item);
    }
  }

  showAllActiveEdges() {
    if (this.inited) {
      let imgList = this.scene.boxManager.imgList;
      if (this.activeEdges.length > 0) {
        this.activeEdges.forEach((edge) => {
          const exist = imgList.find((item) => item.userData === edge.id);
          if (exist) {
            let others = [0, 1, 2, 3].filter((x) => !edge.dir.includes(x));
            // console.log("others", others);
            edge.dir.forEach((dir) => {
              exist.touchLines.children[dir].visible = true;
            });
            // console.log("others", others);
            others.forEach((dir) => {
              exist.touchLines.children[dir].visible = false;
            });
          }
        });
      } else {
        imgList.forEach((img) => {
          // console.log("img", img);
          img.touchLines.children.forEach((line) => {
            if (line.visible) {
              line.visible = false;
            }
          });
        });
      }
    }
  }
  deleteItemByType(type, data) {
    if (type === 1) {
      const index = this.renderMarkers.findIndex((mk) => {
        const p = new THREE.Vector3().fromArray(mk.point);
        const v = new THREE.Vector3().fromArray(data.point);
        return p.equals(v);
      });
      this.renderMarkers.splice(index, 1);
    }
    if (type === 2) {
      const { imgId, id, dir, points } = data;
      const index = this.renderLines.findIndex((item) => item.id === id);
      index > -1 && this.renderLines.splice(index, 1);
      //线段处理完成
      const egIndex = this.activeEdges.findIndex((eg) => eg.id === imgId);
      if (egIndex > -1) {
        //存在activeEdge 再找renderLines的sibling
        const cluEgArr = this.renderLines
          .filter((l) => l.imgId === this.activeEdges[egIndex].id)
          .reduce((pre, curr) => pre.concat(curr["dir"]), []);
        const uni_dir = [...new Set(cluEgArr)];
        console.log("uni_dir", uni_dir);
        if (uni_dir.length > 0) {
          this.activeEdges[egIndex].dir = uni_dir;
        } else {
          console.log("全空", this.activeEdges[egIndex].id);
          let imgList = this.scene.boxManager.imgList;
          const image = imgList.find(
            (item) => item.userData === this.activeEdges[egIndex].id
          );
          image.touchLines.children.forEach((line) => {
            line.visible = false;
          });
          this.activeEdges.splice(egIndex, 1);
          this.update();
        }
      }
    }
    if (type === 3) {
      const index = this.renderSymbols.findIndex((syb) => {
        const p = new THREE.Vector3().fromArray(syb.point);
        const v = new THREE.Vector3().fromArray(data);
        return p.equals(v);
      });
      this.renderSymbols.splice(index, 1);
    }
    if (type === 4) {
      const { id } = data;
      const index = this.renderTexts.findIndex((item) => item.id === id);
      index > -1 && this.renderTexts.splice(index, 1);
    }
  }
  editing(item) {
    if (item.type === 4) {
      if (this.text) {
        const { pos } = this.text.userData;
        const newP = new THREE.Vector3().fromArray(pos);
        this.scene.scene.remove(this.text);
        this.text = null;
        this.showText = item.text;
        console.log("editing", item, newP);
        // // console.log("this.text", lastPos, newP, item);
        this.text = new PureTextLabel(
          item.text,
          newP,
          item.fontsize,
          item.color,
          item.id
        );
        this.scene.scene.add(this.text);
        const activeTextItem = this.text.userData;
        console.log("activeTextItem", activeTextItem);
        this.insertrenderTexts(activeTextItem);
      }
    }
  }
  getDrawData() {
    let data;
    if (this.scene.sceneType === 1) {
      data = {
        hor_lines: this.renderLines,
        hor_activeEdges: this.activeEdges,
        hor_markers: this.renderMarkers,
        hor_symbols: this.renderSymbols,
        hor_texts: this.renderTexts,
        vir_lines: [],
        vir_activeEdges: [],
        vir_markers: [],
        vir_symbols: [],
        vir_texts: [],
      };
    } else {
      data = {
        hor_lines: [],
        hor_activeEdges: [],
        hor_markers: [],
        hor_symbols: [],
        hor_texts: [],
        vir_lines: this.renderLines,
        vir_activeEdges: this.activeEdges,
        vir_markers: this.renderMarkers,
        vir_symbols: this.renderSymbols,
        vir_texts: this.renderTexts,
      };
    }

    // console.log("sceneType", this.scene.sceneType);
    return data;
  }

  syncDrawData() {
    const data = this.getDrawData();
    this.scene.emit("data", data);
  }
  load(type, data) {
    if (type === 1) {
      console.log("data1", data);
      const {
        hor_activeEdges,
        hor_lines,
        hor_markers,
        hor_symbols,
        hor_texts,
      } = data;
      hor_activeEdges && (this.activeEdges = hor_activeEdges);
      if (hor_lines && Array.isArray(hor_lines)) {
        this.renderLines = hor_lines;
        hor_lines.forEach((line) => {
          const finishLine = new LinePoints(
            line.points,
            this.matLine,
            line.dir,
            line.imgId,
            line.id
          );
          this.scene.scene.add(finishLine);
        });
      }
      if (hor_markers && Array.isArray(hor_markers)) {
        this.renderMarkers = hor_markers;
        hor_markers.forEach((pos) => {
          console.log("pos");
          const p = new THREE.Vector3().fromArray(pos.point);
          const marker = new Marker(p, pos.id);
          this.scene.scene.add(marker);
        });
      }

      if (hor_symbols && Array.isArray(hor_symbols)) {
        this.renderSymbols = hor_symbols;
        hor_symbols.forEach((syb) => {
          console.log("pos");
          const p = new THREE.Vector3().fromArray(syb.point);
          const symbol = new CircleTextLabel(syb.index, p);
          this.scene.scene.add(symbol);
        });
      }
      if (hor_texts && Array.isArray(hor_texts)) {
        this.renderTexts = hor_texts;
        hor_texts.forEach((txt) => {
          console.log("pos");
          const p = new THREE.Vector3().fromArray(txt.pos);
          const text = new PureTextLabel(
            txt.text,
            p,
            txt.fontsize,
            txt.color,
            txt.id
          );
          this.scene.scene.add(text);
        });
      }
    }

    if (type === 2) {
      const {
        vir_activeEdges,
        vir_lines,
        vir_markers,
        vir_symbols,
        vir_texts,
      } = data;
      vir_activeEdges && (this.activeEdges = vir_activeEdges);
      if (vir_lines && Array.isArray(vir_lines)) {
        this.renderLines = vir_lines;
        vir_lines.forEach((line) => {
          const finishLine = new LinePoints(
            line.points,
            this.matLine,
            line.dir,
            line.imgId,
            line.id
          );
          this.scene.scene.add(finishLine);
        });
      }
      if (vir_markers && Array.isArray(vir_markers)) {
        this.renderMarkers = vir_markers;
        vir_markers.forEach((pos) => {
          const p = new THREE.Vector3().fromArray(pos.point);
          const marker = new Marker(p);
          this.scene.scene.add(marker);
        });
      }
      if (vir_symbols && Array.isArray(vir_symbols)) {
        this.renderSymbols = vir_symbols;
        vir_symbols.forEach((syb) => {
          // console.log("pos", syb);
          const p = new THREE.Vector3().fromArray(syb.point);
          const symbol = new CircleTextLabel(syb.index, p);
          this.scene.scene.add(symbol);
        });
      }
      if (vir_texts && Array.isArray(vir_texts)) {
        this.renderTexts = vir_texts;
        vir_texts.forEach((txt) => {
          console.log("pos");
          const p = new THREE.Vector3().fromArray(txt.pos);
          const text = new PureTextLabel(
            txt.text,
            p,
            txt.fontsize,
            txt.color,
            txt.id
          );
          this.scene.scene.add(text);
        });
      }
    }
    this.syncDrawData();
  }
  reset() {
    if (this.marker) {
      this.scene.scene.remove(this.marker);
      this.marker = null;
    }
    if (this.drawLine) {
      this.scene.scene.remove(this.drawLine);
      this.drawLine = null;
    }
    if (this.touchImg) {
      this.touchImg = null;
    }
    if (this.activeEdge) {
      this.activeEdge = null;
    }
    if (this.text) {
      this.text = null;
      this.scene.scene.remove(this.text);
    }
    this.showText = "文本";
    this.drawing = false;
  }

  clear() {
    this.activeEdges = [];
    this.renderLines = [];
    this.renderMarkers = [];
    this.renderSymbols = [];
    this.renderTexts = [];
    this.reset();
    this.scene.clearDrawScene();
    this.syncDrawData();
  }

  //单多张图片删除时要删除相关数据
  deleteImageDataByIds(ids) {
    setTimeout(() => {
      console.warn("单多张图片删除时要删除相关数据", ids);
      this.clear();
      this.scene.emit("autoSave");
      // this.t_deleteImageDataByIds(ids);
    }, 500);
  }
  t_deleteImageDataByIds(ids) {
    ids.forEach((id) => {
      const makerIndex = this.renderMarkers.findIndex((item) => item.id === id);
      if (makerIndex > -1) {
        this.renderMarkers.splice(makerIndex, 1);
      }
      const lines = this.renderLines.filter(
        (item) => item.imgId === id || item.startId === id
      );

      lines.forEach((line) => {
        const edge = this.activeEdges.find(
          (item) => item.id === line.imgId || item.startId === line.imgId
        );
        if (edge) {
          if (edge.dir.length > 0) {
            const dirIndex = Array.from(edge.dir).findIndex(
              (d) => d === line.dir
            );
            edge.dir.splice(dirIndex, 1);
          } else {
            const indexEdge = this.activeEdges.findIndex(
              (a) => a.id === edge.id
            );
            console.warn("edge没dir", indexEdge);
            indexEdge > -1 && this.activeEdges.splice(indexEdge, 1);
          }
        }

        const lineIndex = this.renderLines.findIndex(
          (item) => item.imageId === line.imageId
        );
        console.log("lineIndex", lineIndex);
        if (lineIndex > -1) {
          this.renderLines.splice(lineIndex, 1);
        }
      });
      console.log("lines", lines);
    });

    setTimeout(() => {
      this.syncDrawData();
      this.scene.emit("autoSave");
    }, 2500);
  }

  checkDeleteing() {
    const makers = this.scene.scene.children.filter((obj) =>
      String(obj.name).includes("marker_")
    );
    Array.from(makers).forEach((marker) => {
      const { imageId, point } = marker.userData;
      const image = this.scene.boxManager.imgList.find(
        (item) => item.userData === imageId
      );
      if (image) {
        const nPoint = new THREE.Vector3().fromArray(point);
        nPoint.project(this.orthCamera);
        console.log("nPoint", nPoint, point);

        this.raycaster.setFromCamera(nPoint, this.orthCamera);
        const intersects = this.raycaster.intersectObjects(
          this.scene.boxManager.imgList,
          false
        );

        if (image.userData !== intersects[0].object.userData) {
          console.log("相交不正确");
          this.scene.scene.remove(marker);
        }
      }
      // const
    });
  }

  update = () => {
    if (this.floorplanControls.enabled) {
      this.floorplanControls && this.floorplanControls.update();
      this.scene.boxManager && this.showAllActiveEdges();
    }
  };
}
