<template>
  <div class="page-wrap">
    <div class="index-wrap ppt-page-wrap flex-column">
        <div class="cover-wrap" @click="openChooseCover">
            <div class="cover" :style="'background: no-repeat center/cover url('+bgList[firstPage.BackIndex].image_url+')'">
                <img src="~@/assets/img/ppt_m/add_first.png" />
            </div>
            <p class="hint-text">选择封面页</p>
        </div>
        <div class="hint-box"><div class="hint"  @click="showHint"><span class="el-icon-info" style="margin-right:5px;"></span>操作说明</div></div>
        <div style="display:flex;justify-content: space-between;">
          <p style="text-align:start;color:#999999;">已添加{{pageList.length}}页</p>
          <!-- <p class="hint-text" style="cursor: pointer;margin-left:auto;" @click="insertPageShow=true">插入PPT</p> -->
          <p class="hint-text" style="cursor: pointer;" @click="saveCopyPages('cut')">剪切</p>
          <p class="hint-text" style="cursor: pointer;" @click="saveCopyPages('copy')">复制</p>
          <p style="color:#B72E18;cursor: pointer;" @click="openDeletePageDialog">批量删除</p>
        </div>
        
        <div class="index-list" ref="pptList" v-click-outside="resetCopyPages">
            <div class="empty" v-if="pageList.length===0">
                <img src="~@/assets/img/ppt_m/ppt-empty.png" alt="">
                <p>添加正文后,会在这里生成</p>
            </div>
            <transition-group name="flip-list">
                <index-item 
                    v-for="(item,index) in pageList" :key="item.id"
                    :pageItem="item"
                    :pageIndex="index"
                    :currentItem="currentItem"
                    :pageLength="pageList.length"
                    :copyPagesMap="copyPagesMap"
                    :ctrlKeyActive="ctrlKeyActive"
                    :savePagesArrLength="savePagesArr.length"
                    @deletePage="delPage"
                    @click.native="handleClickItem(item)"
                    @dragstart.native="(e)=>{dragstart(e,item)}" 
                    @dragenter.native="(e)=>{dragenter(e,item)}" 
                    @dragend.native="dragend(item)"
                    @dragover.native="(e)=>{e.preventDefault()}"
                    @changePage="changePageIndex"
                    @operatePpt="handleOperate"
                />
            </transition-group>
        </div>
    </div>
    <div class="ppt-editor-wrap ppt-page-wrap" v-loading="isChartLoading" :element-loading-text="chartLoadingText">
        <div class="ppt-editor" ref="pptEditor" @paste="handlePasteOutSide">
            <!-- 显示全部ppt -->
            <template v-if="pageList.length">
                <!-- <transition-group name="flip-list"> -->
                <div class="ppt-editor-item flex-column" v-for="(item,index) in pageList" :key="item.id">
                    <AddFormat @addPage="addPage($event,index)" :chooseModalId="chooseModalId"/>
                    <div class="ppt-item" :class="{'choose':currentItem.id===item.id}" 
                        v-loading="item.isUpdating" element-loading-text="正在更新图表..."
                        @click="changeCurrentItem(item)">
                        <!-- 标题 -->
                        <div class="title-wrap">
                            <input type="text" placeholder="单击输入标题" v-model="item.title"/> 
                        </div>
                        <!-- 内容 -->
                        <component  :is="getComponentName(item.modelId)"
                                    :ref="`pptPage_${index}`"
                                    :pageIndex="index"
                                    :pageItem="item"
                                    :key="item.key"
                                    :isCopy="true"
                                    :isAdd="true"
                                    :isEditLayer="isEditLayer"
                                    :choosedId="currentItem.id"
                                    :activeLayerEl="activeLayerEl"
                                    :amendatoryPositionInfo="item.positionInfo"
                                    @delChart="handleDelChart"
                                    @pasteImg="handlePasteImg"
                                    @changeText="handleChangeText"
                                    @changeActEl="changeActLayerEl"
                                    @deleteLayer="deleteLayerEl"
                                    @copyShape="getCopyItem"
                                    @reload="reloadPage"
                                    @addChart="handleAddChartToGallery"
                        ></component>
                        <!-- 删除按钮 -->
                        <el-popconfirm
                            @onConfirm="delPage(item)"
                            confirmButtonText='删除'
                            cancelButtonText='取消'
                            confirmButtonType="text"
                            icon="el-icon-info"
                            iconColor="red"
                            title="确定删除该页ppt吗">
                            <span class="close-btn" @click.stop slot="reference"></span>
                        </el-popconfirm>
                        <!-- 页码 -->
                        <span class="page-num">第{{index+1}}页</span>
                        <!-- 更新图表 -->
                        <span class="update-btn" v-show="item.modelId!==6&&item.elements.find((i)=>i.type==='chart')" @click.stop="updatePage(item)"><span class="update-ico"></span> 更新图表</span>
                    </div>
                    <AddFormat v-if="index===pageList.length-1" @addPage="addPage($event,index+1)" :chooseModalId="chooseModalId"/>
                </div> 
                <!-- 自定义右键菜单 -->
                <context-menu :menu="[{id:1,text:'粘贴元素',eventName:'paste',canClick:Boolean(copyShape.id)}]" @paste="pasteLayerEl"/>
                <!-- </transition-group> -->
            </template>
            <template v-else>
               <div class="ppt-editor-item flex-column">
                  <add-format @addPage="addPage($event,0)"/>
                </div>  
            </template>
        </div>
        <div class="ppt-tool flex-column">
            <div class="tool-btn">
                <el-button type="primary" @click="handlePublish">去发布</el-button>
                <el-button @click="handleSave('save')">保存</el-button>
                <el-button type="text" @click="handleChangeEditModal"><i class="el-icon-sort" style="transform: rotate(90deg);margin-right:5px;"></i>{{isEditLayer?'ppt编辑':'图层编辑'}}</el-button>
            </div>
            <div class="richtext-tool"></div>
            <div class="addppt-right-box" v-if="!isEditLayer">

              <el-tabs v-model="tabsactive">
                <el-tab-pane :label="tab" :name="tab" v-for="tab in panelTabs" :key="tab"></el-tab-pane>
              </el-tabs>
              <div class="chart-tool flex-column" v-show="tabsactive == '图表'">
                <div class="chart-search">
                    <el-input placeholder="关键字查找" v-model="key_word" size="medium" prefix-icon="el-icon-search" @input="() => {search_page=1;$refs.chartListRef.scrollTop = 0;getreportlist()}" style="max-width:420px;"></el-input>
                </div>
                <el-radio-group v-model="chart_source" @change="() => {search_page=1;$refs.chartListRef.scrollTop = 0;getreportlist()}" style="margin: 10px 0;">
                  <el-radio :label="1" style="margin-bottom:5px">ETA图库</el-radio>
                  <el-radio :label="2" style="margin-bottom:5px">商品价格曲线</el-radio> 
                  <el-radio :label="3" style="margin-bottom:5px">相关性图表</el-radio>
                  <el-radio :label="6" style="margin-bottom:5px">拟合方程曲线</el-radio>
                  <el-radio :label="7" style="margin-bottom:5px">统计特征</el-radio>
                </el-radio-group>
                <div style="margin: 10px 0">
                  <el-checkbox v-model="isShowMe" @change="() => {search_page=1;$refs.chartListRef.scrollTop = 0;getreportlist()}">只看我的</el-checkbox>
                </div>
                <div class="chart-list" v-infinite-scroll="loadReportHandle" :infinite-scroll-immediate="false" ref="chartListRef">
                    <template v-if="chartList.length">
                    <div v-for="(item, index) in chartList" :key="index" @click="chooseChart(item,'chart')" class="chart-item" :style="item.Disabled && 'cursor: not-allowed;'">
                        <p class="chart_tit">{{ item.ChartName }}</p>
                        <img :src="item.ChartImage" ref="insert_img" />
                    </div>
                    </template>
                    <img v-else src="~@/assets/img/ppt_m/nodata.png"  style="max-width:186px;height:195px;display:inline-block;margin-top:200px;">
                </div>
              </div>
              <div v-show="tabsactive == '沙盘'" class="chart-tool flex-column">
                <div class="chart-search">
                    <el-input placeholder="沙盘名称/品种" v-model="sandTabelQuery.Keyword" size="medium" prefix-icon="el-icon-search" style="max-width:420px;"></el-input>
                </div>
                <div class="chart-list" id="sandTable" @scroll="sandTableHandleScroll">
                  <template v-if="sandTableList.length">
                    <div v-for="(item,index) in sandTableList" :key="index" class="sandTable-item" >
                      <p class="chart_tit">{{item.Name}}</p>
                      <img :src="item.PicUrl" style="width:100%"  @click="chooseChart(item,'sandImage')"/>
                      <p class="source-identification">来源：弘则研究</p>
                    </div>
                    <div v-loading = "sandTableLoading" class="loaded-text">{{loadedText}}</div>
                  </template>
                  <img v-else src="~@/assets/img/ppt_m/nodata.png"  style="max-width:186px;height:195px;display:inline-block;margin-top:200px;">
                </div>
              </div>
              <div v-show="tabsactive == '表格'" class="chart-tool flex-column">
                <div class="chart-search">
                    <el-input placeholder="表格名称" v-model="sheetSearchObj.Keyword" size="medium" prefix-icon="el-icon-search" style="max-width:420px;" @input="getSheetList"></el-input>
                </div>
                <div class="chart-list" id="sandTable">
                  <template v-if="sheetSearchList.length">
                    <div v-for="(item,index) in sheetSearchList" :key="index" class="sandTable-item" >
                      <p class="chart_tit">{{item.ExcelName}}</p>
                      <img :src="item.ExcelImage" style="width:100%;object-fit: contain;height: 250px"  @click="chooseChart(item,'sheet')"/>
                    </div>
                  </template>
                  <img v-else src="~@/assets/img/ppt_m/nodata.png"  style="max-width:186px;height:195px;display:inline-block;margin-top:200px;">
                </div>
              </div>
              <div v-show="tabsactive == 'MyETA批量'" class="chart-tool flex-column">
                <insert-charts @handleImportMyChart="handleImportMyChart"/>
              </div>
            </div>
            <!-- 图层编辑 -->
            <div class="layer-edit-box" v-else>
              	<el-collapse v-model="activeNames" class="tool-list">
                  <el-collapse-item title="图层元素" name="el">
                    <div class="el-wrap">
                      <div class="el-item" 
                       v-for="(shape,index) in layerElArr" :key="index" @click="addLayerEl(shape)">
                        <el-tooltip class="item" effect="dark" :content="shape.name" placement="top">
                          <ShapePreview :shape="shape" />
                        </el-tooltip>
                      </div>
                    </div>
                  </el-collapse-item>
                  <!-- <el-collapse-item v-if="activeLayerEl.type" :name="activeLayerEl.type"
                  :title="{'line':'线条','shape':'线框','text':'文本'}[activeLayerEl.type]+`设置`" >
                    <LayerEditTool :elInfo="activeLayerEl" />
                  </el-collapse-item> -->
                  <el-collapse-item  name="line"
                    title="线条设置" >
                    <LayerEditTool 
                      :isActiveEl="activeLayerEl.type==='line'?true:false"
                      :elInfo="activeLayerEl.type==='line'?activeLayerEl:BaseLineShape" 
                      baseType="line"/>
                  </el-collapse-item>
                  <el-collapse-item  name="shape"
                    title="线框设置" >
                    <LayerEditTool 
                      :isActiveEl="activeLayerEl.type==='shape'?true:false"
                      :elInfo="activeLayerEl.type==='shape'?activeLayerEl:BaseRectShape" 
                      baseType="shape"/>
                  </el-collapse-item>
                  <el-collapse-item  name="text"
                    title="文本设置" >
                    <LayerEditTool 
                      :isActiveEl="activeLayerEl.type==='text'?true:false"
                      :elInfo="activeLayerEl.type==='text'?activeLayerEl:BaseTextShape" 
                      baseType="text"/>
                  </el-collapse-item>
                </el-collapse>
            </div>
          </div>
    </div>

    <!-- 选择封面弹窗 -->
    <choose-cover  v-if="isShowChooseCover"
        :firstPage="firstPage"
        @close="closeChooseCover"
        @save="saveCover"
    />
    <!-- 批量删除弹窗 -->
    <delete-page-dialog 
      :deletePageShow="deletePageShow"
      :pageList="pageList"
      :optionMap="optionMap"
      ref="deletePage"
      @cancel="deletePageShow=false"
      @delete="handleDeletePages"
    />
    <!-- 一键改版弹窗 -->
    <change-format-dialog 
      :changeFormatPageShow="changeFormatPageShow"
      :pptModelId="choosedItem?choosedItem.modelId:0"
      @cancel="changeFormatPageShow=false"
      @changeModel="changeFormatPage"
    />
    <!-- 插入PPT弹窗 -->
    <insert-page-dialog 
      :insertPageShow="insertPageShow"
      @cancel="insertPageShow=false"
      @insert="handleInsert"
    />
    <!-- 添加到 我的图库 弹窗 -->
    <addMyClassifyDia
      :isAddMyDialog="addMyChartShow"
      :add_id="addChartInfoId"
      :add_ids="addChartClassifyIds"
      @cancel="addMyChartShow = false"
      @addSuccess="addChartToGallery"
    />
  </div>
