<template>
  <div class="editor-header">
    <div class="left">
      <div v-if="SalesEditor==0&&!searchData.isTeamManage" class="menu-item" v-tooltip="'返回首页'" @click="goBack(1)">返回</div>
      <Popover v-if="SalesEditor>0"  trigger="click" placement="bottom-start" v-model:value="mainBackVisible">
        <template #content>
          <div class="menu-item" @click="goBack(1)">重选 {{searchData.TemplateType==2?'广告':'模版'}}</div>
          <div class="menu-item" @click="goBack(0)">返回首页</div>
        </template>
        <div class="menu-item">
          <el-icon color="#564bec"><ArrowLeftBold /></el-icon>
        </div>
        <!-- <div class="menu-item ArrowLeftBold"> </div> -->
      </Popover>
      <Popover trigger="click" placement="bottom-start" v-model:value="mainMenuVisible">
        <template #content>
          <!-- <FileInput accept=".pptist"  @change="files => {
            importSpecificFile(files)
            mainMenuVisible = false
          }">
            <PopoverMenuItem>导入 pptist 文件</PopoverMenuItem>
          </FileInput>
          <FileInput accept="application/vnd.openxmlformats-officedocument.presentationml.presentation"  @change="files => {
            importPPTXFile(files)
            mainMenuVisible = false
          }">
            <PopoverMenuItem>导入 pptx 文件（测试版）</PopoverMenuItem>
          </FileInput> -->
          <PopoverMenuItem @click="setDialogForExport('image')">导出文件</PopoverMenuItem>
          <!-- <PopoverMenuItem @click="resetSlides(); mainMenuVisible = false">重置幻灯片</PopoverMenuItem> -->
          <!-- <PopoverMenuItem @click="goLink('https://github.com/pipipi-pikachu/PPTist/issues')">意见反馈</PopoverMenuItem>
          <PopoverMenuItem @click="goLink('https://github.com/pipipi-pikachu/PPTist/blob/master/doc/Q&A.md')">常见问题</PopoverMenuItem> -->
          <PopoverMenuItem @click="mainMenuVisible = false; hotkeyDrawerVisible = true">快捷键</PopoverMenuItem>
        </template>
        <div class="menu-item"><IconHamburgerButton class="icon" /></div>
      </Popover>

      <div class="title">
        <Input 
          ref="titleInputRef"
          v-model:value="titleValue" 
          @blur="handleUpdateTitle()"
          maxlength="250"
          v-if="editingTitle" 
        ></Input>
        <div 
          class="title-text"
          @click="startEditTitle()"
          :title="title"
          v-else
        >{{ title }}</div>
      </div>
    </div>

    <div class="right">
      <!-- <div class="group-menu-item">
        <div class="menu-item" v-tooltip="'幻灯片放映'" @click="enterScreening()">
          <IconPpt class="icon" />
        </div>
        <Popover trigger="click" center>
          <template #content>
            <PopoverMenuItem @click="enterScreeningFromStart()">从头开始</PopoverMenuItem>
            <PopoverMenuItem @click="enterScreening()">从当前页开始</PopoverMenuItem>
          </template>
          <div class="arrow-btn"><IconDown class="arrow" /></div>
        </Popover>
      </div> -->
      <div class="group-menu-item" v-if="(userInfo.isTemplate==1||userInfo.iv || userInfo.ic || userInfo.ia)&&model==1">
        <div class="menu-item" v-tooltip="'导入PSD'" @click="UploadPsdHandler">
          <IconUpload class="icon" />
        </div>
      </div>
      <div v-if="!searchData.noExportPermission" class="menu-item q-mr-md" v-tooltip="'导出'" @click="setDialogForExport('image')">
        <IconDownload class="icon" />
      </div>
      <el-button type="primary" 
      v-if="(userInfo.isTemplate==1||userInfo.iv || userInfo.ic || userInfo.ia||ConfigId>0)&&model!=2"
      size="small" :loading="datas.loading"
      @click="setTemplate" style="color: #ffff;margin-left: 10px;">
        <template v-if="(userInfo.isTemplate==1||userInfo.iv || userInfo.ic || userInfo.ia)&&model==1">
          保存{{searchData.TemplateType!=2?'模板':'广告'}}
        </template>
        <template v-if="ConfigId>0&&model!=2">
          保存行程
        </template>
    </el-button>
    <template v-if="model==2">
      <el-dropdown v-if="searchData.sellId>0&&!searchData.noCopyPermission" split-button 
        size="small" type="primary" @click="setTemplate(0)">
        保存
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>
              <el-button type="default" 
                size="large" :loading="datas.loading"
                link
                @click.stop="setTemplate(0)">
                保存<!-- {{searchData.TemplateType!=2?'行程':'广告'}} -->
              </el-button>
            </el-dropdown-item>
            <el-dropdown-item>
              <el-button type="default" 
                size="large" :loading="datas.loading"
                link
                @click.stop="setTemplate(1)">
                另存为...
                <!-- {{searchData.TemplateType!=2?'行程':'广告'}} -->
              </el-button>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button v-if="!searchData.sellId||(searchData.sellId>0&&searchData.noCopyPermission)" type="primary" 
        size="small" :loading="datas.loading"
        style="color: #ffff;margin-left: 10px;"
        @click="setTemplate(0)">
        保存{{searchData.TemplateType!=2?'行程':'广告'}}
      </el-button>
    </template>
    
    </div>

    <Drawer
      :width="320"
      v-model:visible="hotkeyDrawerVisible"
      placement="right"
    >
      <HotkeyDoc />
    </Drawer>

    <FullscreenSpin :loading="exporting" tip="正在导入..." />
    <Psd-Upload :visible="psdVisibleStatus" @closed="psdVisibleStatus=false"></Psd-Upload>

    <CopyFile v-if="isCopyTo" 
    :details="journeyAdsDetails"
    :type="2"
    @close="() => {journeyAdsDetails = '';isCopyTo=false;datas.loading = false}"
    @success="(type:Number,FolderId:Number)=>SetSellTemplate(type,FolderId)"></CopyFile>
  </div>
  
