import { v4 as uuidv4 } from 'uuid';
import { getActualRect, calculateRect, getActualPoint } from './utils'

const convertToElement = (annotations, viewport) => {
  const elements = annotations.reduce((elements, item) => {
    if (!item.name) {
      item.name = uuidv4()
    }
    let element = null
    switch (item.type) {
      case 'circle':
      case 'square':
        const { start, end } = getActualRect(item, viewport)
        const rect = calculateRect(start, end, item)
        element = {
          name: item.name,
          type: item.type,
          start,
          end,
          rect,
          x: rect.left,
          y: rect.top,
          lineWidth: item.lineWidth || item.width,
          strokeStyle: item.borderColor || item.color,
          globalAlpha: item.transparency
        }
        break;
      case 'line':
        if (!item.linePoints && item.start && item.end) {
          item.linePoints = item.start + ',' + item.end
        }
        let [startX, startY, endX, endY] = item.linePoints.split(',')

        const startPoint = getActualPoint({
          x: startX,
          y: startY
        }, viewport)

        const endPoint =  getActualPoint({
          x: endX,
          y: endY
        }, viewport)
        const lineRect = calculateRect(startPoint, endPoint, item)
        element = {
          name: item.name,
          type: item.type,
          start: startPoint,
          end: endPoint,
          rect: lineRect,
          x: lineRect.left,
          y: lineRect.top,
          strokeStyle: item.borderColor || item.color,
          lineWidth: item.lineWidth || item.width,
          globalAlpha: item.transparency
        }
        if (item.arrow) {

          const angle = Math.atan2(endY + 10 - startY, endX + 10 - startX);

          // 计算箭头的两个点的坐标
          const point1X = endX - 10 * Math.cos(angle - Math.PI / 5);
          const point1Y = endY - 10 * Math.sin(angle - Math.PI / 5);
          const point2X = endX - 10 * Math.cos(angle + Math.PI / 5);
          const point2Y = endY - 10 * Math.sin(angle + Math.PI / 5);
          element.arrow = true
          element.point1 = {
            x: point1X,
            y: point1Y
          }
          element.point2 = {
            x: point2X,
            y: point2Y
          }
        }
        break;
    }
    elements.push(element)
    return elements
  }, [])
  return elements
}

export default convertToElement
