<template>
  <!-- ↓ @click="handleMouseDown" -->
  <div class="merge-ppt-dialog-wrap">
     <el-dialog
      v-if="mergePptShow"  
      :visible.sync="mergePptShow" 
      :close-on-click-modal="false" 
      :modal-append-to-body="false"
      @close="cancelHandle" width="40%" v-dialogDrag center>
      <div slot="title" style="display: flex; alignitems: center">
        <span style="fontsize: 16px">合并PPT</span>
      </div>
      <div class="dialog-container">
      <!--  <div class="tree-container-wrap">
          <div class="public-tree">
            <h3>公共PPT</h3>
            <div class="tree-container">
              <div class="tree-list" :key="treeKey">
                <div class="list-item" v-for="(item,index) in publicList" :key="item.nodeKeyId" @click.stop="expandList(index,'public')">
                  <p class="item-label"><span @click.stop="expandList(index,'public')"><i :class="item.expand?'el-icon-caret-bottom':'el-icon-caret-right'"></i></span> {{item.label}}</p>
                  <template v-if="item.expand">
                    <div class="list-child" v-for="i in item.children" :key="i.nodeKeyId">
                      <el-checkbox
                        :disabled="disabled&&!choosedIdArr.includes(i.PptId)||i.disabled"
                        v-model="i.checked"
                        @change="(checked)=>{changeCheck(checked,i,'public')}"
                      >{{i.label}}</el-checkbox>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
          <div class="private-tree">
            <h3>我的PPT</h3>
            <div class="tree-container">
              <div class="tree-list" :key="treeKey">
                <div class="list-item" v-for="(item,index) in privateList" :key="item.nodeKeyId" @click.stop="expandList(index,'private')">
                  <p class="item-label"><span @click.stop="expandList(index,'private')"><i :class="item.expand?'el-icon-caret-bottom':'el-icon-caret-right'"></i></span> {{item.label}}</p>
                  <template v-if="item.expand">
                    <div class="list-child" v-for="i in item.children" :key="i.nodeKeyId">
                      <el-checkbox
                        :disabled="disabled&&!choosedIdArr.includes(i.PptId)||i.disabled"
                        v-model="i.checked"
                        @change="(checked)=>{changeCheck(checked,i,'private')}"
                      >{{i.label}}</el-checkbox>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div> -->
        <div class="ppt-form">
          <div class="input-item" style="position:relative;">
            <h3>请选择PPT</h3>
            <!-- <div class="select-node-show" @click.stop="showCatalog = !showCatalog">
              <div class="select-node" v-for="item in choosedItemArr" :key="item.PptId">
                <span>{{ item.Title }}</span>
                <i class="el-icon-error" @click.stop="changeCheck(false,item,'unknow')"></i>
              </div>
              <div v-show="choosedItemArr.length===0" style="color:#606266;opacity:.54;margin-left:10px;">请选择PPT</div>
              <span class="expand" @click.stop="showCatalog = !showCatalog"><i :class="showCatalog?'el-icon-arrow-up':'el-icon-arrow-down'"></i></span>
            </div>
            <div class="catalog-wrap" v-show="showCatalog">
              <div class="public-tree">
                <h3>公共PPT</h3>
                <div class="tree-container">
                  <div class="tree-list" :key="treeKey">
                    <div class="list-item" v-for="(item,index) in publicList" :key="item.nodeKeyId" @click.stop="expandList(index,'public')">
                      <p class="item-label"><span @click.stop="expandList(index,'public')"><i :class="item.expand?'el-icon-caret-bottom':'el-icon-caret-right'"></i></span> {{item.label}}</p>
                      <template v-if="item.expand">
                        <div class="list-child" v-for="i in item.children" :key="i.nodeKeyId">
                          <el-checkbox
                            :disabled="disabled&&!choosedIdArr.includes(i.PptId)||i.disabled"
                            v-model="i.checked"
                            @change="(checked)=>{changeCheck(checked,i,'public')}"
                          >{{i.label}}</el-checkbox>
                        </div>
                      </template>
                    </div>
                  </div>
                </div>
              </div>
              <div class="private-tree" style="margin-top:10px;">
                <h3>我的PPT</h3>
                <div class="tree-container">
                  <div class="tree-list" :key="treeKey">
                    <div class="list-item" v-for="(item,index) in privateList" :key="item.nodeKeyId" @click.stop="expandList(index,'private')">
                      <p class="item-label"><span @click.stop="expandList(index,'private')"><i :class="item.expand?'el-icon-caret-bottom':'el-icon-caret-right'"></i></span> {{item.label}}</p>
                      <template v-if="item.expand">
                        <div class="list-child" v-for="i in item.children" :key="i.nodeKeyId">
                          <el-checkbox
                            :disabled="disabled&&!choosedIdArr.includes(i.PptId)||i.disabled"
                            v-model="i.checked"
                            @change="(checked)=>{changeCheck(checked,i,'private')}"
                          >{{i.label}}</el-checkbox>
                        </div>
                      </template>
                    </div>
                  </div>
                </div>
              </div>
            </div> -->
            <div class="select-ppt-wrap select-wrap">
              <el-tabs value="public">
                <el-tab-pane label="公共PPT" name="public">
                  <div class="tree-container">
                    <div class="tree-list" :key="treeKey">
                      <div class="list-item" v-for="(item,index) in publicList" :key="item.nodeKeyId" @click.stop="expandList(index,'public')">
                        <p class="item-label"><span @click.stop="expandList(index,'public')"><i :class="item.expand?'el-icon-caret-bottom':'el-icon-caret-right'"></i></span> {{item.label}}</p>
                        <template v-if="item.expand">
                          <div class="list-child" v-for="i in item.children" :key="i.nodeKeyId">
                            <el-checkbox
                              :disabled="disabled&&!choosedIdArr.includes(i.PptId)||i.disabled"
                              v-model="i.checked"
                              @change="(checked)=>{changeCheck(checked,i,'public')}"
                            >{{i.label}}</el-checkbox>
                          </div>
                        </template>
                      </div>
                    </div>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="我的PPT" name="private">
                  <div class="tree-container">
                    <div class="tree-list" :key="treeKey">
                      <div class="list-item" v-for="(item,index) in privateList" :key="item.nodeKeyId" @click.stop="expandList(index,'private')">
                        <p class="item-label"><span @click.stop="expandList(index,'private')"><i :class="item.expand?'el-icon-caret-bottom':'el-icon-caret-right'"></i></span> {{item.label}}</p>
                        <template v-if="item.expand">
                          <div class="list-child" v-for="i in item.children" :key="i.nodeKeyId">
                            <el-checkbox
                              :disabled="disabled&&!choosedIdArr.includes(i.PptId)||i.disabled"
                              v-model="i.checked"
                              @change="(checked)=>{changeCheck(checked,i,'private')}"
                            >{{i.label}}</el-checkbox>
                          </div>
                        </template>
                      </div>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
            <div class="selected-ppt-wrap ">
              <span>已选择：</span>
              <div class="selected-ppt">
                <div class="select-node" v-for="item in choosedItemArr" :key="item.PptId">
                  <span>{{ item.Title }}（{{item.PptPage}}页）</span>
                  <i class="el-icon-error" @click.stop="changeCheck(false,item,'unknow')"></i>
                </div>
              </div>  
            </div>
          </div>
          <div class="input-item">
            <h3>请选择合并到目录</h3>
            <div class="select-catalog-wrap select-wrap">
              <el-radio-group v-model="selectedCatalogId">
                <el-radio v-for="item in MyPrivateList" :key="item.GroupId" 
                :label="item.GroupId">{{item.GroupName}}</el-radio>
              </el-radio-group>
            </div>
          </div>
          <div class="input-item">
            <h3>PPT标题</h3>
            <el-input  placeholder="请输入PPT标题" v-model="pptInfo.Title" required ></el-input>
          </div>
          <div class="input-item">
            <h3>PPT类型</h3>
            <el-input  placeholder="请输入PPT类型" v-model="pptInfo.ReportType" required ></el-input>
          </div>
  <!--         <div class="input-item date-picker">
            <h3>PPT日期</h3>
            <el-date-picker
              v-model="pptInfo.PptDate"
              type="month"
              ref="date_pic"
              format="yyyy年M月"
              value-format="yyyy年M月"
              placeholder="请选择日期">
            </el-date-picker>
          </div> -->
        </div>
      </div>
      <div slot="footer" class="foot-container">
        <el-button type="primary" @click="saveChange">确 定</el-button>
        <el-button @click="cancelHandle">取 消</el-button>
      </div>
    </el-dialog>
  </div>
   
