<template>
    <div v-if="isFinish" style="height: 100vh;background: rgb(243, 246, 251);">
      <!-- <Screen v-if="screening" /> -->
      <PreviewCustomSlider v-if="model==448963"></PreviewCustomSlider>
      <Market v-else-if="(market&&model!=2&&!query().ViewSlideshow)||(market&&SalesEditor>0&&!query().ViewSlideshow)"></Market>
      <Workspace v-else-if="model==2&&SalesEditor==0"/>
      <Editor v-else-if="_isPC" />
      <Mobile v-else />
    </div>
    <el-result v-if="loading" title="404" :sub-title="ShareTips">
      <template #icon></template>
      <template #extra></template>
    </el-result>
  </template>
  
  <script lang="ts" setup>
  import { ApiResult } from '@/configs/axios';
  import { onMounted,ref,provide } from 'vue'
  import { storeToRefs } from 'pinia'
  import { useScreenStore, useMainStore, useSnapshotStore, 
    useFontStore, useSellTemplateStore, useSlidesStore } from '@/store'
  import { LOCALSTORAGE_KEY_DISCARDED_DB } from '@/configs/storage'
  import { deleteDiscardedDB } from '@/utils/database'
  import { isPC, query } from '@/utils/common'
  import { useUserStore } from '@/store/user'
  import { injectKeyTemplate } from '@/types/injectKey'
  import ConfigService from '@/services/ConfigService'
  import { domainManager } from '@/utils/domainManager'
  import { enterFullscreen, exitFullscreen, isFullscreen } from '@/utils/fullscreen'
  import { VIEWPORT_SIZE, VIEWPORT_VER_SIZE } from '@/configs/canvas'
  
  import Editor from './Editor/index.vue'
  import Screen from './Screen/index.vue'
  import Mobile from './Mobile/index.vue'
  import Market from './Market/Index.vue'
  import PreviewCustomSlider from './Preview/PreviewCustomSlider.vue'
  import SellTemplate from './SellTemplate/index.vue'
  import Workspace from './SellTemplate/Workspace.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  const searchData = ref({} as any)
  provide(injectKeyTemplate,searchData)
  const autoSave = ref(0)
  provide("SellTravelSave",autoSave)
  
  const isFinish = ref(false)
  const loading = ref(false)
  const ShareTips = ref('')
  const _isPC = isPC()
  const mainStore = useMainStore()
  const snapshotStore = useSnapshotStore()
  const modelStore = useScreenStore()
  const ConfigIdStore = useScreenStore()
  const marketStore = useScreenStore()
  const isModelStore = useScreenStore()
  const TempIdStore = useScreenStore()
  const ScreenStore = useScreenStore()
  const SellTemplateStore = useSellTemplateStore()
  const slidesStore = useSlidesStore()
  const { databaseId } = storeToRefs(mainStore)
  const { screening, market, model, ConfigId } = storeToRefs(useScreenStore())
  const { userInfo } = storeToRefs(useUserStore())
  const { SalesEditor, SalesTripId } = storeToRefs(useSellTemplateStore())
  const { slides } = storeToRefs(useSlidesStore())
  const { enterScreeningFromStart } = storeToRefs(useScreenStore())
  
  
  const userLoginHandler = async ()=>{
    let param = query()
    let userId = 0
    let ConfigId = 0 // 9117
    let model = 0
    let SalesTripId = ''
    await useFontStore().loadAllFonts()
    if(param.uid) userId=parseInt(param.uid)
    if(param.ConfigId) ConfigId=parseInt(param.ConfigId)
    if(param.model) model=parseInt(param.model)
    if(param.SalesTripId) {
      SalesTripId = param.SalesTripId
      SellTemplateStore.setSalesTripId(SalesTripId)
      try {
        await sellShareTemplate()
      } catch (error) {}
    }
    ConfigIdStore.setConfigId(ConfigId)
    modelStore.setModel(model)
    try {
      if(param.uid) await useUserStore().setUserAutoLoginAsync(userId) 
      if(ConfigId>0&&model!=2) await GetTripConfig(ConfigId)
    } catch (error) {}
    if(userId>0)isFinish.value=true
    
    if(param.ViewSlideshow) {
      searchData.value.ViewSlideshow = param.ViewSlideshow
      try {
        await sellHistoryTripTemplate(param.sellId,param.LogId)
      } catch (error) {} 
    }
    if(!ConfigId&&!model&&(param.SalesTripId&&param.SalesTripId=='')) ElMessageBox.confirm(
      '当前没有权限进行任何操作，请联系管理员！',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {})
    .catch(() => {})
    
  }  
  // 销售历史版本模版数据
  const sellHistoryTripTemplate = async (sellId:any,LogId:any) => {
    const loadingObj = ElLoading.service({
      text:'正在渲染数据',
      lock:true
    })
    try {
        let queryMsg 
        let dataRes
        if(!LogId){
          
          queryMsg = {
            Id: sellId,
            Status: searchData.value.ViewSlideshow==1?1:0
          }
          // 行程广告浏览记录
          if(queryMsg.Status==0) await ConfigService.SetTripBrowse({FileId: sellId});
          dataRes = await ConfigService.sellGetTemplateDetails(queryMsg);
        }else{
          queryMsg = {
            LogId: LogId,
            FileId: sellId,
          }
          dataRes = await ConfigService.GetHistoryInfo(queryMsg);
        }
        if (dataRes.data.resultCode==ApiResult.SUCCESS) {
          loadingObj.close()
          loading.value = false
          isFinish.value=true
          let dataObj = dataRes.data.data
          let viewportRatios = 0
          if(dataObj.TemplateType!=2) {
            viewportRatios = 1.414
            if(dataObj.TempType==1) viewportRatios = 0.7069
          }
          if(dataObj.TemplateType==2&&dataObj.Width&&dataObj.Height) {
            viewportRatios = dataObj.Height/dataObj.Width
          }
          if(dataObj.Width&&dataObj.Height) {
            VIEWPORT_SIZE.Value = dataObj.Height
            VIEWPORT_VER_SIZE.Value = dataObj.Width
          }else{
            VIEWPORT_SIZE.Value = 1754
            VIEWPORT_VER_SIZE.Value = 1240
          }
          slidesStore.setViewportRatio(viewportRatios)
  
          let SlidesData = JSON.parse(dataObj.TempData)
          let newSlides = []
          await SlidesData.forEach((x,i)=>{
            newSlides.push(x)
          })
          slidesStore.setSlides(newSlides)
          ScreenStore.setScreening(true)
          enterScreeningFromStart
          slidesStore.updateSlideIndex(0)
          
        }else{
          loading.value = true
          ShareTips.value = dataRes.data.message
          loadingObj.close()
        }
    } catch (error) {
        
    }
  }
  // 销售分享模版数据
  const sellShareTemplate = async () =>{
    
    const loadingObj = ElLoading.service({
      text:'正在渲染数据',
      lock:true
    })
    try {
        let queryMsg = {
          Code: SalesTripId.value
        }
        const slidesData = slides.value
        let dataRes = await ConfigService.GetTripOtherByCode(queryMsg);
        if (dataRes.data.resultCode==ApiResult.SUCCESS) {
          loadingObj.close()
          loading.value = false
          isFinish.value=true
          let dataObj = dataRes.data.data
          let viewportRatios = 0
          if(dataObj.TemplateType!=2) {
            viewportRatios = 1.414
            if(dataObj.TempType==1) viewportRatios = 0.7069
          }
          if(dataObj.TemplateType==2&&dataObj.Width&&dataObj.Height) {
            viewportRatios = dataObj.Height/dataObj.Width
          }
          if(dataObj.Width&&dataObj.Height) {
            VIEWPORT_SIZE.Value = dataObj.Height
            VIEWPORT_VER_SIZE.Value = dataObj.Width
          }else{
            VIEWPORT_SIZE.Value = 1754
            VIEWPORT_VER_SIZE.Value = 1240
          }
          slidesStore.setViewportRatio(viewportRatio)
  
          let SlidesData = JSON.parse(dataObj.TempData)
          let newSlides = []
          await SlidesData.forEach((x,i)=>{
            newSlides.push(x)
          })
          slidesStore.setSlides(newSlides)
          slidesStore.updateSlideIndex(0)
          ScreenStore.setScreening(true)
          enterScreeningFromStart
        }else{
          loading.value = true
          ShareTips.value = dataRes.data.message
          loadingObj.close()
        }
    } catch (error) {
      loading.value = true
      ShareTips.value = error
      loadingObj.close()
    }
  }
  
  
  /**
   * 根据团期配置编号获取行程详情
   */
  const GetTripConfig = async (ConfigId) =>{
    try {
        let queryMsg = {
            ConfigId: ConfigId
        }
        let datasRes = await ConfigService.triptemplateGetTripConfig(queryMsg);
        if (datasRes.data.resultCode==ApiResult.SUCCESS && datasRes.data.data) {
          let dataObj = datasRes.data.data
          if(dataObj.TempId==0){
            return window.parent.postMessage(`暂无行程数据`, `${domainManager().notificationUrl}`);
          }
          isModelStore.setIsModel(true)
          marketStore.setMarket(!market)
          TempIdStore.setTempId(dataObj.TempId)
        }
    } catch (error) {
    }
  }
  userLoginHandler()
  
  </script>
  
  <style lang="scss">
  #app {
    height: 100%;
  }
  .el-overlay{
    
  }
  </style>