<template>
  <div class="export-pdf-dialog">
    <div class="thumbnails-view">
      <div class="thumbnails" ref="pdfThumbnailsRef">
        <ThumbnailSlide 
          class="thumbnail" 
          :slide="currentSlide" 
          :size="viewportRatio<1 ? VIEWPORT_SIZE.Value : VIEWPORT_VER_SIZE.Value" 
          v-if="rangeType === 'current'"
        />
        <template v-else>
          <ThumbnailSlide 
            class="thumbnail" 
            :class="{ 'break-page': (index + 1) % count === 0 }"
            v-for="(slide, index) in newSlides" 
            :key="slide.id" 
            :slide="slide" 
            :size="viewportRatio<1 ? VIEWPORT_SIZE.Value : VIEWPORT_VER_SIZE.Value" 
          />
        </template>
      </div>
    </div>
    <div class="configs">
      <div class="row">
        <div class="title">导出范围：</div>
        <RadioGroup
          class="config-item"
          v-model:value="rangeType"
        >
          <RadioButton style="width: 50%;" value="all">全部</RadioButton>
          <RadioButton style="width: 50%;" value="current">当前页</RadioButton>
        </RadioGroup>
      </div>
      <div class="row">
        <div class="title">每页数量：</div>
        <Select 
          class="config-item"
          v-model:value="count"
          :options="[
            { label: '1', value: 1 },
            { label: '2', value: 2 },
            { label: '3', value: 3 },
          ]"
        />
      </div>
      <div class="row">
        <div class="title">边缘留白：</div>
        <div class="config-item">
          <Switch v-model:value="padding" />
        </div>
      </div>
      <div class="tip">
        提示：若打印预览与实际样式不一致，请在弹出的打印窗口中勾选【背景图形】选项。
      </div>
      <div class="tip" style="color:red" v-if="searchData.sellId==0">当前设计文档没有保存，无法下载PDF，请先保存文档。</div>
    </div>
    <a ref="downloadLink" target="_blank" :href="fileUrl" style="display:none" v-if="model==2 &&searchData.sellId!=0"></a>
    <!-- <a ref="downloadLink" :href="fileUrl" @click.prevent="downloadFile" style="display:none"  v-else></a> -->
    
    <div class="btns">
      <Button class="btn export" type="primary" @click="exportOnlinePdf()" v-if="model==2 && searchData.sellId!=0">导出PDF</Button>
      <Button class="btn export" type="primary" @click="expPDF()" v-else>导出PDF</Button>
      <Button class="btn close" @click="emit('close')">关闭</Button>
    </div>
   
  </div>
</template>

<script lang="ts" setup>
import { Ref, ref,inject } from 'vue'
import { storeToRefs } from 'pinia'
import { useSellTemplateStore, useSlidesStore, useScreenStore } from '@/store'
import { print } from '@/utils/print'
import { VIEWPORT_SIZE, VIEWPORT_VER_SIZE } from '@/configs/canvas'
import { query } from '@/utils/common'

import ThumbnailSlide from '@/views/components/ThumbnailSlide/index.vue'
import Switch from '@/components/Switch.vue'
import Button from '@/components/Button.vue'
import RadioButton from '@/components/RadioButton.vue'
import RadioGroup from '@/components/RadioGroup.vue'
import Select from '@/components/Select.vue'
import { injectKeyTemplate } from '@/types/injectKey'
import { watch } from 'vue'
import { nextTick } from 'vue'


const emit = defineEmits<{
  (event: 'close'): void
}>()

const { slides, currentSlide, viewportRatio } = storeToRefs(useSlidesStore())
const { model } = storeToRefs(useScreenStore())

const newSlides = ref<Array<any>>([])
const searchData = ref({} as any)
searchData.value = inject(injectKeyTemplate)
const pdfThumbnailsRef = ref<HTMLElement>()
const rangeType = ref<'all' | 'current'>('all')
const count = ref(1)
const padding = ref(false)

const autoSave = inject('SellTravelSave') as Ref<number>
const loadingObj = ref<any>()
const downloadLink= ref()
const fileUrl = ref("")

const expPDF = () => {
  if (!pdfThumbnailsRef.value) return
  const width = viewportRatio.value<1 ? VIEWPORT_SIZE.Value : VIEWPORT_VER_SIZE.Value
  const pageSize = {
    width: width,
    height: rangeType.value === 'all' ? width * viewportRatio.value * count.value : width * viewportRatio.value,
    margin: padding.value ? 50 : 0,
  }
  print(pdfThumbnailsRef.value, pageSize)
}

const formatSliders =()=>{
  const width = viewportRatio.value<1 ? VIEWPORT_SIZE.Value : VIEWPORT_VER_SIZE.Value
  slides.value.forEach((x)=>{
    let item = JSON.parse(JSON.stringify(x))
    item.elements = item.elements.filter(y=>y.left<width && (y.left+y.width)>=0)
    newSlides.value.push(item)
  })
}

const exportOnlinePdf=()=>{
  autoSave.value=1
}
const beginDownload = async ()=>{
  fileUrl.value =  `https://fileservice.oytour.com/api/pdf/${searchData.value.sellId}/${useSellTemplateStore().SaleHashCode}`
  nextTick(()=>{
    downloadLink.value.click()
  })
}

watch(()=>autoSave.value,(newVal)=>{
  if(newVal==2){
    beginDownload()
  }else if(newVal==0){
    if(loadingObj.value) loadingObj.value.close()
    loadingObj.value=null
  }
})
formatSliders()
</script>

<style lang="scss" scoped>
.export-pdf-dialog {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}
.thumbnails-view {
  @include absolute-0();

  &::after {
    content: '';
    background-color: #fff;
    @include absolute-0();
  }
}
.thumbnail {
  &.break-page {
    break-after: page;
  }
}
.configs {
  width: 300px;
  height: calc(100% - 100px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  z-index: 1;

  .row {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 25px;
  }

  .title {
    width: 100px;
  }
  .config-item {
    flex: 1;
  }

  .tip {
    font-size: 12px;
    color: #aaa;
    line-height: 1.8;
    margin-top: 25px;
  }
}
.btns {
  width: 300px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1;

  .export {
    flex: 1;
  }
  .close {
    width: 100px;
    margin-left: 10px;
  }
}
</style>