import React__default, { useState, useRef, useCallback, useEffect, useMemo } from 'react';
import MoveContentView from '../MoveContent/index.js';
import { cloneDeep, flatten, isFunction } from 'lodash';
import { resizeObserver } from '@zenview/micro-utils';
import { Tooltip } from 'antd';
import IconFont from '../IconFont/index.js';
import FullScreen from '../FullScreen/index.js';
import 'add-dom-event-listener';
import '../_rollupPluginBabelHelpers-736b301a.js';

/**
 * 计算抓拍区域
 */
function getRectImagePath(sourceImage, cuurentImage, rect, options = {
  scale: 1,
  rotate: 0,
  x: 0,
  y: 0
}) {
  if (!sourceImage || !cuurentImage) {
    return null;
  }
  const {
    scale,
    rotate
  } = options;
  const [x, y, w, h] = rect;
  const {
    width,
    height
  } = sourceImage;
  const sourceSize = {
    width,
    height,
    cwidth: cuurentImage.width,
    cheight: cuurentImage.height,
    wScale: width / cuurentImage.width,
    hScale: height / cuurentImage.height
  };
  const area = [x * sourceSize.wScale, y * sourceSize.hScale, w * sourceSize.wScale, h * sourceSize.hScale];
  let fullCanvas = document.createElement('canvas');
  let fullCtx = fullCanvas.getContext('2d');
  fullCanvas.width = width;
  fullCanvas.height = height;
  fullCtx.save();
  // fullCtx.transform;
  // document.body.appendChild(fullCanvas);
  fullCtx.setTransform(scale, 0, 0, scale, options.x * sourceSize.wScale - (scale - 1) * width / 2, options.y * sourceSize.hScale - (scale - 1) * height / 2);
  fullCtx.translate(width / 2, height / 2);
  fullCtx.rotate(rotate * Math.PI / 180);
  fullCtx.drawImage(sourceImage, -width / 2, -height / 2, width, height);
  fullCtx.restore();
  let imageData = fullCtx.getImageData(...area);
  let tempCanvas = document.createElement('canvas');
  let tempCtx = tempCanvas.getContext('2d');
  tempCanvas.width = area[2];
  tempCanvas.height = area[3];
  // document.body.appendChild(tempCanvas);
  tempCtx.putImageData(imageData, 0, 0);
  const dataUrl = tempCanvas.toDataURL();
  setTimeout(() => {
    fullCanvas.remove();
    tempCanvas.remove();
    fullCanvas = null;
    tempCanvas = null;
    tempCtx = null;
    fullCtx = null;
    imageData = null;
  }, 100);
  return dataUrl;
}

function computedBound(ele, currentPosition, scale, rotate) {
  const data = currentPosition;
  const eleRect = ele.getBoundingClientRect();
  const isHorizontal = Math.abs(rotate) % 180 === 0;
  const w = eleRect.width;
  const h = eleRect.height;
  let lx = 0,
    ly = 0;
  if (scale === 1 && isHorizontal) {
    return {
      x: 0,
      y: 0
    };
  }
  if (scale === 1 && !isHorizontal) {
    lx = 0;
    ly = (w - h) / 2;
  } else {
    //TODO 这是限制x区域，应该是使用原来高度的缩放大小来计算，
    if (h * scale < w && !isHorizontal) {
      //TODO 放大后竖向是 h*scale<w是 x = 0， 
      lx = 0;
    } else {
      //TODO 得到缩放后可移动区域 在减去误差 (w - h) / 2
      lx = !isHorizontal ? Math.round(h * (scale - 1) / 2 - (w - h) / 2) : Math.round(w * (scale - 1) / 2);
    }
    //TODO y的限制区域应该是原来宽度的限制区域计算后还要加上原始的（w-h）/2
    ly = !isHorizontal ? Math.round(w * (scale - 1) / 2 + (w - h) / 2) : Math.round(h * (scale - 1) / 2);
  }
  let x = 0,
    y = 0;
  if (data.x >= 0 && data.x > lx) {
    x = lx;
  }
  if (data.x >= 0 && data.x < lx) {
    x = data.x;
  }
  if (data.x < 0 && data.x < -lx) {
    x = -lx;
  }
  if (data.x < 0 && data.x > -lx) {
    x = data.x;
  }
  if (data.y >= 0 && data.y > ly) {
    y = ly;
  }
  if (data.y >= 0 && data.y < ly) {
    y = data.y;
  }
  if (data.y < 0 && data.y < -ly) {
    y = -ly;
  }
  if (data.y < 0 && data.y > -ly) {
    y = data.y;
  }
  if (x !== data.x || y !== data.y) {
    return {
      x,
      y
    };
  } else {
    return;
  }
}