</template>

<script>
import {pptInterface} from '@/api/api.js';
import {pptEnInterface} from '@/api/modules/pptEnApi.js';
import {changeCatalogArr,createRandomCode} from '../../utils/untils';
export default {
  props:{
    mergePptShow:{
      type:Boolean,
      default:false
    },
/*     catalogId:{
      type:Number,
      default:0
    } */
  },
  data() {
    return {
      pptInfo:{
        Title:'',
        ReportType:'',
        BackgroundImg:'https://hzstatic.hzinsights.com/ppt/bg3.jpg',
        PptDate:(new Date().getFullYear())+'年'+(new Date().getMonth()+1)+'月',
        BackIndex:0,
        TemplateType:1
      },//PPT的标题信息
      publicList:[],
      privateList:[],
      treeKey:0,
      disabled:false,//判断所有的checkbox是否应该是启用/禁用状态
      choosedIdArr:[],//选中的PPTIds
      choosedItemArr:[],//选中的PPT item
      choosedTreesName:{},//选中的ppt分别来自哪个目录
      PptId:0,//合并后的pptId
      showCatalog:false,
      selectedCatalogId:0,//选择的目录Id
      saveLoading:null,//加载loading
      MyPrivateList:[]
    };
  },
  watch:{
    mergePptShow(newValue){
      if(newValue){
        this.init()
        this.getCatalogsList()
        this.getPrivateList()
      }
      if(!newValue){
        if(this.saveLoading){
          this.saveLoading.close()
        }
      }
    }
  },
  methods: {
    cancelHandle(){
      this.$emit('cancel')
    },
    async saveChange(){
      const {result,msg} = this.checkForm()
      if(!result){
        this.$message.warning(msg)
        return
      }
      this.saveLoading = this.$loading({
        fullscreen:true,
        lock: true,
        text: '合并中...',
        spinner: 'el-icon-loading',
        customClass:'loading',
        background: 'rgba(255, 255, 255, 0.8)'
      })
      await this.getPptsDetail()
      if(this.$parent.currentLang==='en'){
        this.pptInfo.PptDate = (new Date().getFullYear())+'.'+(new Date().getMonth()+1)
      }
      await this.addNewPpt()
      if(this.PptId!==0){
        this.$emit('merged',{PptId:this.PptId,catalogId:this.selectedCatalogId})
      }
        
    },
    //检查填写的信息是否合法
    checkForm(){
      //选中的PPT数量是否为两个(在选择时已剔除会有两个一样ID的情况)
      if(this.choosedIdArr.length!==2){
        return {result:false,msg:'请选择两个PPT'}
      }
      if(!this.pptInfo.Title.length){
        return {result:false,msg:'请填写PPT标题'}
      }
      if(!this.pptInfo.ReportType){
        return {result:false,msg:'请填写PPT类型'}
      }
      if(!this.pptInfo.PptDate){
        return {result:false,msg:'请选择日期'}
      }
      if(this.selectedCatalogId===0){
        return {result:false,msg:'请选择一个目录'}
      }
      return {result:true,msg:''}
    },
    //获取PPT详情
    async getPptsDetail(){
      //只需要content
      let content_font = [],content_back=[]
      const res_font = this.$parent.currentLang!=='en'
      ? await pptInterface.getpptDetail({
          PptId:this.choosedIdArr[0]
        })
      : await pptEnInterface.getpptDetail({
          PptId:this.choosedIdArr[0]
        })
      if(res_font.Ret===200){
        content_font = JSON.parse(res_font.Data.Content)
      } 
      const res_back = this.$parent.currentLang!=='en'
      ? await pptInterface.getpptDetail({
          PptId:this.choosedIdArr[1]
        })
      : await pptEnInterface.getpptDetail({
          PptId:this.choosedIdArr[1]
        })
      if(res_back.Ret===200){
        content_back = JSON.parse(res_back.Data.Content)
      }
      //合并两个content,并给每个重新赋id,保证id唯一
      let content = content_font.concat(content_back)
      this.content = content.map(item=>{
        item.id = createRandomCode()
        return item
      })
    },
    //添加PPT
    async addNewPpt(){
      const res = this.$parent.currentLang!=='en'
      ? await pptInterface.addppt({
          FirstPage:this.pptInfo,
          Content:JSON.stringify(this.content),
          GroupId:this.selectedCatalogId
        })
      : await pptEnInterface.addppt({
          FirstPage:this.pptInfo,
          Content:JSON.stringify(this.content),
          GroupId:this.selectedCatalogId
        })
      if(res.Ret===200){
        this.$message.success('合并成功')
        this.PptId = res.Data.PptId
      }else{
        //添加失败时关闭loading
        if(this.saveLoading){
          this.saveLoading.close()
        }
      }  
    },
    //PPT的选中和取消选中处理
    changeCheck(type,i,treeName){
      let ListName = treeName==='public'?'privateList':'publicList'
      //从已选择的PPT内点击,只能是取消选中
      if(treeName==='unknow'){
        ListName = this.choosedTreesName[i.PptId]+'List'
      }
      if(type){
        this.choosedIdArr.push(i.PptId)
        this.choosedItemArr.push(i)
        this.choosedTreesName[i.PptId] = treeName
        //选中时,同时要将另一个List的对应i也勾选,如果有
        this.setNodeChecked(ListName,i.PptId,true)  
      }else{
        const index = this.choosedIdArr.findIndex(item=>item===i.PptId)
        index!==-1&&this.choosedIdArr.splice(index,1)
        index!==-1&&this.choosedItemArr.splice(index,1)
        //取消选中时,同时要将另一个List的对应i也取消勾选,如果有
        this.setNodeChecked(ListName,i.PptId,false)
        if(treeName==='unknow'){
          ListName = this.choosedTreesName[i.PptId]==='public'?'privateList':'publicList'
          this.setNodeChecked(ListName,i.PptId,false)
        }
        delete this.choosedTreesName[i.PptId]
      }
      if(this.choosedIdArr.length===2){
        this.disabled = true
      }else if(this.choosedIdArr.length<2){
        if(this.disabled){
          this.disabled=false
        }
      }
    },
    //设置ppt的选中取消和禁用启用属性
    setNodeChecked(listName,PptId,checked){
      this[listName].forEach(item=>{
        if(item.children.length>0){
          item.children.forEach(i=>{
            if(i.PptId===PptId){
              i.checked = checked
              //顺便禁用下,不然看起来就像选了四个
              i.disabled = checked
            }
          })
        }
      })
    },
    //展开收起列表
    expandList(index,treeName){
      const {expand} = this[`${treeName}List`][index]
      this.$set(this[`${treeName}List`][index],'expand',!expand)
      this.treeKey++
    },
    //获取PPT目录
    async getCatalogsList(){
      const res = this.$parent.currentLang!=='en'
        ? await pptInterface.getCatalogsList({IsNewPpt:1})
        : await pptEnInterface.getCatalogsList({IsNewPpt:1})
      if(res.Ret===200){
        const {PublicList,PrivateList} = res.Data
        this.publicList = changeCatalogArr(PublicList)
        this.privateList = changeCatalogArr(PrivateList)
        this.publicList.forEach(item=>{
          item.expand = false
        })
        this.privateList.forEach(item=>{
          item.expand = false
        })
      }
    },
    //获取私有PPT目录
    async getPrivateList(){
      const res = this.$parent.currentLang!=='en'
        ? await pptInterface.getPrivateCatalogList()
        : await pptEnInterface.getPrivateCatalogList()
      if(res.Ret===200){
        this.MyPrivateList = res.Data.List||[]
        this.selectedCatalogId = this.MyPrivateList[0].GroupId
      }
    },
    //模拟blur事件,隐藏展开的目录框
    handleMouseDown(target){
      //console.log(target)
      const {path} = target
      for(let i=0;i<path.length;i++){
        if(path[i].className==="catalog-wrap")return
      }
      if(this.showCatalog){
        this.showCatalog = false
      }
    },
    //重置data的值
    init(){
      Object.assign(this.$data,this.$options.data())
    }
  },
  mounted(){
    //console.log('merge')
    //this.getCatalogsList()
  }
};
</script>

