<template>
  <div class="page-wrap ppt-content-wrap">
    <div class="ppt-scroll">
      <template  v-for="(item,index) in loadArr">
          <div class="ppt-item" id="cover" v-if="index===0" :key="item.id">
            <Cover :pageInfo="firstPage" v-show="firstPage"></Cover>
            <div class="ppt-info">
              <p>作者：{{pptItem.AdminRealName}}</p>
              <p>{{pptItem.PptxUrl?'发布':'保存'}}时间：{{$moment(pptTime).format('YYYY-MM-DD')}}</p>
            </div>
          </div>
          <div class="ppt-item" id="back" v-else-if="isLoadBack&&item.name==='back'&&pptBackImage.length" :key="item.id">
            <img :src="pptBackImage" class="pptbg" style="width:100%;height:100%;object-fit: fill !important;"/>
          </div>
          <div class="ppt-item" v-else :key="item.id">
              <div class="title-wrap" :title="item.title" 
                :style="`${getStrCount(item.title)<52?'top:4.5%;left:8%;width:62%;':'top:0;left:8%;width:62%;height:14%;'}`"
                :class="{'title-ellipsis':getStrCount(item.title)>150}">
                {{item.title}}
              </div>
              <component  :is="getComponentName(item.modelId)"
                          :ref="`pptPage_${index-1}`"
                          :pageIndex="index-1"
                          :pageItem="item"
                          :isCopy="true"
                          :isAdd="true"
                          type="show"
                          @addChart="handleAddChartToGallery"
              ></component>
              <span class="page-num">第{{index}}页</span>
          </div>
      </template> 
    </div>
    <!-- 添加到 我的图库 弹窗 -->
    <addMyClassifyDia
      :isAddMyDialog="addMyChartShow"
      :add_id="addChartInfoId"
      :add_ids="addChartClassifyIds"
      @cancel="addMyChartShow = false"
      @addSuccess="addChartToGallery"
    />
  </div>
</template>