function customContextMenu(e, menu) {
  e.preventDefault();
  return false;
}
function cloneImageNode(image) {
  if (!image) {
    return Promise.resolve();
  }
  let newImage = image.cloneNode();
  return new Promise((resolve, reject) => {
    newImage.addEventListener('load', function () {
      resolve(this);
    }, false);
    newImage.addEventListener('error', function (e) {
      reject(e);
    }, false);
  });
}
function computedRectScale({
  imageSource,
  domImg,
  rects
}) {
  if (!imageSource || !domImg) {
    return [];
  }
  const width = domImg.width;
  const height = domImg.height;
  let scaleOptions = {
    scaleX: width / imageSource.width,
    scaleY: height / imageSource.height
  };
  return rects.map(item => {
    let rect = item.needExpand ? getCaptureRect(cloneDeep(item.rect), item.type) : cloneDeep(item.rect);
    rect[0] = Math.round(rect[0] * scaleOptions.scaleX);
    rect[0] < 0 && (rect[0] = 0);
    rect[2] = Math.round(rect[2] * scaleOptions.scaleX);
    rect[2] < 0 && (rect[2] = 0);
    rect[1] = Math.round(rect[1] * scaleOptions.scaleY);
    rect[1] < 0 && (rect[1] = 0);
    rect[3] = Math.round(rect[3] * scaleOptions.scaleY);
    rect[3] < 0 && (rect[3] = 0);
    rect[2] > width - rect[0] && (rect[2] = width - rect[0]);
    rect[3] > height - rect[1] && (rect[3] = height - rect[1]);
    return {
      ...item,
      rect
    };
  });
}
function computedDrawAreaScale({
  imageSource,
  domImg,
  drawArea = []
}) {
  if (!imageSource || !domImg) {
    return [];
  }
  const width = domImg.width;
  const height = domImg.height;
  let scaleOptions = {
    scaleX: width / imageSource.width,
    scaleY: height / imageSource.height
  };
  return cloneDeep(drawArea).map(item => {
    item[0] = Math.round(item[0] * scaleOptions.scaleX);
    item[0] < 0 && (item[0] = 0);
    item[1] = Math.round(item[1] * scaleOptions.scaleY);
    item[1] < 0 && (item[1] = 0);
    return {
      rect: item,
      color: '#127aff'
    };
  });
}
function computedRoiRectScale({
  imageSource,
  domImg,
  roiRects = []
}) {
  if (!imageSource || !domImg) {
    return [];
  }
  let allRoiRects = flatten(roiRects.map(v => v.boundaries)) || [];
  allRoiRects = allRoiRects.map(item => {
    let polygonArea = item.polygonArea || [];
    item.rect = polygonArea.map(v => {
      return [Math.round(v.x * imageSource.width), Math.round(v.y * imageSource.height)];
    });
    return item;
  });
  const width = domImg.width;
  const height = domImg.height;
  let scaleOptions = {
    scaleX: width / imageSource.width,
    scaleY: height / imageSource.height
  };
  let arr = cloneDeep(allRoiRects).map(roiRect => {
    roiRect.rect = roiRect.rect.map(item => {
      item[0] = Math.round(item[0] * scaleOptions.scaleX);
      item[0] < 0 && (item[0] = 0);
      item[1] = Math.round(item[1] * scaleOptions.scaleY);
      item[1] < 0 && (item[1] = 0);
      return item;
    });
    return roiRect;
  });
  return arr;
}
function getCaptureRect(rect, type) {
  let rectArea = rect;
  if (rectArea.length !== 4) {
    console.error('区域有误 实例：string = "x,y,w,h"! ', rect);
    return [0, 0, 0, 0];
  }
  let x, y, w, h;
  switch (type) {
    case 'body':
      x = rectArea[0] - rectArea[2] * 0.2;
      y = rectArea[1] - rectArea[3] * 0.2;
      w = rectArea[2] * 1.4;
      h = rectArea[3] * 1.4;
      break;
    case 'nonVehicle':
    case 'vehicle':
    case 'thing':
      x = rectArea[0];
      y = rectArea[1];
      w = rectArea[2];
      h = rectArea[3];
      break;
    default:
      // face
      x = rectArea[0] - rectArea[2] * 0.8;
      y = rectArea[1] - rectArea[3] * 1.5;
      w = rectArea[2] * 2.6;
      h = rectArea[3] * 3.2;
      break;
  }
  return [x, y, w, h];
}