</template>

<script>
import {countComponentName,checkClipboardItems,createRandomCode,checkPPTpageElemant,getChartInfo} from './utils/untils';
import {modelInfo,defaultPosition} from './utils/config'
import { dataBaseInterface ,sandInterface } from "@/api/api.js";
import futuresInterface from '@/api/modules/futuresBaseApi';
import chartRelevanceApi from '@/api/modules/chartRelevanceApi';
import { fittingEquationInterface,statisticFeatureInterface } from '@/api/modules/chartRelevanceApi';
import pptmixin from '../mixins/pptMixins';
import mixins from '../mixins/mixins';
import layerMixins from '../mixins/layerMixins';
import pptEditorMixins from '../mixins/pptEditorMixins';
import Highcharts from "highcharts/highstock";
import HighchartszhCN  from '@/utils/highcahrts-zh_CN'
HighchartszhCN(Highcharts)
import IndexItem from './components/IndexItem.vue';
import ChooseCover from './components/editor/ChooseCover.vue';
import AddFormat from './components/editor/AddFormat.vue';
import {pptInterface} from '@/api/api.js';
import * as sheetInterface from '@/api/modules/sheetApi.js';
import ShapePreview from './components/layer/shapePreview.vue';
import LayerEditTool from './components/layer/layerEditTool.vue';
import DeletePageDialog from './components/editor/DeletePageDialog.vue';
import ChangeFormatDialog from './components/editor/ChangeFormatDialog.vue';
import InsertPageDialog from './components/editor/InsertPageDialog.vue';
import addMyClassifyDia from '@/views/dataEntry_manage/components/addMyClassifyDia';
import InsertCharts from './components/editor/InsertCharts.vue';
import ContextMenu from './components/ContextMenu.vue';
export default {
  mixins:[pptmixin,//ppt页面共同逻辑
          mixins,//图表加载逻辑
          layerMixins,//图层操作逻辑
          pptEditorMixins,//编辑页共同逻辑
          ],
  components: { 
        IndexItem, ChooseCover, AddFormat,ShapePreview,
    LayerEditTool,DeletePageDialog,ChangeFormatDialog,InsertPageDialog,addMyClassifyDia,InsertCharts,ContextMenu
  },
  data() {
    return {
        pageList:[],//ppt数组
        currentItem:null,//当前活跃的page
        currentIndex:0,//当前活跃的pageIndex
        oldNum:null,//拖动相关
        newNum:null,//拖动相关
        chooseModalId:1,//上一次选择的版式Id
        firstPage:{
            Title:'',
            ReportType:'',
            BackgroundImg:'https://hzstatic.hzinsights.com/ppt/bg3.jpg',
            PptDate:(new Date().getFullYear())+'年'+(new Date().getMonth()+1)+'月',
            BackIndex:0,
            TemplateType:1
        },//封面信息
        key_word:'',//搜索图表关键字
        chartList:[],//图表数组
        imgUrl:'',//黏贴图片上传后的地址
        isShowChooseCover:false,
        getDataLoading:null,//获取动态图表数据/上传图片的loading,
        isSave:false,//是否已手动保存过
        pptId:null,//新增后获得的pptid
        maxPageNum:0,//可以添加的最大页数
        maxPageChart:0,//可以添加的最大图表数
        chartNum:0,//当前PPT的总图表数
        tabsactive:'图表', //右侧区域显示内容 图表 | 沙盘
        // 沙盘图查询参数
        sandTabelQuery:{
          PageSize: 20,
          CurrentIndex: 1,
          Keyword: '',
			  },
        sandTableLoading:false,
        sandTableTotal:0,//沙盘总共条数
        sandTableList:[],
        loadedText:'',
        // 沙盘图分页加载  是否在加载中
        isRequesting:false,
        catalogId:0,//ppt目录id,添加ppt时需要
        ReportId:0,//ppt对应的双周报id,如果没转过,则为0
        isChartLoading:false,//是否正在加载图表/图片
        panelTabs: [ '图表','MyETA批量','沙盘','表格' ],
        sheetSearchList:[],
        sheetSearchObj: {
          Keyword:''
        },
        deletePageShow:false,//控制批量删除弹窗是否显示
        chartLoadingText:'拼命加载中...',
        loopTimer:null,//自动保存标识

        search_page: 1,
        search_page_sizes: 20,
        search_have_more: true,

        chart_source: 1,//图表来源 1 eta 2 商品价格
        isShowMe: false
    };
  },
  created() {
    //获取图表,沙盘,表格数据
    this.getreportlist()
		this.getSandTable()
    this.getSheetList()
    //获取PPT限制
    this.getPPTLimit()
	},
  mounted(){
      if(Highcharts.charts){
        Highcharts.charts.length=0
      }
      this.init()
      window.addEventListener('message',this.reInitIframe)
  },
  watch:{
		'sandTabelQuery.Keyword'(newval,oldval){
			$('#sandTable').animate({scrollTop:0},100);
			this.sandTabelQuery.CurrentIndex = 1
			this.getSandTable()
		}
	},
  methods: {
    getPPTLimit(){
      pptInterface.getConfig().then(res=>{
        if(res.Ret===200){
          this.maxPageNum = res.Data.ppt_num
          this.maxPageChart = res.Data.chart_num
        }
      })
     /*  this.maxPageNum = 60
      this.maxPageChart = 8 */
    },
    async init(){
       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)'
				});
      await this.getpptData()
      //遍历pageList,初始化图表,文字
      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
        await this.initPageElements(this.pageList[i])
      }
      //获取已加载图表的信息
      let chartInfoMap = {}
      for(let i=0;i<this.pageList.length;i++){
        this.pageList[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)
      //添加ppt的情况:获取目录id
      if(!this.$route.query.id){
        this.catalogId = Number(sessionStorage.getItem('selectedCatalog'))
      }
      //防止自动保存时，有某一页处于更新图表的状态，其isUpdating为true
      this.pageList.forEach(i=>{
        i.isUpdating = false
      })     
      this.dataLoading.close();
    },
    async getpptData(){
      const {id} = this.$route.query
      if(id){
        await this.getpptDataById(id)
        const {status} = this.result
        if(status===200){
          const {content,FirstPage,ReportId} = this.result
          this.pageList = content
          this.firstPage = FirstPage
          this.firstPage.BackIndex = FirstPage.TemplateType-1
          this.currentItem = this.pageList[0]
          this.ReportId=ReportId
          //开启自动保存
          this.autoSave()
        }else{
          this.$message.error('获取ppt数据失败!')
          this.dataLoading.close();
          window.close()
        }
      }else{
        this.pageList = []
        this.currentItem = null
      }
      this.currentIndex = 0
    },
    //打开选择封面页弹窗
    openChooseCover(){
        this.isShowChooseCover = true
    },
    //关闭选择封面页弹窗
    closeChooseCover(){
        this.isShowChooseCover = false
    },
    //保存修改的封面页
    saveCover(info){
        console.log(info)
        this.firstPage = info
        this.closeChooseCover()
    },
    //在指定位置添加一个有版式的空白页
    addPage(modelId,index) {
        let page = {
            id: createRandomCode(),
            key:0,
            /* isUpdating:false, */
            modelId: modelId,
            title:'',
            elements: [],
        }
        //限制取消
        /* if(this.pageList.length>=this.maxPageNum){
          this.$message.warning(`最多可添加${this.maxPageNum}页PPT,已超过最大页数!`)
          return
        } */
        this.pageList.splice(index,0,page)
        this.changeCurrentItem(page)
        this.chooseModalId = modelId
    },
    //计算ppt的版式名称
    getComponentName(modelId){
        return countComponentName(modelId);
    },
    //删除一页
    delPage(item) {
      //找到index
      const index = this.pageList.findIndex((i) => i.id === item.id);
      //选中它
      this.changeCurrentItem(item)
      //计算出该页有多少个图表,chartNum-=num
      const chartElements = this.pageList[index].elements.filter((item) => {
          return item.type === "chart";
        });
      this.chartNum-=chartElements.length
      //从pageList移除这一页
      this.pageList.splice(index, 1);
      //更新活动页(currentItem)
      if (this.pageList.length === 0) {
        //删除的是仅有的一页
        this.currentIndex = 0;
      } else if (this.pageList.length === this.currentIndex) {
        //删除的是最后一页
        this.currentIndex = this.pageList.length - 1;
      }
      if(this.pageList.length===0){
        this.currentItem = null
      }else{
        this.changeCurrentItem(this.pageList[this.currentIndex])
      }
      this.$message.success('删除成功')
    },
    //删除活跃页的某一位置的图表/图片/其他组件
    handleDelChart(position) {
      this.currentItem.elements.map((i)=>{
        if(i.position===position){
          this.deleteFormatEl(i.type,position)
        }
      })
      //更新currentItem和pageList[currentIndex]
      //console.log(this.currentItem.elements);
      
      this.currentItem.elements = this.currentItem.elements.filter(
        (i) => i.position !== position
      );
      //console.log(this.currentItem.elements);
      
      this.pageList[this.currentIndex] = this.currentItem;
      //不使用强制刷新，而用deleteFormatEl代替
      //this.pageList[this.currentIndex].key++
      //有已经初始化了的文本框的话,做个标记
      const textElements = this.currentItem.elements.filter((item)=>{
        return item.type === 'text'
      })
      if(textElements.length>0){
        this.pageList[this.currentIndex].isLoadText = true
      }
      //通过deleteFormatEl重新渲染被删除的区域，下面这几行都不需要了
      //this.$refs[`pptPage_${this.currentIndex}`][0].initPositionInfo()
      //this.initPageElements(this.pageList[this.currentIndex])
      //this.initPreviewPageEl('delete')
    },
    deleteFormatEl(type,position){
      if(type==='chart'){
        this.chartNum--
        $(`#${type}_${this.currentIndex}_${position}`).html(`<img id="img_${this.currentIndex}_${position}" />`)
        $(`#preview_${type}_${this.currentIndex}_${position}`).html(`<img id="preview_img_${this.currentIndex}_${position}" />`)
      }
      if(type==='image'){
        $(`#${type}_${this.currentIndex}_${position}`).parent().html(`<img id="${type}_${this.currentIndex}_${position}" />`)
        $(`#preview_${type}_${this.currentIndex}_${position}`).parent().html(`<img id="preview_${type}_${this.currentIndex}_${position}" />`)
      }
      if(type==='sheet'){
        this.$refs[`pptPage_${this.currentIndex}`][0].$refs[`sheet_${this.currentIndex}_${position}`].getSheetData('',[])
        this.$refs.deletePage.isLoaded&&this.$refs.deletePage.$refs[`preview_${this.currentIndex}`][0].$refs[`preview_sheet_${this.currentIndex}_${position}`].getSheetData('',[])
      }
    },
    handlePasteOutSide:_.throttle(async function(e){
       //e:粘贴板事件
      console.log(e)
      //如果是标题/文本编辑框,直接返回
      if(e.target.tagName=='INPUT'||e.target.id==='mcepastebin') {
        return
      }
      //如果是文本框内右键粘贴,也返回
      if(e.target.tagName!=='DIV') return
      //算出currentItem还有哪些位置可以插入图表
      const {isAdd,addPositions}=this.checkElements(this.currentItem.modelId,this.currentItem.elements,'chart')
      if(!isAdd){
        this.$message("已无位置,请删除现有图表/图片")
        return
      }
      
      //从clipboardData中获取图片
      if(!e.clipboardData) return
      const clipboardDataItems = e.clipboardData.items
      const clipboardDataFirstItem = clipboardDataItems[0]
      if(clipboardDataFirstItem){
        for (const item of clipboardDataItems) {
          if (item.kind === 'file' && item.type.indexOf('image') !== -1) {
            const imageFile = item.getAsFile()
            if (imageFile) this.$refs[`pptPage_${this.currentIndex}`][0].handlePaste(imageFile,addPositions[0])
            return
          }
        }
      }
      //clipboardData中没有图片，从navigator.clipboard.read里获取图片
      let clipboardItems = null
      try{
          clipboardItems = await navigator.clipboard.read()
      }catch(error){
          this.$message.error("剪贴板读取不到文件!")
          return
      }
      const blob = await checkClipboardItems(clipboardItems)
      this.$refs[`pptPage_${this.currentIndex}`][0].handlePaste(blob,addPositions[0])
    },300),
    //黏贴图片
    handlePasteImg:_.throttle(async function($event){
      /** $event:
       * position:1
       * src:base64格式的
       */
      //这里进行上传操作
      if(this.isChartLoading) return
      this.chartLoadingText = "上传图片中..."
      this.isChartLoading = true
      const params = new FormData();
			params.append('Image',$event.src)
      const { Data } = await dataBaseInterface.uploadImg(params);
      this.imgUrl = Data.ResourceUrl
      /* this.imgUrl = $event.src */
      //console.log('OK',$event)
      let temp_elements = this.addElement(
            this.currentItem.elements,
            [$event.position],
            "image",
            -1,
            ""
      );
      this.refleshElements(temp_elements)
      this.initImage(`#image_${this.currentIndex}_${$event.position}`,this.imgUrl)
      this.initPreviewPageEl()
      this.isChartLoading = false
    },300),
    //改变活跃页某一位置的文字
    handleChangeText({ position, text, richContent,pageItemId }) {
      //console.log('addText',this.currentItem.id,pageItemId)
      //处理初始化的场景
      if(this.currentItem.id!==pageItemId) return
      //如果该位置元素为空,说明文字编辑器没有初始化,添加一个元素
      if (
        this.currentItem.elements.findIndex((i) => i.position === position) ===
        -1
      ) {
        //console.log('addElement',this.currentItem)
        let tempEls = this.addElement(
          this.currentItem.elements,
          [position],
          "text",
          -1,
          { text, richContent }
        );
        this.refleshElements(tempEls);
      }

      this.currentItem.elements.map((i) => {
        if (i.position === position) {
          i.content = text;
          i.richContent = richContent;
        }
      });
      this.pageList[this.currentIndex] = this.currentItem;
    },
    //切换活跃页(currentItem)
    changeCurrentItem(item){
        const {id} = item
        //切换到其他活跃页的时候,需退出图层编辑模式
        if(this.currentItem&&this.currentItem.id!==id){
          this.isEditLayer = false
          this.activeLayerEl = {}
        }
        this.pageList.map((item,index)=>{
          if(item.id===id){
            this.currentItem = item
            this.currentIndex = index
          }
        })
        this.$nextTick(()=>{
          let height = $('.ppt-editor-item')[0].offsetHeight
          //pptEditor的滚动条动画
          this.$refs.pptEditor.scrollTo({
              top:height*this.currentIndex,
              left:0,
              behavior: 'smooth'
          })
          let listDomArr = $('.index-item')
          let heightSum = 0
          for(let i=0;i<this.currentIndex;i++){
              //console.log('height?',listDomArr[i].offsetHeight)
              heightSum+=listDomArr[i].offsetHeight+5
          }
          //console.log('index',this.currentIndex,'height',heightSum)
          //pptList的滚动条动画
          this.$refs.pptList.scrollTo({
              top:heightSum,
              left:0,
              behavior: 'smooth'
          })
        })
    },
    //获取图表列表
    async getreportlist(){
      let params = {
        Keyword: this.key_word,
        CurrentIndex: this.search_page,
        PageSize: this.search_page_sizes,
        IsShowMe: this.isShowMe
      }
      let res=null
      if(this.chart_source === 1){
        res=await dataBaseInterface.chartSearchByEs(params)
      }else if(this.chart_source === 2){
        res=await futuresInterface.searchChart(params)
      }else if(this.chart_source === 3){
        res=await chartRelevanceApi.searchChart(params)
      }else if(this.chart_source === 6){
        res=await fittingEquationInterface.searchChart(params)
      }else if(this.chart_source === 7){
        res=await statisticFeatureInterface.searchChart(params)
      }

      if (res.Ret !== 200) return;
      res.Data.List = res.Data.List || [];
      this.chartList = this.search_page > 1 ? [...this.chartList,...res.Data.List] : res.Data.List;
      this.search_have_more = this.search_page <= res.Data.Paging.Pages;
    },

    loadReportHandle() {
			if(!this.search_have_more) return
			this.search_page++;
			this.getreportlist(this.key_word);
		},

    // 获取沙盘图列表 分页
		getSandTable(){
			this.sandTableLoading = true
			this.isRequesting = true
			sandInterface.sandlistByQuote(this.sandTabelQuery).then(({Data:{List,Paging}})=>{
				if(this.sandTabelQuery.CurrentIndex>1){
					this.sandTableList = [...this.sandTableList,...List]
          
				}else{
					this.sandTableList = List
					this.sandTableTotal = Paging.Totals
          console.log(this.sandTableList.length,this.sandTableTotal);
					if(this.sandTableList.length>=this.sandTableTotal){
            
						this.loadedText = '已全部加载完'
					}else{
						this.loadedText=''
					}
				}		
			})
			.finally(()=>{
				this.sandTableLoading = false
				this.isRequesting = false
			})
		},
		// 沙盘列表滚动事件，触底加载下一页数据
		sandTableHandleScroll:_.debounce(function (e) {
			if(this.sandTableList.length>=this.sandTableTotal){
				this.loadedText = '已全部加载完'
				return
			}
			if(e.target.scrollHeight-e.target.clientHeight-e.target.scrollTop<10 && !this.isRequesting){
				this.sandTabelQuery.CurrentIndex++
				this.getSandTable()
			}
		},200),
    //点击右侧图表/沙盘图/表格
    chooseChart:_.throttle(async function(item,type){
        if(this.pageList.length===0||!this.currentItem){
          this.$message.warning("请先添加页面");
          return;
        }
        if(item.Disabled&&type==='chart') return this.$message.warning('内部图表，不允许插入ppt') 
        if(this.isChartLoading) return
        //获取当前活动页
        const { elements, modelId } = this.currentItem;
        //判断element是否能再加入图表
        const { isAdd, addPositions } = this.checkElements(
            modelId,
            elements,
            "chart"
        );
        if (!isAdd) {
            this.$message.warning("已无位置,请删除现有图表/图片/表格");
            return;
        }

        let temp_elements = null;
        this.chartLoadingText = '拼命加载中...'
        // type:sandImage 沙盘图  chart 图表 sheet
        if(type=='chart'){
          //判断选择的图表是否已经插入
          /* const length = this.pageList.length
          for(let i=0;i<length;i++){
            let hasChart = this.pageList[i].elements.some(i=>i.chartId===item.UniqueCode)
            if(hasChart){
              this.$message.warning("该图表已被使用");
              return
            }
          } */
          //限制取消
          /* if(this.chartNum>=this.maxPageChart){
            this.$message.warning("超过可设置的最大图表数,请删除现有图表");
            return;
          } */
          this.isChartLoading = true
          await this.getchartData(item.UniqueCode);
          
          //加入图表
          temp_elements = this.addElement(
              elements,
              addPositions,
              "chart",
              item.UniqueCode,
              ""
          );
          this.chartNum++
          this.refleshElements(temp_elements);
          /* const page = this.currentItem
          const pageElements = page.elements.filter(i=>i.type==='chart') */
          //优化一下
          const tempEls = [{type:'chart',position:addPositions[0],chartId:item.UniqueCode}]
          const tempPage = {id:this.currentItem.id,elements:tempEls}
          //这里不直接用initChart是因为initCharts里可以判断该图表有没有数据，然后显示图表或显示“该图表已被删除”
          this.initCharts(/* pageElements,page */tempEls,tempPage) 
          this.isChartLoading = false
          //更新图表数据
          let chartInfoMap = _.cloneDeep(this.$store.state.ppt.chartInfoMap)
          let chartInfo = getChartInfo(this.optionMap[item.UniqueCode])
          chartInfoMap[item.UniqueCode] = chartInfo
          this.$store.commit('SET_CHART_INFO_MAP',chartInfoMap)
          //需要重新渲染一次缩略图
          this.initPreviewPageEl()
        }else if(type === 'sandImage'){
          // 插入沙盘图
          this.imgUrl = item.PicUrl
          this.isChartLoading = true
          //加入沙盘图
          temp_elements = this.addElement(
              elements,
              addPositions,
              "image",
              -1,
              ""
          );
          this.refleshElements(temp_elements);
          this.initImage(`#image_${this.currentIndex}_${addPositions[0]}`,this.imgUrl)
          this.isChartLoading = false
          this.initPreviewPageEl()
        }
        type === 'sheet' && this.insertSheet(item,elements,addPositions,temp_elements);
        
    },300),
    //检查是否还能再加入元素,返回{isAdd:bool,addPosition:[]},isAdd:是否能插入,addPositions:可以插入的位置
    //type:[chart,text] chart包含除text外的全部元素
    checkElements(modelId, elements, type) {
      const info = modelInfo[modelId];
      let addPositions = [],
        isAdd = false;
      const elPositions = elements.map((i) => i.position);
      let typeNum = 0
      elements.forEach(i=>{
        if(i.type!=='text') typeNum++
      })
      //先判断长度
      if (elements.length >= info.elNum) return { isAdd, addPositions };
      //去重:info.positions和el
      let tempArr = info.positions.filter((i) => elPositions.indexOf(i) < 0);
      if (!tempArr.length) return { isAdd, addPositions };
      //同一版式下的位置支持互换，位置和类型根据 当前版式.positionInfo决定
      //判断数量
      if(typeNum>=info.elChartNum){
        return { isAdd, addPositions };
      }
      const positionInfo = this.$refs[`pptPage_${this.currentIndex}`][0].positionInfo
      //判断类型
      tempArr.forEach((i)=>{
        if(positionInfo[i].type!=='text'){
          addPositions.push(i)
        }
      })
      if (!addPositions.length) {
        return { isAdd, addPositions };
      } else {
        isAdd = true;
        return { isAdd, addPositions };
      }
    },
    //添加一个元素进els,type:[chart,text,image],chart时有chartId,text为空;text/image时,chartId为-1
    addElement(
      el,
      positions,
      type,
      UniqueCode,
      { text, richContent } = { text: "", richContent: "" }
    ) {
      let temp = null;
      if (type === "chart") {
        temp = {
          type: "chart",
          position: positions[0],
          chartId: UniqueCode,
        };
      } else if (type === "text") {
        temp = {
          type: "text",
          position: positions[0],
          content: text,
          richContent: richContent,
        };
      }else if (type==='image'){
        temp = {
          type:'image',
          position:positions[0],
          src:this.imgUrl
        }
      }else if(type==='sheet'){
        temp={
          type:'sheet',
          position:positions[0],
          sheetId:UniqueCode
        }
      }
      el.push(temp);
      return el;
    },
    //更新ppt页元素(数据)
    refleshElements(els){
        this.currentItem.elements = els;
        this.pageList[this.currentIndex] = this.currentItem;
        this.$refs[`pptPage_${this.currentIndex}`][0].initPositionInfo()
    },
    //手动保存PPT
    handleSave(type){
     /*  const {result,hintText} = this.checkPPT()
      if(!result){
        this.$message.warning(hintText)
        return
      } */
      //保存走save_checkPPT,发布走checkPPT
      let checkResult = null
      if(type==='save'){
        checkResult = this.save_checkPPT()
      }else{
        checkResult = this.checkPPT()
      }
      if(!checkResult.result){
        this.$message.warning(checkResult.hintText)
        return
      }
      let Content = JSON.stringify(this.pageList)
      //console.log(Content)
      //console.log('firstPage',this.firstPage)
      const {Title,ReportType,PptDate,BackgroundImg,BackIndex} = this.firstPage
      const FirstPage = {
        Title,ReportType,PptDate,BackIndex,
        ImgUrl:BackgroundImg,
        TemplateType:BackIndex+1
      }
      if(this.$route.query.id||this.pptId){
        this.editPPT(FirstPage,Content,type)
      }else{
        this.addPPT(FirstPage,Content)
      }
    },
    addPPT(FirstPage,Content){
      pptInterface.addppt({
        FirstPage:FirstPage,
        Content:Content,
        GroupId:this.catalogId
      }).then(res=>{
        if(res.Ret===200){
          this.$message.success('新增成功')
          //this.$router.push({path:'/pptlist'})
          this.isSave = true
          this.pptId = res.Data.PptId
          sessionStorage.removeItem('selectedCatalog')
          //开启自动保存
          this.autoSave()
        }
      })
    },
    editPPT(FirstPage,Content,type){
      //console.log(type)
      const ppt_id = this.$route.query.id||this.pptId
      pptInterface.editppt({
        PptId:parseInt(ppt_id),
        FirstPage:FirstPage,
        Content:Content
      }).then(res=>{
        if(res.Ret===200){
          if(type==='save'){
            this.$message.success('编辑成功')
          }
          this.isSave = true
          this.pptId = res.Data.PptId
          //如果ppt已转成双周报,则更新
          /* if(this.ReportId!==0){
            pptInterface.transReport({
              PptId:Number(this.pptId),
            }).then(res=>{})
          } */
        }
      })
    },
    //自动保存PPT
    autoSave(){
      if(this.loopTimer) return 
      this.loopTimer = setInterval(()=>{
        const ppt_id = this.$route.query.id||this.pptId
        const {Title,ReportType,PptDate,BackgroundImg,BackIndex} = this.firstPage
        const FirstPage = {
          Title,ReportType,PptDate,BackIndex,
          ImgUrl:BackgroundImg,
          TemplateType:BackIndex+1
        }
        //防止自动保存时，有某一页处于更新图表的状态，其isUpdating为true
        let pageList = this.pageList.map(i=>{
          i.isUpdating = false
          return i
        })
        let Content = JSON.stringify(pageList) 
        pptInterface.saveLog({
          PptId:parseInt(ppt_id),
          FirstPage:FirstPage,
          Content:Content
        }).then((res)=>{})
      },10000)
    },
    //保存时的校验规则:封面信息,至少一页
    save_checkPPT(){
      if(!this.firstPage.Title){
        return {result:false,hintText:'请输入封面标题!'}
      }else if(!this.firstPage.ReportType){
        return {result:false,hintText:'请输入ppt类型!'}
      }
      if(this.pageList.length===0){
        return {result:false,hintText:'请至少添加一张PPT!'}
      }
      return {result:true,hintText:''}
    },
    //发布时的校验规则:封面信息,每一页标题及内容
    checkPPT(){
      //检验首页
      if(!this.firstPage.Title){
        return {result:false,hintText:'请输入封面标题!'}
      }else if(!this.firstPage.ReportType){
        return {result:false,hintText:'请输入ppt类型!'}
      }
      if(this.pageList.length===0){
        return {result:false,hintText:'请至少添加一张PPT!'}
      }
      //检验每一页
      for(let i=0;i<this.pageList.length;i++){
        if(!this.pageList[i].title){
          return {result:false,hintText:`请输入第${i+1}张PPT的标题!`}
        }
        //无内容
        if(this.pageList[i].elements.length===0){
          return {result:false,hintText:`请填写第${i+1}张PPT的内容!`}
        }
        //有文本框,但是文本框无内容
      }
      return {result:true,hintText:''}
    },
    async handlePublish(){
      if(!this.isSave){
        this.$message.warning("请先保存!")
        return
      }else{
        const {result,hintText} = this.checkPPT()
        if(!result){
          this.$message.warning(hintText)
          return
        }
      }
      await this.handleSave('pub')
      //ppt4.0后,合并后的PPT可能会超出页数or图表限制,在这里做个校验
      if(this.pageList.length>this.maxPageNum){
        this.$message.warning(`最多可添加${this.maxPageNum}页PPT,请修改后再试!`)
        return
      }
      if(this.chartNum>this.maxPageChart){
        this.$message.warning(`最多可添加${this.maxPageChart}图表,请修改后再试!`);
        return;
      }
      this.$router.push({path:'/pptpublish',query:{id:this.pptId}})
    },
    //拖动相关
    dragstart(e,value) {
      e.dataTransfer.effectAllowed = "move";
      this.oldNum = value;
    },
    dragend() {
        if (this.oldNum != this.newNum) {
            let oldIndex = this.pageList.indexOf(this.oldNum);
            let newIndex = this.pageList.indexOf(this.newNum);
            let newItems = [...this.pageList];
            // 删除老的节点
            newItems.splice(oldIndex, 1); 
            // 在列表中目标位置增加新的节点
            newItems.splice(newIndex, 0, this.oldNum);
            this.pageList = [...newItems];
            this.$message.success('移动成功')
            //如果拖动的是当前选中的item,就定位到该item
            if(this.oldNum.id===this.currentItem.id){
              this.changeCurrentItem(this.currentItem)
            }
        }
    },
    dragenter(e,value) {
      e.preventDefault()
      this.newNum = value;  
    },
    changePageIndex($event){
      this.oldNum = this.pageList[$event.oldPos-1]
      this.newNum = this.pageList[$event.newPos-1]
      this.dragend()
    },
    
     /* 搜索表格 */
    getSheetList() {
      sheetInterface
        .sheetList({
          Keyword: this.sheetSearchObj.Keyword,
          CurrentIndex: 1,
          PageSize: 10000
        })
        .then((res) => {
          if (res.Ret !== 200) return
          this.sheetSearchList = res.Data.List || [];
        });
    },

    /* 插入表格 */
    async insertSheet({ExcelImage,UniqueCode},elements,addPositions,temp_elements) {
       // 插入沙盘图
      this.imgUrl = ExcelImage;
      this.isChartLoading = true
      const idName = `sheet_${this.currentIndex}_${addPositions[0]}`
      const res = await this.getsheetData(UniqueCode)
      if(!res) {
        this.isChartLoading = false
        return
      }
      //加入表格
      temp_elements = this.addElement(
          elements,
          addPositions,
          "sheet",
          UniqueCode,
          ""
      );
      this.refleshElements(temp_elements);
      this.initSheet(this.$refs[`pptPage_${this.currentIndex}`][0],idName,UniqueCode,'insert')
      this.isChartLoading = false
      this.initPreviewPageEl()
    },
    
    //打开批量删除弹窗
    openDeletePageDialog(){
      //添加一页才能打开弹窗
      if(this.pageList.length===0){
        this.$message.warning('请至少添加一页！')
        return
      }
      this.deletePageShow = true
    },
    async handleDeletePages(list){
      this.$refs.deletePage.loadingText="删除中..."
      this.$refs.deletePage.dataLoading=true
      this.deletePages(list)
    },
    //批量删除
    deletePages(list){  
      let temp = this.pageList.filter((item,index)=>{
        if(!list.includes(index)){
          return item
        }
      })
      this.pageList = temp
      this.currentIndex=0
      if(this.pageList.length>0){
        this.changeCurrentItem(this.pageList[0])
      }else{
        this.currentItem=null
      }
      //删除后，需要重新计算图表数
      let newChartNum = 0
      for(let i=0;i<this.pageList.length;i++){
        const page = this.pageList[i]
        page.elements.forEach(item=>{
          if(item.type==='chart'){
            newChartNum++
          }
        })
      }
      this.chartNum = newChartNum
      this.$nextTick(()=>{
        this.$refs.deletePage.dataLoading = false
        this.deletePageShow = false
        this.$message.success('批量删除成功')
      })
      
    },
    initPreviewPageEl(type,page){
      const currentItem = page||this.currentItem
      const isLoaded = this.$refs.deletePage.isLoaded
      if(isLoaded){
        type!=='delete'&&this.$refs.deletePage.$refs[`preview_${this.currentIndex}`][0].initPositionInfo()
        this.$refs.deletePage.initPreviewEl(currentItem)
      }
    },
    reloadPage({id,positionInfo}){
      const index = this.pageList.findIndex(i=>i.id===id)
      this.pageList[index].key++
      this.pageList[index].positionInfo = positionInfo
      this.initPageElements(this.pageList[index])
      this.initPreviewPageEl()
    },
  },
  updated(){
    $('.ppt-item').css('height',$('.ppt-item').width()*0.7);
    window.onresize = ()=>{
      $('.ppt-item').css('height',$('.ppt-item').width()*0.7);
    }
  },
  destroyed(){
    sessionStorage.removeItem('selectedCatalog')
    window.removeEventListener('message',this.reInitIframe)
    window.onresize=null
    if(this.loopTimer) clearInterval(this.loopTimer)
  }
};
</script>

