<template>
  <div class="compare-document-container" :class="{ under: toolMode !== 'compare' || (toolMode === 'compare' && compareStatus === 'finished') }">
    <!-- 左边窗口 -->
    <div class="old">
      <div class="file-type">{{ $t('compare.oldFile') }}</div>
      <div class="file-content" :class="{ 'no-file': !oldFile }">
        <!-- 未上传 -->
        <div class="drop-area pc"
          v-if="!oldFile"
          id="oldDropArea"
          @dragover.prevent
          @dragenter="handleDragEnter('old')"
          @dragleave="handleDragLeave"
          @drop="handleDrop($event, 'old')"
          :class="{ 'drag-over': isDragOverOld }">
          <div class="upload-tip">
            <p>{{ $t('compare.dropFile[0]') }}<br>{{ $t('compare.dropFile[1]') }}</p>
            <div class="rect-button white">{{ $t('compare.chooseOldFile') }}<input type="file" @change="uploadFile($event, 'old')" accept=".pdf" name="compare"></div>
            <!-- <p v-if="oldFile" class="file-name">{{ oldFile.name }}</p> -->
          </div>
        </div>
        <!-- 已上传 -->
        <div class="uploaded pc" v-if="oldFile">
          <div class="header-info">
            <ZoomOverlay :docNum="2"/>
            <p class="file-name">{{ oldFile.name }}</p>
            <CloseA class="close" @click="removeFile('old')" />
          </div>
        </div>
        <div class="old-file-container file-container pc" ref="oldFileContainer" :class="{ 'no-file': !oldFile }">
          <div ref="oldViewerContainer" class="document"></div>
        </div>

        <!-- 移动端 -->
        <div class="drop-area mobile">
          <div class="upload-tip mobile">
            <div class="text">
              <p>{{ $t('compare.oldFile') }}</p>
            </div>
            <div class="rect-button white">{{ $t('compare.chooseOldFile') }}
              <input type="file" @change="uploadFile($event, 'old')" accept=".pdf" name="compare">
              <p class="file-name" v-if="oldFile">{{ oldFile.name }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右边窗口 -->
    <div class="new">
      <div class="file-type">{{ $t('compare.newFile') }}</div>
      <div class="file-content" :class="{ 'no-file': !newFile }">
        <!-- 未上传 -->
        <div class="drop-area pc"
          v-if="!newFile"
          id="newDropArea"
          @dragover.prevent 
          @dragenter="handleDragEnter('new')"
          @dragleave="handleDragLeave"
          @drop="handleDrop($event, 'new')"
          :class="{ 'drag-over': isDragOverNew }">
          <div class="upload-tip">
            <p>{{ $t('compare.dropFile[0]') }}<br>{{ $t('compare.dropFile[1]') }}</p>
            <div class="rect-button white">{{ $t('compare.chooseNewFile') }}<input type="file" @change="uploadFile($event, 'new')" accept=".pdf" name="compare"></div>
            <!-- <p v-if="newFile" class="file-name">{{ newFile.name }}</p> -->
          </div>
        </div>
        <!-- 已上传 -->
        <div class="uploaded pc" v-if="newFile">
          <div class="header-info">
            <ZoomOverlay :docNum="3" />
            <p class="file-name">{{ newFile.name }}</p>
            <CloseA class="close" @click="removeFile('new')" />
          </div>
        </div>
        <div class="new-file-container file-container pc" ref="newFileContainer" :class="{ 'no-file': !newFile }">
          <div ref="newViewerContainer" class="document"></div>
        </div>

        <!-- 移动端 -->
        <div class="drop-area mobile">
          <div class="upload-tip">
            <div class="text">
              <p>{{ $t('compare.newFile') }}</p>
            </div>
            <div class="rect-button white">{{ $t('compare.chooseNewFile') }}
              <input type="file" @change="uploadFile($event, 'new')" accept=".pdf" name="compare">
              <p class="file-name" v-if="newFile">{{ newFile.name }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <CompareSettingDialog />
  <DownloadSettingDialog />
  <PrintSettingDialog />
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { useViewerStore } from '@/stores/modules/viewer'
import { useDocumentStore } from '@/stores/modules/document'
import getHashParameters from '@/helpers/getHashParameters'
import core from '@/core'
const { loadDocument, initializeViewer, initConfig } = core

defineProps({
  docNum: Number
})

const useViewer = useViewerStore()
const useDocument = useDocumentStore()
const toolMode = computed(() => useViewer.getToolMode)
const compareStatus = computed(() => useViewer.getCompareStatus)

const oldFileContainer = ref()
const oldViewerContainer = ref()
const newFileContainer = ref()
const newViewerContainer = ref()
let oldFile = computed(() => useDocument.getCompareFile('oldFile'))
let newFile = computed(() => useDocument.getCompareFile('newFile'))
let isDragOverOld = ref(false)
let isDragOverNew = ref(false)

const verified = computed(() => useViewer.getVerified)

watch(() => toolMode.value, (newValue, oldValue) => {
  if (oldValue === 'compare' && newValue !== oldValue) {
    removeFile()
    clearDocumentViewer()
  }
  if (newValue === 'compare' && newValue !== oldValue) {
    setTimeout(() => {
      if (!verified.value) {
        alert('Invalid license')
      }
      initDocumentView()
    }, 1)
  }
})

// 点击选择文件上传
const uploadFile = async (e, flag) => {
  if (!e.target.files[0]) return

  let url = URL.createObjectURL(e.target.files[0])
  const pass = await core.checkPassword(url, true)
  if (pass === false) {
    e.target.value = ''
    return
  }

  const filename = e.target.files[0].name
  if (flag === 'old') {
    useDocument.setCompareFiles('oldFile', e.target.files[0])
    useDocument.setCompareFiles('oldFilePassword', pass)
    handleUpload(url, filename, 2)
  }
  if (flag === 'new') {
    useDocument.setCompareFiles('newFile', e.target.files[0])
    useDocument.setCompareFiles('newFilePassword', pass)
    handleUpload(url, filename, 3)
  }
}

// 清空文件
const removeFile = (flag) => {
  if (flag === 'old') {
    useDocument.setCompareFiles('oldFile', null)
    useDocument.setCompareFiles('oldFilePassword', '')
  } else if (flag === 'new') {
    useDocument.setCompareFiles('newFile', null)
    useDocument.setCompareFiles('newFilePassword', '')
  } else {
    useDocument.initCompareFiles()
  }
  useViewer.setCompareStatus('')
}

// 拖拽上传
const handleDrop = async (e, flag) => {
  e.preventDefault()
  const files = e.dataTransfer.files
  isDragOverOld.value = false
  isDragOverNew.value = false

  if (files[0].type !== 'application/pdf') return

  let url = URL.createObjectURL(files[0])
  const pass = await core.checkPassword(url, true)
  if (pass === false) {
    e.target.value = ''
    return
  }

  const filename = files[0].name
  if (flag === 'old') {
    useDocument.setCompareFiles('oldFile', files[0])
    useDocument.setCompareFiles('oldFilePassword', pass)
    handleUpload(url, filename, 2)
  }
  if (flag === 'new') {
    useDocument.setCompareFiles('newFile', files[0])
    useDocument.setCompareFiles('newFilePassword', pass)
    handleUpload(url, filename, 3)
  }
}

// 拖拽高亮
const handleDragEnter = (flag) => {
  if (flag === 'old') {
    isDragOverOld.value = true
  }
  if (flag === 'new') {
    isDragOverNew.value = true
  }
}
const handleDragLeave = (e) => {
  const oldDropArea = document.getElementById('oldDropArea')
  const newDropArea = document.getElementById('newDropArea')
  let currentElement = e.relatedTarget

  // 逐级向上遍历，检查是否是 drop-area 或其子元素
  while (currentElement) {
    if (currentElement === oldDropArea || oldDropArea.contains(currentElement) || currentElement === newDropArea || newDropArea.contains(currentElement)) return
    currentElement = currentElement.parentElement
  }
  isDragOverOld.value = false
  isDragOverNew.value = false
}

// 创建文档窗口对象
const initDocumentView = () => {
  const license = useViewer.getLicense
  if (!license) return

  core.setDocumentViewer(2, null, {
    $t: instance.$t
  })
  core.setDocumentViewer(3, null, {
    $t: instance.$t
  })
  initConfig({
    license
  }, 2)
  initializeViewer({
    container: oldFileContainer.value,
    viewer: oldViewerContainer.value,
  }, 2)
  
  initConfig({
    license
  }, 3)
  initializeViewer({
    container: newFileContainer.value,
    viewer: newViewerContainer.value,
  }, 3)
}

// 删除文档对象
const clearDocumentViewer = () => {
  core.deleteDocumentViewer(2)
  core.deleteDocumentViewer(3)
}

// 上传文件
async function handleUpload (url, filename, docNum) {
  useViewer.setUpload(true)
  useViewer.setUploadLoading(true)
  await handlePdf(url, filename, docNum)
  useViewer.setUploadLoading(false)
}

// 预览pdf
async function handlePdf (pdf, filename, docNum) {
  let pwd = null
  if (docNum === 2) {
    pwd = useDocument.getCompareFile('oldFilePassword')
  } else if (docNum === 3) {
    pwd = useDocument.getCompareFile('newFilePassword')
  }
  const options = {
    extension: getHashParameters('extension', null),
    filename: getHashParameters('filename', null) || filename,
    externalPath: getHashParameters('p', ''),
    documentId: getHashParameters('did', null),
    progress: useDocument.setLoadingProgress,
    pageChangedCallback: useViewer.setCurrentPage,
    scaleChangedCallback: docNum === 2 ? useViewer.setOldCurrentScale : useViewer.setNewCurrentScale,
    annotationsNumChangedCallback: useDocument.setAnnotationsCount,
    distanceChangedCallback: useDocument.setDistance,
    notUploadPdf: true
  }
  if (pwd) {
    options.pwd = pwd
  }
  try {
    await loadDocument(pdf, options, docNum)
  } catch (error) {
    console.log(error)
    if (error === 'invalid_file_error' || error === 'no_password_given' || error === 'incorrect_password') {
      useViewer.setUpload(false)
      useDocument.setLoadingProgress(0)
      useViewer.resetSetting()
    }
  }
}

</script>

<style lang="scss">
.compare-document-container {
  display: flex;
  width: 100%;
  background-color: var(--c-file-header);

  &.under {
    display: none;
  }
  .old, .new {
    width: 100%;
    max-width: calc(50% - 5px);
    display: flex;
    flex-direction: column;
  }
  .old {
    margin-right: 10px;
    border-right: 1px solid rgba(0, 0, 0, 0.12);
  }
  .new {
    border-left: 1px solid rgba(0, 0, 0, 0.12);
  }
  .file-type {
    padding: 10px 22px;
    background-color: var(--c-file-header);
    border-bottom: 1px solid rgba(0, 0, 0, 0.12);
    color: var(--c-text);
    font-family: Helvetica;
    font-size: 14px;
    line-height: normal;
  }
  .file-content {
    flex: 1;
    background-color: var(--c-header-bg);
    position: relative;
    &.no-file {
      padding: 20px 20px 25px;
    }
    .drop-area {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      border-radius: 4px;
      .upload-tip {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;
        width: 300px;
        height: 126px;
        font-family: Helvetica;
        font-size: 16px;
        line-height: 24px;
        text-align: center;
        .rect-button {
          position: relative;
          padding: 0 20px;
          min-width: 240px;
          height: 48px;
          font-weight: 700;
          border-radius: 4px;
          input {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
          }
        }
        .file-name {
          height: 62px;
          text-align: center;
          font-size: 16px;
          font-weight: 700;
          line-height: 24px;
        }
      }
      &.drag-over {
        border-color: #1460F3;
        background: #DDE9FF;
      }
    }

    .uploaded {
      .header-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 4px 12px;
        height: 40px;
        background-color: var(--c-header-bg);
        .file-name {
          font-family: Helvetica;
          font-size: 14px;
          line-height: 20px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .close {
          min-width: 20px;
          cursor: pointer;
          &:hover {
            opacity: 0.8;
          }
        }
      }
    }
    .file-container {
      overflow: auto;
      position: absolute;
      left: 0;
      top: 40px;
      right: 0;
      bottom: 0;
      outline: none;
      transition: all .3s ease-in-out;
      background: var(--c-bg);
      &.no-file {
        z-index: -1;
      }
    }
  }
  .mobile {
    display: none !important;
  }
}
@media screen and (max-width: 768px) {
  .compare-document-container {
    flex-direction: column;
    .pc {
      display: none !important;
    }
    .mobile {
      display: flex !important;
    }
    .old, .new {
      flex: 1;
      max-width: none;
    }
    .old {
      margin-right: 0;
      border-right: none;
      .file-content {
        padding-bottom: 0;
      }
    }
    .new {
      border-left: none;
    }
    .file-type {
      display: none;
    }
    .file-content {
      padding: 16px;
      .drop-area {
        border: 2px dashed #D9D9D9;
        position: relative;
        .upload-tip {
          margin: 0 20px;
          width: 260px;
          height: auto;
          .text {
            position: absolute;
            left: 16px;
            top: 16px;
            text-align: left;
            p {
              margin-bottom: 8px;
              font-weight: 700;
              color: var(--c-right-side-header-text);
              font-size: 14px;
              line-height: 16px;
            }
          }
          .rect-button {
            position: relative;
            width: 100%;
            height: 40px;
            min-width: auto;
          }
        }
        .file-name {
          position: absolute;
          left: 0;
          top: 48px;
          font-size: 14px;
          font-weight: 700;
          line-height: 16px;
          color: var(--c-text);
          text-align: left;
          width: 100%;
          word-wrap: break-word;
        }
      }
    }
  }
}
@media screen and (min-width: 769px) {
  .compare-document-container .file-content.no-file .drop-area {
    border: 2px dashed #D9D9D9;
  }
}
</style>