</template>

<script lang="ts" setup>
import { ArrowDown } from '@element-plus/icons-vue'
import { nextTick, ref, reactive, inject, computed, watch, provide } from 'vue'
import { storeToRefs } from 'pinia'
import { toPng, toJpeg } from 'html-to-image'
import message from '@/utils/message'
import { useMainStore, useSlidesStore, useSellTemplateStore } from '@/store'
import useScreening from '@/hooks/useScreening'
import useImport from '@/hooks/useImport'
import useSlideHandler from '@/hooks/useSlideHandler'
import type { DialogForExportTypes } from '@/types/export'
import { useUserStore } from "@/store/user";
import { useScreenStore } from "@/store/screen";
import ConfigService from '@/services/ConfigService'
import { injectKeyDataSource, injectKeyTemplate } from '@/types/injectKey'
import PsdUpload from '@/components/PSD/Index.vue'
import { svg2Base64 } from '@/utils/svg2Base64'
import UploadService from '@/services/UploadService'
import { domainManager } from '@/utils/domainManager'
import { ToolbarStates } from '@/types/toolbar'
import useEditor from '@/utils/Editor/index'


import HotkeyDoc from './HotkeyDoc.vue'
import FileInput from '@/components/FileInput.vue'
import FullscreenSpin from '@/components/FullscreenSpin.vue'
import Drawer from '@/components/Drawer.vue'
import Input from '@/components/Input.vue'
import Popover from '@/components/Popover.vue'
import PopoverMenuItem from '@/components/PopoverMenuItem.vue'
import { PPTImageElement } from '@/types/slides'
import AliyunUpload from '@/utils/upload/aliyun'
import { ElLoading, ElMessage } from 'element-plus'
import ThumbnailSlide from '@/views/components/ThumbnailSlide/index.vue'
import CopyFile from "@/views/SellTemplate/components/CopyFile.vue";
import router from '@/router'
import { useRouter } from "vue-router";
import { managerTemplateLink, openNewBlank } from '@/utils/common'

