<template>
  <div class="add-page-setting-popup" v-if="show">
    <Dialog :show="show" :dialogName="dialogName" :close="false">

      <!-- 插入页面类型 -->
      <p class="title">{{ $t('documentEditor.dialog.insertPages') }}</p>
      <div class="container">
        <div class="select-content">
          <!-- 空白页 -->
          <div @click="type = 'blank'" class="option"><RadioBtnSel v-if="type === 'blank'" /><RadioBtnDis v-else />{{ $t('documentEditor.dialog.blankPage') }}</div>
          <!-- 自定义空白页 -->
          <div @click="type = 'custom'" class="option"><RadioBtnSel v-if="type === 'custom'" /><RadioBtnDis v-else />{{ $t('documentEditor.dialog.customPage') }}</div>
          <div v-if="type === 'custom'" class="addition">
            <select name="customPageSize" v-model="customPageSize">
              <option value="A3">A3</option>
              <option value="A4">A4</option>
              <option value="A5">A5</option>
            </select>
            <ArrowDown />
          </div>
          <!-- 从其他PDF -->
          <div @click="type = 'pdf'" class="option"><RadioBtnSel v-if="type === 'pdf'" /><RadioBtnDis v-else />{{ $t('documentEditor.dialog.fromPdf') }}</div>
          <div v-if="type === 'pdf'" class="addition">
            <div class="file-input-underbox">
              <span :class="{ 'uploaded': inputFile?.name }">{{ inputFile?.name || $t('documentEditor.dialog.selectFile') }}</span>
              <FileFolder />
            </div>
            <input type="file" @change="handleFile" accept=".pdf" name="document-editor">
          </div>
          <div v-if="type === 'pdf'" class="addition from-pdf">
            <span>{{ $t('documentEditor.dialog.pageRange') }}</span>
            <div>
              <div class="addition">
                <select name="inputFileRange" v-model="inputFileRange">
                  <option value="all">{{ $t('documentEditor.dialog.allPages') }}</option>
                  <option value="odd">{{ $t('documentEditor.dialog.oddPage') }}</option>
                  <option value="even">{{ $t('documentEditor.dialog.evenPage') }}</option>
                  <option value="custom">{{ $t('documentEditor.dialog.customRange') }}</option>
                </select>
                <ArrowDown />
              </div>
              <input v-if="inputFileRange === 'custom'" type="text" v-model="customRange" :placeholder="$t('documentEditor.dialog.pageTip')" @blur="validateCustomRange" name="document-editor">
            </div>
          </div>
        </div>
      </div>

      <!-- 插入页面位置 -->
      <p class="title">{{ $t('documentEditor.dialog.insertTo') }}</p>
      <div class="container">
        <div class="select-content">
          <!-- 首页 -->
          <div @click="place = 'first'" class="option"><RadioBtnSel v-if="place === 'first'" /><RadioBtnDis v-else />{{ $t('documentEditor.dialog.firstPage') }}</div>
          <!-- 末页 -->
          <div @click="place = 'last'" class="option"><RadioBtnSel v-if="place === 'last'" /><RadioBtnDis v-else />{{ $t('documentEditor.dialog.lastPage') }}</div>
          <!-- 自定义位置 -->
          <div @click="place = 'custom'" class="option" :class="{ 'custom-page': place === 'custom' }">
            <div class="left">
              <RadioBtnSel v-if="place === 'custom'" /><RadioBtnDis v-else />{{ $t('documentEditor.dialog.page') }}
            </div>
            <div v-if="place === 'custom'" class="right">
              <div class="addition">
                <input v-model.number="targetIndex" type="number" :max="totalPages" min="1" pattern="\d*" onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))" @input="validatePageInput" @blur="onblurPageInput" name="document-editor">
                <span>/ {{ totalPages }}</span>
              </div>
              <div class="addition">
                <select name="targetPlace" v-model="targetPlace">
                  <option :value="0">{{ $t('documentEditor.dialog.before') }}</option>
                  <option :value="1">{{ $t('documentEditor.dialog.after') }}</option>
                </select>
                <ArrowDown />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- footer -->
      <template #footer>
        <div class="rect-button white" @click="closeDialog">{{ $t('cancel') }}</div>
        <div class="rect-button blue" :class="{ 'disabled': type === 'pdf' && (!inputFile || (inputFileRange === 'custom' && !validCustomRange)) }" @click="confirm">{{ $t('documentEditor.insert') }}</div>
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, h } from 'vue'
import { useViewerStore } from '@/stores/modules/viewer'
import core from '@/core'

const props = defineProps(['selectedPageList', 'totalPages'])
const emits = defineEmits(['insertPage'])

const useViewer = useViewerStore()

const dialogName = 'insertPageSettingDialog'
const show = computed(() => useViewer.isElementOpen(dialogName))

const type = ref('blank')
const customPageSize = ref('A4')
const inputFile = ref(null)
const inputFileRange = ref('all')
const customRange = ref('')
const validCustomRange = ref('')

const place = ref('first')
const targetIndex = ref(1)
const targetPlace = ref(1)
const password = ref('')

watch(() => show.value, (newVal, oldVal) => {
  if (newVal) {
    if (props.selectedPageList.length > 0) place.value = 'custom'
    targetIndex.value = props.selectedPageList[0] + 1
  }
})

// 关闭弹窗
const closeDialog = () => {
  useViewer.closeElement(dialogName)

  // 初始化
  type.value = 'blank'
  customPageSize.value = 'A4'
  inputFile.value = null
  inputFileRange.value = 'all'
  customRange.value = ''
  validCustomRange.value = ''

  place.value = 'first'
  targetPlace.value = 1
  password.value = ''
}

