import { nanoid } from 'nanoid';
import { useHistory } from '@/hooks/useHistory';
import { deepClone, getRgba } from '@/utils';
import { countCircleArea, countRectangleArea } from '@/utils/geometryUtil';

interface DrawToolOptions {
  color: string;
  drawType: string;
  lineWidth: string;
  graphicsType: string;
  onDrawCompleted?: Function;
}
export function useDrawTool() {
  let drawOptions = {
    strokeColor: '#f80102',
    strokeOpacity: 1,
    strokeWeight: '1',
    fillColor: '#f80102',
    fillOpacity: 0.5,
    strokeStyle: 'solid'
  };
  const { currentState, commit, undo, history, future } = useHistory();
  const overlays = [];
  const overlaysData = [];
  let mouseTool, contextMenu, container, map, AMap, rightClickObj;
  const initMouseTool = (options2) => {
    container = document.getElementById('aMap');
    map = options2.map;
    AMap = options2.AMap;
    // 初始化绘制工具
    mouseTool = new AMap.MouseTool(map);
    //创建右键菜单
    contextMenu = new AMap.ContextMenu();
  };

  // 删除图形
  const deleteGraphics = () => {
    const id = rightClickObj.getExtData()?.id;
    if (id) {
      for (let i = 0; i < overlays.length; i++) {
        const overlay = Array.isArray(overlays[i]) ? overlays[i][0] : overlays[i];
        if (overlay?.getExtData().id === id) {
          removeOverlayByIndex(i);
          commit(deepClone(overlaysData));
          rightClickObj = null;
        }
      }
    }
  };
  // 绘制图形
  const drawGraphics = (newOptions: MouseTool) => {
    const data = getRgba(newOptions.color);
    if (['circle', 'rectangle', 'polygon', 'measureArea'].includes(newOptions.graphicsType)) {
      drawOptions = {
        type: newOptions.graphicsType,
        strokeColor: !!data.color ? data.color : newOptions.color,
        strokeOpacity: 1,
        strokeWeight: newOptions.lineWidth,
        fillColor: data.color,
        fillOpacity: data.opacity,
        strokeStyle: 'solid'
      };
    } else if (['anyLine', 'straightLine'].includes(newOptions.graphicsType)) {
      drawOptions = {
        type: newOptions.graphicsType,
        strokeColor: !!data.color ? data.color : newOptions.color,
        strokeOpacity: data.opacity,
        strokeWeight: newOptions.lineWidth,
        strokeStyle: 'solid'
      };
    } else if (newOptions.graphicsType === 'marker') {
      drawOptions = {
        type: newOptions.graphicsType,
        anchor: 'bottom-center',
        title: newOptions.title,
        icon: newOptions.icon,
        size: [newOptions.size[0], newOptions.size[1]]
      };
    } else if (newOptions.graphicsType === 'text') {
      drawOptions = {
        type: newOptions.graphicsType,
        text: newOptions.text,
        fontSize: newOptions.fontSize,
        fontColor: newOptions.fontColor,
        lnglat: newOptions.lnglat
      };
    }
    closeDraw();
    if (newOptions.graphicsType === 'circle') {
      // 绘制圆形
      mouseTool.circle(drawOptions);
    } else if (newOptions.graphicsType === 'rectangle') {
      // 绘制矩形
      mouseTool.rectangle(drawOptions);
    } else if (newOptions.graphicsType === 'polygon') {
      // 绘制多边形
      mouseTool.polygon(drawOptions);
    } else if (newOptions.graphicsType === 'anyLine') {
      drawAnyLine(drawOptions);
    } else if (newOptions.graphicsType === 'straightLine') {
      // 绘制直线
      mouseTool.polyline(drawOptions);
    } else if (newOptions.graphicsType === 'text') {
      // 绘制文字
      return addText(drawOptions);
    } else if (newOptions.graphicsType === 'marker') {
      // 绘制图标
      mouseTool.marker(drawOptions);
    } else if (newOptions.graphicsType === 'measureArea') {
      // 测量面积
      mouseTool.polygon(drawOptions);
    }
    return drawOptions;
  };
  // 空间分析绘制图形
  const drawGraphics2 = (newOptions: MouseTool) => {
    drawOptions = {
      type: newOptions.graphicsType,
      strokeColor: newOptions.color,
      strokeOpacity: 1,
      strokeWeight: '1',
      fillColor: newOptions.color,
      fillOpacity: newOptions.drawType === '1' ? 0 : 0.5,
      strokeStyle: 'solid'
    };
    closeDraw();
    if (newOptions.graphicsType === 'circle') {
      // 绘制圆形
      mouseTool.circle(drawOptions);
    } else if (newOptions.graphicsType === 'rectangle') {
      // 绘制矩形
      mouseTool.rectangle(drawOptions);
    } else if (newOptions.graphicsType === 'polygon') {
      // 绘制多边形
      mouseTool.polygon(drawOptions);
    }
  };
  const addText = (options) => {
    // 文本覆盖物的样式
    const textStyle = {
      fontSize: options.fontSize,
      color: options.fontColor,
      borderColor: 'transparent',
      backgroundColor: 'transparent',
      borderWidth: 0,
      cursor: 'pointer' // 鼠标悬停时显示指针
    };

    // 创建文本覆盖物
    const text = new AMap.Text({
      text: options.text, // 文本内容，可以根据需要自定义
      position: options.lnglat, // 文本位置（经纬度）
      style: textStyle, // 文本样式
      zIndex: 100, // 文本层级
      draggable: false // 是否可拖动（可选）
    });
    // 将文本覆盖物添加到地图
    map.add(text);
    const id = nanoid();
    text._opts.extData = {
      id: id
    };
    const data: any = deepClone(options);
    data.id = id;
    return { text, data };
  };
  let polyline = null;
  let startPoint = null;
  let isDrawing = false;
  let lastPoint = null;
  // 绘制任意线
  const drawAnyLine = (options) => {
    // container.addEventListener('mousedown', drawAnyLineMouseDown);
    //
    // container.addEventListener('mousemove', (e) => {
    //   e.preventDefault();
    //   if (!isDrawing) return;
    //
    //   const mapPoint = this.map.getContainer().getBoundingClientRect();
    //   const lngLat = this.map.getLngLatFromContainerPixel([e.clientX - mapPoint.left, e.clientY - mapPoint.top]);
    //
    //   // 更新线条（这里需要手动管理polyline的坐标）
    //   if (polyline) {
    //     polyline.setPath(polyline.getPath().concat([lngLat]));
    //   } else {
    //     // 首次绘制时创建polyline
    //     polyline = new AMap.Polyline({
    //       map: this.map,
    //       path: [startPoint, lngLat],
    //       strokeColor: options.strokeColor,
    //       strokeWeight: options.strokeWeight,
    //       strokeOpacity: options.strokeOpacity,
    //       strokeStyle: 'solid',
    //       lineJoin: 'round',
    //       lineCap: 'round',
    //       zIndex: 50
    //     });
    //   }
    //   lastPoint = lngLat;
    //   console.log(lngLat);
    // });
    //
    // container.addEventListener('mouseup', (e) => {
    //   isDrawing = false;
    //   map.setDraggable(true);
    // });
  };
  // 任意线 鼠标按下事件
  const drawAnyLineMouseDown = (e) => {
    // 阻止默认行为
    e.preventDefault();
    // 获取鼠标在地图上的位置
    const mapPoint = map.getContainer().getBoundingClientRect();
    const lngLat = map.getLngLatFromContainerPixel([e.clientX - mapPoint.left, e.clientY - mapPoint.top]);

    startPoint = lngLat;
    isDrawing = true;
    lastPoint = startPoint;
  };
  // 关闭绘制
  const closeDraw = () => {
    mouseTool.close();
  };
  // 返回鼠标工具对象
  const getMouseTool = () => {
    return mouseTool;
  };
  // 创建图形
  const createGraphics = (data: any) => {
    if (data.type === 'circle') {
      // 绘制圆形
      return createCircle(data);
    } else if (['polygon', 'rectangle'].includes(data.type)) {
      // 绘制矩形、多边形
      return createPolygon(data);
    } else if (data.type === 'marker') {
      // 绘制图标
      return createMarker(data);
    } else if (data.type === 'measureArea') {
      // 绘制面积
      return createMeasureArea(data);
    } else if (data.type === 'text') {
      // 文字
      return addText(data);
    } else if (data.type === 'straightLine') {
      // 直线
      return createStraightLine(data);
    }
  };
  // 创建圆形
  const createCircle = (options) => {
    const circle = new AMap.Circle({
      center: options.center,
      radius: options.radius, //半径
      strokeColor: options.strokeColor,
      strokeOpacity: options.strokeOpacity,
      strokeWeight: options.strokeWeight,
      fillColor: options.fillColor,
      fillOpacity: options.fillOpacity,
      strokeStyle: 'solid'
    });
    map.add(circle);
    return circle;
  };
  // 创建矩形
  const createRectangle = (options: any) => {
    const southWest = new AMap.LngLat(options.southWest[0], options.southWest[1]);
    const northEast = new AMap.LngLat(options.northEast[0], options.northEast[1]);
    const bounds = new AMap.Bounds(southWest, northEast);
    const rectangle = new AMap.Rectangle({
      bounds: bounds,
      strokeColor: options.strokeColor,
      strokeOpacity: options.strokeOpacity,
      strokeWeight: options.strokeWeight,
      fillColor: options.fillColor,
      fillOpacity: options.fillOpacity,
      strokeStyle: 'solid'
    });
    overlays.push(rectangle);
    map.add(rectangle);
  };
  // 创建多边形
  const createPolygon = (options: any) => {
    // 将数组转换为AMap.LngLat对象的数组
    const path = options.path.map((coord) => {
      return new AMap.LngLat(coord[0], coord[1]);
    });
    const polygon = new AMap.Polygon({
      path: path,
      strokeColor: options.strokeColor,
      strokeOpacity: options.strokeOpacity,
      strokeWeight: options.strokeWeight,
      fillColor: options.fillColor,
      fillOpacity: options.fillOpacity,
      strokeStyle: 'solid'
    });
    map.add(polygon);
    return polygon;
  };
  // 创建直线
  const createStraightLine = (options: any) => {
    // 将数组转换为AMap.LngLat对象的数组
    const path = options.path.map((coord) => {
      return new AMap.LngLat(coord[0], coord[1]);
    });
    const polyline = new AMap.Polyline({
      path: path,
      strokeColor: options.strokeColor,
      strokeOpacity: options.strokeOpacity,
      strokeWeight: options.strokeWeight,
      strokeStyle: 'solid'
    });
    overlays.push(polyline);
    map.add(polyline);
  };
  // 绘制图标
  const createMarker = (options: any) => {
    const marker = new AMap.Marker({
      position: options.path,
      // 将一张图片的地址设置为 icon
      icon: options.icon,
      size: [options.size[0], options.size[1]],
      anchor: 'bottom-center'
    });
    map.add(marker);
  };
  // 绘制测量面积
  const createMeasureArea = (options: any) => {
    // 将数组转换为AMap.LngLat对象的数组
    const path = options.path.map((coord) => {
      return new AMap.LngLat(coord[0], coord[1]);
    });
    const polygon = new AMap.Polygon({
      path: path,
      strokeColor: options.strokeColor,
      strokeOpacity: 1,
      strokeWeight: options.strokeWeight,
      fillColor: options.fillColor,
      fillOpacity: options.fillOpacity,
      strokeStyle: 'solid'
    });
    // 计算区域面积
    const area = Math.round(AMap.GeometryUtil.ringArea(options.path));
    const text = new AMap.Text({
      position: path[path.length - 1],
      text: '区域面积' + area + '平方米',
      offset: new AMap.Pixel(-20, -20)
    });
    overlays.push(polygon, text);
    map.add(polygon);
    map.add(text);
  };
  // 处理撤销
  const handleUndo = () => {
    const previous = history.value[history.value.length - 2];
    if (history.value.length > 1) {
      if (currentState.value.length > previous.length) {
        // 撤销新增
        removeOverlayByIndex(currentState.value.length - 1);
      } else {
        let restoreData;
        for (let i = 0; i < previous.length; i++) {
          let index = 0;
          for (let k = 0; k < currentState.value.length; k++) {
            if (previous[i].id !== currentState.value[k].id) {
              index++;
            } else {
              break;
            }
          }
          if (index === previous.length - 1) {
            restoreData = previous[i];
            break;
          }
        }
        if (restoreData) {
          createGraphics(restoreData);
        }
      }
      undo();

      console.log(history.value, future.value, currentState.value);
    }
  };
  // 根据索引移除覆盖物
  const removeOverlayByIndex = (index: number) => {
    if (Array.isArray(overlays[index])) {
      overlays[index].forEach((overlay) => {
        // 移除地图上覆盖物
        map.remove(overlay);
      });
    } else {
      // 移除地图上覆盖物
      map.remove(overlays[index]);
    }
    overlays.splice(index, 1);
    overlaysData.splice(index, 1);
  };
  const getContextMenu = () => {
    return contextMenu;
  };
  const getAMap = () => {
    return AMap;
  };
  const getMap = () => {
    return map;
  };
  return {
    overlays,
    getMouseTool,
    getAMap,
    getMap,
    initMouseTool,
    getContextMenu,
    createGraphics,
    drawGraphics,
    drawGraphics2,
    closeDraw,
    createCircle,
    removeOverlayByIndex,
    handleUndo,
    currentState,
    history
  };
}