const mainStore = useMainStore()
const slidesStore = useSlidesStore()
const layoutsStore = useSlidesStore()
const { title, slides, slideIndex, viewportRatio } = storeToRefs(slidesStore)
const { SalesEditor, SalesBack } = storeToRefs(useSellTemplateStore())
const SalesEditorStore = useSellTemplateStore()
const SalesBackStore = useSellTemplateStore()
const { enterScreening, enterScreeningFromStart } = useScreening()
const { importSpecificFile, importPPTXFile, exporting } = useImport()
const { resetSlides } = useSlideHandler()

const imageThumbnailsRef = ref<HTMLElement>()
const mainMenuVisible = ref(false)
const mainBackVisible = ref(false)
const hotkeyDrawerVisible = ref(false)
const editingTitle = ref(false)
const titleInputRef = ref<InstanceType<typeof Input>>()
const titleValue = ref('')
const { setNewDatasList } = useEditor()
const autoSave = inject("SellTravelSave") as any

const { userInfo } = storeToRefs(useUserStore())

const datas = reactive({
  DataSource:{},
  loading: false
})
const queryObj = ref({} as any)
const searchData = ref({} as any)
datas.DataSource = inject(injectKeyDataSource)
queryObj.value = inject(injectKeyDataSource).queryObj
searchData.value = inject(injectKeyTemplate)
const marketStore = useScreenStore()
const CoverImgStore = useScreenStore()
const dataLoadingStore = useScreenStore()
const TempIdStore = useScreenStore()
const ConfigIdStore = useScreenStore()
const loadingInstance = ref<any>(null)
const thumbnails = ref<string[]>()
const isCopyTo = ref(false)
const journeyAdsDetails = ref<Object>()

const psdVisibleStatus = ref(false)
const { market, model, ConfigId, CoverImg, dataLoading, TempId, TempType, SourceLoading } = storeToRefs(useScreenStore())
const routers = useRouter();

// 返回到首页 type 1 模版列表页 0 销售在线模版页
const goBack = (type:any) =>{
  mainBackVisible.value = false
  ElMessageBox.confirm(
    '退出此页面将清空当前数据，请谨慎操作?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    setNewDatas(type,0)
    mainStore.setToolbarState(ToolbarStates.SLIDE_DESIGN)
    let path ='/'
    const t = useSlidesStore().viewportRatio<0?1:2
    if(model.value==0) {
      path = `/market/op/${ConfigId.value}/${TempType.value}`
      router.push({path})
    }else if(model.value==2&&searchData.value.currentMenu>=0){
      if(type==1) path = `/market/create`
      else {
        path = `/space/${searchData.value.currentMenu}`
        searchData.value.currentMenu = null
      }
      router.push({path})
    }
    else window.history.back()
    
  }).catch(() => {})
}
// 返回是否清空数据
const setNewDatas = (type,i) => {
    if(type) {
      marketStore.setMarket(true)
      if(model.value==2) {
        if(searchData.value.TempId) searchData.value.TempId2 = searchData.value.TempId
        SalesBackStore.setSalesBack(1)
      }
    }else {
      searchData.value.TempId2 = 0
      searchData.value.sellId = 0
      searchData.value.sellTempId = 0
      searchData.value.TemplateType = 0
      SalesBackStore.setSalesBack(0)
      SalesEditorStore.setSalesEditor(0)
    }
    searchData.value.TempId = 0
    // i 1模版权限 0无模版权限
    CoverImgStore.setCoverImg(null)
}
// 导入PSD
const UploadPsdHandler = () => {
  psdVisibleStatus.value = true
}