function useDraw(dom, flag) {
  const [state, setState] = useState({
    rect: [0, 0, 0, 0],
    isEnd: false
  });
  const selectOptionsRef = useRef({
    start: [0, 0],
    end: [0, 0],
    startSelect: false
  });

  /**
   * 绘制框选矩形区域
   */
  const drawSelectRact = useCallback(isEnd => {
    const {
      left,
      top,
      width,
      height
    } = dom.getBoundingClientRect();
    let [x, y, w, h] = [0, 0, 0, 0];
    //TODO 开始X > 结束X
    if (selectOptionsRef.current.end[0] > selectOptionsRef.current.start[0]) {
      x = selectOptionsRef.current.start[0] - left;
      w = selectOptionsRef.current.end[0] - selectOptionsRef.current.start[0];
    }

    //TODO 开始X < 结束X
    if (selectOptionsRef.current.end[0] < selectOptionsRef.current.start[0]) {
      x = selectOptionsRef.current.end[0] - left;
      w = selectOptionsRef.current.start[0] - selectOptionsRef.current.end[0];
    }

    //TODO 开始Y > 结束Y
    if (selectOptionsRef.current.end[1] > selectOptionsRef.current.start[1]) {
      y = selectOptionsRef.current.start[1] - top;
      h = selectOptionsRef.current.end[1] - selectOptionsRef.current.start[1];
    }

    //TODO 开始Y < 结束Y
    if (selectOptionsRef.current.end[1] < selectOptionsRef.current.start[1]) {
      y = selectOptionsRef.current.end[1] - top;
      h = selectOptionsRef.current.start[1] - selectOptionsRef.current.end[1];
    }
    if (w + x > width) {
      w = width - x;
    }
    if (h + y > height) {
      h = height - y;
    }
    if (w * h < 160 && isEnd) {
      setState({
        rect: [0, 0, 0, 0],
        isEnd: !!isEnd
      });
    } else {
      setState({
        rect: [x, y, w, h],
        isEnd: !!isEnd
      });
    }
  }, [dom]);

  /**
   * move 修改框选区域
   */
  const changeSelect = useCallback(event => {
    if (selectOptionsRef.current.startSelect) {
      selectOptionsRef.current.end = [event.clientX, event.clientY];
      drawSelectRact(false);
    }
  }, [drawSelectRact]);

  /**
   * 结束当前框选
   */
  const selectEnd = useCallback(event => {
    if (selectOptionsRef.current.startSelect) {
      selectOptionsRef.current.startSelect = false;
      selectOptionsRef.current.end = [event.clientX, event.clientY];
      drawSelectRact(true);
    }
  }, [drawSelectRact]);
  const openSelect = useCallback(event => {
    selectOptionsRef.current.startSelect = true;
    selectOptionsRef.current.start = [event.clientX, event.clientY];
  }, []);
  useEffect(() => {
    if (dom && flag) {
      dom.addEventListener('mousedown', openSelect, false);
      dom.addEventListener('mousemove', changeSelect, false);
      dom.addEventListener('mouseup', selectEnd, false);
    }
    if (dom && !flag) {
      setState(old => ({
        ...old,
        rect: [0, 0, 0, 0]
      }));
    }
    return () => {
      if (dom) {
        dom.removeEventListener('mousedown', openSelect, false);
        dom.removeEventListener('mousemove', changeSelect, false);
        dom.removeEventListener('mouseup', selectEnd, false);
      }
    };
  }, [changeSelect, dom, flag, openSelect, selectEnd]);
  return [state.rect, state.isEnd];
}