<style lang="scss">
.dialog-container{
  .tree-container-wrap{
    .tree-container{
      .el-tree-node {
        .is-leaf + .el-checkbox .el-checkbox__inner {
          display: inline-block;
        }
        .el-checkbox .el-checkbox__inner {
          display: none;
        }
        /* .el-checkbox.is-disabled{
          display: none;
        } */
      }
    }
  }
  .ppt-form{
    .input-item{
      .el-input{
        width:100%;
      }
      .select-ppt-wrap{
        .el-tabs__item{
          height:22px;
          line-height: 22px;
          font-size: 14px;
          color:#999999FF;
          &.is-active{
            color: #409EFF
          }
        }
        .el-tabs__nav-wrap.is-top{
          margin-bottom: 5px;
          &::after{
            display: none;
          }
        }
        .el-tabs__header{
          margin-bottom: 0px;
        }
      }
      .select-catalog-wrap{
        .el-radio-group{
          display: flex;
          flex-direction: column;
          .el-radio{
            margin-top: 6px;
          }
        }
      }
    }
  }
}
</style>
<style scoped lang="scss">
.dialog-container{
  .tree-container-wrap{
    width: 100%;
    display: flex;
    justify-content: space-between;
    .public-tree,.private-tree{
     /*  flex: 1; */
      width:47.5%;
      .tree-container{
        margin-top: 10px;
        width:100%;
        height:300px;
        overflow-y: scroll;
        border: 1px dashed #999;
        .tree-list{
          .list-item{
            cursor: pointer;
            .item-label{
              &:hover{
                background-color: #f0f4ff;
              }
            }
            .list-child{
              margin-left: 10px;
              &:hover{
                background-color: #f0f4ff;
              }
            }
          }
        }
      }
    }
    
  }
  .ppt-form{
   /*  margin-top: 20px; */
    width:100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    position:relative;
    .input-item{
      width: 90%;
      margin-top:20px;
      &:first-child{
        margin-top: 0;
      }
      &.date-picker{
        position: absolute;
        right: 15%;
        top: 0;
        width: 20%;
      }
      h3{
        margin-bottom: 10px;
      }
      .select-node-show{
        width:100%;
        display: inline-block;
        border-radius: 4px;
        border: 1px solid #DCDFE6;
        height:40px;
        padding-left: 5px;
        display: flex;
        align-items: center;
        position: relative;
        .expand{
          position:absolute;
          right:10px;
          top:10px;
          cursor: pointer;
        }
      }
      .catalog-wrap{
        position:absolute;
        top:62px;
        left:50%;
        transform: translateX(-50%);
        width:100%;
        border-radius: 4px;
        border: 1px solid #DCDFE6;
        background-color: #ffffff;
        z-index: 2;
        height:200px;
        overflow-y: scroll;
        padding: 10px;
        .tree-list{
          /* margin-left: 10px; */
          .list-item{
            margin-top: 6px;
            cursor: pointer;
            .item-label{
              &:hover{
                background-color: #f0f4ff;
              }
            }
            .list-child{
              margin-left: 10px;
              margin-top: 3px;
              &:hover{
                background-color: #f0f4ff;
              }
            }
          }
        }
      }
      .select-ppt-wrap{
        .tree-container{
          height:200px;
          overflow-y: scroll;
          .tree-list{
            .list-item{
              margin-left: 20px;
              margin-top: 6px;
              cursor: pointer;
              &:first-child{
                margin-top:0;
              }
              .item-label{
                &:hover{
                  background-color: #f0f4ff;
                }
              }
              .list-child{
                margin-left: 10px;
                margin-top: 6px;
                &:hover{
                  background-color: #f0f4ff;
                }
              }
            }
          }
        }
      }
      .selected-ppt-wrap{
        display: flex;
        margin-top: 10px;
        >span{
          display: inline-block;
          min-width:65px;
          color: #999999FF;
        }
        .selected-ppt{
          display: flex;
          flex-wrap: wrap;
        }
      }
      .select-catalog-wrap{
        height: 150px;
        overflow-y: scroll;
      }
      .select-node{
        margin: 0 10px 10px 0;
        padding: 5px 10px;
        background-color: #f0f2f5;
        border-radius: 4px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        /* max-width: 45%; */
        span,
        i {
          color: #909399;
          font-size: 14px;
        }
        span {
          margin-right: 5px;
          max-width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        i {
          cursor: pointer;
          margin-top: 2px;
          &:hover {
            color: #a5a8af;
          }
        }
      }
      .select-wrap{
        padding:5px 10px;
        border-radius: 4px;
        border: 1px solid #DCDFE6;
      }
    }
  }
}
</style>