// 确认
const confirm = async () => {
  const data = {
    type: type.value === 'pdf' ? 'pdf' : 'blank',
  }

  if (type.value === 'custom') {
    // A3纸的尺寸是297mm × 420mm
    // A4纸的尺寸是210mm × 297mm
    // A5纸的尺寸是148mm × 210mm
    // 1px = 25.4 * 1mm / PPI
    const pageSize = {
      A3: {
        width: 297,
        height: 420
      },
      A4: {
        width: 210,
        height: 297
      },
      A5: {
        width: 148,
        height: 210
      }
    }
    data.size = {
      width: pageSize[customPageSize.value].width / 25.4 * 72,
      height: pageSize[customPageSize.value].height / 25.4 * 72
    }
  }

  if (type.value === 'pdf' && inputFile.value) {
    data.file = inputFile.value
    data.range = inputFileRange.value === 'custom' ? customRange.value : inputFileRange.value
    data.password = password.value
  }

  if (place.value === 'custom') {
    data.place = targetIndex.value - 1 + targetPlace.value
    data.targetPlace = targetPlace.value
  } else if (place.value === 'last') {
    data.place = props.totalPages
  } else {
    data.place = 0
  }

  emits('insertPage', data)
  closeDialog()
}

// 上传文件
const handleFile = async (e) => {
  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
  }
  
  inputFile.value = e.target.files[0]
  password.value = pass
}

// 输入页码校验
const validatePageInput = (e) => {
  const value = e.target.valueAsNumber
  if (value > props.totalPages) {
    targetIndex.value = props.totalPages
  } else if (value < 1) {
    targetIndex.value = 1
  }
}
const onblurPageInput = () => {
  if (!targetIndex.value) targetIndex.value = 1
}

// 输入自定义页面范围校验 格式化
const validateCustomRange = () => {
  validCustomRange.value = formatText(customRange.value)
  customRange.value = validCustomRange.value
}
const formatText = (inputText) => {
  const text = inputText.replace(/\s/g, '')
  const matches = text.match(/\d+-\d+|\d+|\d+/g)

  if (matches) {
    const sortedNums = matches
      .flatMap(match => {
        if (match.includes('-')) {
          const [start, end] = match.split('-')
          const smallest = Math.max(1, Math.min(start, end))
          const largest = Math.max(1, start, end)
          return Array.from({ length: largest - smallest + 1 }, (_, i) =>
            String(Number(smallest) + i)
          )
        } else {
          return Math.max(1, match)
        }
      })
      .sort((a, b) => a - b)

    const formattedText = []

    let start = sortedNums[0]
    let prev = sortedNums[0]

    for (let i = 1; i < sortedNums.length; i++) {
      const current = sortedNums[i]

      const prevNum = Number(prev)
      const currentNum = Number(current)

      if (currentNum - prevNum > 1) {
        formattedText.push(formatRange(start, prev))
        start = current
      }
      prev = current
    }
    formattedText.push(formatRange(start, prev))
    return formattedText.join(', ')
  }
  return '1'
}
const formatRange = (start, end) => {
  return (start === end) ? start.toString() : `${start}-${end}`
}
</script>

<style lang="scss">
.add-page-setting-popup {
  .dialog-container {
    width: 420px;
    box-shadow: 0px 4px 32px 0px var(--c-doc-editor-popup-shadow);

    main {
      margin: 0;
    }
  }

  .title {
    font-size: 16px;
    font-weight: 700;
    line-height: 24px;
  }

  .container {
    margin-top: 8px;
    margin-bottom: 16px;
    padding: 8px 16px 16px;
    border-radius: 4px;
    background: var(--c-toolbar-bg);

    .select-content .option:not(:first-child) {
      margin-top: 16px;
    }
    
    .addition {
      position: relative;
      display: flex;
      align-items: center;

      & + .addition {
        margin-top: 4px;
      }
      
      span {
        white-space: nowrap;
        font-size: 14px;
        line-height: 16px;
      }

      svg {
        position: absolute;
        right: 4px;
        pointer-events: none;
      }

      select,
      input,
      .file-input-underbox {
        padding: 0 20px 0 8px;
        width: 100%;
        height: 24px;
        background: var(--c-right-side-content-fillbox-bg);
        border: 1px solid var(--c-right-side-content-fillbox-border);
        border-radius: 1px;
        font-size: 14px;
        line-height: 16px;
      }

      input {
        font-size: 16px;
        &::placeholder {
          font-size: 14px;
        }
      }

      input,
      select {
        color: var(--c-text);
      }

      select {
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
      }

      .file-input-underbox {
        display: flex;
        align-items: center;
        color: #999;

        .uploaded {
          color: var(--c-text);
          overflow: hidden;
          text-overflow: ellipsis;
        }

        svg {
          color: var(--c-side-outline-text);
        }
      }

      input[type="file"] {
        position: absolute;
        width: 100%;
        height: 100%;
        opacity: 0;
        cursor: pointer;

        &::file-selector-button {
          cursor: pointer;
        }
      }

      &.from-pdf {
        align-items: baseline;

        span {
          margin-right: 8px;
        }

        > div {
          flex: 1;

          input[type="text"] {
            margin-top: 4px;
          }
        }
      }

      input[type="text"]:focus {
        border-color: #0078D7;
      }
    }

    .option.custom-page {
      padding: 0;
      align-items: baseline;

      .left {
        display: flex;
        align-items: center;
      }

      .right {
        flex: 1;
        margin-left: 20px;

        .addition {
          span {
            margin-left: 8px;
            color: #999;
          }

          &:last-child {
            margin-top: 16px;
            max-width: 70%;
          }
        }
      }
    }
  }
}
</style>