function Tools({
  scale,
  imgDownload,
  setScale,
  setRotate,
  containerEle,
  resetPicture,
  fullScreenChange
}) {
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("div", {
    className: "picture-tools"
  }, /*#__PURE__*/React__default.createElement(Tooltip, {
    placement: "left",
    title: "\u590D\u4F4D"
  }, /*#__PURE__*/React__default.createElement("div", {
    onClick: resetPicture
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: "icon-S_View_RotateMiddle"
  }))), /*#__PURE__*/React__default.createElement(Tooltip, {
    placement: "left",
    title: "\u653E\u5927"
  }, /*#__PURE__*/React__default.createElement("div", {
    onClick: () => setScale(0.2),
    className: scale === 3 ? 'disabled' : ''
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: "icon-S_View_ZoomIn"
  }))), /*#__PURE__*/React__default.createElement(Tooltip, {
    placement: "left",
    title: "\u7F29\u5C0F"
  }, /*#__PURE__*/React__default.createElement("div", {
    onClick: () => setScale(-0.2),
    className: scale === 1 ? 'disabled' : ''
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: "icon-S_View_ZoomOut"
  }))), /*#__PURE__*/React__default.createElement(Tooltip, {
    placement: "left",
    title: "\u5411\u5DE6"
  }, /*#__PURE__*/React__default.createElement("div", {
    onClick: () => setRotate(-90)
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: "icon-S_View_RotateLeft"
  }))), /*#__PURE__*/React__default.createElement(Tooltip, {
    placement: "left",
    title: "\u5411\u53F3"
  }, /*#__PURE__*/React__default.createElement("div", {
    onClick: () => setRotate(90)
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: "icon-S_View_RotateRight"
  })))), /*#__PURE__*/React__default.createElement("div", {
    className: "picture-actions"
  }, imgDownload && /*#__PURE__*/React__default.createElement("div", {
    onClick: imgDownload
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: "icon-S_Edit_LoadDown"
  })), /*#__PURE__*/React__default.createElement("div", null, /*#__PURE__*/React__default.createElement(FullScreen, {
    className: "footer_window",
    getContainer: () => containerEle,
    fullScreenChange: fullScreenChange
  }, isFullscreen => /*#__PURE__*/React__default.createElement(IconFont, {
    title: !isFullscreen ? '全屏' : '退出全屏',
    type: !isFullscreen ? 'icon-S_View_ScreenViewFull' : 'icon-S_View_ScreenViewExit',
    theme: "outlined"
  })))));
}

function computedMenuPosition({
  width,
  height,
  position,
  size
}) {
  let x, y;
  x = position[0];
  y = position[1];
  if (width - x < size.w) {
    x = width - size.w;
  }
  if (height - y < size.h) {
    y = height - size.h;
  }
  return {
    x,
    y
  };
}

