import type { MarkingItem, MarkingShape, SpecialMark, TextAnnotation } from '../types'
import Konva from 'konva'

/**
 * 标记渲染器配置
 */
interface RenderOptions {
  /** 缩放比例 */
  scale: number
  /** 是否显示分数 */
  showScore?: boolean
  /** 是否显示老师名称 */
  showTeacherName?: boolean
}

/**
 * 标记渲染器 - 负责将标记数据渲染到 Konva Layer
 */
export function useMarkingRenderer() {
  /**
   * 生成唯一 ID
   */
  const generateId = (): string => {
    return `mark_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 创建形状节点
   */
  function createShape(shape: MarkingShape, scale: number): Konva.Shape | null {
    const commonProps = {
      id: shape.id,
      stroke: shape.stroke || '#ff0000',
      strokeWidth: (shape.strokeWidth || 4) * scale, // 增加线宽：2 -> 4
      fill: shape.fill || 'transparent',
      opacity: 0.9, // 增加不透明度：0.7 -> 0.9
    }

    if (shape.type === 'rect') {
      return new Konva.Rect({
        ...commonProps,
        x: shape.x * scale,
        y: shape.y * scale,
        width: (shape.width || 0) * scale,
        height: (shape.height || 0) * scale,
      })
    }

    if (shape.type === 'line') {
      const scaledPoints = (shape.points || []).map(p => p * scale)
      return new Konva.Line({
        ...commonProps,
        points: scaledPoints,
        lineCap: 'round',
        lineJoin: 'round',
      })
    }

    if (shape.type === 'circle') {
      return new Konva.Circle({
        ...commonProps,
        x: shape.x * scale,
        y: shape.y * scale,
        radius: (shape.radius || 0) * scale,
      })
    }

    return null
  }

  /**
   * 创建特殊标记（对错符号）
   */
  const createSpecialMark = (mark: SpecialMark, scale: number): Konva.Group => {
    const group = new Konva.Group({
      id: mark.id,
      x: mark.x * scale,
      y: mark.y * scale,
      scaleX: (mark.scale || 1) * scale * 1.5, // 增加符号大小 1.5 倍
      scaleY: (mark.scale || 1) * scale * 1.5,
    })

    const strokeWidth = 6 // 增加符号线宽：4 -> 6
    const color = '#ff0000'

    if (mark.type === 'correct') {
      // ✓ 符号
      const checkmark = new Konva.Line({
        points: [-8, -2, -3, 4, 8, -8],
        stroke: color,
        strokeWidth,
        lineCap: 'round',
        lineJoin: 'round',
      })
      group.add(checkmark)
    }
    else if (mark.type === 'wrong') {
      // ✗ 符号
      const line1 = new Konva.Line({
        points: [-8, -8, 8, 8],
        stroke: color,
        strokeWidth,
        lineCap: 'round',
      })
      const line2 = new Konva.Line({
        points: [8, -8, -8, 8],
        stroke: color,
        strokeWidth,
        lineCap: 'round',
      })
      group.add(line1, line2)
    }
    else if (mark.type === 'half') {
      // 半对标记
      const checkmark = new Konva.Line({
        points: [-8, -2, -3, 4, 8, -8],
        stroke: color,
        strokeWidth,
        lineCap: 'round',
        lineJoin: 'round',
      })
      const line = new Konva.Line({
        points: [-3, -8, 10, 2],
        stroke: color,
        strokeWidth,
        lineCap: 'round',
      })
      group.add(checkmark, line)
    }

    return group
  }

  /**
   * 创建文本节点
   */
  const createText = (annotation: TextAnnotation, scale: number): Konva.Text => {
    return new Konva.Text({
      id: annotation.id,
      x: annotation.x * scale,
      y: annotation.y * scale,
      text: annotation.text,
      fontSize: annotation.fontSize * scale * 1.3, // 增加文本大小 1.3 倍
      fill: annotation.color,
      fontStyle: 'bold', // 改为粗体
      opacity: 0.95, // 增加不透明度
      stroke: '#ffffff', // 添加白色描边，提高可读性
      strokeWidth: 0.5 * scale,
    })
  }

  /**
   * 渲染单个标记到图层
   */
  const renderMarking = (
    layer: Konva.Layer,
    marking: MarkingItem,
    options: RenderOptions,
  ): void => {
    const { scale, showScore = true, showTeacherName = true } = options
    const { areaPos, markingData, score, fullScore, teacherName } = marking

    // 创建一个组来容纳所有标记元素
    // Group 的位置和内部元素都需要按 scale 缩放
    const group = new Konva.Group({
      id: `marking_group_${marking.questionId}`,
      name: 'marking_group',
      x: areaPos[0] * scale,
      y: areaPos[1] * scale,
    })

    // 渲染形状 - 这里传入 1 作为 scale，因为坐标是相对于原始图片的，不是相对于 Group 的
    // 实际上坐标系统中的所有元素都需要缩放
    markingData.shapes.forEach((shape) => {
      const node = createShape(shape, scale)
      if (node) {
        group.add(node)
      }
    })

    // 渲染特殊标记
    markingData.specialMarks.forEach((mark) => {
      const node = createSpecialMark(mark, scale)
      if (node) {
        group.add(node)
      }
    })

    // 渲染文本注释
    markingData.annotations.forEach((annotation) => {
      const node = createText(annotation, scale)
      if (node) {
        group.add(node)
      }
    })

    // 添加分数和老师名称
    const areaWidth = areaPos[2] * scale // 区域宽度也需要缩放

    if (showScore && score !== undefined && fullScore !== undefined) {
      const scoreText = `${score}/${fullScore}分`
      const fontSize = 48 * scale // 增加字号：32 -> 48
      const scoreNode = new Konva.Text({
        id: generateId(),
        x: areaWidth - scoreText.length * fontSize * 0.6, // 估算文字宽度
        y: 0,
        text: scoreText,
        fontSize,
        fill: '#ff0000',
        fontStyle: 'bold',
        stroke: '#ffffff', // 白色描边
        strokeWidth: 1 * scale,
      })
      group.add(scoreNode)
    }

    if (showTeacherName && teacherName) {
      const teacherText = `阅卷: ${teacherName}`
      const fontSize = 32 * scale // 增加字号：24 -> 32
      const teacherNode = new Konva.Text({
        id: generateId(),
        x: areaWidth - teacherText.length * fontSize * 0.6, // 估算文字宽度
        y: 60 * scale, // 调整位置：40 -> 60
        text: teacherText,
        fontSize,
        fill: '#ff0000', // 颜色更深：#666666 -> #333333
        fontStyle: 'bold',
        stroke: '#ffffff', // 白色描边
        strokeWidth: 0.8 * scale,
      })
      group.add(teacherNode)
    }

    layer.add(group)
  }

  return {
    renderMarking,
  }
}