// 销售新增修改行程、广告
const SetSellTemplate = async (type:Number,FolderId:Number) => {
  if(FolderId>=0) datas.loading = true
  try {
    let TempId = 0
    if(queryObj.value.TempId) TempId = queryObj.value.TempId
    if(!TempId){
      return ElMessage({
        showClose: true,
        message: `${queryObj.value.TemplateType==2?'广告':'模版'}不存在, 请重选`,
        type: 'warning',
      })
    }
      let Id = 0
      if(searchData.value.sellId&&type==0) Id = searchData.value.sellId
      if(type==1) Id = 0
      let queryMsg = {
        Id: Id,
        TempId: TempId,
        TempData: queryObj.value.TempData,
        Title: queryObj.value.Title,
        OWidth: 0,
        OHeight: 0,
        FolderId: FolderId>=0?FolderId:searchData.value.ParentFileId,
        IsUseCreare: autoSave.value==1?0:1
      }
      if(queryObj.value.TemplateType==2){
        queryMsg.OWidth = queryObj.value.Width
        queryMsg.OHeight = queryObj.value.Height
      }
      journeyAdsDetails.value = ''
      isCopyTo.value = false
      let TemplateRes = await ConfigService.sellSetTemplate(queryMsg);
      if (TemplateRes.data.resultCode == 1) {
        SalesEditorStore.setSaleHashCode(TemplateRes.data.data.HashInfo)
        ElMessage({
          showClose: true,
          message: '操作成功',
          type: 'success',
        })
        if(type==1) setTimeout(()=>{
          SalesEditorStore.setSalesEditor(0)
        },100)
        if(autoSave.value==1)autoSave.value=2
        if(type == 0 && Id==0){
          let FileId = searchData.value.sellId=TemplateRes.data.data.Id
          let FileType = TemplateRes.data.data.FileType?TemplateRes.data.data.FileType:0
          //@TODO:返回字段中缺少CreateBy,
          const url = createSaleEditorLink(FileId,TempId,queryObj.value.TempType,queryMsg.FolderId,1,1)
          router.push({
              path:url
          })
        }
      }else{
        ElMessage({
          showClose: true,
          message: '操作失败',
          type: 'warning',
        })
        if(autoSave.value==1)autoSave.value=0
      }
    } catch (error) {}
    datas.loading = false
}


// 新增修改行程、广告模版
const SetTripTemplateSlide = async () => {
  try {
    let TemplateRes = await ConfigService.SetTripTemplateSlide(queryObj.value);
    if (TemplateRes.data.resultCode == 1) {
      ElMessage({
        showClose: true,
        message: '操作成功',
        type: 'success',
      })
      datas.DataSource.DataSourceOverlay = false
      dataLoadingStore.setDataLoading(1)
      useSlidesStore().setThumbnails([])
      if(!queryObj.value.TempId){
        queryObj.value.TempId = TemplateRes.data.data.TempId
        searchData.value.TempId = TemplateRes.data.data.TempId
        let url = ''
        url = managerTemplateLink(queryObj.value.TempId,queryObj.value.TemplateType)
        if(url!='') {
          routers.push({
              path:url
          })
        }
      }
      
    }else{
      ElMessage({
        showClose: true,
        message: '操作失败',
        type: 'warning',
      })
    }
  } catch (error) {}
  datas.loading = false
}

