<template>
    <div style="
      position: fixed;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      overflow: auto;
    ">
        <div class="export-img-dialog">
            <div class="thumbnails-view" ref="refThumbnails">
                <div class="thumbnails" :style="{width:viewportRatio < 1
                            ? VIEWPORT_SIZE.Value
                            : VIEWPORT_VER_SIZE.Value+'px'}" v-for="slide in slides">
                    <ThumbnailSlide class="thumbnail" :key="slide.id" :slide="slide" :size="viewportRatio < 1
                            ? VIEWPORT_SIZE.Value
                            : VIEWPORT_VER_SIZE.Value
                        " />
                </div>
            </div>
        </div>
    </div>
    <div style="position: fixed;left: 200px;top: -100px;opacity: 0;">
      <canvas style="display: none" id="canvas"></canvas>
      <div
         id="extract-color-id"
         class="extract-color"
         style="display: flex;padding: 0 20px; justify-content:end;">
      </div>
  </div>
</template>

<script setup lang="ts">
import ThumbnailSlide from '../components/ThumbnailSlide/index.vue'
import ConfigService from '@/services/ConfigService'
import FileService from '@/services/FileService'
import { storeToRefs } from 'pinia'
import { useSlidesStore } from '../../store'
import { VIEWPORT_SIZE, VIEWPORT_VER_SIZE } from '../../configs/canvas'
import { ref } from 'vue';
import { ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from "@/store";
import themeColor from '@/utils/colorExtraction';
import { getRgbLevel } from '@/utils/common'

const router = useRouter()
const param = router.currentRoute.value.params
const slidesStore = useSlidesStore()
const { slides, viewportRatio } = storeToRefs(slidesStore)
const { userInfo } = storeToRefs(useUserStore())

const acquiesceLogo = ref([
  'https://im.oytour.com/pptist/static/logo1.png',
  'https://im.oytour.com/pptist/static/logo2.png',
  'https://im.oytour.com/pptist/static/logo3.png',
  'https://im.oytour.com/pptist/static/logo4.png',
  'https://im.oytour.com/pptist/static/logo5.png',
  'https://im.oytour.com/pptist/static/logo6.png',  
])

const tempDatas = ({} as any)
const colorList = ([] as any)

const w = ref(0)
const h = ref(0)

const loadSliders = async ()=>{
  const loadingObj = ElLoading.service({text:'正在渲染数据',lock:true})
  let response = await ConfigService.GetTripTemplateSlide({TempId:parseInt(param.tempId.toString())})
  loadingObj.close()
  if (response.data.resultCode == 1) {
      
      let dataObj = response.data.data
      w.value=dataObj.Width
      h.value=dataObj.Height

      colorList.value = []
      tempDatas.value = dataObj

      for(let i=0;i<tempDatas.value.PageImageList.length;i++){
        const img = new Image();
        img.src = `${tempDatas.value.PageImageList[i]}`;
        img.crossOrigin = 'anonymous';
        img.onload = () => {
          themeColor(1, img, 20, SetColor);
        };
      }
      if(w.value>0){
        viewportRatio.value = h.value/w.value
        if(viewportRatio.value>=1) VIEWPORT_VER_SIZE.Value=w.value
        if(viewportRatio.value<1) VIEWPORT_SIZE.Value=w.value
      }else{
        viewportRatio.value = dataObj.TempType==1? 0.7069:1.414
      }
      let SlidesData = JSON.parse(dataObj.TempData)
      let newSlides:any[] = []
      SlidesData&&SlidesData.forEach((x:any,i:number)=>{
        newSlides.push(x)
      })
      setTimeout(()=>{
        getColorShade(newSlides)
      },500)
  }
}

// 获取是否深色
const getColorShade = async (newSlides:any) => {
  let dark = false
  // 根据集团渲染logo
  console.log(tempDatas.value.AuthType<=1,'-----------')
  if(tempDatas.value.AuthType<=1){
    for(let j=0;j<colorList.value.length;j++){
      if (getRgbLevel(colorList.value[j].Color) > 50) dark = true
    }
    for(let i=0;i<newSlides.length;i++){
      if(i>colorList.value.length-2) dark = false
      let x = newSlides[i]
      let eles = x.elements.filter(y=>y.layerName && y.layerName.indexOf('logo')!=-1)
      let newElementsImg = await ResolveTripLogoHandler(eles,i,dark)
      let newElements = []
      x.elements.forEach(y=>{
        if(newElementsImg?.elements){
          newElementsImg?.elements.forEach(z=>{
            if(y.id==z.id) y = JSON.parse(JSON.stringify(z))
          })
        }
        newElements.push(y)
      })
      x.elements = newElements
    }
  }
  slidesStore.setSlides(newSlides)
  slidesStore.updateSlideIndex(0)
}


const ResolveTripLogoHandler = async (items:any, slideIndex:number,dark:false) =>{
    let elements = []
    let tempNewSlide:any = null
    let templateObj = JSON.parse(JSON.stringify(items))
    for(let i=0;i<templateObj.length;i++){
      try {
          let Colors = templateObj[i].layerName.split(',')
          let y = templateObj[i]
          let tempSize = await FileService.getImageSizeWithoutDownloading(templateObj[i].src)
          let scale = parseInt(tempSize.width/tempSize.height)
          // if(Colors[1]||scale==6) templateObj[i].filters.invert = '20%'
          if(scale==1) templateObj[i].src = dark==true?acquiesceLogo.value[0]:acquiesceLogo.value[3]
          if(scale<1) templateObj[i].src = dark==true?acquiesceLogo.value[1]:acquiesceLogo.value[4]
          if(scale>1) templateObj[i].src = dark==true?acquiesceLogo.value[2]:acquiesceLogo.value[5]
          if(tempNewSlide){
            tempNewSlide.elements.push(...templateObj)
          }else{
            elements.push(...templateObj)
            tempNewSlide = copySlidHandlerLogo(slideIndex)
          }
          let newTempSize = await FileService.getImageSizeWithoutDownloading(templateObj[i].src)
          let width = 0
          let height =  0
          //按照宽度进行缩放
          let ratio = newTempSize.width / y.width
          width = y.width
          height = newTempSize.height / ratio
          if(height<y.height){
              ratio = height / y.height
              height =  y.height
              width = width / ratio
          }
          y.height = height
          y.width = width
        } catch (error) {

        }
    }
    
    return {
      elements,
      newSlider:tempNewSlide,
    }
}

const SetColor = (colorArr: number[][]) => {
    // 初始化删除多余子节点
    const extractColor = document.querySelector('#extract-color-id') as HTMLElement;
    while (extractColor.firstChild) {
      extractColor.removeChild(extractColor.firstChild);
    }
    // 创建子节点
    for (let index = 0; index < colorArr.length; index++) {
      const bgc = '(' + colorArr[index][0] + ',' + colorArr[index][1] + ',' + colorArr[index][2] + ')';
      const colorBlock = document.createElement('div') as HTMLElement;
      colorBlock.id = `color-block-id${index}`;
      colorBlock.style.cssText = 'height: 50px;width: 50px;margin-right: 10px;border-radius: 50%;';
      colorBlock.style.backgroundColor = `rgb${bgc}`;
      let list = [parseInt(colorArr[index][0]),parseInt(colorArr[index][1]),parseInt(colorArr[index][2])]
      let obj = {
        Color: list
      }
      colorList.value.push(obj)
      extractColor.appendChild(colorBlock);
    }
}

if(param.tempId){
    loadSliders()
}
</script>