/**
 * pptEditor&pptEnEditor 共通逻辑
 * ppt7.2 ppt7.4 ppt7.5
 */
//lodash
import _ from "lodash";
import {createRandomCode,checkPPTpageElemant,getChartInfo} from '../newVersion/utils/untils';
import {modelInfo,defaultPosition} from '../newVersion/utils/config';
export default{
  data(){
    return {
      changeFormatPageShow:false,//控制一键改版弹窗是否显示
      choosedItem:null,//当前点击的page-item,不一定是currentItem
      insertPageShow:false,//控制插入PPT弹窗是否显示
      ctrlKeyActive:false,//ctrl键是否按着
      copyPages:[],//选中的ppt页
      copyPagesMap:{},//选中的ppt页Id
      savePagesArr:[],//存储上一次选中的ppt页
    }
  },
  directives: {
    'click-outside':{
      bind(el, binding) {
        const clickHandle = (e)=>{
          //点击index-list和复制按钮之外的地方，取消复制
          if(el.contains(e.target)||e.target.className==='hint-text'){
            return false
          }
          if(binding.value && typeof binding.value === 'function'){
            binding.value(e)
          }
        }
        el.__click__outside = clickHandle
        document.addEventListener('click',clickHandle)
      },
      unbind(el,binding,vnode){
        document.removeEventListener('click',el.__click__outside)
      }
    },
  },
  methods:{
    //显示切换模板弹窗
    handleChangeFormat(item){
      this.choosedItem = item
      this.changeFormatPageShow = true
    },
    //切换版式
    changeFormatPage(modelId){
      const oldModel = modelInfo[this.choosedItem.modelId]
      const newModel = modelInfo[modelId]
      const newModelPosition = defaultPosition[modelId]
      const compare = (pos)=>{
        return (a,b)=>{return a[pos] - b[pos]}
      }
      const chartsEl = this.choosedItem.elements.filter((item) => {
        return item.type&&item.type !== "text";
      });
      const textEl = this.choosedItem.elements.find(i=>i.type==='text')
      let elements = []
      //情况1,少元素的版式转为多元素的版式
      if(this.checkModel(oldModel,newModel,'more')){
      //按顺序加载除text以外的元素,如果有elTextNum,根据newModel.elTextPosition加载text元素
      //chartsEl需要按照position排序后强制指定为newModelPosition的位置
      const posChartsEl = chartsEl.sort(compare('position'))
      let newChartsPos = [],chartsIndex=0
      for(let pos in newModelPosition){
        if(newModelPosition[pos].type==='chart'){
          let chart = posChartsEl[chartsIndex]
          if(!chart) break
          chart.position = Number(pos)
          newChartsPos.push(chart)
          chartsIndex++
        }
      }
      elements = newChartsPos
      //更新图表数
      this.chartNum = this.chartNum - (posChartsEl.length-elements.length)
      if(textEl&&newModel.elTextNum>0){
        elements.push({...textEl,...{position:newModel.elTextPosition}})
      }
      }
      //情况2,多元素的版式转为少元素的版式
      if(this.checkModel(oldModel,newModel,'less')){
      //按顺序加载除text以外的元素,直到达到elChartNum,如果有elTextNum,则在对应位置加载text元素
        //chartsEl需要按position排一下序
        const posChartsEl = chartsEl.sort(compare('position'))
        elements = posChartsEl.slice(0,newModel.elChartNum)
        //超出的目标版式的position要舍弃
        elements = elements.filter((i)=>{
          return i.position<=newModel.elChartNum
        })
        /* console.log('posEl',posChartsEl)
        console.log('element',elements) */
        //更新统计图表数
        this.chartNum = this.chartNum - (posChartsEl.length-elements.length)
        if(textEl&&newModel.elTextNum>0){
          elements.push({...textEl,...{position:newModel.elTextPosition}})
        }
      }
      //新建一页,不保留该页的图层,因为版式转换后图层所有位置都会对不上
      let page = {
        id: createRandomCode(),
        key:0,
        modelId: modelId,
        title:this.choosedItem.title,
        elements: elements,
      }
      //把这页删掉,添加新的一页
      const index = this.pageList.findIndex((i) => i.id === this.choosedItem.id); 
      this.pageList.splice(index,1,page)
      //选中新添加的一页,更新缩略图会用到
      this.changeCurrentItem(page)
      this.initPageElements(this.pageList[index])
      this.initPreviewPageEl()
      this.changeFormatPageShow=false
    },
    checkModel(oldModel,newModel,type){
      if(type==='more'){
        return oldModel.elNum<=newModel.elNum &&
        oldModel.elChartNum<=newModel.elChartNum &&
        oldModel.elTextNum<=newModel.elTextNum
      }
      if(type==='less'){
        return oldModel.elNum>newModel.elNum ||
        oldModel.elChartNum>newModel.elChartNum ||
        oldModel.elTextNum>newModel.elTextNum
      }
    },
    //插入PPT页
    handleInsert(list){
      //console.log('pageList',list)
      //重新设置每一页的id,过滤不合法 element
      let pages = []
      list.forEach(page=>{
        page.id = createRandomCode()
        page.elements = checkPPTpageElemant(page)
        pages.push(page)
      })
      //当前PPT没有页
      if(this.pageList.length===0){
        this.pageList = pages
        this.changeCurrentItem(this.pageList[0])
      //当前PPT有页
      }else{
        /* pages.forEach((page,index)=>{
          this.pageList.splice(this.currentIndex+index+1,0,page)
        }) */
        this.pageList.splice(this.currentIndex+1,0,...pages)
      }
      this.insertPageShow = false
      this.initPages(pages,true)
    },
    //加载pageList新增的pages,reload:是否需要重新加载图表数据
    async initPages(pages,reload=false){
      this.dataLoading = this.$loading({
        lock: true,
        text: '正在获取ppt数据...',
        spinner: 'el-icon-loading',
        customClass:'loading',
        target:document.querySelector('.page-wrap'),
        background: 'rgba(255, 255, 255, 0.8)'
      });
      //遍历pages,初始化版式元素,计算图表数量,初始化pages的缩略图
      for(let i=0;i<pages.length;i++){
        const page = pages[i]
        //计算图表总数
        const chartElements = page.elements.filter((item) => {
          return item.type === "chart";
        });
        this.chartNum+=chartElements.length
        if(reload){
          for(let i=0;i<chartElements.length;i++) {
            await this.getchartData(chartElements[i].chartId);
          }
        }
        await this.initPageElements(page)
        this.initPreviewPageEl('',page)
      }
      //获取已加载的图表信息,更新store.chartInfoMap
      let chartInfoMap = _.cloneDeep(this.$store.state.ppt.chartInfoMap)
      for(let i=0;i<pages.length;i++){
        pages[i].elements.forEach(item=>{
          if(item.type==='chart'){
            let temp = getChartInfo(this.optionMap[item.chartId])
            chartInfoMap[item.chartId] = temp
          }
        })
      }
      this.$store.commit('SET_CHART_INFO_MAP',chartInfoMap)
      this.dataLoading.close();
    },
    //批量插入图表
    handleImportMyChart(list){
      //排除无法插入图表的情况
      if(this.pageList.length===0||!this.currentItem){
        this.$message.warning("请先添加页面");
        return;
      }
      if(this.currentItem.modelId===6){
        this.$message.warning("当前模板不支持图表插入，请重新选择模板")
        return
      }
      const {elChartNum} = modelInfo[this.currentItem.modelId]
      const chartNum = this.currentItem.elements.filter((item) => {
        return item.type&&item.type !== "text";
      }).length;
      let chartList = _.cloneDeep(list)
      let page = _.cloneDeep(this.currentItem)
      //如果当前版式还有位置,添加满后重新加载page
      if(chartNum<elChartNum){
        for(let position = chartNum+1;position<=elChartNum;position++){
          if(!chartList.length) break
          const {UniqueCode} = chartList.shift()
          page.elements.push({
            type:'chart',
            position:position,
            chartId:UniqueCode
          })
        }
      }
      this.refleshElements(page.elements)
      //剩余页重新生成pages,调用initPages
      const pageNum = Math.ceil(chartList.length/elChartNum)
      let pages = []
      for(let num=0;num<pageNum;num++){
        let newPage = {
            id: createRandomCode(),
            key:0,
            modelId: page.modelId,
            title:'',
            elements: [],
        }
        for(let position=1;position<=elChartNum;position++){
          if(!chartList.length) break
          const {UniqueCode} = chartList.shift()
          newPage.elements.push({
            type:'chart',
            position:position,
            chartId:UniqueCode
          })
        }
        pages.push(newPage)
      }
      /* pages.forEach((page,index)=>{
        this.pageList.splice(this.currentIndex+index+1,0,page)
      }) */
      this.pageList.splice(this.currentIndex+1,0,...pages)
      this.initPages([page,...pages],true)
    },
    //更新页面图表
    async updatePage(page){
      page.isUpdating = true
      const index = this.pageList.findIndex(i=>i.id===page.id)
      this.pageList.splice(index,1,page)
      const chartElements = page.elements.filter((item) => {
        return item.type === "chart";
      });
      //刷新图表
      //暂停自动保存
      this.loopTimer&&clearInterval(this.loopTimer)
      this.loopTimer=null
      for(let i=0;i<chartElements.length;i++){
        await this.getRefreshChart(chartElements[i].chartId);
      }
      //重新获取图表数据
      for(let i=0;i<chartElements.length;i++){
        await this.getchartData(chartElements[i].chartId);
      }
      //更新vuex里的图表信息
      let chartInfoMap = _.cloneDeep(this.$store.state.ppt.chartInfoMap)
      for(let i=0;i<chartElements.length;i++){     
        let temp = getChartInfo(this.optionMap[chartElements[i].chartId])
        chartInfoMap[chartElements[i].chartId] = temp
      }
      this.$store.commit('SET_CHART_INFO_MAP',chartInfoMap)
      //渲染图表
      await this.initCharts(chartElements, page);
      page.isUpdating = false
      this.$message.success('刷新成功')
      this.pageList.splice(index,1,page)
      //开启自动保存
      this.autoSave()
    },
    //设置ctrl按键的状态
    handlePasteKey(e){
      const { ctrlKey} = e
      this.ctrlKeyActive = ctrlKey
    },
    //点击左侧item
    handleClickItem(page){
      //如果按住ctrl 
      if(this.ctrlKeyActive){
        this.setCopyPages(page)
      }else{
        this.resetCopyPages()
      }
      this.changeCurrentItem(page)
    },
    //选中/取消选中单个ppt
    setCopyPages(page){
      const {id} = page 
      //去除重复添加page的情况
      if(this.copyPagesMap[id]){
        this.$set(this.copyPagesMap,id,false)
        //this.copyPagesMap[id] = false
        this.copyPages = this.copyPages.filter(i=>i.id!==id)
      }else{
        //this.copyPagesMap[id]= true
        this.$set(this.copyPagesMap,id,true)
        this.copyPages.push(page)
      }
    },
    //取消选中全部ppt
    resetCopyPages(){
      if(this.copyPages.length){
        this.copyPages = []
        this.copyPagesMap = {}
      }
    },
    //点击复制按钮
    saveCopyPages(type){
      if(this.copyPages.length===0){
        this.$message.warning('请按住ctrl+鼠标左键选择ppt页')
        return
      }
      if(type==='copy'){
        this.$message.success('复制ppt页成功')
      }else{
        //禁用动画效果
        $('.flip-list-move').css('transition','transform 0s')
        const copyPageIds = this.copyPages.map(page=>{return page.id}) 
        let temp = this.pageList.filter(page=>{return !copyPageIds.includes(page.id)})
        this.pageList = temp
        //如果currentItem被剪切,指定currentItem&currentIndex
        if(this.pageList.length>0&&copyPageIds.includes(this.currentItem.id)){
          this.changeCurrentItem(this.pageList[0])
        }
        this.$message.success('剪切ppt页成功')
        this.$nextTick(()=>{
          $('.flip-list-move').css('transition','transform 0.5s')
        })
        
      }
      this.savePagesArr = this.copyPages
      this.resetCopyPages()
    },
    //处理Ppt页的操作 
    handleOperate({type,pageItem}){
      const operateMap = {
        'insertPpt':()=>{this.insertPageShow=true},//插入ppt页
        'changeFormat':this.handleChangeFormat,//切换模板
        'pasteBefore':this.pastePages,//粘贴ppt页（前）
        'pasteAfter':this.pastePages,//粘贴ppt页（后）
      }
      operateMap[type](pageItem,type)
    },
    //粘贴ppt页
    pastePages(_pageItem,type){
      let pages = []
      const arr = _.cloneDeep(this.savePagesArr)
      arr.forEach(page=>{
        page.id = createRandomCode()
        page.elements = checkPPTpageElemant(page)
        pages.push(page)
      })
      const coefficient = type.includes('Before')?0:1
      /* pages.forEach((page,index)=>{
        this.pageList.splice(this.currentIndex+index+coefficient,0,page)
      }) */
      this.pageList.splice(this.currentIndex+coefficient,0,...pages)
      this.changeCurrentItem(this.currentItem)
      this.initPages(pages)
    },
    //操作提示弹窗
    showHint(){
      const title = '操作说明'
      const hintText = `<p>复制与剪切功能操作说明如下所述：</p>`+
                      `<p>1、ctrl+鼠标左键，选择PPT页，支持多选；</p>`+
                      `<p>2、选择所要复制或剪切的PPT页位置，点击PPT页的更多操作项，选择“粘贴到此页前”或“粘贴到此页后”。</p>`
      this.$alert(hintText, title, {
        confirmButtonText: '知道了',
        dangerouslyUseHTMLString: true,
        callback: action => {
          //啥也不干
        }
      });
    }
  },
  mounted(){
    document.addEventListener("keydown",this.handlePasteKey)
    document.addEventListener("keyup",this.handlePasteKey)
    //离开页面
    document.body.onblur = ()=>{
      this.ctrlKeyActive = false
      this.resetCopyPages()
    }
  },
  unmounted(){
    document.removeEventListener("keydown")
    document.removeEventListener("keyup")
    document.body.onblur = null
  },
}