const uploadImageHandler = async ()=>{
  let count = 0
  let index = 0
  loadingInstance.value = ElLoading.service({
    text:'收集需要处理的图片'
  })
  for (let i = 0; i < slides.value.length; i++) {
    const slide = slides.value[i];
    if(slide.elements){
      count += (slide.elements.filter(x => "src" in x && x.src && x.src.startsWith("data:image")) ?? []).length
    }
  }

  if(count>0){
    for (let i = 0; i < slides.value.length; i++) {
      const slide = slides.value[i];
      if(slide.elements){
        let temp = slide.elements.filter(x => "src" in x && x.src && x.src.startsWith("data:image")) ?? []
        for(let j = 0; j < temp.length; j++){
          index++
          loadingInstance.value.text = `当前图片处理进度：${index} / ${count}`
          const item = temp[j] as PPTImageElement

          let name = new Date().getTime()+".png"
          const file = dataURLtoFile(item.src, name)
          let url = await AliyunUpload.UploadAsync(file,`pptist/desgin/${name}`)
          if(url != ''){
            item.src = url
            const props = { src: url }
            slidesStore.updateElement({ id: item.id, props, slideId:slide.id })
          }
        }
      }
    }
  }
  
  const thumbnails = useSlidesStore().getThumbnails
  if(thumbnails && thumbnails.length>0){
    loadingInstance.value.text='正在上传模板缩略图'
    queryObj.value.PageImage=[]
    for (let i = 0; i < thumbnails.length; i++) {
      loadingInstance.value.text = `缩略图处理进度：${i+1} / ${thumbnails.length}`
      let name = new Date().getTime()+".png"
      const file = dataURLtoFile(thumbnails[i], name)
      let url = await AliyunUpload.UploadAsync(file,`pptist/desgin/${name}`)
      if(url!=''){
        queryObj.value.PageImage.push(url)
      }
    }
    
  }

  loadingInstance.value.close()
  loadingInstance.value = null
  //instance.close()
}

