<script setup lang="ts">
import { computed, ref, nextTick } from 'vue'
import { $sleep } from '@/utils'
import hud from '@/utils/hud'
import obj from '@/utils/obj'

import html2canvas from 'html2canvas'
import { jsPDF as JsPDF } from 'jspdf'

const props = defineProps<{
  modelValue: boolean
  words: any[]
  title: any
}>()

const emit = defineEmits(['update:modelValue', 'success'])

defineOptions({ name: 'WordPrint' })

const value = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

// 类型映射
// const type_cn_en_line = '3'
const type_cn_en = '1'
const type_en_cn = '2'
const typeOptions = [
  // {
  //   label: '中英连线',
  //   value: type_cn_en_line,
  // },
  {
    label: '中译英',
    value: type_cn_en,
  },
  {
    label: '英译中',
    value: type_en_cn,
  },
]
const typeMap = obj.options2map(typeOptions)
const type = ref(type_cn_en)

const printRef = ref()
async function savePdf() {
  await $sleep(1000)
  const width = printRef.value.offsetWidth
  const height = printRef.value.offsetHeight
  const canvas = await html2canvas(printRef.value, {
    scale: 2,
  })
  const imgData = canvas.toDataURL('image/jpeg', 0.7)
  const pdf = new JsPDF()

  // 设置图片尺寸（以毫米为单位）
  const imgWidth = 210 // A4纸张的宽度
  const pageHeight = 295 // A4纸张的高度
  const imgHeight = (height * imgWidth) / width // 缩放后的总高度

  let printHeight = imgHeight // 打印的高度
  // let position = 0
  // const maxPage = 2

  // 将图像添加到 PDF
  // pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, undefined, 'FAST')
  // printHeight -= pageHeight
  while (printHeight > 0) {
    const position = printHeight - imgHeight
    if (position < 0) {
      pdf.addPage()
    }
    pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, undefined, 'FAST')
    printHeight -= pageHeight
  }
  // 如果内容超出一页，将剩余内容添加到新的一页
  // while (page < maxPage) {
  //   position = printHeight - imgHeight
  //   pdf.addPage()
  //   pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, undefined, 'FAST')
  //   printHeight -= pageHeight
  //   page++
  // }

  pdf.save(`${props.title}_${typeMap[type.value]}_${props.words?.length}.pdf`)
}

async function print() {
  await hud.load({
    task: async () => {
      await savePdf()
      emit('success')
    },
    option: '导出',
  })
}
</script>

<template>
  <mj-dialog v-model="value" :title="`单词导出(共${words.length}个单词)`" :width="1600" :ok="print">
    <div class="word-print">
      <div class="mj-data-row">
        <div class="mj-data-item status-item">
          <span class="mj-data-item-title">类型</span>
          <select-tab v-model="type" :data-list="typeOptions" />
        </div>
      </div>
      <div class="preview">
        <div ref="printRef" class="print-content">
          <p class="title">
            {{ title }}
          </p>
          <div class="words">
            <div v-for="item in words" :key="item.meaningId" class="word">
              <span class="question">
                {{ type === type_en_cn ? item.spell : `${item.typeAbbr} ${item.simpleDesc}` }}
              </span>
              <span class="answer"></span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </mj-dialog>
</template>

<style lang="scss" scoped>
.word-print {
  .preview {
    width: 1400px;
    margin: 2vh auto 1vh;
    font-size: 16px;
    height: 60vh;
    overflow: auto;
    border: 1px dashed #000;
    .print-content {
      font-family: '宋体';
      padding: 0 24px;
      $row_h: 95px;
      $row_g: 20px;
      $row_ch: $row_h - $row_g;
      .title {
        font-size: 36px;
        font-weight: bold;
        text-align: center;
        height: $row_h;
        padding-top: 20px;
      }

      .words {
        display: grid;
        grid-template-columns: repeat(3, 1fr); /* 三列等宽 */
        // grid-template-rows: repeat(6, 9.4vh); /* 两行等高 */
        // column-gap: 20px;
        // row-gap: 2vh;
        column-gap: 40px;
        row-gap: $row_g;
        font-size: 24px;
        justify-content: center;
      }

      .word {
        display: flex;
        height: $row_ch;
        .question {
          padding: 5px 10px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .question,
        .answer {
          border: 1px solid #000;
          // width: 120px;
          flex: 1;
        }
      }
    }
  }
}
</style>