const MENU_WIDTH = 110;
const MENU_HEIGHT = 30;
function RectMenu({
  x,
  y,
  menus,
  containerDom,
  onMenuClick
}) {
  const {
    width,
    height
  } = useMemo(() => containerDom.getBoundingClientRect(), [containerDom]);
  const size = useMemo(() => ({
    w: MENU_WIDTH,
    h: MENU_HEIGHT * menus.length
  }), [menus.length]);
  const position = useMemo(() => computedMenuPosition({
    width,
    height,
    size,
    position: [x, y]
  }), [height, size, width, x, y]);
  const domRef = useRef(null);
  const handleCancelB = useCallback(e => e.stopPropagation(), []);

  //防止click事件冒泡到查看器
  useEffect(() => {
    const dom = domRef.current;
    if (dom) {
      dom.addEventListener('mousedown', handleCancelB, false);
      dom.addEventListener('mousemove', handleCancelB, false);
      dom.addEventListener('mouseup', handleCancelB, false);
    }
    return () => {
      if (dom) {
        dom.removeEventListener('mousedown', handleCancelB, false);
        dom.removeEventListener('mousemove', handleCancelB, false);
        dom.removeEventListener('mouseup', handleCancelB, false);
      }
    };
  }, [handleCancelB]);
  const onClickMenu = useCallback((e, item) => {
    e.stopPropagation();
    onMenuClick && onMenuClick(item);
  }, [onMenuClick]);
  return /*#__PURE__*/React__default.createElement("div", {
    className: "select-rect-menu-layout",
    style: {
      left: position.x,
      top: position.y
    },
    ref: domRef
  }, menus.map(v => /*#__PURE__*/React__default.createElement("div", {
    className: "menu-action-item",
    key: v.pathname,
    onClick: e => onClickMenu(e, v)
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: v.icon
  }), v.title)));
}

function DrawRect({
  rect = [],
  canRenderMenu,
  containerDom,
  onMenuClick,
  menus,
  getRectImage
}) {
  const x = useMemo(() => rect[0] + rect[2], [rect]);
  const y = useMemo(() => rect[1] + rect[3], [rect]);
  const onMenuClickAction = useCallback(item => {
    onMenuClick && onMenuClick({
      ...item,
      base64: getRectImage(rect)
    });
  }, [getRectImage, onMenuClick, rect]);
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("div", {
    className: "select-rect-layout",
    style: {
      left: rect[0],
      top: rect[1],
      width: rect[2],
      height: rect[3]
    }
  }), canRenderMenu && /*#__PURE__*/React__default.createElement(RectMenu, {
    x: x,
    y: y,
    containerDom: containerDom,
    onMenuClick: onMenuClickAction,
    menus: menus
  }));
}

function WheelScale({
  dom,
  setScale
}) {
  const onWheel = useCallback(e => {
    if (e.ctrlKey || e.metaKey) {
      e.preventDefault();
      e.stopPropagation();
      setScale(e.deltaY > 0 ? -0.2 : 0.2);
    }
  }, [setScale]);

  //滚轮缩放
  useEffect(() => {
    if (dom) {
      dom.addEventListener('mousewheel', onWheel, {
        passive: false
      });
    }
    return () => {
      if (dom) {
        dom.removeEventListener('mousewheel', onWheel, {
          passive: false
        });
      }
    };
  }, [dom, onWheel]);
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null);
}

const RECT_INFO_WIDTH = 150;
const RECT_INFO_HEIGHT = 24;
const RECT_WINDOW_MARGIN = 6;
function RectInfo({
  item,
  containerDom
}) {
  const position = useMemo(() => {
    const {
      width,
      height
    } = containerDom.getBoundingClientRect();
    const {
      rectInfoWidth,
      rectInfoHeight
    } = {
      rectInfoWidth: RECT_INFO_WIDTH,
      rectInfoHeight: item.tags.length * RECT_INFO_HEIGHT + 6 + 30
    };
    const [rectLeft, rectTop, rectWidth] = item.rect;
    let x, y;
    if (rectWidth + rectLeft + rectInfoWidth < width) {
      x = rectWidth + rectLeft + RECT_WINDOW_MARGIN;
    } else {
      x = rectLeft - RECT_WINDOW_MARGIN - rectInfoWidth;
    }
    if (rectTop + rectInfoHeight < height) {
      y = rectTop;
      y = y < 0 ? RECT_WINDOW_MARGIN : y;
    } else {
      y = height - rectInfoHeight;
    }
    return {
      x,
      y,
      width: rectInfoWidth,
      height: rectInfoHeight
    };
  }, [containerDom, item.rect, item.tags.length]);
  return /*#__PURE__*/React__default.createElement("div", {
    className: "rect-info-list-wrapper",
    style: {
      left: position.x,
      top: position.y,
      width: position.width,
      height: position.height
    }
  }, /*#__PURE__*/React__default.createElement("div", {
    className: "data-type"
  }, item.hasOwnProperty('lowQuality') && /*#__PURE__*/React__default.createElement("span", {
    className: "data-tag low"
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: 'icon-S_View_Cluster'
  }), item.lowQuality ? '低质量' : '高质量'), item.hasOwnProperty('dupId') && item.dupId && /*#__PURE__*/React__default.createElement("span", {
    className: "data-tag repeat"
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: 'icon-S_Photo_repeatingdata'
  }), "\u91CD\u590D")), /*#__PURE__*/React__default.createElement("ul", {
    className: "rect-info-list"
  }, item.tags.map((v, index) => /*#__PURE__*/React__default.createElement("li", {
    className: "info-item",
    key: index,
    title: v.tagLabel
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: v.icon
  }), /*#__PURE__*/React__default.createElement("span", {
    className: "item-value"
  }, v.label)))));
}

