import { defineStore } from 'pinia'
import core from '@/core'

const type = ['ink', 'line', 'square', 'circle', 'freetext', 'text', 'highlight', 'underline', 'squiggly', 'strikeout', 'image', 'stamp']

export const useDocumentStore = defineStore({
  id: 'document',
  state: () => ({
    totalPages: 0,
    loadingProgress: 0,
    annotationsCount: 0,
    info: null,
    measure: {
      precision: 1,
      scale: {
        origin: {
          num: 1,
          unit: 'pt'
        },
        actual: {
          num: 1,
          unit: 'pt'
        }
      },
      distance: 0
    },
    optionUrl: null,
    markupTool: 'highlight',
    highlight: {
      color: '#FFEC66'
    },
    underline: {
      color: '#FF0000'
    },
    squiggly: {
      color: '#FF0000'
    },
    strikeout: {
      color: '#FF0000'
    },
    shapeTool: 'square',
    square: {
      color: '#FF0000',
      opacity: '0.8',
      stroke: '1pt'
    },
    circle: {
      color: '#FF0000',
      opacity: '0.8',
      stroke: '1pt'
    },
    arrow: {
      color: '#FF0000',
      opacity: '0.8',
      stroke: '1pt'
    },
    line: {
      color: '#FF0000',
      opacity: '0.8',
      stroke: '1pt'
    },
    ink: {
      color: '#FF0000',
      opacity: '0.8',
      stroke: '2pt'
    },
    freetext: {
      color: '#000000'
    },
    text: {
      color: '#FF0000'
    },
    activeTool: '',
    annotations: null,
    textfield: {
      color: '#DDE9FF'
    },
    checkbox: {
      color: '#DDE9FF',
      borderColor: '#43474D'
    },
    radiobutton: {
      color: '#DDE9FF',
      borderColor: '#43474D'
    },
    listbox: {
      color: '#DDE9FF',
      borderColor: '#43474D'
    },
    combobox: {
      color: '#DDE9FF',
      borderColor: '#43474D'
    },
    pushbutton: {
      color: '#DDE9FF',
      borderColor: '#43474D'
    },
    link: {
      color: '#DDE9FF'
    },
    signatureFields: {
      color: '#DDE9FF'
    },
    redaction: {
      color: '#000000'
    },
    remove: {
      color: '#FF0000'
    },
    propertyPanel: {
      fieldName: '',
      isHidden: '0',
      title: '',
      backgroundColor: '#DDE9FF',
      color: '#000000',
      fontName: 'Helvetica',
      fontStyle: 'normal',
      fontSize: '14',
      textAlignment: '0',
      contents: '',
      isMultiLine: false,
      project: '',
      projectList: '',
      checkStyle: 0,
      isChecked: '',
      actionType: '0',
      text: 'OK',
      url: '',
      destPage: '',
      items: [],
      item: null,
      deleteItemIndex: null,
      moveOption: null
    },
    compareFiles: {
      oldFile: null,
      oldFilePassword: '',
      newFile: null,
      newFilePassword: ''
    },
    compareSettings: {
      oldFileColor: '#FBBDBF',
      newFileColor: '#93B9FD'
    },
    currentPdfData: null,
    fileHasPwd: false,
    pwd: null,
    compareResult: null, // 内容对比结果
    outlines: [],
    activeOutlineId: null,
    searchResults: [],
    docEditorOperationList: [], // 页面编辑操作记录
    signatures: [],
    selectedSignature: null, // 在侧边栏签名面板选中的签名
    trustedCertificateLists: [],
    author: 'ComPDFKit', // 文档作者
    annotator: 'Guest', // 注释作者
    highlightLink: true,
    highlightForm: true,
    redactionPrompted: false, // redaction首次进入提示
    autoJumpNextSign: false,
  }),
  getters: {
    getTotalPages () {
      return this.totalPages
    },
    getLoadingProgress () {
      return this.loadingProgress
    },
    getAnnotationsCount () {
      return this.annotationsCount + ' annotation' + (this.annotationsCount > 1 ? 's' : '')
    },
    getMeasure () {
      return this.measure
    },
    getPrecision () {
      return this.measure.precision === 1 ? 0.1 : 0.01
    },
    getInfo () {
      return this.info
    },
    getOptionUrl () {
      return this.optionUrl
    },
    getMarkupToolState () {
      return this.markupTool
    },
    getLineType () {
      return this.line.type
    },
    getActiveToolColor () {
      if (this.activeTool) {
        return this[this.activeTool].color
      }
    },
    getActiveTool () {
      return this.activeTool
    },
    getShapeToolState () {
      return this.shapeTool
    },
    getAllAnnotations () {
      const annotationsContainers = {
        annotations: {},
        annotationsCount: 0
      }
      const annotations = this.annotations

      for (const page in annotations) {
        const pageAnnotations = annotations[page]
        const len = pageAnnotations.length
        if (len) {
          for (let i = 0; i < len; i++) {
            const annotation = pageAnnotations[i]
            if (!pageAnnotations[i]) continue
           // if (pageAnnotations[i].type === 'line' && pageAnnotations[i].tail === 'OpenArrow') continue
            if (annotation && annotation.type === 'line') {
              let supportLine = true
              if(annotation.tail || annotation.head)
              {
                if (annotation.tail === 'None' && annotation.head === 'None') {
                  supportLine = true
                } else {
                  if (annotation.head && annotation.head !== 'OpenArrow' && annotation.head !== 'None' && annotation.head !== 'Unknown') {
                    supportLine = false
                    continue
                  }

                  if (annotation.tail && annotation.tail !== 'OpenArrow' && annotation.tail !== 'None' && annotation.tail !== 'Unknown') {
                    supportLine = false
                    continue
                  }
                } 
              }
            }

            if (type.includes(annotation.type) && !annotation.mainName) {
              if (!annotationsContainers.annotations[page]) {
                annotationsContainers.annotations[page] = {
                  pageAnnotationsCount: 0,
                  annotations: []
                }
              }
              annotationsContainers.annotations[page].pageAnnotationsCount++
              annotationsContainers.annotationsCount++
              annotationsContainers.annotations[page].annotations.push(annotation)

              // let replies = annotation.replies
              // if (replies && replies.length) {
              //   replies = replies.filter(reply => reply.contents)
              // }
              // annotation.replies = replies
            }
          }
        }
      }
      return annotationsContainers
    },
    getAnnotations (pageNum) {
      return this.annotations && this.annotations[pageNum]
    },
    getCompareFile (state) {
      return (key) => state.compareFiles[key]
    },
    getCompareFiles () {
      return this.compareFiles
    },
    getCompareSetting (state) {
      return (prop) => state.compareSettings[prop]
    },
    getCurrentPdfData () {
      return this.currentPdfData
    },
    getFilehasPwd () {
      return this.fileHasPwd
    },
    getPassword () {
      return this.pwd
    },
    getCompareResult () {
      return this.compareResult
    },
    getOutlines () {
      return this.outlines
    },
    getActiveOutlineId () {
      return this.activeOutlineId
    },
    getSearchResults () {
      return this.searchResults
    },
    getDocEditorOperationList () {
      return this.docEditorOperationList
    },
    getSignatures () {
      return this.signatures
    },
    getSelectedSignature () {
      return this.selectedSignature
    },
    getPkcs12 () {
      return this.pkcs12
    },
    getTrustedCertificateLists () {
      return this.trustedCertificateLists
    },
    getAuthor () {
      return this.author
    },
    getAnnotator () {
      return this.annotator
    },
    getHighlightLink () {
      return this.highlightLink
    },
    getHighlightForm () {
      return this.highlightForm
    },
    getRedactionPrompted () {
      return this.redactionPrompted
    },
    getAutoJumpNextSign () {
      return this.autoJumpNextSign
    },
  },
  actions: {
    resetSetting () {
      this.totalPages = 0
      this.loadingProgress = 0
      this.annotationsCount = 0
      this.annotations = null
      this.outlines = []
      this.activeOutlineId = null
      this.searchResults = []
      this.docEditorOperationList = []
      this.signatures = []
    },
    setTotalPages (totalPages) {
      this.totalPages = totalPages
    },
    setLoadingProgress (percent) {
      this.loadingProgress = percent
    },
    setAnnotationsCount (count) {
      this.annotationsCount = count
    },
    setOptionUrl (optionUrl) {
      this.optionUrl = optionUrl
    },
    setToken (info) {
      this.info = info
    },
    setDistance (distance) {
      this.measure.distance = Math.round(distance * 10) / 10
    },
    setMarkupToolState (tool) {
      this.markupTool = tool
    },
    setMarkupToolColor (color) {
      this[this.markupTool] = color
    },
    setShapeToolState (tool) {
      this.shapeTool = tool
    },
    setLineType (type) {
      this.line.type = type
    },
    setLineColor (color) {
      this.line.color = color
    },
    setActiveTool (tool) {
      this.activeTool = tool
    },
    setActiveToolColor (color) {
      if (this.activeTool) {
        this[this.activeTool].color = color
        core.setTool({
          tool: this.activeTool,
          color: color
        })
      }
    },
    setToolState (tool) {
      if (this.activeTool === tool || !tool) {
        this.activeTool = ''
        core.setTool({
          tool: '',
          color: ''
        })
      } else {
        this.activeTool = tool
        core.setTool({
          tool,
          color: this[tool]?.color || ''
        })
        if (this.activeTool === 'textfield' || this.activeTool === 'checkbox' || this.activeTool === 'radiobutton' || this.activeTool === 'pushbutton') {
          core.setInitProperty()
        }
      }
    },
    initAnnotations (annotations) {
      this.annotations = null
      this.annotations = annotations
    },
    setAnnotations (annotation, type) {
      const annotations = this.annotations
      if (type === 'add') {
        if (!annotations[annotation[page]]) {
          annotations[page] = []
        }
        annotations[page].push(annotation)
      } else {
        const annotationsPage = annotations[annotation[page]]
        const deleteIndex = annotationsPage.findIndex((item) => item.index ===  annotation.index)
        if (type === 'delete') {
          annotationsPage[deleteIndex].isDelete = true
        } else {
          annotationsPage[deleteIndex] = {
            ...annotationsPage[deleteIndex],
            ...annotation
          }
        }
      }
    },
    setPropertyPanel (props) {
      let updatedProps = {}
      for (const item in props) {
        for (const key in this.propertyPanel) {
          if (item === key) {
            updatedProps[key] = props[item]
          }
        }
      }
      core.setPropertyPanel(updatedProps)
    },
    setCompareFiles (key, val) {
      this.compareFiles[key] = val
    },
    initCompareFiles () {
      this.compareFiles.oldFile = null
      this.compareFiles.oldFilePassword = ''
      this.compareFiles.newFile = null
      this.compareFiles.newFilePassword = ''
    },
    setCompareSetting (key, value) {
      this.compareSettings[key] = value
    },
    initCompareSetting () {
      this.compareSettings = {
        oldFileColor: '#FBBDBF',
        newFileColor: '#93B9FD'
      }
    },
    setCurrentPdfData (pdf, options) {
      if (pdf && options) {
        if (!this.currentPdfData) this.currentPdfData = {}
        this.currentPdfData.pdf = pdf
        this.currentPdfData.options = options
      } else if (pdf) {
        this.currentPdfData.pdf = pdf
      } else (
        this.currentPdfData = null
      )
    },
    setFileHasPwd (bool) {
      this.fileHasPwd = bool
    },
    setPassword (pwd) {
      this.pwd = pwd
    },
    setCompareResult (files) {
      this.compareResult = files
    },
    setOutline (outlines) {
      this.outlines = outlines
    },
    setActiveOutlineId (outlineId) {
      this.activeOutlineId = outlineId
    },
    setSearchResults (searchResults) {
      this.searchResults = searchResults
    },
    setDocEditorOperationList (operation) {
      if (operation === 'reset') {
        this.docEditorOperationList = []
      } else if (operation) {
        this.docEditorOperationList.push(operation)
      }
    },
    setSelectedSignature (data) {
      this.selectedSignature = null
      this.selectedSignature = data
    },
    initSignatures (signatures) {
      this.signatures = null
      this.signatures = signatures.filter(signature => signature.signerList.length > 0)
    },
    setPkcs12 (data) {
      this.pkcs12 = data
    },
    setTrustedCertificateLists (certificatesBuffer) {
      this.trustedCertificateLists.push(certificatesBuffer)
    },
    setAuthor (author) {
      this.author = author
    },
    setAnnotator (annotator) {
      this.annotator = annotator
      core.setAnnotator(annotator)
    },
    setHighlightLink (bool) {
      this.highlightLink = bool
      core.setHighlightLink(bool)
    },
    setHighlightForm (bool) {
      this.highlightForm = bool
      core.setHighlightForm(bool)
    },
    dispatch(action) { // api中使用
      return this[action];
    },
    getState(key) { // api中使用
      if (key) return this.$state[key];
      return this.$state;
    },
    setRedactionPrompted (val) {
      this.redactionPrompted = val
    },
    setAutoJumpNextSign (val) {
      this.autoJumpNextSign = val
      core.setAutoJumpNextSign(val)
    },
  }
})
