import Line from './line.js'
import Shape from './shape.js'
import Ink from './ink.js'
import Freetext from './freetext.js'
import Text from './text.js'
import Stamp from './stamp.js'
import PaintFreetext from './paint/freetext'
import PaintShape from './paint/shape'
import PaintText from './paint/text'
import TextField from '../form/text_field.js'
import AddTextField from '../form/add_text_field.js'
import CheckBox from '../form/check_box.js'
import AddCheckBox from '../form/add_check_box.js'
import RadioButton from '../form/radio_button.js'
import AddRadioButton from '../form/add_radio_button.js'
import PushButton from '../form/push_button.js'
import AddPushButton from '../form/add_push_button.js'
import ListBox from '../form/list_box.js'
import AddListBox from '../form/add_list_box.js'
import ComboBox from '../form/combo_box.js'
import AddComboBox from '../form/add_combo_box.js'
import MarkupTextAnnotation from '../markup/text_annotation.js'
import PaintLink from './paint/link'
import Link from './link.js'
import AddSignatureFields from '../form/add_signature_fields.js'
import SignatureFields from '../form/signature_fields.js'
import PaintRedaction from './paint/redaction'
import Redaction from './redaction.js'

// 注释的画布层
class ComPDFAnnotationLayer {
  constructor({
    documentViewer,
    annotationStore,
    pageViewer,
    messageHandler,
    pageDiv,
    pdfPage,
    annotations = null,
    annotationsAll,
    viewport,
    scale,
    pageIndex,
    eventBus,
    enableReply = true,
    $t
  }) {
    this.documentViewer = documentViewer
    this.annotationStore = annotationStore
    this.pageViewer = pageViewer
    this.pageDiv = pageDiv;
    this.pdfPage = pdfPage;
    this.messageHandler = messageHandler
    this.annotations = annotations || [];
    this.annotationsAll = annotationsAll;
    this.viewport = viewport
    this.annotationsArray = []
    this.scale = scale
    this.eventBus = eventBus
    this.page = pageIndex
    this.annotationStore.$t = $t
    this.enableReply = enableReply

    this._cancelled = false
    this.tool = pageViewer.tool || ''
    this.color = pageViewer.color || ''
    this.annotateManager = null
    this.isDraging = false
    this.selectedElementName = null
    this.addMode = false
    this.toolMode = pageViewer.toolMode || ''
    this.managerArray = ['freetextManager', 'textManager', 'textFieldManager', 'checkBoxManager', 'radioButtonManager', 'pushButtonManager', 'listBoxManager', 'comboBoxManager', 'annotateManager', 'linkManager', 'signFieldManager', 'redactionManager']
    this.ratio = window.devicePixelRatio || 1
    this.markupType = ['highlight', 'underline', 'squiggly', 'strikeout']
    this.pageViewer.canvas && (this.ctx = this.pageViewer.canvas.getContext('2d'))

    this.onHandleTool = this.handleTool.bind(this)
    this.onHandleToolMode = this.handleToolMode.bind(this)
    this.onHandlePropertyPanelChanged = this.handlePropertyPanelChanged.bind(this)
    this.onHandleAddSign = this.addSign.bind(this)
    this.onRedrawMarkups = this.redrawMarkups.bind(this)
  }