<style lang="scss">
@import './css/common.scss';
@import './css/format.scss';
.page-wrap{
  .ppt-editor-wrap{
    .ppt-tool{
      .layer-edit-box{
        .tool-list{
          .el-collapse-item__header{
            margin-bottom: 0;
          }
          .el-collapse-item__wrap{
            overflow: visible;
          }
        }
      }
    }
  }
}

</style>
<style scoped lang="scss">
$titleColor:#333333;
.page-wrap{
    display: flex;
    width: 100%;
    overflow-x: scroll;
    &::-webkit-scrollbar-track{
        display: none;
    }
    div::-webkit-scrollbar-track{
        display: none;
    }
    .index-wrap{
        min-width: 280px;
        margin-right: 10px;
        padding:10px;
        .cover-wrap{
            cursor: pointer;
            width: 100%;
            margin-bottom: 10px;
            .cover{
               //高:宽 0.75
                height: 195px;
                display: flex;
                justify-content: center;
                align-items: center;
                /* background: no-repeat center/cover url(~@/assets/img/ppt_m/bg3.jpg); */
            }
        }
        .hint-box{
          color:#409EFF;
          display: flex;
          justify-content: flex-end;
          align-items: center;
          margin-bottom:10px;
        }
        .hint{
          border: 1px solid transparent;
          cursor: pointer;
          padding:5px;
          &:hover{
            border: 1px solid #409EFF;
            border-radius: 4px;
            background: #ECF5FF;
          }
        }
        .index-list{
            //margin-top: 10px;
            flex: 1;
            overflow-y: scroll;
            .empty{
                margin-top:120px;
                text-align: center;
                img{
                    width:76px;
                    height:76px;
                    display: inline-block;
                }
                p{
                    font-size: 14px;
                    color: $titleColor;
                }
            }
        }
    }
    .ppt-editor-wrap{
        flex:1;
       /*  min-width: 1370px; */
       padding:20px;
       display: flex;
       .ppt-editor{
           flex:1;
          /*  max-width: 980px;
           min-width:776px; */
           max-width: 980px;
           min-width: 980px;
           height:100%;
           /* background-color: pink; */
           background-color: #fff;
           border:2px solid #EBEBEB;
           border-radius: 4px;
           margin-right: 30px;
           overflow-y: scroll;
           position:relative;
            .ppt-editor-item {
                position: relative;
                align-items: center;
                .ppt-item {
                    /* width: 835px;
                    height: 580px; */
                    //padding 两边 40 减掉边框两边 8 max-width:100% - 32px
                    width:calc(100% - 64px);
                    /* height: 0;
                    padding-bottom: calc(69.408% - 64px); */
                    background: url('~@/assets/img/pptnextimg.png') no-repeat center;
                    background-size: cover;
                    /* margin-bottom: 30px; */
                    position: relative;
                    border: 4px solid transparent;
                    cursor: pointer;
                    &.choose {
                        // box-shadow: 1px 1px 2px rgba($color: #409eff, $alpha: 0.6);
                        border: 4px solid rgba($color: #4B8DFF, $alpha: 0.7);
                    }
                    .close-btn{
                        color:#BDBDBD;
                        width:20px;
                        height:20px;
                        position:absolute;
                        cursor: pointer;
                        top:-10px;
                        right:-10px;
                        background: url('~@/assets/img/ppt_m/ppt-del.png') no-repeat center/cover;
                        background-color: white;
                        border-radius: 50%;
                    }
                    .page-num{
                        color:#666666;
                        position:absolute;
                        bottom:10px;
                        right:20px;
                    }
                    .update-btn{
                      position:absolute;
                      top:16px;
                      left:12px;
                      color:#409EFF;
                      cursor: pointer;
                      display: flex;
                      justify-content: center;
                      .update-ico{
                        width:20px;
                        height:20px;
                        background:url('~@/assets/img/ppt_m/update-ico.png') no-repeat center/cover;
                        margin-right: 4px;
                      }
                    }
                    .loading-cover{
                      position: absolute;
                      top:20px;
                      left:0;
                      height:20px;
                      background-color: #409EFF;
                    }
                }
            }
       }
       .ppt-tool{
           min-width:320px;
           width: 320px;
           height:100%;
           .tool-btn{
               margin-bottom: 12px;
           }
            .addppt-right-box{
              flex: 1;
              height: calc(100% - 182px);
              padding: 0 10px;
              margin-top: 12px;
              box-sizing: border-box;
              border:1px solid #B2B9C3;
              min-width: 320px;
              #tabs {
                padding: 0px 40px;
                box-sizing: border-box;
                margin: 15px 0;
                overflow: hidden;
                > p {
                  float: left;
                  width: 50%;
                  font-size: 18px;
                  cursor: pointer;
                  color: #1f2e4d;
                  padding: 10px 0;
                  text-align: center;
                }
                > p.active {
                  border-bottom: 2px solid #3464e0;
                  color: #3464e0;
                }
              }
              .chart-tool{
               //btn:40+20,wrapPadding:40 -> 120+100
               //height: calc(100vh - 220px);
               flex: 1;
               margin-top: 10px;
              //  height:calc(100% - 230px);
              height: calc(100% - 80px);
               .chart-search{
                   margin-bottom: 10px;
               }
               .chart-list{
                   /* background-color: rgb(82, 106, 106); */
                   flex: 1;
                   border:2px solid #EBEBEB;
                   border-radius: 4px;
                   overflow-y: scroll;
                   text-align: center;
                    .chart-item {
                        /* border: 0.5px solid rgba(116, 129, 141,0.1); */
                        cursor: pointer;
                        text-align: center;
                        color: #74818d;
                        font-size: 18px;
                        margin-bottom: 10px;
                        padding:10px;
                        img {
                            width: 100%;
                        }
                    }
                  .sandTable-item{
                    border-bottom: solid 1px #eeeeee;
                    padding: 20px 0 10px 0;
                    p{
                      font-size: 16px;
                      color: #3464e0;
                      text-align: center;
                    }
                    img{
                      cursor: pointer;
                    }
                    .source-identification{
                      color: #000;
                      text-align: left;
                      padding-left: 12px;
                    }
                  }
                  .loaded-text{
                      height: 20px;
                      text-align: center;
                      color: #666;
                      font-size: 14px;
                    }
                }
              }

		        }
            .layer-edit-box{
              flex: 1;
              height: calc(100% - 182px);
              padding: 0 20px;
              margin-top: 12px;
              box-sizing: border-box;
              border: 2px solid #EBEBEB;
              border-radius: 4px;
              min-width: 320px;
              overflow-y: scroll;
              .tool-list{
                .el-wrap{
                  display: flex;
                  justify-content: space-between;
                  flex-wrap: wrap;
                  .el-item{
                    border: 1px solid #DCDFE6;
                    border-radius: 4px;
                    width:55px;
                    height:55px;
                    margin-bottom: 20px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    cursor: pointer;
                    &:hover,&.active{
                      border: 1px solid #409EFF;
                    }
                  }
                }
                .el-collapse-item__wrap{
                  overflow: visible;
                }
              }
            }
       }
    }
}
</style>
<style lang="scss">
.page-wrap {
	.el-tabs__nav-wrap::after {
		height: 0;
	}
	.el-tabs__item { font-size: 16px; }
	.layer-edit-box{
		.tool-list{
			.el-collapse-item:first-child{
				.el-collapse-item__content{
					padding-bottom: 5px;
				}
			}
		}
	}
}	
</style>