function computedZIndex(rects) {
  let areas = rects.map(v => {
    let width = v.rect[2];
    let height = v.rect[3];
    v.area = width * height;
    return v;
  });
  return areas.sort((a, b) => b.area - a.area);
}

function DefaultRects({
  rects,
  containerDom,
  onClickRect,
  getRectImage
}) {
  const renderRects = useMemo(() => computedZIndex(rects), [rects]);
  const rectClick = useCallback((e, item) => {
    e.stopPropagation();
    onClickRect && onClickRect({
      ...item,
      base64: getRectImage(item.rect)
    });
  }, [getRectImage, onClickRect]);
  return renderRects.map((v, k) => {
    return /*#__PURE__*/React__default.createElement("div", {
      className: `rect-item-wrapper rect-item-${v.type}-wrapper`,
      key: k
    }, /*#__PURE__*/React__default.createElement("div", {
      className: 'rect-item',
      onDoubleClick: e => rectClick(e, v),
      style: {
        left: v.rect[0],
        top: v.rect[1],
        width: v.rect[2],
        height: v.rect[3],
        zIndex: k
      }
    }, /*#__PURE__*/React__default.createElement("div", {
      className: "border-top-decorator"
    }), /*#__PURE__*/React__default.createElement("div", {
      className: "border-bottom-decorator"
    })), Array.isArray(v.tags) && v.tags.length > 0 && /*#__PURE__*/React__default.createElement(RectInfo, {
      item: v,
      containerDom: containerDom
    }));
  });
}

