<template>
    <div style="
      position: fixed;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
    "
    :style="{'overflow':param.w?'':'auto'}">
    <!-- :size="viewportRatio < 1
                            ? VIEWPORT_SIZE.Value
                            : VIEWPORT_VER_SIZE.Value
                        "  -->
    <!-- :style="{width:viewportRatio < 1
        ? VIEWPORT_SIZE.Value
        : VIEWPORT_VER_SIZE.Value+'px'}" -->
        <div class="export-img-dialog">
            <div class="thumbnails-view" ref="refThumbnails">
                <div class="thumbnails"  v-for="slide in slides">
                    <ThumbnailSlide class="thumbnail" 
                    :key="slide.id" 
                    :slide="slide" 
                    :size="param.w?param.w:(viewportRatio<1 ? VIEWPORT_SIZE.Value : VIEWPORT_VER_SIZE.Value )" />
                </div>
            </div>
        </div>
    </div>
    <!-- 获取行程颜色dom -->
    <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, watch } 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'
import { domainManager } from '@/utils/domainManager'

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',  
  'https://im.oytour.com/pptist/static/logo7.png',  
])

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

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

const refThumbnails = ref(null)
watch(() => refThumbnails.value, () => {
  setTimeout(()=>{
    getDomeWH()
  },1000)
})
const getDomeWH = async () => {
  if(refThumbnails.value){
    let height = await refThumbnails.value.offsetHeight;
    window.parent.postMessage(`行程特色高-${height}`, `${domainManager().notificationUrl}`);
  }
}

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) {
      if(!response.data.data.TempId) window.parent.postMessage(`暂无行程数据`, `${domainManager().notificationUrl}`);
      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
  let day = 0
  // 根据集团渲染logo
  if(tempDatas.value.AuthType<=2){
    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++){
      day = 0
      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 layerNames =  x.elements.filter(z=>{
        if(z.layerName&&z.layerName.indexOf('DAY')!=-1) return z
      })
      day = layerNames&&layerNames.length>0?1:0
      let newElementsImg = await ResolveTripLogoHandler(eles,i,dark,day)
      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,day:Number) =>{
    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(y.width/y.height)
          let url = ''
          if(scale>=1&&scale<3&&!day) url = dark==true?acquiesceLogo.value[0]:acquiesceLogo.value[3]
          if(scale>=1&&scale<3&&day) url = acquiesceLogo.value[6]
          if(scale<1) url = dark==true?acquiesceLogo.value[1]:acquiesceLogo.value[4]
          if(scale>=5) url = dark==true?acquiesceLogo.value[2]:acquiesceLogo.value[5]
          if(scale>=3&&scale<5&&!day) url = dark==true?acquiesceLogo.value[2]:acquiesceLogo.value[5]
          if(scale>=3&&scale<5&&day) url = acquiesceLogo.value[2]
          let newTempSize = await FileService.getImageSizeWithoutDownloading(url)
          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
          delete y.clip
          templateObj[i].src = url
          if(tempNewSlide){
            tempNewSlide.elements.push(...templateObj)
          }else{
            elements.push(...templateObj)
            tempNewSlide = copySlidHandlerLogo(slideIndex)
          }
          
        } 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>