const dataURLtoFile = (dataurl:string, filename:string) => {
  let arr = dataurl.split(",")
  let mime = arr[0].match(/:(.*?);/)[1],
  bstr = atob(arr[1]),
  n = bstr.length,
  u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

// 用户新增修改行程数据
const SetTripTemplateConfig = async () => {
    try {
      let queryMsg = {
        ConfigId: ConfigId.value,
        TempId: queryObj.value.TempId,
        TempData: queryObj.value.TempData,
      }
      let TemplateRes = await ConfigService.SetTripConfig(queryMsg);
      if (TemplateRes.data.resultCode == 1) {
        if(!ConfigId.value){
          ConfigIdStore.value = TemplateRes.data.data.ConfigId
        }
        ElMessage({
          showClose: true,
          message: '操作成功',
          type: 'success',
        })
        window.parent.postMessage('行程数据保存成功', `${domainManager().notificationUrl}`);
        dataLoadingStore.setDataLoading(2)
      }else{
        ElMessage({
          showClose: true,
          message: '操作失败',
          type: 'warning',
        })
      }
    } catch (error) {}
    datas.loading = false
 
}
// 保存
const setTemplate = async (type) =>{
  queryObj.value.Title = title.value
 
  if(SourceLoading.value) setNewDatasList(datas.DataSource)

  await uploadImageHandler()
  let arr = JSON.parse(JSON.stringify(slides.value))
  if(dataLoading.value){
    dataLoadingStore.setDataLoading(0)
  }
  if(model.value==1&&(userInfo.value.isTemplate==1||userInfo.value.iv || userInfo.value.ic || userInfo.value.ia)){
    arr.forEach(x=>{
      if(searchData.value.TemplateType==2) {
        x.pageType = 0
        x.width = queryObj.value.Width
        x.height = queryObj.value.Height
      }
      x.elements.forEach(y=>{
        delete y.TemplateList
      })
    })
    if(queryObj.value.CoverImg=='' && CoverImg.value=='') {
      datas.loading = false
      mainStore.setToolbarState(ToolbarStates.EL_TEMPLATEDATA)
        return ElMessage({
          showClose: true,
          message: '请生成封面图',
          type: 'warning',
      })
    }else if(queryObj.value.CoverImg=='' && CoverImg.value && CoverImg.value.startsWith("data:image")){
      let name = new Date().getTime()+".jpg"
      const file = dataURLtoFile(CoverImg.value, name)
      let url = await AliyunUpload.UploadAsync(file,`Feature/CoverImg_${name}`)
      queryObj.value.CoverImg = url
    }
    if(searchData.value.TemplateType!=2&&(queryObj.value.Title==''||queryObj.value.CountryName==''
    ||queryObj.value.ColorStr==''||queryObj.value.SeasonName=='')){
        datas.loading = false
        mainStore.setToolbarState(ToolbarStates.EL_TEMPLATEDATA)
        return ElMessage({
          showClose: true,
          message: '请完善右侧模版数据',
          type: 'warning',
        })
      }
  } else {
    arr.forEach(x=>{
      x.elements.forEach(y=>{
        delete y.TemplateList
        delete y.TemplateDataSource
      })
    })
  }
  for(let i=0;i<slides.value.length;i++){
    if(slides.value[i].elements.length==0) {
      datas.loading = false
      mainStore.setToolbarState(ToolbarStates.EL_TEMPLATEDATA)
      return ElMessage({
          showClose: true,
          message: `请设计 第 ${i+1} 页 的数据`,
          type: 'warning',
        })
    }
  }
  queryObj.value.TempData = JSON.stringify(arr)

  if(model.value==1&&(userInfo.value.isTemplate==1||userInfo.value.iv || userInfo.value.ic || userInfo.value.ia)){
    datas.loading = true
    await SetTripTemplateSlide()
  }else if(ConfigId.value&&model.value!=2){
    datas.loading = true
    await SetTripTemplateConfig()
  }else if(model.value==2&&SalesEditor.value>0){
    if(type==1||!searchData.value.sellId){
      let obj = {
        FileName: queryObj.value.Title,
        FileType: queryObj.value.TemplateType,
        type: type,
      }
      journeyAdsDetails.value = obj
      isCopyTo.value = true
    }else{
      datas.loading = true
      await SetSellTemplate(type)
    }
  }
}


const startEditTitle = () => {
  titleValue.value = title.value
  editingTitle.value = true
  nextTick(() => titleInputRef.value?.focus())
}

const handleUpdateTitle = () => {
  slidesStore.setTitle(titleValue.value)
  editingTitle.value = false
  queryObj.value.Title = titleValue.value
}

const goLink = (url: string) => {
  window.open(url)
  mainMenuVisible.value = false
}

const setDialogForExport = (type: DialogForExportTypes) => {
  mainStore.setDialogForExport(type)
  mainMenuVisible.value = false
}

watch(()=>autoSave.value,(newVal)=>{
  if(newVal==1){
    setTemplate(0)
  }
})
handleUpdateTitle()
</script>

<style lang="scss" scoped>
.export-img-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();
  }
}
.configs {
  width: 350px;
  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;
    position: relative;

    &::after {
      content: attr(data-range);
      position: absolute;
      top: 20px;
      left: 0;
    }
  }
  .config-item {
    flex: 1;
  }
}
.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;
  }
}
.editor-header {
  background-color: #fff;
  user-select: none;
  border-bottom: 1px solid $borderColor;
  display: flex;
  justify-content: space-between;
  padding: 0 5px;
}
.left, .right {
  display: flex;
  justify-content: center;
  align-items: center;
}
.left{
  flex:1;
  justify-content:left !important;
}
.menu-item {
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  padding: 0 10px;
  border-radius: $borderRadius;
  cursor: pointer;

  .icon {
    font-size: 18px;
    color: #666;
  }

  &:hover {
    background-color: #f1f1f1;
  }
}
.group-menu-item {
  height: 30px;
  display: flex;
  margin: 0 8px;
  padding: 0 2px;
  border-radius: $borderRadius;

  &:hover {
    background-color: #f1f1f1;
  }

  .menu-item {
    padding: 0 3px;
  }
  .arrow-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
}
.title {
  height: 32px;
  margin-left: 2px;
  font-size: 13px;
  flex:1;
  min-width: 0;
  width: 0;

  .title-input {
    // width: 200px;
    height: 100%;
    padding-left: 0;
    padding-right: 0;
    // max-width: 100%;
  }
  .title-text {
    min-width: 20px;
    max-width: 100%;
    
    line-height: 32px;
    padding: 0 6px;
    border-radius: $borderRadius;
    cursor: pointer;

    @include ellipsis-oneline();

    &:hover {
      background-color: #f1f1f1;
    }
  }
}
.github-link {
  display: inline-block;
  height: 30px;
}
</style>