<script>
import {countComponentName,calcScale,getChartInfo,countStrSize} from '../../utils/untils';
import {pptCoverEn} from '../../utils/config'
import pptmixin from '../../../mixins/pptMixins';
import mixins from '../../../mixins/mixins';
import Cover from '../CoverEn.vue';
import {pptEnInterface} from '@/api/modules/pptEnApi.js';
import Highcharts from "highcharts/highstock";
import HighchartszhCN  from '@/utils/highcahrts-zh_CN'
HighchartszhCN(Highcharts)
import addMyClassifyDia from '@/views/dataEntry_manage/components/addMyClassifyDia';
export default {
  props:{
    pptItem:{ //ppt信息
      type:Object
    }
  },
  mixins:[pptmixin,mixins],
  components:{Cover,addMyClassifyDia},
  data() {
    return {
        pageList:[],//ppt数组
        firstPage:{
            Title:'',
            ReportType:'',
            BackgroundImg:'https://hzstatic.hzinsights.com/ppt/bg3.jpg',
            PptDate:(new Date().getFullYear())+'年'+(new Date().getMonth()+1)+'月',
            BackIndex:0,
            TemplateType:1
        },//封面信息
        loadedPage:0,//当前加载到第几页PPT
        loadArr:[],//页面展示的ppt数组,包含封面
        isloading:false,//当前是否在加载中
        isLoadBack:false,//是否已加载尾页
        contentScale:1,//ppt-title的缩放系数
        maxPageNum:0,//可以添加的最大页数
        maxPageChart:0,//可以添加的最大图表数
        chartNum:0,//当前PPT的总图表数
        isLegalObj:{
          chartNum:true,//动态图标数量
          pageNum:true,//页数
        },//当前PPT的页数和总图表数是否合法
        interruptLoad:false,//是否中断加载
        pptTime:null,//ppt的最近一次保存时间or最近一次发布时间
        currentLang:'en',//语言标识
    };
  },
  watch:{
    'pptItem.PptId'(){
    }
  },
  mounted(){
    if(Highcharts.charts){
      Highcharts.charts.length=0
    }
    this.init()
  },
  destroyed(){
    this.interruptLoad = true
    window.onresize = null
  },
  methods: {
    async getPPTLimit(){
      const res = await pptEnInterface.getConfig()
      if(res.Ret===200){
        this.maxPageNum = res.Data.ppt_num
        this.maxPageChart = res.Data.chart_num
      }
    },
    async init(){
      //重置所有值
      this.loadedPage = 0
      this.loadArr=[]
      this.interruptLoad = false
      this.isloading = false
      this.isLoadBack=false
      this.isLegalObj = {chartNum:true,pageNum:true}
      if(this.dataLoading)
        this.dataLoading.close();
      this.dataLoading = this.$loading({
        lock: true,
        text: '正在获取ppt数据...',
        spinner: 'el-icon-loading',
        customClass:'loading',
        target:document.querySelector('.ppt-content-wrap'),
        background: 'rgba(255, 255, 255, 0.8)'
      });
      await this.getpptData()
      await this.getPPTLimit()
      this.checkLimit()
      this.loadArr.push(this.firstPage)
      //全部加载
      for(let i=0;i<this.pageList.length;i++){
        if(this.interruptLoad) return
        this.loadArr.push(this.pageList[i])
        await this.initPageElements(this.pageList[i],'show')
      }
      this.isLoadBack = true
      this.loadArr.push({name:'back'})
      //获取已加载图表的信息
      let chartInfoMap = {}
      for(let i=1;i<this.loadArr.length-1;i++){
        this.loadArr[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();
      $('.ppt-item').css('background-image',`url(${this.pptBgImage})`);
    },
    async getpptData(){
      const id = this.pptItem.PptId
      if(id){
        await this.getpptDataById(id)
        const {status} = this.result
        if(status===200){
          const {content,FirstPage,ModifyTime,PublishTime} = this.result
          this.pageList = content
          this.firstPage = FirstPage
          this.firstPage.BackIndex = FirstPage.TemplateType-1
          this.firstPage.imgLocalUrl = pptCoverEn[FirstPage.TemplateType-1]
          this.pptTime = this.pptItem.PptxUrl?PublishTime:ModifyTime
        }else{
          this.$message.error('获取ppt数据失败!')
          this.dataLoading.close();
        }
      }else{
        this.pageList = []
      }
    },
    //计算ppt的版式名称
    getComponentName(modelId){
        return countComponentName(modelId);
    },
    //触底时加载下几页数据
    handleScroll:_.debounce(async function (e) {
			if(this.loadedPage>=this.pageList.length){
        if(!this.isLoadBack){
          this.loadArr.push({name:'back'})
          this.isLoadBack = true
        }
				return
			}
			if(e.target.scrollHeight-e.target.clientHeight-e.target.scrollTop<30&&!this.isloading){
        this.dataLoading = this.$loading({
					lock: true,
					text: '正在加载ppt数据...',
					spinner: 'el-icon-loading',
					customClass:'loading',
          target:document.querySelector('.ppt-content-wrap'),
					background: 'rgba(255, 255, 255, 0.8)'
				});
        this.isloading = true
        this.loadArr.push(this.pageList[this.loadedPage])
        await this.initPageElements(this.pageList[this.loadedPage++],'show')
        this.isloading = false
        this.dataLoading.close()
			}
		},200),
    checkLimit(){
      for(let i=0;i<this.pageList.length;i++){
        //计算图表总数
        const chartElements = this.pageList[i].elements.filter((item) => {
          return item.type === "chart";
        });
        this.chartNum+=chartElements.length
      }
      //校验总页数
      this.isLegalObj.pageNum = this.pageList.length>this.maxPageNum?false:true
      //校验总图表数
      this.isLegalObj.chartNum = this.chartNum>this.maxPageChart?false:true
      this.$emit('isLegal',this.isLegalObj)
    },
    //图层元素自适应
    changeLayerStyle(){
      for(let i=1;i<this.loadArr.length-1;i++){
        if(this.loadArr[i].layers){
          this.loadArr[i].layers.map(shape=>{
            const scale = calcScale({w:906,h:906*0.7},{w:$('.ppt-item').width(),h:$('.ppt-item').width()*0.7})
            $('.shape').css('transform',`scale(${scale.x},${scale.y})`)
            if(shape.type==='text'){
              this.$nextTick(()=>{
                $('.shape-text').css('transform',`scale(1)`)
              })
            }
          })
        } 
      }
    },
    //计算title的字节数
    getStrCount(title){
        return countStrSize(title)
    }
  },
  updated(){
    $('.ppt-item').css('height',$('.ppt-item').width()*0.7);
    this.contentScale = $('.ppt-item').width()/900
    this.$nextTick(()=>{
      //版式文本框自适应
      if($('.content')[0]){
        $('.content').css('transform',`scale(${this.contentScale})`)
      }
      //标题自适应
      if($('.title-wrap')[0]){
        //$('.title-wrap').css('transform',`scale(${this.contentScale})`)
        $('.title-wrap').css('font-size',this.contentScale*24*0.9+'px')
      }
      this.changeLayerStyle()
      //图层元素-文本自适应
      if($('.editor-content')[0]){
        $('.editor-content').css('transform',`scale(${this.contentScale})`)
      }
      
    })
    window.onresize = ()=>{
      $('.ppt-item').css('height',$('.ppt-item').width()*0.7);
      this.contentScale = $('.ppt-item').width()/900
      this.$nextTick(()=>{
        if($('.content')[0]){
          $('.content').css('transform',`scale(${this.contentScale})`)
        }
        if($('.title-wrap')[0]){
          //$('.title-wrap').css('transform',`scale(${this.contentScale})`)
          $('.title-wrap').css('font-size',this.contentScale*24*0.9+'px')
        }
        this.changeLayerStyle()
        if($('.editor-content')[0]){
          $('.editor-content').css('transform',`scale(${this.contentScale})`)
        }
      })
    }
  }
};
</script>

<style lang="scss">
@import './../../css/common.scss';
@import './../../css/format.scss';
.ppt-item{
  &#cover,&#back{
    overflow: hidden;
    background:none !important;
    img{
      width:100%;
    }
  }
}
</style>
<style scoped lang="scss">
.page-wrap{
  display: flex;
  width: 100%;
  height: 100%;
  position: relative;
  div::-webkit-scrollbar-track{
      display: none;
  }
  .ppt-scroll{
    height: calc(100vh - 120px);
    overflow-y: scroll;
    padding:20px;
    width: 100%;
    min-width:776px;
    //position: relative;
    background-color: #fff;
    .ppt-item{
      position:relative;
      width:100%;
      background: url('~@/assets/img/ppt_en_bg.png') no-repeat center;
      /* background-size: cover; */
      background-size: 100% 104.5%;
      margin-bottom: 20px;
      border: 4px solid transparent;
      .ppt-info{
        position:absolute;
        top:10px;
        right:15px;
        color: #fff;
        font-size: 14px;
      }
      .page-num{
        color:#666666;
        position:absolute;
        bottom:10px;
        right:20px;
      }
    }
  }
}
</style>
