<template>
  <div class="delete-page-wrap">
    <el-dialog
      :visible.sync="deletePageShow"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="cancelHandle"
      width="1075px"
      v-dialogDrag
      center
    >
      <div slot="title" style="display: flex; alignitems: center">
        <span style="fontsize: 16px"
          >批量删除</span
        >
      </div>
      <div class="dialog-container" 
        v-loading="dataLoading"
        :element-loading-text="loadingText"
        >
        <div class="preview-box">
          <div class="checkbox-wrap">
            <div class="checkbox" v-for="(page,index) in checkBoxList" :key="index">
              <el-checkbox  v-model="page.checked" @change="(val)=>{changeCheckBox(val,index)}"></el-checkbox>
            </div>
          </div>
          <div class="preview-wrap">
            <div class="preview-item" v-for="(item,index) in pageList" :key="item.id">
              <div class="ppt-item"
                :style="$parent.currentLang==='en'?{
                  background:`url(${require('@/assets/img/ppt_en_bg.png')}) no-repeat center`,
                }:{}"
              >
                <div class="title-wrap">
                  {{item.title||'无标题'}}
                </div>
                <component  :is="getComponentName(item.modelId)"
                            :ref="`preview_${index}`"
                            :pageIndex="index"
                            :pageItem="item"
                            :key="item.key" 
                            type="show"
                            :isPreview="true"         
                ></component>
              </div>
            <p class="preview-page">第{{index+1}}页</p>
          </div>
          </div>
          
        </div>
        <div class="select-box">
          <h3>请选择PPT页</h3>
          <div class="input-box">
            第&nbsp;
              <input type="text"
                      :min="1" :max="pageList.length"
                      v-model.trim="startPageNum" 
                      @input="handleInput('start')"
              />
              &nbsp;至&nbsp;
              <input type="text"
                      :min="1" :max="pageList.length"
                      v-model.trim="endPageNum"
                      @input="handleInput('end')"
              />
            &nbsp;页
            <span style="margin-left:5px; color:#409EFF;cursor:pointer;" @click="checkPage">确认</span>
          </div>
          <div class="choose-box">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <el-checkbox-group v-model="checkedPages" @change="handleCheckedPagesChange">
              <el-checkbox v-for="(page,index) in pageList" :label="index" :key="page.id">第{{index+1}}页&nbsp;&nbsp;{{page.title||'无标题'}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <p style="margin-top:15px;height:20px;">{{checkedPages.length?`已选择${checkedPages.length}页，确认删除吗？`:``}}</p>
          <div class="btn-box">
            <el-button type="primary" @click="saveHandle" >确 定</el-button>
            <el-button @click="cancelHandle">取 消</el-button>
          </div>
        </div>
      </div>
      <!-- <div slot="footer" class="foot-container">
        <el-button @click="cancelHandle">取 消</el-button>
        <el-button type="primary" @click="saveHandle">确 定</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import Highcharts from "highcharts/highstock";
import HighchartszhCN  from '@/utils/highcahrts-zh_CN'
HighchartszhCN(Highcharts)
import FormatOne from '@/views/ppt_manage/newVersion/components/formatPage/FormatOne.vue';
import FormatTwo from '@/views/ppt_manage/newVersion/components/formatPage/FormatTwo.vue';
import FormatThree from '@/views/ppt_manage/newVersion/components/formatPage/FormatThree.vue';
import FormatFour from '@/views/ppt_manage/newVersion/components/formatPage/FormatFour.vue';
import FormatFive from '@/views/ppt_manage/newVersion/components/formatPage/FormatFive.vue';
import FormatSix from '@/views/ppt_manage/newVersion/components/formatPage/FormatSix.vue';
import FormatSeven from '@/views/ppt_manage/newVersion/components/formatPage/FormatSeven.vue';
import FormatEight from '@/views/ppt_manage/newVersion/components/formatPage/FormatEight.vue';
import FormatNine from '@/views/ppt_manage/newVersion/components/formatPage/FormatNine.vue';
import {countComponentName} from '@/views/ppt_manage/newVersion/utils/untils';
export default {
  props:{
    deletePageShow:{//控制弹窗是否显示
      type:Boolean,
      default:false
    },
    pageList:{//ppt页数据
      type:Array,
    },
    optionMap:{//ppt图表数据，用于缩略图渲染
      type:Object
    }
  },
  components:{ FormatOne,FormatTwo,FormatThree,
    FormatFour,FormatFive,FormatSix,FormatSeven,FormatEight,FormatNine},  
  data() {
    return {
      startPageNum:null,//开始的页数
      endPageNum:null,//结束的页数
      isIndeterminate:false,//全选的状态,false:全部选中or全部未选中；true:非全部选中
      checkAll:false,//是否全部选中
      checkedPages:[],//选中的页数index
      isStartInput:false,//第一个Input是否输入
      isEndInput:false,//第二个Input是否输入
      dataLoading:false,//v-loading
      isLoaded:false,//是否已经加载过
      checkBoxList:[],
      loadingText:'加载缩略图中...'
    };
  },
  watch:{
    deletePageShow(val){
      if(val){
        //仅在第一次显示时，加载全部缩略图
        this.init()
        if(!this.isLoaded){
          this.dataLoading = true
          setTimeout(()=>{
            this.initPreview()
          },1000)
        }
        this.$nextTick(()=>{
          //所有滚动条置顶
          document.querySelector(".preview-box").scrollTop=0
          document.querySelector(".choose-box").scrollTop=0 
        })
        
      }
    }
  },
  methods: {
    cancelHandle(){
      this.$emit('cancel')
    },
    saveHandle(){
      this.$emit('delete',this.checkedPages)
    },
    //点击全选框
    handleCheckAllChange(val){
      if(val){
        //将pageList全部选中
        this.checkedPages = this.pageList.map((_,index)=>{
          return index
        })
        //将缩略图多选框全部选中
        this.checkBoxList.map(i=>{
          i.checked=true
        })
      }else{
        //将pageList全部取消选中
        this.checkedPages=[]
        //将缩略图多选框全部取消选中
        this.checkBoxList.map(i=>{
          i.checked=false
        })
      }
      this.isIndeterminate = false
      this.startPageNum = null
      this.endPageNum = null
      this.isStartInput = false
      this.isEndInput = false
    },
    //点击多选框
    handleCheckedPagesChange(val){
      this.checkAll = val.length===this.pageList.length
      this.isIndeterminate = val.length>0&&val.length<this.pageList.length
      this.startPageNum = null
      this.endPageNum = null
      this.isStartInput = false
      this.isEndInput = false
      this.checkBoxList.map(i=>{
        i.checked=false
      })
      //同步缩略图的多选框
      val.forEach(i=>{
        if(!this.checkBoxList[i].checked){
          this.checkBoxList[i].checked = true
        }
      })
    },
    handleInput(type){
      if(type==='start'){
        this.startPageNum = this.formatInputValue(this.startPageNum)
        this.isStartInput = this.startPageNum?true:false
      }else{
        this.endPageNum = this.formatInputValue(this.endPageNum)
        this.isEndInput = this.endPageNum?true:false
      }
    },
    checkPage(){
      //如果两个都输入了，检验输入的数字是否合法
      if(this.isStartInput&&this.isEndInput){
        //开始数字是否小于等于结束数字
        if(this.startPageNum>this.endPageNum){
          this.$message.warning('起始页数需小于等于终止页数，请重新输入！')
          this.isStartInput = false
          this.startPageNum = null
          return
        }
        //检验通过 重置多选项
        this.checkedPages = []
        this.checkBoxList.map(i=>{
          i.checked=false
        })
        //选中[startNum,endNum]之间的多选框和缩略图的多选框
        for(let i=this.startPageNum;i<=this.endPageNum;i++){
          this.checkedPages.push(i-1)
          this.checkBoxList[i-1].checked=true
        }
        this.checkAll = this.checkedPages.length===this.pageList.length
        this.isIndeterminate = this.checkedPages.length>0&&this.checkedPages.length<this.pageList.length
      }
    },
    //格式化输入的数字
    formatInputValue(input){
      if(input==='') return input
      let newInput = Number(input.replace(/[^\d]+/g,''))
      if(newInput<=0){
        newInput = 1
      }
      if(newInput>this.pageList.length){
        newInput = this.pageList.length
      }
      return newInput
    },
    getComponentName(modelId){
      return countComponentName(modelId);
    },
    async initPreview(){
      for(let i=0;i<this.pageList.length;i++){
        await this.initPreviewEl(this.pageList[i])
      }
      this.dataLoading = false
      this.isLoaded = true
    },
    //简略版的initPageElements,渲染缩略图;目的是为了跟渲染ppt的逻辑分开
    initPreviewEl(page){
      const chartElements = page.elements.filter((item) => {
        return item.type === "chart";
      });
      const imageElements = page.elements.filter((item) => {
        return item.type === "image";
      });
      const sheetElements = page.elements.filter((item)=>{
        return item.type === 'sheet'
      })
      this.initPreviewCharts(chartElements,page)
      this.initPreviewImages(imageElements,page)
      this.initPreviewSheets(sheetElements,page)
    },
    //简略版不需要渲染text
    initPreviewImages(elements,page){
      const index = this.pageList.findIndex((i) => i.id === page.id)
      elements.forEach((item)=>{
        this.$parent.initImage(`#preview_image_${index}_${item.position}`,item.src)
      })
    },
    initPreviewCharts(elements,page){
      const index = this.pageList.findIndex((i) => i.id === page.id)
      if(index===-1) return
      elements.forEach((item)=>{
        if (this.optionMap[item.chartId] instanceof Object){
          this.$parent.initChart(
				    `preview_chart_${index}_${item.position}`,
				    this.optionMap[item.chartId],
				    page
			    )
        }else{
          //显示图表已被删除
          this.$parent.initImage(
          `#preview_img_${index}_${item.position}`,
          "https://hzstatic.hzinsights.com/static/ppt_default.png")
        }
      })
    },
    initPreviewSheets(elements,page){
      const index = this.pageList.findIndex((i) => i.id === page.id)
      this.$nextTick(()=>{
        const formatRef = this.$refs[`preview_${index}`][0]
        elements.forEach((item)=>{
          this.$parent.initSheet(formatRef,`preview_sheet_${index}_${item.position}`,item.sheetId)
        })
      })
    },
    init(){
      let isLoaded = this.isLoaded
      Object.assign(this.$data,this.$options.data())
      this.isLoaded = isLoaded
      this.checkBoxList = this.pageList.map(()=>{
        return {checked:false}
      })
    },
    changeCheckBox(val,index){
      if(val){
        !this.checkedPages.find(i=>i===index)&&this.checkedPages.push(index)
      }else{
        const pos = this.checkedPages.findIndex(i=>i===index)
        pos!==-1&&this.checkedPages.splice(pos,1)
      }
      this.checkAll = this.checkedPages.length===this.pageList.length
      this.isIndeterminate = this.checkedPages.length>0&&this.checkedPages.length<this.pageList.length
      this.startPageNum = null
      this.endPageNum = null
      this.isStartInput = false
      this.isEndInput = false
    }
  },
};
</script>
<style scoped lang="scss">
.delete-page-wrap{
  .dialog-container{
    display: flex;
    .preview-box{
      width:500px;
      min-width: 500px;
      max-height: 450px;
      overflow-y:scroll;
      /* border:1px solid black; */
      /* padding:10px; */
      display: flex;
      .preview-wrap{
        .preview-item{
          /* border:1px solid green; */
          width: 450px;
          height: 0;
          padding-bottom: 70%;
          margin-bottom: 40px;
          position:relative;
          .ppt-item{
            width:906px;
            border:4px solid transparent;
            transform-origin: 0 0;
            transform: scale(0.496);
            background: url('~@/assets/img/pptnextimg.png') no-repeat center;
            background-size: cover;
            position:relative;
            .title-wrap{
              position:absolute;
              width:68%;
              height: 14%;
              top: 1.5%;
              left: 10%;
              z-index: 100;
              display: flex;
              font-size: 24px;
              color:#333333;
              align-items: center;
            }
          }
          .preview-page{
            position:absolute;
            width:100%;
            bottom:-20px;
            text-align: center;
            color: #999999;
          }
        }
      }
      .checkbox-wrap{
        width:20px;
        margin-right: 5px;
        .checkbox{
          height:315px;
          margin-bottom: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      
    }
    .select-box{
      flex:1;
      margin-left: 15px;
      display: flex;
      flex-direction: column;
      padding-bottom: 20px;
    }
    .input-box{
      margin-top: 10px;
      color: #333333;
      input{
        border: 1px solid #D9D9D9;
        border-radius: 2px;
        text-align: center;
        width:40px;
        height:30px;
      }
    }
    .choose-box{
      margin-top:10px;
      border: 1px solid #DCDFE6;
      padding:20px;
      max-height: 350px;
      min-height: 275px;
      overflow-y:scroll ;
      border-radius: 8px;
      .el-checkbox-group{
        display: flex;
        flex-direction: column;
        .el-checkbox{
          margin-top:15px;
        }
      }
    }
    .btn-box{
      flex: 1;
      display: flex;
      align-items: flex-end;
      justify-content: center;
      >>>.el-button--primary{
        background-color: #5882EF;
        border-color: #5882EF;
        &:hover{
          background: #5882EF;
          border-color: #5882EF;
        }
      }
    }

  }
}
</style>