  // 处理注释工具切换
  handleTool({
    tool,
    color
  }) {
    this.tool = tool
    this.color = color
    this.pageViewer.tool = tool
    this.pageViewer.color = color

    if (!this.svgElement) {
      this.destroy()
      this.renderPaintScene()
    }

    if (!tool || this.markupType.includes(tool)) {
      document.querySelector('.document').classList.remove('annotation-edit')
    }

    if (this.markupType.includes(tool) || tool === 'cropPage' || tool === 'selectText') {
      this.resetManagers()
    }

    const shapes = ['line', 'arrow', 'circle', 'square', 'ink']
    if (this.markupType.includes(tool) && color) {
      this.svgElement.classList.add('point-none')
    }

    this.managerArray.forEach(manager => {
      if (this[manager]) {
        this[manager].tool = this.tool
        this[manager].color = this.color
      }
    })

    if (shapes.includes(tool) && color) {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('annotateManager')
      if (this.annotateManager) {
        this.annotateManager.init()
        return
      }
      this.annotateManager = new PaintShape({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'freetext') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('freetextManager')
      if (this.freetextManager) {
        this.freetextManager.init()
        return
      }
      this.freetextManager = new PaintFreetext({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'text') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('textManager')
      if (this.textManager) {
        this.textManager.init()
        return
      }
      this.textManager = new PaintText({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'textfield') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('textFieldManager')
      if (this.textFieldManager) {
        this.textFieldManager.init()
        return
      }
      this.textFieldManager = new AddTextField({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'checkbox') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('checkBoxManager')
      if (this.checkBoxManager) {
        this.checkBoxManager.init()
        return
      }
      this.checkBoxManager = new AddCheckBox({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'radiobutton') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('radioButtonManager')
      if (this.radioButtonManager) {
        this.radioButtonManager.init()
        return
      }
      this.radioButtonManager = new AddRadioButton({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'pushbutton') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('pushButtonManager')
      if (this.pushButtonManager) {
        this.pushButtonManager.init()
        return
      }
      this.pushButtonManager = new AddPushButton({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'combobox') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('comboBoxManager')
      if (this.comboBoxManager) {
        this.comboBoxManager.init()
        return
      }
      this.comboBoxManager = new AddComboBox({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'listbox') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('listBoxManager')
      if (this.listBoxManager) {
        this.listBoxManager.init()
        return
      }
      this.listBoxManager = new AddListBox({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'stamp') {
      this.resetManagers()
    } else if (tool === 'link') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('linkManager')
      if (this.linkManager) {
        this.linkManager.init()
        return
      }
      this.linkManager = new PaintLink({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'signatureFields') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('signFieldManager')
      if (this.signFieldManager) {
        this.signFieldManager.init()
        return
      }
      this.signFieldManager = new AddSignatureFields({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    } else if (tool === 'redaction' || tool === 'remove') {
      document.querySelector('.document').classList.add('annotation-edit')
      this.resetManagers('redactionManager')
      if (this.redactionManager) {
        this.redactionManager.init()
        return
      }
      this.redactionManager = new PaintRedaction({
        tool,
        color,
        container: this.pageDiv,
        svgElement: this.svgElement,
        layer: this,
        viewport: this.viewport,
        scale: this.scale,
        page: this.page,
        eventBus: this.eventBus,
        selectedElementName: this.selectedElementName
      })
    }
  }

  resetManagers(ignoreManagers = []) {
    if (!Array.isArray(ignoreManagers)) ignoreManagers = [ignoreManagers]
    const managers = this.managerArray.filter(item => !ignoreManagers.includes(item))
    managers.forEach(manager => {
      this[manager] && this[manager].reset()
    })
  }

  // 渲染注释
  render(viewport) {
    if (this._cancelled) {
      return;
    }
    this.renderPaintScene()
    this.eventBus._on('toolChanged', this.onHandleTool)
    this.eventBus._on('toolModeChanged', this.onHandleToolMode)
    this.eventBus._on('setDefaultSelect', this.onHandleDefaultSelect)
    this.eventBus._on('propertyPanelChanged', this.onHandlePropertyPanelChanged)
    this.eventBus._on('redrawMarkups', this.onRedrawMarkups)

    if (viewport) {
      const clonedViewport = viewport.clone({ dontFlip: true });
      this.viewport = clonedViewport;
      this.scale = clonedViewport.scale

      this.managerArray.forEach(manager => {
        if (this[manager]) {
          this[manager].viewport = clonedViewport
        }
      })
    }
    if (!this.div) {
      this.renderContainer()
    }
    if (this.annotations && this.annotations.length) {
      const enableReply = this.enableReply
      for (let i = 0; i < this.annotations.length; i++) {
        const annotation = this.annotations[i]
        if (!annotation) continue
        if (this.markupType.includes(annotation.type)) {
          const markup = new MarkupTextAnnotation({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            enableReply,
            pageViewer: this.pageViewer,
            messageHandler: this.messageHandler
          })
          this.annotationsArray.push(markup)
        } else if (annotation.type === 'line' && !annotation.isDelete) {
          let supportLine = true
          if (annotation.tail || annotation.head) {
            const noneLine = ['None', 'Unknown']
            if (noneLine.includes(annotation.tail) && noneLine.includes(annotation.head)) {
              supportLine = true
            } else {
              if (annotation.head && annotation.head !== 'OpenArrow' && annotation.head !== 'None') {
                supportLine = false
              }

              if (annotation.tail && annotation.tail !== 'OpenArrow' && annotation.tail !== 'None') {
                supportLine = false
              }
            }
          }
          if(supportLine) {
            const line = new Line({
              container: this.div,
              annotation,
              page: this.page,
              viewport: this.viewport,
              scale: this.scale,
              eventBus: this.eventBus,
              layer: this,
              enableReply
            })
            this.annotationsArray.push(line)
          }
          
        } else if ((annotation.type === 'square' || annotation.type === 'circle') && !annotation.isDelete) {
          const shape = new Shape({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            enableReply
          })
          this.annotationsArray.push(shape)
        } else if (annotation.type === 'ink' && !annotation.isDelete) {
          const ink = new Ink({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            enableReply
          })
          this.annotationsArray.push(ink)
        } else if (annotation.type === 'freetext' && !annotation.isDelete) {
          const freetext = new Freetext({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            enableReply
          })
          this.annotationsArray.push(freetext)
        }
        if (annotation.type === 'text' && !annotation.isDelete) {
          const text = new Text({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            enableReply
          })
          this.annotationsArray.push(text)
        }
        if ((annotation.type === 'stamp' || annotation.type === 'image') && !annotation.isDelete) {
          const text = new Stamp({
            container: this.div,
            annotation,
            messageHandler: this.messageHandler,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            enableReply
          })
          this.annotationsArray.push(text)
        }
        if (annotation.type?.replace('-', '') === 'textfield' && !annotation.isDelete) {
          const textfield = new TextField({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            highlight: this.annotationStore.highlightForm,
            messageHandler: this.messageHandler
          })
          this.annotationsArray.push(textfield)
        }
        if (annotation.type?.replace('-', '') === 'checkbox' && !annotation.isDelete) {
          const checkbox = new CheckBox({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            highlight: this.annotationStore.highlightForm,
            messageHandler: this.messageHandler
          })
          this.annotationsArray.push(checkbox)
        }
        if (annotation.type?.replace('-', '') === 'radiobutton' && !annotation.isDelete) {
          const radiobutton = new RadioButton({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            highlight: this.annotationStore.highlightForm,
            messageHandler: this.messageHandler
          })
          this.annotationsArray.push(radiobutton)
        }
        if (annotation.type?.replace('-', '') === 'pushbutton' && !annotation.isDelete) {
          const pushbutton = new PushButton({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            highlight: this.annotationStore.highlightForm,
            messageHandler: this.messageHandler
          })
          this.annotationsArray.push(pushbutton)
        }
        if (annotation.type?.replace('-', '') === 'listbox' && !annotation.isDelete) {
          const listbox = new ListBox({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            highlight: this.annotationStore.highlightForm,
            messageHandler: this.messageHandler
          })
          this.annotationsArray.push(listbox)
        }
        if (annotation.type?.replace('-', '') === 'combobox' && !annotation.isDelete) {
          const combobox = new ComboBox({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            highlight: this.annotationStore.highlightForm,
            messageHandler: this.messageHandler
          })
          this.annotationsArray.push(combobox)
        }
        if (annotation.type?.replace('-', '') === 'link' && !annotation.isDelete) {
          const link = new Link({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            highlight: this.annotationStore.highlightLink,
            messageHandler: this.messageHandler
          })
          this.annotationsArray.push(link)
        }
        if (annotation.type === 'signatureFields' && !annotation.isDelete) {
          const signatureFields = new SignatureFields({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            messageHandler: this.messageHandler
          })
          this.annotationsArray.push(signatureFields)
        }
        if (annotation.type === 'redact' && !annotation.isDelete) {
          const redaction = new Redaction({
            container: this.div,
            annotation,
            page: this.page,
            viewport: this.viewport,
            scale: this.scale,
            eventBus: this.eventBus,
            layer: this,
            messageHandler: this.messageHandler
          })
          this.annotationsArray.push(redaction)
        }
      }
    }

    this.handleTool({
      tool: this.tool,
      color: this.color
    })

    this.annotationStore.toSelectAnnotationName && this.pageViewer.selectAnnotation(this.annotationStore.toSelectAnnotationName)
  }

  renderContainer() {
    const div = document.createElement("div")
    div.className = "annotationContainer"
    this.scene.append(div)
    this.div = div
  }

  emptyAnnotations() {
    const length = this.annotationsArray.length
    for (let i = length - 1; i >= 0; i--) {
      this.annotationsArray[i].delete()
    }

    this.annotationsArray = []
  }

  // 取消渲染
  cancel() {
    this._cancelled = true;
    this.destroy();
  }

  // 画布重置
  destroy () {
    if (!this.svgElement) {
      this.svgElement = this.pageDiv.querySelector('.annotationLayer svg')
    }
    this.svgElement?.remove()
    this.svgElement = null
    if (!this.div) {
      this.div = this.pageDiv.querySelector('.annotationContainer')
    }
    this.div?.remove()
    this.div = null
    this.resetManagers()

    this.eventBus._off('toolChanged', this.onHandleTool)
    this.eventBus._off('toolModeChanged', this.onHandleToolMode)
    this.eventBus._off('setDefaultSelect', this.onHandleDefaultSelect)
    this.eventBus._off('propertyPanelChanged', this.onHandlePropertyPanelChanged)
    this.eventBus._off('redrawMarkups', this.onRedrawMarkups)

    this.annotationStore.notFirstRender = true
  }

  // 缩放或旋转重新设置画布css
  setSceneDimensions (viewport) {

    if (viewport) {
      const clonedViewport = viewport.clone({ dontFlip: true });
      this.viewport = clonedViewport
      if (this.annotateManager) {
        this.annotateManager.viewport = clonedViewport
      }
    }
    if (this.svgElement) {
      const viewport = this.viewport
      const scene = this.scene
      scene.style.width = viewport.width + 'px'
      scene.style.height = viewport.height + 'px'

      this.svgElement.setAttribute("viewBox", `0 0 ${viewport.width} ${viewport.height}`);
    }
  }

  // 渲染画布节点
  renderPaintScene() {
    if (!this.svgElement) {
      this.svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      this.scene = this.pageDiv.querySelector('.annotationLayer')
      this.scene.append(this.svgElement)
    }
    this.setSceneDimensions()
  }

  // 渲染注释
  renderAnnotation (annotation, show) {
    if (!this.div) {
      this.renderContainer()
    }

    const enableReply = this.enableReply
    if (this.markupType.includes(annotation.type)) {
      const markup = new MarkupTextAnnotation({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        layer: this,
        enableReply,
        pageViewer: this.pageViewer,
        messageHandler: this.messageHandler
      })
      this.annotationsArray.push(markup)
    } else if (annotation.type === 'line' || annotation.type === 'arrow') {
      const line = new Line({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        show,
        layer: this,
        enableReply
      })
      this.annotationsArray.push(line)
    } else if (annotation.type === 'square' || annotation.type === 'circle') {
      const shape = new Shape({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        show,
        layer: this,
        enableReply
      })
      this.annotationsArray.push(shape)
    } else if (annotation.type === 'ink' && !annotation.isDelete) {
      const ink = new Ink({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        show,
        layer: this,
        enableReply
      })
      this.annotationsArray.push(ink)
    } else if (annotation.type === 'freetext' && !annotation.isDelete) {
      const freetext = new Freetext({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        layer: this,
        show,
        enableReply
      })
      this.annotationsArray.push(freetext)
    } else if (annotation.type === 'text' && !annotation.isDelete) {
      const text = new Text({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        show,
        layer: this,
        enableReply
      })
      this.annotationsArray.push(text)
    } else if ((annotation.type === 'stamp') && !annotation.isDelete) {
      const text = new Stamp({
        container: this.div,
        annotation,
        messageHandler: this.messageHandler,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        show,
        layer: this,
        enableReply
      })
      this.annotationsArray.push(text)
    } else if (annotation.type === 'textfield' && !annotation.isDelete) {
      const textfield = new TextField({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        show,
        layer: this,
        highlight: this.annotationStore.highlightForm,
        messageHandler: this.messageHandler
      })
      this.annotationsArray.push(textfield)
    } else if (annotation.type === 'checkbox' && !annotation.isDelete) {
      const checkbox = new CheckBox({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        show,
        layer: this,
        highlight: this.annotationStore.highlightForm,
        messageHandler: this.messageHandler
      })
      this.annotationsArray.push(checkbox)
    } else if (annotation.type === 'radiobutton' && !annotation.isDelete) {
      const radiobutton = new RadioButton({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        show,
        layer: this,
        highlight: this.annotationStore.highlightForm,
        messageHandler: this.messageHandler
      })
      this.annotationsArray.push(radiobutton)
    } else if (annotation.type === 'pushbutton' && !annotation.isDelete) {
      const pushbutton = new PushButton({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        layer: this,
        show,
        highlight: this.annotationStore.highlightForm,
        messageHandler: this.messageHandler
      })
      this.annotationsArray.push(pushbutton)
    } else if (annotation.type === 'listbox' && !annotation.isDelete) {
      const listbox = new ListBox({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        layer: this,
        show,
        highlight: this.annotationStore.highlightForm,
        messageHandler: this.messageHandler
      })
      this.annotationsArray.push(listbox)
    } else if (annotation.type === 'combobox' && !annotation.isDelete) {
      const combobox = new ComboBox({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        layer: this,
        show,
        highlight: this.annotationStore.highlightForm,
        messageHandler: this.messageHandler
      })
      this.annotationsArray.push(combobox)
    } else if (annotation.type === 'link' && !annotation.isDelete) {
      const link = new Link({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        layer: this,
        show,
        highlight: this.annotationStore.highlightLink,
        messageHandler: this.messageHandler
      })
      this.annotationsArray.push(link)
    } else if (annotation.type === 'signatureFields' && !annotation.isDelete) {
      const signatureFields = new SignatureFields({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        show,
        layer: this,
        messageHandler: this.messageHandler
      })
      this.annotationsArray.push(signatureFields)
    } else if (annotation.type === 'redact' && !annotation.isDelete) {
      const redaction = new Redaction({
        container: this.div,
        annotation,
        page: this.page,
        viewport: this.viewport,
        scale: this.scale,
        eventBus: this.eventBus,
        layer: this,
        show,
        highlight: this.annotationStore.highlightLink
      })
      this.annotationsArray.push(redaction)
    }
  }

  // 处理 Form 切换
  handleToolMode (mode) {
    this.toolMode = mode
    this.pageViewer.toolMode = mode
    this.eventBus.dispatch('changeSelectAvailable')
  }

  // 处理面板属性修改
  handlePropertyPanelChanged (props) {
    if (this.annotations && this.annotations.length) {
      const annotation = this.annotations.find((element) => element.name === this.annotationStore.selectedElementName)
      if (annotation) {
        if (annotation.type?.replace('-', '') === 'textfield') {
          this.eventBus.dispatch("textfieldPropertyPanelChanged", props);
        } else if (annotation.type?.replace('-', '') === 'checkbox') {
          this.eventBus.dispatch("checkboxPropertyPanelChanged", props);
        } else if (annotation.type?.replace('-', '') === 'radiobutton') {
          this.eventBus.dispatch("radioButtonPropertyPanelChanged", props);
        } else if (annotation.type?.replace('-', '') === 'pushbutton') {
          this.eventBus.dispatch("pushButtonPropertyPanelChanged", props);
        } else if (annotation.type?.replace('-', '') === 'listbox') {
          this.eventBus.dispatch("listBoxPropertyPanelChanged", props);
        } else if (annotation.type?.replace('-', '') === 'combobox') {
          this.eventBus.dispatch("comboBoxPropertyPanelChanged", props);
        } else if (annotation.type === 'link') {
          this.eventBus.dispatch("linkPropertyPanelChanged", props);
        }
      }
    }
  }

  addSign (data) {
    const imgEle = document.getElementsByClassName('sign-ink-save')
    if (!imgEle.length) {
      this.pageDiv.removeEventListener('click', this.onHandleAddSign)
      return
    }
    const isEvent = data instanceof PointerEvent
    if (isEvent) {
      this.eventBus.dispatch('getSignData', {
        page: this.page,
        viewport: this.viewport,
        clickX: data.offsetX,
        clickY: data.offsetY
      })
    }
    if (data && data.page === this.page && data.annotationData && !isEvent) {
      this.renderAnnotation(data.annotationData)
    }
    this.pageDiv.removeEventListener('click', this.onHandleAddSign)
    this.eventBus.dispatch('initCursorStyle')
  }

  // 在canvas上重绘markup
  redrawMarkups (data) {
    const { pageIndex, afterContentEdit, pagePtr, rect } = data
    if (pageIndex !== this.page) return

    if (!afterContentEdit) {
      const canvasWidth = Math.round(this.viewport.width * this.ratio)
      const canvasHeight = Math.round(this.viewport.height * this.ratio)
      this.ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      this.ctx.putImageData(this.pageViewer.baseImageData, 0, 0)
    }

    for (let i = 0; i < this.annotationsArray.length; i++) {
      const annotObj = this.annotationsArray[i]
      const { annotation, positionArray } = annotObj
      if (!annotation.isDelete && this.markupType.includes(annotation.type)) {
        const drawMethod = afterContentEdit ? annotObj.reRenderAfterContentEdit : annotObj.drawCanvas
        drawMethod.call(annotObj, afterContentEdit ? { pagePtr, rect } : positionArray)
      }
    }
  }

  getAnnoationIndex(annotation) {
    const annotationsArray = this.annotationsArray
    const index = annotationsArray.findIndex(item => item.annotation.name === annotation.name);
    return index
  }

  deleteAnnotationInLayer (annotation) {
    const annotationsArray = this.annotationsArray
    const index = this.getAnnoationIndex(annotation)
    index > -1 && annotationsArray.splice(index, 1)
  }

  deleteAnnotation(annotation) {
    const annotationsArray = this.annotationsArray
    const index = this.getAnnoationIndex(annotation)
    index > -1 && annotationsArray[index].handleDelete()
  }
}

export default ComPDFAnnotationLayer;