/* eslint-disable react-hooks/exhaustive-deps */
function Picture({
  drawArea,
  roiRects,
  className = '',
  width,
  height,
  minHeight = 300,
  disabledDrag = false,
  imagePath,
  rects = [],
  imgDownload,
  isOpenSelect = false,
  disabledDrawMenu = false,
  menus = [],
  onClickRect,
  onMenuClick,
  children,
  hasTool = true,
  fullScreenEle = null
}) {
  var _domImgRef$current3, _domImgRef$current4, _domImgRef$current5, _domImgRef$current6;
  const [state, setState] = useState({
    x: 0,
    y: 0,
    rotate: 0,
    scale: 1,
    baseXOrY: 'x',
    forceUpdateKey: Date.now(),
    fullScreenStatus: false
  });
  const layoutRef = useRef(null);
  const moveActionRef = useRef(null);
  const domImgRef = useRef(null);
  const imageSourceRef = useRef(null);
  const canvasRef = useRef(null);
  const [selectArea, isEnd] = useDraw(layoutRef.current, isOpenSelect);
  const loadImageSuccess = useCallback(async flag => {
    imageSourceRef.current = await cloneImageNode(domImgRef.current);
    const {
      width,
      height
    } = domImgRef.current;
    setState(old => ({
      ...old,
      forceUpdateKey: Date.now(),
      baseXOrY: width > height ? 'x' : 'y',
      fullScreenStatus: !!flag
    }));
  }, []);
  /**
   * 设置图片缩放
   */
  const setScale = useCallback(changeValue => {
    const currentValue = state.scale;
    if (currentValue === 3 && changeValue > 0) {
      return;
    }
    if (currentValue === 1 && changeValue < 0) {
      return;
    }
    let scale = currentValue + changeValue;
    if (scale > 3) {
      scale = 3;
    }
    if (scale < 1) {
      scale = 1;
    }
    setState(old => ({
      ...old,
      scale
    }));
  }, [state.scale]);

  /**
   * 设置图谱旋转
   */
  const setRotate = useCallback(changeValue => {
    const currentValue = state.rotate;
    setState(old => ({
      ...old,
      rotate: currentValue + changeValue
    }));
  }, [state.rotate]);

  /**
   * 重置图片位置
   */
  const resetPicture = useCallback(event => {
    event.stopPropagation(event);
    setState(old => ({
      ...old,
      scale: 1,
      rotate: 0
    }));
    moveActionRef.current.updatePosition({
      x: 0,
      y: 0
    });
  }, []);

  /**
   * 拖拽更新位置
   */
  const onDragChange = useCallback(({
    x,
    y
  }) => setState(old => ({
    ...old,
    x,
    y
  })), []);

  /**
   * 拖拽结束更新位置，计算边界
   */
  const onDragEnd = useCallback((_, currrentPosition) => {
    const {
      scale,
      rotate
    } = state;
    if (!layoutRef.current) {
      return;
    }
    let position = computedBound(layoutRef.current, currrentPosition, scale, rotate);
    if (position) {
      moveActionRef.current.updatePosition(position);
    }
  }, [state]);

  /**
   * 获取结构化的小图(base64)
   */
  const getRectImage = useCallback(rect => {
    let {
      scale,
      rotate,
      x,
      y
    } = state;
    return getRectImagePath(imageSourceRef.current, domImgRef.current, rect, {
      scale,
      rotate,
      x,
      y
    });
  }, [state]);
  useEffect(() => {
    let timer = null;
    const fn = () => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        setState(old => ({
          ...old,
          forceUpdateKey: Date.now()
        }));
      }, 200);
    };
    const dom = layoutRef.current;
    resizeObserver.createResizeObserver(dom, fn);
    return () => {
      resizeObserver.unResizeObserver(dom);
    };
  }, []);
  const scaleRects = useMemo(() => computedRectScale({
    imageSource: imageSourceRef.current,
    domImg: domImgRef.current,
    rects
  }), [rects, state.forceUpdateKey]);
  const scaleDrawArea = useMemo(() => computedDrawAreaScale({
    imageSource: imageSourceRef.current,
    domImg: domImgRef.current,
    drawArea
  }), [drawArea, state.forceUpdateKey]);
  const scaleRoiRects = useMemo(() => computedRoiRectScale({
    imageSource: imageSourceRef.current,
    domImg: domImgRef.current,
    roiRects
  }), [roiRects, state.forceUpdateKey]);
  const isEmpty = useMemo(() => selectArea.includes(0), [selectArea]);
  const {
    x,
    y,
    scale,
    rotate,
    baseXOrY
  } = useMemo(() => state, [state]);
  const renderOptions = {
    isEnd,
    isOpenSelect,
    selectArea,
    getRectImage: getRectImage,
    containerEle: layoutRef.current,
    fullScreenStatus: state.fullScreenStatus
  };
  const drawRoi = rectItem => {
    const {
      rect,
      color = '#127aff'
    } = rectItem;
    if (rect && rect.length) {
      var _domImgRef$current, _domImgRef$current2;
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');
      canvas.width = (_domImgRef$current = domImgRef.current) === null || _domImgRef$current === void 0 ? void 0 : _domImgRef$current.width;
      canvas.height = (_domImgRef$current2 = domImgRef.current) === null || _domImgRef$current2 === void 0 ? void 0 : _domImgRef$current2.height;
      // 多边形的顶点坐标相对于左下角原点的偏移量  
      ctx.beginPath();
      ctx.lineWidth = 2;
      ctx.setLineDash([5, 10]);
      ctx.strokeStyle = color; // 设置边线颜色rgba(151, 71, 255); ,rgba(211 ,85 ,167);
      ctx.fillStyle = `${color}1a`; // 设置填充颜色

      rect.forEach((v, k) => {
        if (k === 0) {
          ctx.moveTo(v[0], v[1]); // 起点在左下角，向右上方移动到第一个顶点  
        } else {
          ctx.lineTo(v[0], v[1]); // 起点在左下角，向右上方移动到第一个顶点  
        }
      });
      ctx.closePath();
      ctx.stroke();
      ctx.fill();
    }
  };
  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    [...scaleRoiRects, scaleDrawArea].forEach(item => {
      //管网roi和图库roi合并成一个数组,同时绘制,绘制前先清空画布
      drawRoi(item);
    });
  }, [canvasRef, scaleRoiRects, scaleDrawArea, (_domImgRef$current3 = domImgRef.current) === null || _domImgRef$current3 === void 0 ? void 0 : _domImgRef$current3.width, (_domImgRef$current4 = domImgRef.current) === null || _domImgRef$current4 === void 0 ? void 0 : _domImgRef$current4.height]);

  // useEffect(() => {
  //   drawRoi(scaleDrawArea)

  // }, [canvasRef, scaleDrawArea, domImgRef.current?.width, domImgRef.current?.height])
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("div", {
    className: `picture-view-layout ${className}`,
    style: {
      width: width || '100%',
      height: height || '100%',
      minHeight
    },
    ref: layoutRef,
    onContextMenu: customContextMenu
  }, /*#__PURE__*/React__default.createElement(MoveContentView, {
    className: "picture-move-layout",
    disabled: isOpenSelect || disabledDrag,
    position: {
      x,
      y
    },
    ref: moveActionRef,
    onDragChange: onDragChange,
    onDragEnd: onDragEnd,
    style: {
      minHeight: minHeight
    },
    size: {
      width: width ? 'max-content' : '100%',
      height: height ? 'max-content' : '100%'
    }
  }, /*#__PURE__*/React__default.createElement("div", {
    style: {
      transform: `scale(${scale}) rotate(${rotate}deg)`
    }
  }, /*#__PURE__*/React__default.createElement("img", {
    alt: "",
    ref: domImgRef,
    crossOrigin: "anonymous",
    style: {
      maxWidth: baseXOrY === 'x' ? width || '100%' : 'unset',
      maxHeight: baseXOrY === 'x' ? 'unset' : height || '100%'
    },
    draggable: false,
    src: imagePath,
    key: imagePath,
    onLoad: loadImageSuccess
  }), !isOpenSelect ? /*#__PURE__*/React__default.createElement("canvas", {
    style: {
      width: (_domImgRef$current5 = domImgRef.current) === null || _domImgRef$current5 === void 0 ? void 0 : _domImgRef$current5.width,
      height: (_domImgRef$current6 = domImgRef.current) === null || _domImgRef$current6 === void 0 ? void 0 : _domImgRef$current6.height
    },
    ref: canvasRef,
    className: "scale-draw-area-canvas"
  }) : null, !isEmpty ? /*#__PURE__*/React__default.createElement(DrawRect, {
    rect: selectArea,
    onMenuClick: onMenuClick,
    getRectImage: getRectImage,
    menus: menus,
    canRenderMenu: isEnd && !disabledDrawMenu && menus.length > 0,
    containerDom: layoutRef.current
  }) : !isOpenSelect ? /*#__PURE__*/React__default.createElement(DefaultRects, {
    rects: scaleRects,
    onClickRect: onClickRect,
    getRectImage: getRectImage,
    containerDom: layoutRef.current
  }) : null)), hasTool && /*#__PURE__*/React__default.createElement(Tools, {
    setScale: setScale,
    setRotate: setRotate,
    scale: scale,
    containerEle: fullScreenEle || layoutRef.current,
    resetPicture: resetPicture,
    imgDownload: imgDownload,
    fullScreenChange: loadImageSuccess
  }), /*#__PURE__*/React__default.createElement(WheelScale, {
    setScale: setScale,
    dom: layoutRef.current
  })), isFunction(children) && children(renderOptions));
}

export { Picture as default };
//# sourceMappingURL=index.js.map
