<template>
  <div class="editor-header">
    <div class="left">
      <div class="menu-item" v-tooltip="'去首页'" @click="goBack()">首页</div>
      <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('pptx')">导出文件</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 
          class="title-input" 
          ref="titleInputRef"
          v-model:value="queryObj.Title" 
          @blur="handleUpdateTitle()" 
          v-if="editingTitle" 
        ></Input>
        <div 
          class="title-text"
          @click="startEditTitle()"
          :title="queryObj.Title"
          v-else
        >{{ queryObj.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.IsEditTripTemplate==1&&model">
        <div class="menu-item" v-tooltip="'导入PSD'" @click="UploadPsd()">
          <IconUpload class="icon" />
        </div>
      </div>
      <div class="menu-item" v-tooltip="'导出'" @click="setDialogForExport('pptx')">
        <IconDownload class="icon" />
      </div>
      <el-button v-tooltip="'保存'" type="danger" 
      size="small" icon="Check" circle :loading="datas.loading"
      @click="setTemplate()" style="color: #ffff;"></el-button>
      <!-- <a class="github-link" href="https://github.com/pipipi-pikachu/PPTist" target="_blank">
        <div class="menu-item"><IconGithub class="icon" /></div>
      </a> -->
    </div>

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

    <FullscreenSpin :loading="exporting" tip="正在导入..." />
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, reactive, inject } from 'vue'
import { storeToRefs } from 'pinia'
import { useMainStore, useSlidesStore } from '@/store'
import useScreening from '@/hooks/useScreening'
import useImport from '@/hooks/useImport'
import useSlideHandler from '@/hooks/useSlideHandler'
import type { DialogForExportTypes } from '@/types/export'
import { userStore } from "@/store/user";
import { useScreenStore } from "@/store/screen";
import ConfigService from '@/services/ConfigService'
import { injectKeyDataSource, injectKeyTemplate } from '@/types/injectKey'
import { svg2Base64 } from '@/utils/svg2Base64'

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'

const mainStore = useMainStore()
const slidesStore = useSlidesStore()
const layoutsStore = useSlidesStore()
const { title, slides } = storeToRefs(slidesStore)
const { enterScreening, enterScreeningFromStart } = useScreening()
const { importSpecificFile, importPPTXFile, exporting } = useImport()
const { resetSlides } = useSlideHandler()

const mainMenuVisible = ref(false)
const hotkeyDrawerVisible = ref(false)
const editingTitle = ref(false)
const titleInputRef = ref<InstanceType<typeof Input>>()
const titleValue = ref('')

const { userInfo } = storeToRefs(userStore())

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 { market, model, ConfigId, CoverImg, dataLoading } = storeToRefs(useScreenStore())

// 返回到首页
const goBack = () =>{
  let list = [
    {
      id: 'test-slide-1',
      pageType: 1,
      elements: [],
      background: {
        type: 'solid',
        color: '#ffffff',
      },
    }
  ]
  if(model.value) {
    searchData.value.TempId = 0
    marketStore.setMarket(true)
    slidesStore.setSlides(list)
    layoutsStore.setLayouts([])
    CoverImgStore.setCoverImg(null)
    return
  }
  ElMessageBox.confirm(
    '退出此页面将清空当前数据，请谨慎操作?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    searchData.value.TempId = 0
    marketStore.setMarket(true)
    slidesStore.setSlides(list)
    layoutsStore.setLayouts([])
    CoverImgStore.setCoverImg(null)
  })
  .catch(() => {
    
  })
  
}
// 导入PSD
const UploadPsd = () => {

}


// 新增修改模版
const SetTripTemplateSlide = async () => {
  // console.log(JSON.parse(queryObj.value.TempData),'--------')
  try {
    console.log(queryObj.value,'新增修改模版---')
      let TemplateRes = await ConfigService.SetTripTemplateSlide(queryObj.value);
      if (TemplateRes.data.resultCode == 1) {
        
      }
      dataLoadingStore.setDataLoading(true)
      datas.loading = false
  } catch (error) {
      datas.loading = false
      console.log("TemplateGetTripFiled", error);
  }
}
// 用户新增修改数据
const SetTripTemplateConfig = async () => {
  try {
      let queryMsg = {
        ConfigId: ConfigId.value,
        TempId: queryObj.value.TempId,
        TempData: queryObj.value.TempData
      }
      console.log(queryMsg,'新增修改团数据---')
      let TemplateRes = await ConfigService.SetSetTripConfig(queryMsg);
      if (TemplateRes.data.resultCode == 1) {
        
      }
      dataLoadingStore.setDataLoading(true)
      datas.loading = false
  } catch (error) {
      datas.loading = false
      console.log("TemplateGetTripFiled", error);
  }
}
// 保存
const setTemplate = async () =>{
  if(dataLoading.value){
    dataLoadingStore.setDataLoading(false)
  }
  // console.log(JSON.stringify(slides.value),'----保存接口',queryObj.value)
  if(model.value&&userInfo.value.IsEditTripTemplate==1){
    if(CoverImg&&CoverImg.value) queryObj.value.CoverImg = CoverImg.value
    else return ElMessage({
        showClose: true,
        message: '请生成封面图',
        type: 'warning',
      })

    if(queryObj.value.Title==''||!queryObj.value.LineId||!queryObj.value.LtId
    ||queryObj.value.CoverImg==''
    ||queryObj.value.CountryName==''||queryObj.value.SeasonName==''
    ||queryObj.value.ColorName==''||queryObj.value.ColorStr==''||queryObj.value.LineName==''){
      return ElMessage({
        showClose: true,
        message: '请完善右侧模版数据',
        type: 'warning',
      })
    }
  }
  
  for(let i=0;i<slides.value.length;i++){
    if(slides.value[i].elements.length==0) {
        return ElMessage({
            showClose: true,
            message: `请设计 第 ${i+1} 页 的数据`,
            type: 'warning',
          })
      }
    // for(let j=0;j<slides.value[i].elements.length;j++){
    //   if(model.value&&userInfo.value.IsEditTripTemplate==1){
    //     if(slides.value[i].elements[j].type=="text"||slides.value[i].elements[j].type=="image"){
    //       if(!slides.value[i].elements[j].TemplateDataSource
    //       ||!slides.value[i].elements[j].TemplateDataSource.Id) {
    //         return ElMessage({
    //           showClose: true,
    //           message: `请完善 第 ${i+1} 页 需要绑定的数据源`,
    //           type: 'warning',
    //         })
    //       }
    //     }
    //   }
    // }
  }
  queryObj.value.TempData = JSON.stringify(slides.value)
  datas.loading = true
  if(model.value&&userInfo.value.IsEditTripTemplate==1){
    await SetTripTemplateSlide()
  }else if(ConfigId.value){
    await SetTripTemplateConfig()
  }
}


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

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

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

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

<style lang="scss" scoped>
.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;
}
.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;

  .title-input {
    width: 200px;
    height: 100%;
    padding-left: 0;
    padding-right: 0;
  }
  .title-text {
    min-width: 20px;
    max-width: 400px;
    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>