<template>
  <div class="page-wrap catalog-wrap">
    <span
        class="slide-icon slide-right"
        @click="slideHandle"
        v-show="isSlideLeft"
      >
        <i class="el-icon-d-arrow-right"></i>
      </span>
    <div class="list-wrap ppt-page-wrap" id="left" v-show="!isSlideLeft">
      <div class="add-btn">
        <el-button type="primary" @click="handleChooseCatalog('add')">添加ppt</el-button>
        <el-button type="primary" plain @click="handleOpenMergeDialog">合并ppt</el-button>
      </div>
      <div class="select-wrap">
        <el-select
          filterable remote
          placeholder="请输入PPT标题"
          v-model="searchTitle"
          :remote-method="searchHandle"
          clearable
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
          <el-option
            v-for="item in searchOptions"
            :key="item.PptId"
            :label="item.Title"
            :value="item.PptId"
          >
          </el-option>
        </el-select>
      </div>
      <div class="ppt-list-wrap">
        <el-tabs v-model="default_tab">
          <el-tab-pane :label="tab.label" :name="tab.key" v-for="tab in panelTabs" :key="tab.key"></el-tab-pane>
        </el-tabs>

        <!-- 公共 -->
        <div class="public-ppt" v-show="default_tab === 3">
          <!-- <h3>公共PPT <span @click="listExpand=!listExpand">{{listExpand?'收起':'展开'}} <i :class="listExpand?'el-icon-arrow-up':'el-icon-arrow-down'"></i></span></h3> -->
          <div class="ppt-list">
            <el-tree
              ref="publicTree"
              class="target-tree"
              empty-text="暂无分类"
              :data="publicList"
              node-key="nodeKeyId"
              :expand-on-click-node="false"
              :default-expanded-keys="publicExpandKeys"
              @node-expand="(data,node,item)=>{handleNodeExpand(data,node,item,'public')}"
              @node-collapse="(data,node,item)=>{handleNodeCollapse(data,node,item,'public')}"
              @current-change="(data,node)=>{nodeChange(data,node,'public')}"
            >
              <span class="custom-tree-node" slot-scope="{ data }"
                @mouseover="data.copyIconShow=true" @mouseout="data.copyIconShow=false"
              >
                <span class="tree-label">{{ data.label }}</span>
                <span
                  style="display: flex; align-items: center"
                >
                  <i class="el-icon-document-copy"
                    style="display:inline-block;width: 14px; height: 14px; margin-right: 8px;color:#409eff;"
                    v-show="(data.copyIconShow&&data.PptVersion===2)||checkNode(data)"
                    @click.stop="handleCopy(data)"
                  ></i>
                  <!-- v-show="(data.copyIconShow&&data.PptVersion===2)||(data.copyIconShow&&data.GroupId&&!data.OnlyOld)||checkNode(data)" -->
                </span>
              </span>
            </el-tree>
          </div>
        </div>

        <!-- 我的 -->
        <div class="private-ppt" v-show="default_tab === 1">
          <!-- <h3>我的PPT</h3> -->
          <div class="ppt-list">
            <el-tree
              ref="privateTree"
              class="target-tree"
              empty-text="暂无分类"
              :data="privateList"
              node-key="nodeKeyId"
              :expand-on-click-node="false"
              draggable 
              :allow-drag="checkAllowDrag"
              :allow-drop="checkAllowDrop"
              :default-expanded-keys="privateExpandKeys"
              @node-expand="(data,node,item)=>{handleNodeExpand(data,node,item,'private')}"
              @node-collapse="(data,node,item)=>{handleNodeCollapse(data,node,item,'private')}"
              @current-change="(data,node)=>{nodeChange(data,node,'private')}"
              @node-drop="handleDropOver"
            >
              <span class="custom-tree-node" slot-scope="{ data }"
              >
                <span class="tree-label">{{ data.label }}</span>
                <span
                  style="display: flex; align-items: center"
                >
                <el-dropdown @command="handleShareCommand" v-if="data.PptVersion">
                  <img
                    :src="data.isShare===1?require('@/assets/img/chart_m/User.png'):require('@/assets/img/chart_m/Group.png')"
                    style="width: 14px; height: 14px; margin-right: 8px"
                  />
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="{key:'cancel',item:data}"
                      class="treenode-dropdown-item"
                      :class="data.isShare===0?'treenode-dropdown-item-act':''" 
                    >
                      <img src="~@/assets/img/chart_m/Group.png"
                        style="width: 14px; height: 14px; margin-right: 8px"
                      />仅自己可见
                    </el-dropdown-item>
                    <el-dropdown-item :command="{key:'share',item:data}"
                      class="treenode-dropdown-item"
                      :class="data.isShare===1?'treenode-dropdown-item-act':''" 
                    >
                      <img src="~@/assets/img/chart_m/User.png"
                        style="width: 14px; height: 14px; margin-right: 8px"
                      />所有人可见
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-dropdown @command="handleOperateCommand" trigger="click">
                  <span class="el-dropdown-link"> 
                    <i class="el-icon-more" style="font-size: 16px;transform: rotate(90deg);cursor: pointer"/>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="{key:'copy',item:data}" v-if="(data.PptVersion&&data.PptVersion===2)||(data.GroupId&&!data.OnlyOld)">复制</el-dropdown-item>
                    <el-dropdown-item :command="{key:'edit',item:data}" v-if="data.GroupId">重命名</el-dropdown-item>
                    <el-dropdown-item :command="{key:'del',item:data}">删除</el-dropdown-item>
                    <el-dropdown-item :command="{key:'openShare',item:data}" v-if="data.PptVersion && !data.IsGrant">设置共享</el-dropdown-item>
                    <el-dropdown-item :command="{key:'cancelShare',item:data}" v-if="data.PptVersion && data.IsGrant">取消共享</el-dropdown-item>
                    <el-dropdown-item :command="{key:'transform',item:data}">转英文PPT</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                </span>
              </span>
            </el-tree>
          </div>
        </div>

        <!-- 共享 -->
        <div class="shared-ppt" v-show="default_tab === 2">
          <div class="ppt-list">
            <el-tree
              ref="sharedTree"
              class="target-tree"
              empty-text="暂无分类"
              :data="sharedList"
              node-key="nodeKeyId"
              :expand-on-click-node="false"
              :default-expanded-keys="sharedExpandKeys"
              @node-expand="(data,node,item)=>{handleNodeExpand(data,node,item,'shared')}"
              @node-collapse="(data,node,item)=>{handleNodeCollapse(data,node,item,'shared')}"
              @current-change="(data,node)=>{nodeChange(data,node,'shared')}"
            >
              <span class="custom-tree-node" slot-scope="{ data }">
                <span class="tree-label">{{ data.label }}</span>
                <el-dropdown @command="dealSharedHandle" trigger="click" v-if="data.PptId&&data.IsGrant">
                  <span class="el-dropdown-link"> 
                    <i class="el-icon-more" style="font-size: 16px;transform: rotate(90deg);cursor: pointer"/>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="{key:'cancelShare',item:data}">取消共享</el-dropdown-item>
                    <el-dropdown-item :command="{key:'set',item:data}">选择用户</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </el-tree>
          </div>
        </div>

        <div class="add-ppt" @click="handleCatalogChange({})">
          <img
            src="~@/assets/img/set_m/add_ico.png"
            alt=""
            style="width: 16px; height: 16px; margin-right: 10px"
          />
          <span>添加我的目录</span>
        </div>
      </div>
      <span class="slide-icon slide-left" @click="slideHandle">
          <i class="el-icon-d-arrow-left"></i>
      </span>
      <span
        class="move-btn resize"
        v-drag
        id="resize"
      ></span>
    </div>
    <div class="detail-wrap ppt-page-wrap" id="right">
      <div class="detail-list" v-if="model==='list'">
        <div class="total">共{{catalogPPTList.length}}个PPT</div>
        <div class="ppt-list">
          <draggable
            class="drag-cont"
            v-model="catalogPPTList"
            animation="300"
            @start="dragStartHandler"
            @update="dragenter"
            @end="moveListPPT"
            :disabled="treeName!=='private'"
            >
            <div class="list-item" 
              v-for="item in catalogPPTList" :key="item.PptId"
              @click="changeModel('ppt',item)"
              >
              <div class="item-title">
                <span>{{item.Title}}</span>
                <img
                  v-if="treeName==='private'"
                  src="~@/assets/img/data_m/move_ico.png"
                  style="width: 14px; height: 14px; margin-right: 8px"
                />
              </div>
              <div style="height:1px;background:#ECECEC;margin:0 -10px;"></div>
              <div class="item-image">
                <span>{{item.Title}}</span>
              </div>
              <span style="font-size:14px;">创建时间：{{$moment(item.PptCreateTime).format('YYYY-MM-DD')}}</span>
            </div>
          </draggable>
          <div class="empty" v-if="catalogPPTList.length===0">
            <img
              src="~@/assets/img/data_m/table_no.png"
              style="
                display: block;
                width: 140px;
                height: 148px;
                margin: 5% auto 10px;
              "
            />
            暂无数据
          </div>
        </div>
      </div>
      <div class="detail-ppt" v-else>
        <div class="ppt-show-box ppt-page-wrap">
          <ppt-content
            v-if="pptItem.PptVersion===2"
            :pptItem="pptItem"
            :key="pptItem.PptId"
            @isLegal="handleIsLegal"
          ></ppt-content>
          <ppt-content-old 
            v-else
            :pptItem="pptItem"
          ></ppt-content-old>
        </div>
        <div class="tool-side ppt-page-wrap">
          <span>操作</span>
          <div class="tool-list">
            <span v-for="item in pptToolList" :key="item.key" 
              :class="{'delete':item.key==='delete'}"
              @click="handleToolClick(item)">
              {{item.label}}
            </span>
          </div>
        </div>
      </div>
      
    </div>
    <!-- 添加/编辑目录弹窗 -->
    <modify-catalog
      :catalogItem="catalogItem" 
      :modifyCatalogShow="modifyCatalogShow"
      @changeCatalog="changeCatalog"
      @cancel="closeDialog('modifyCatalogShow')"
    />
    <!-- 选择目录弹窗 -->
    <choose-catalog 
      :chooseCatalogShow="chooseCatalogShow"
      :chooseCatalogType="chooseCatalogType"
      @selectCatalog="selectCatalog"
      @cancel="closeDialog('chooseCatalogShow')"
    />
    <!-- 转双周报弹窗 -->
    <trans-report
      v-if="pptItem"
      :transReportShow="transReportShow"
      :pptTitle="pptItem.Title"
      @transSet="getTransSet"
      @cancel="closeDialog('transReportShow')" 
    />
    <!-- 合并ppt弹窗 -->
    <merge-ppt-dialog
      :mergePptShow="mergePptShow"
      @merged="handleMergedPPT"
      @cancel="closeDialog('mergePptShow')"
    />

    <!-- 共享用户弹窗 -->
    <share-user-dialog
      :isShow.sync="openShareUserDia"
      :data="shareObj"
      @successCallback="getCatalogsList"
    />
  </div>
</template>

<script>
import ChooseCatalog from './components/catalog/chooseCatalog.vue';
import ModifyCatalog from './components/catalog/modifyCatalog.vue';
import PptContent from './components/catalog/pptContent.vue';
import PptContentOld from './components/catalog/pptContentOld.vue';
import draggable from 'vuedraggable';
import {toolList} from './utils/config';
import {changeCatalogArr} from './utils/untils';
import {pptInterface} from '@/api/api.js';
import TransReport from './components/catalog/transReport.vue';
import MergePptDialog from './components/catalog/mergePPTDialog.vue';
import shareUserDialog from './components/catalog/chooseShareUserDia.vue';
//触发window.resize,使Highcharts重绘
const reloadPPTWid = ()=>{
  const resizeEvent = new Event('resize')
  window.dispatchEvent(resizeEvent)
}
export default {
  components:{ModifyCatalog, ChooseCatalog, PptContent,PptContentOld,draggable,TransReport, MergePptDialog,shareUserDialog},
  directives: {
    drag(el, bindings) {
      el.onmousedown = function (e) {
        let init = e.clientX;
        let left = $('#left')[0];
        let initWidth = left.offsetWidth;
        document.onmousemove = function (e) {
          let end = e.clientX;
          let newWidth = end - init + initWidth;
          left.style.width = newWidth+'px';
          reloadPPTWid()
        };
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null;
          e.releaseCapture && e.releaseCapture();
        };
        e.setCapture && e.setCapture();
        return false;
      };
    },
  },
  data() {
    return {
      publicList:[],//公共目录
      privateList:[],//我的目录
      catalogPPTList:[],//目录的ppt列表
      catalogItem:{},
      modifyCatalogShow:false,//新增/编辑目录弹窗
      chooseCatalogShow:false,//选择目录弹框
      chooseCatalogType:'add',//当前打开选择目录弹窗的模式:add:添加PPT,copy:复制ppt,transform:转英文ppt
      model:'list',//右侧展示模式:list:目录列表,ppt:ppt详情
      pptToolList:[],
      pptItem:null,
      isSlideLeft:false,//控制目录栏展开,收起
      selectNode:null,//当前选中的节点
      treeName:'private',//当前操作的el-tree
      dragStartIndex:0,//ppt列表当前拖拽前的pptIndex
      dragPpt:null,//当前拖拽的ppt
      dragPrepPpt:null,//ppt拖拽后,在它前面的ppt
      dragNextPpt:null,//ppt拖拽后,在它后面的ppt
      privateExpandKeys:[],//私有ppt目录默认展开的项
      publicExpandKeys:[],//公共ppt目录默认展开的项
      searchOptions:[],//ppt搜索项
      searchTitle:'',
      transReportShow:false,//转换双周报设置弹窗
      listExpand:false,//公共目录是否展开
      mergePptShow:false,//合并ppt弹窗
      /* selectCatalogId:0,//选择的目录 */

      default_tab: 1,
      panelTabs: [
        { label: '我的PPT', key: 1 },
        { label: '共享PPT', key: 2 },
        { label: '公共PPT', key: 3 },
      ],

      sharedList: [],//共享目录
      sharedExpandKeys: [],//共享ppt目录默认展开的项
      /* 共享用户弹窗 */
      openShareUserDia: false,
      shareObj: {
        ppt_id:''
      },
      transData:null,//转换英文PPT数据

    };
  },
  watch:{
    searchTitle(newVal){
      let data = null
      this.publicList.forEach((item)=>{
        item.children.forEach(i=>{
          if(i.PptId===newVal){
            data = i
          }
        })
      })
      this.default_tab = 3;
      //选中该节点
      this.$refs.publicTree.setCurrentKey('ppt'+newVal)
      //展开该节点的父节点...
      const node = this.$refs.publicTree.getCurrentNode()
      this.publicExpandKeys.push(node.catalogId)
      this.nodeChange(data,_,'public')
      this.searchOptions=[]
    },
/*     default_tab(newVal){
      newVal&&this.handleTabClick(newVal) 
    } */
  },
  methods: {
    //编辑or新增目录
   async changeCatalog(item){
      let res = null
      if(item.GroupId){
        //renameCatalog
        res = await pptInterface.renameCatalog({
          GroupId:item.GroupId,
          GroupName:item.GroupName
        })      
      }else{
        //addCatalog
        res = await pptInterface.addCatalog({
          GroupName:item.GroupName
        })
      }
      if(res.Ret===200){
        this.$message.success(item.GroupId?'重命名成功':'新增成功')
        this.getCatalogsList()
        this.modifyCatalogShow = false
      }
    },
    //打开编辑目录弹窗
    handleCatalogChange(item){
      this.catalogItem = item
      this.modifyCatalogShow = true
    },
    //打开选择目录弹窗
    handleChooseCatalog(type){
      this.chooseCatalogType = type 
      this.chooseCatalogShow = true
    },
    //选择目录
    selectCatalog(selectedCatalog){
      this.chooseCatalogShow = false
      //如果是复制ppt
      if(this.chooseCatalogType==='copy'){
        //复制PPT到目录接口
        pptInterface.copyPPT({
          GroupId:selectedCatalog,
          PptId:this.pptItem.PptId
        }).then(async (res)=>{
          if(res.Ret===200){
            this.$message.success('复制成功')
            //更新目录列表
            await this.getCatalogsList()
            //切换到"我的PPT",展开选择的目录,选中复制的PPT
            this.default_tab = 1
            this.$nextTick(()=>{
              const {PptId} = res.Data||{}
              this.$refs.privateTree.setCurrentKey('ppt'+PptId)
              const node = this.$refs.privateTree.getCurrentNode()
              this.privateExpandKeys.push(node.catalogId)
              this.nodeChange(node,_,'private')
            }) 
          }
        })
      }
      //如果是添加ppt,打开添加ppt页面
      if(this.chooseCatalogType==='add'){
        sessionStorage.setItem('selectedCatalog',JSON.stringify(selectedCatalog));
        window.open('/ppteditor','_blank');
      }
      //如果是转英文PPT
      if(this.chooseCatalogType==='transform'){
        if(this.transData.PptId){
          this.transformPPTtoEn(selectedCatalog)
        }else{
          this.transformCatalogtoEn(selectedCatalog)
        }
      }
      //如果是合并ppt,打开合并ppt弹窗
      /* if(this.chooseCatalogType==='merge'){
        this.selectCatalogId = selectedCatalog
        this.mergePptShow = true
      } */
    },
    //关闭弹窗
    closeDialog(name){
      this[name] = false
    },
    //切换展示模式
    async changeModel(model,item,isSetKey = true){
      this.model = model
      if(model==='ppt'){
        this.pptItem = item
        this.setToolList()
        if(!isSetKey) return
        this.$nextTick(()=>{
           //选中节点
          this.$refs[`${this.treeName}Tree`].setCurrentKey(item.nodeKeyId)
          //展开该节点的父节点
          const node = this.$refs[`${this.treeName}Tree`].getCurrentNode()
          !this[`${this.treeName}ExpandKeys`].includes(node.catalogId)&&this[`${this.treeName}ExpandKeys`].push(node.catalogId)
          this.selectNode = item
        })
      }else{
        //获取目录下的ppt列表:getCatalogListByGroupId/getCatalogListByAdminId

        const res = this.treeName==='public' 
          ? await pptInterface.getCatalogListByAdminId({ AdminId:item.AdminId||''})
          : this.treeName==='private'
          ? await pptInterface.getCatalogListByGroupId({ GroupId:item.GroupId||''})
          : await pptInterface.getSharedList({ GroupId:item.GroupId||''});

        if(res.Ret!==200) return
        this.catalogPPTList = res.Data.List.map(item=>{
          item.nodeKeyId = 'ppt'+item.PptId //避免和目录id重复的情况
          //item.isTrans = item.ReportId===0?false:true
          //需求池272 PPT可转多次报告，PPT和转的报告不做同步
          item.isTrans = false
          return item
        })
      }
    },
    //设置操作按钮
    setToolList(){
      //公共目录:显示除 删除, 编辑 外的全部按钮
      if(this.treeName==='public'){
        this.pptToolList = toolList.filter((i)=>{
          return ['publish','present','download','copy','transform','transEn'].includes(i.key)
        })
      }
      //私有目录:显示全部按钮;共享目录:显示除删除外的全部按钮
      if(['private','shared'].includes(this.treeName)){
        this.pptToolList = (this.treeName==='shared' && this.pptItem.IsReceived) 
          ? toolList.filter(_ => _.key !== 'delete')
          : toolList;
      }
      //图库9.0以前的ppt:预览发布,下载
      if(this.pptItem.PptVersion===1){
        this.pptToolList = toolList.filter((i)=>{
          return ['publish','download'].includes(i.key)
        })
      }
      //ppt3.0 除旧版的ppt以外,增加 转报告/查看报告按钮
      const labelName = this.pptItem.isTrans?'查看报告':'转报告'
      this.pptToolList.map(i=>{
        if(i.key==='transform'){
          i.label = labelName
        }
      })
    },
    //判断公共目录按钮是否显示
    checkNode(data){
     if(!this.selectNode||this.treeName!=='public') return false
     /* if(this.model==='list'&&this.selectNode.GroupId===data.GroupId&&!data.OnlyOld){
       return true
     } */
     if(this.model==='list'){
       return false
     }
     if(this.model==='ppt'&&this.selectNode.PptId===data.PptId&&data.PptVersion===2){
       return true
     }
     return false
    },
    //点击目录
    nodeChange(data,node,treeName){
      this.treeName = treeName
      if(treeName==='private'){
        this.$refs.publicTree.setCurrentKey(null)
        this.$refs.sharedTree.setCurrentKey(null)
      }else if(treeName==='public'){
        this.$refs.privateTree.setCurrentKey(null)
        this.$refs.sharedTree.setCurrentKey(null)
      }else {
        this.$refs.publicTree.setCurrentKey(null)
        this.$refs.privateTree.setCurrentKey(null)
      }
      if(data.PptId){
        //是PPT,进入PPT详情
        this.selectNode = data
        this.changeModel('ppt',data,false)
      }else{
        this.selectNode = data
        this.changeModel('list',data)
      }
    },
    //复制目录/PPT事件处理
    handleCopy(data){
      if(data.PptId){
        //复制的是PPT
        //打开选择目录弹窗
        this.pptItem = data
        this.handleChooseCatalog('copy')
      }else{
        //复制的是目录
        this.copyCatalog(data)
      }
    },
    //复制目录
    copyCatalog(data){
      pptInterface.copyCatalog({
        GroupId:data.GroupId
      }).then(res=>{
        if(res.Ret===200){
          this.$message.success('复制成功')
          this.getCatalogsList()
        }
      })
    },
    //删除目录/ppt事件处理
    handleDelete(data){
      if(data.PptId){
        this.deletePPT(data)
      }else{
        this.deleteCatalog(data)
      }
    },
    //删除PPT
    deletePPT(data){
      this.$confirm(
        '删除操作不可恢复，若该PPT被共享，则同步删除共享PPT，确认删除吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
      ).then(()=>{
        pptInterface.deleteppt({
          PptId:data.PptId
        }).then((res)=>{
          if(res.Ret===200){
            this.$message.success('删除成功');
            this.getCatalogsList()
            const catalog = this[`${this.treeName}List`].find(i=>i.GroupId===data.catalogId)
            this.$refs[`${this.treeName}Tree`].setCurrentKey(data.catalogId)
            //删除的是公共目录下,某目录的最后一个PPT时,该公共目录会消失
            if(this.treeName==='public'&&catalog.PptList.length>1){
              this.changeModel('list',catalog)
            }else if(this.treeName==='public'&&catalog.PptList.length===1){
              this.changeModel('list',{})
            }
            //但是私有目录不会
            if(this.treeName==='private'){
              this.changeModel('list',catalog)
            }
          }
        })
      }).catch(() => {});
    },
    //删除目录
    deleteCatalog(data){
      if(data.PptList&&data.PptList.length!==0){
        this.$message.error('该目录下有关联PPT，不允许删除')
        return
      }
      this.$confirm(
        '删除操作不可恢复，确认删除吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(()=>{
        pptInterface.deleteCatalog({
          GroupId:data.GroupId
        }).then((res)=>{
          if(res.Ret===200){
            this.$message.success('删除成功');
            if(data.GroupId===this.selectNode.GroupId){
              this.selectNode=null
            }
            this.getCatalogsList()
          }
        })
      })
    },
    //点击操作栏事件处理
    handleToolClick(item){
      const urlMap = {
        edit:`/ppteditor?id=${this.pptItem.PptId}`,
        publish:`/pptpublish?id=${this.pptItem.PptId}`,
        present:`/pptpresent?id=${this.pptItem.PptId}`
      }
      //要跳转页面的:预览发布,编辑,演示
      if(urlMap[item.key]){
        if(this.pptItem.PptVersion===2){
          if(!this.pptItem.overLimit||item.key!=='publish'){
            window.open(urlMap[item.key],'_blank');
          }else if(item.key==='publish'){
            //this.$message.warning('该PPT页数超过60页或图表数量超过100张,无法发布,请修改后重试')
            if(!this.pptItem.overLimitHint.chartNum){
              this.$message.warning('PPT插入图表数量不能超过100张，请修改后重试')
              return
            }
            if(!this.pptItem.overLimitHint.pageNum){
              this.$message.warning('PPT页数不能超过60页，请修改后重试')
              return
            }
          }     
        }else{
          if(item.key==='publish'){
            sessionStorage.setItem('ppt_id',this.pptItem.PptId);
					  sessionStorage.setItem('ppt_auth',this.pptItem.IsAuth);
            window.open('/pptdtl','_blank');
          }
        }
        return 
      }
      const handleCommand = {
        'copy':this.handleCopy,
        'download':this.downloadPpt,
        'delete':this.deletePPT,
        'transform':this.transformPPT,
        'transEn':this.handleTransform
      }
      handleCommand[item.key](this.pptItem)
      /* if(item.key==='copy'){
        this.handleCopy(this.pptItem)
      }else if (item.key==='download'){
        this.downloadPpt(this.pptItem)
      }
      else if(item.key==='delete'){
        this.deletePPT(this.pptItem)
      }else if(item.key==='transform'){
        this.transformPPT(this.pptItem)
      } */
    },
    //下载pptx
    downloadPpt({PptxUrl,Title}){
      if(PptxUrl){
        let isIE=false;
				if (!!window.ActiveXObject || 'ActiveXObject' in window) {
					isIE=true;
				} else {
					isIE=false;
				}
        if(isIE){
          window.open(PptxUrl, '_blank')
        }else{
          /* let a = document.createElement('a') 
          a.href = PptxUrl 
          a.download=`${Title}aaa.pptx`
          a.click(); */
          const x = new XMLHttpRequest()
          x.open('GET', PptxUrl, true)
          x.responseType = 'blob'
          x.onload = () => {
            const url = window.URL.createObjectURL(x.response)
            let a = document.createElement('a') 
            a.href = url
            a.download=`${Title}.pptx`
            a.click();
            window.URL.revokeObjectURL(url)
          }
          x.send()
        }
      }else{
        this.$message.warning('请先预览发布')
      }
    },
    //共享/取消共享
    handleShareCommand({key,item}){
      //IsShare:0私有,1共享
      if(item.isShare===0&&key==='cancel') return
      if(item.isShare===1&&key==='share') return 
      if(item.GroupId){
        //共享目录
        //ppt5.1:取消私有目录的共享功能
        //shareCatalog
        /* pptInterface.shareCatalog({
          GroupId:item.GroupId
        }).then(res=>{
          if(res.Ret===200){
            this.$message.success('设置成功')
            this.getCatalogsList()
          }
        }) */
      }else{
        //共享ppt
        //ppt5.1:入参更改GroupPptId->PptId
        pptInterface.sharePPT({
          PptId:item.PptId
        }).then(res=>{
          if(res.Ret===200){
            this.$message.success('设置成功')
            this.getCatalogsList()
          }
        })
      }
    },
    //列表事件(目录:重命名,删除,转英文;PPT:复制,共享,删除,转英文)
    handleOperateCommand({key,item}){
      const handleMap = {
        'edit': this.handleCatalogChange,
        'copy': this.handleCopy,
        'del': this.handleDelete,
        'openShare': this.handleOpenShare,
        'cancelShare': this.handleOpenShare,
        'transform':this.handleTransform,
      }

      handleMap[key](item,key==='cancelShare' ? key : key==='openShare' ? 'set' : null);
    },
    /* 目录栏收起 展开 */
    slideHandle() {
      this.isSlideLeft = !this.isSlideLeft;
      this.$nextTick(()=>{
        reloadPPTWid()
        $('.ppt-item').css('height',$('.ppt-item').width()*0.7);
      })
    },
    //判断节点是否能拖拽:目录和ppt均可拖拽
    checkAllowDrag(node){
      /* if(node.isLeaf){
        return true
      } */
      return true
    },
    //判断节点是否能放入
    checkAllowDrop(draggingNode,dropNode,type){
      //拖动的节点是ppt:draggingNode.level===2
      if(draggingNode.level===2){
        //在目录内拖动
        if(dropNode.level===2&&type!=='inner'){
          return true
        }
        //拖动到其他目录
        if(dropNode.level===1&&type==='inner'){
          return true
        }
        //拖动的节点是目录:draggingNode.level===1
        //只有目录下没有ppt时才会走到这一层
      }else if(draggingNode.level===1){
        if(dropNode.level===1&&type!=='inner'){
          return true
        }
      }
      return false
    },
    //节点拖拽完成事件处理
    handleDropOver(dragingNode,dropNode,type,e){
      if(dragingNode.level===1){
        //拖动的是目录
        this.handleDragCatalog(dragingNode,dropNode,type)
      }
      if(dragingNode.level===2){
        //拖动的是ppt
        this.handleDragPpt(dragingNode,dropNode,type)
      }
    },
    //目录拖动事件
    /**
     * item:当前拖动的目录;
     * target:拖动后进入目录;
     * position:当前拖动目录放置位置(before,after) inner已在checkAllowDrop里排除;
     */
    handleDragCatalog(item,target,position){
      //console.log('item',item.data.GroupId,'target',target.data.GroupId,'position',position)
      //console.log(this.privateList)
      //目录拖动后privateList顺序会发生变化 
      const itemIndex = this.privateList.findIndex(i=>i.GroupId===item.data.GroupId)
      //console.log(itemIndex)
      let preGroupId=0,nextGroupId=0
      //position:before && itemIndex===0
      //说明拖动后,item在私有目录下置顶
      if(position==='before'&&itemIndex===0){
        preGroupId=0
        nextGroupId = target.data.GroupId
      }
      //position:before && itemIndex!==0
      //说明拖动后,拖动的目录在target之前
      if(position==='before' && itemIndex!==0){
        preGroupId = this.privateList[itemIndex-1].GroupId
        nextGroupId = target.data.GroupId
      }
      //position:after && itemIndex=== list.length-1
      //说明拖动后,item在私有目录下置底
      if(position==='after' && itemIndex=== this.privateList.length-1){
        preGroupId = target.data.GroupId
        nextGroupId = 0
      }
      //position:after && itemIndex!== list.length-1
      //说明拖动后,拖动的目录在target之后
      if(position==='after' && itemIndex!== this.privateList.length-1){
        preGroupId = target.data.GroupId
        nextGroupId = this.privateList[itemIndex+1].GroupId
      }
      //console.log('preGroupId',preGroupId,'nextGroupId',nextGroupId)
      //移动目录
      pptInterface.moveCatalog({
        PrevGroupId:preGroupId,
        NextGroupId:nextGroupId,
        GroupId:item.data.GroupId
      }).then(res=>{
        if(res.Ret===200){
          this.$message.success('移动成功')
          this.getCatalogsList()
        }
      })
    },
    //ppt拖动事件
    /**
     * item:当前拖动的ppt;
     * target:拖动后进入的目录or ppt;
     * position:当前拖动ppt放置的位置(before,after,inner) 
     *  如果target是目录,则position只能是inner;如果tatger是ppt,则position为before/after
     *  其他情况在checkAllowDrop已排除
     */
    handleDragPpt(item,target,position){
      let preGroupPptId=0,nextGroupPptId=0
      let targetIndexByCatalog = 0
      //console.log('item',item.data.catalogId,item.data.GroupPptId,'target',target.data.GroupPptId,'position',position)
      //target为目录
      if(target.level===1){
        preGroupPptId=0
        nextGroupPptId=0
      }
      //target为ppt
      if(target.level===2){
        //找到拖动后,item在哪个目录下
        //item.catalogId是ppt对应的目录id,在changeCatalogArr中赋值
        const catalogId = item.data.catalogId===target.data.catalogId?item.data.catalogId:target.data.catalogId
        const catalog = this.privateList.find(i=>i.GroupId===catalogId)
        //找到target在该目录下的哪个位置
        targetIndexByCatalog = catalog.PptList.findIndex(i=>i.PptId===target.data.PptId)
        //position:before && targetIndexByCatalog===0
        //说明拖动后,item在该目录下置顶
        if(position==='before'&&targetIndexByCatalog===0){
          preGroupPptId=0
          nextGroupPptId=catalog.PptList[targetIndexByCatalog].GroupPptId
        }
        //position:before && targetIndexByCatalog!==0
        //说明拖动后,item不在目录下第一个
        if(position==='before'&&targetIndexByCatalog!==0){
          preGroupPptId=catalog.PptList[targetIndexByCatalog-1].GroupPptId
          nextGroupPptId=catalog.PptList[targetIndexByCatalog].GroupPptId
        }
        //position:after && targetIndexByCatalog=== list.length-1
        //说明拖动后,item在该目录下置底
        if(position==='after'&&targetIndexByCatalog===catalog.PptList.length-1){
          preGroupPptId=catalog.PptList[targetIndexByCatalog].GroupPptId
          nextGroupPptId=0
        }
        //position:after && targetIndexByCatalog!==list.length-1
        //说明拖动后,item不在目录下第一个
        if(position==='after'&&targetIndexByCatalog!==catalog.PptList.length-1){
          preGroupPptId=catalog.PptList[targetIndexByCatalog].GroupPptId
          nextGroupPptId=catalog.PptList[targetIndexByCatalog+1].GroupPptId
        }  
      }
      //console.log('preGroupPptId',preGroupPptId,'nextGroupPptId',nextGroupPptId)
      pptInterface.movePPT({
        GroupId:target.level===1?target.data.GroupId:target.data.catalogId,
        GroupPptId:item.data.GroupPptId,
        PrevGroupPptId:preGroupPptId,
        NextGroupPptId:nextGroupPptId
      }).then(res=>{
        if(res.Ret===200){
          this.$message.success('移动成功')
          this.getCatalogsList()
        }
      })
    },
    //ppt列表拖动事件
    //拖动开始,记录当前拖动的ppt
    dragStartHandler({oldIndex}){
      console.log('start',oldIndex)
      this.dragStartIndex = oldIndex
      this.dragPpt = this.catalogPPTList[oldIndex]
    },
    //拖动时,获取前一个位置和后一个位置
    dragenter({newIndex}){
      //console.log('draging',e)
      //拖动后,catalogPPTList也会跟着改变
      //置顶
      if(newIndex===0){
        this.dragPrepPpt=null
        this.dragNextPpt=this.catalogPPTList[newIndex+1]
      }
      //置底
      if(newIndex===this.catalogPPTList.length-1){
        this.dragPrepPpt = this.catalogPPTList[newIndex-1]
        this.dragNextPpt = null
      }
      if(newIndex!==0&&newIndex!==this.catalogPPTList.length-1){
        this.dragPrepPpt = this.catalogPPTList[newIndex-1]
        this.dragNextPpt = this.catalogPPTList[newIndex+1]
      }
    },
    //拖动结束,移动ppt
    moveListPPT({newIndex}){
      console.log('end',newIndex)
      if(this.dragStartIndex===newIndex){
        return
      }
      //console.log('list',this.catalogPPTList)
      //console.log('pre',this.dragPrepPpt.Title,'next',this.dragNextPpt.Title,'item',this.dragPpt.Title)
      //movePPT
      pptInterface.movePPT({
        GroupPptId:this.dragPpt.GroupPptId,
        GroupId:this.selectNode.GroupId,
        PrevGroupPptId:this.dragPrepPpt?this.dragPrepPpt.GroupPptId:0,
        NextGroupPptId:this.dragNextPpt?this.dragNextPpt.GroupPptId:0
      }).then(res=>{
        if(res.Ret===200){
          this.$message.success('移动成功')
          this.getCatalogsList()
        }
      })
    },
    //节点展开事件
    handleNodeExpand(data,node,item,type){
      type==='private'
        ? !this.privateExpandKeys.includes(data.nodeKeyId)&&this.privateExpandKeys.push(data.nodeKeyId)
        : type==='public'
        ? !this.publicExpandKeys.includes(data.nodeKeyId)&&this.publicExpandKeys.push(data.nodeKeyId)
        : !this.sharedExpandKeys.includes(data.nodeKeyId)&&this.sharedExpandKeys.push(data.nodeKeyId)     
    },
    //节点收起事件
    handleNodeCollapse(data,node,item,type){
      if(type==='private'){
        const index = this.privateExpandKeys.findIndex(i=>i===data.nodeKeyId)
        index!==-1&&this.privateExpandKeys.splice(index,1)
      }else if(type==='public'){
        const index = this.publicExpandKeys.findIndex(i=>i===data.nodeKeyId)
        index!==-1&&this.publicExpandKeys.splice(index,1)
      } else {
        const index = this.sharedExpandKeys.findIndex(i=>i===data.nodeKeyId)
        index!==-1&&this.sharedExpandKeys.splice(index,1)
      }
    },
    //搜索ppt标题
    searchHandle(keyword){
      //searchPPT->searchPPTByKeyWorld
      pptInterface.searchPPTByKeyWorld({
        Keyword:keyword
      }).then(res=>{
        if(res.Ret===200){
          this.searchOptions = res.Data.List||[]
        }
      })
    },
    //ppt转双周报
    transformPPT(data){
      if(data.isTrans){
        //跳转到双周报详情
        let {href} = this.$router.resolve({name:'预览报告',query:{id:data.ReportId,code:data.ReportCode}});
        window.open(href,'_blank');
      }else{
        if(data.PptxUrl){
          //打开报告设置弹窗
          this.transReportShow = true
        }else{
          this.$message.warning('请先预览发布!')
        }
        
      }
    },
    getTransSet(data){
      pptInterface.transReport({
        PptId:this.pptItem.PptId,
        ClassifyIdSecond:data.type,
        Title:data.title
      }).then(res=>{
        if(res.Ret===200){
          this.$message.success('转换成功')
          this.transReportShow = false
          this.getCatalogsList()
          //更新item
          //this.pptItem.isTrans = true
          //需求池272 PPT可转多次报告，PPT和转的报告不做同步
          this.pptItem.isTrans = false
          this.pptItem.ReportId = res.Data.report_id
          this.pptItem.ReportCode = res.Data.report_code
          this.changeModel('ppt',this.pptItem)
        }
      })
    },
    //合并PPT成功后处理:设置合并后的PPT为选中状态,并展开其父节点
    async handleMergedPPT({PptId,catalogId}){
      await this.getCatalogsList()
      let pptItem = null
      this.privateList.forEach(item=>{
        if(item.GroupId===catalogId){
          item.children.forEach(i=>{
            if(i.PptId===PptId){
              pptItem = i
            }
          })
        }
      })
      this.treeName='private'
      this.changeModel('ppt',pptItem)
      this.mergePptShow = false
      this.default_tab=1
    },
    //合并PPT成功后,PPT页数和图表数校验
    handleIsLegal(isLegalObj){
      this.pptItem.overLimit = Object.values(isLegalObj).includes(false)
      this.pptItem.overLimitHint = isLegalObj
    },
    //获取所有目录
    async getCatalogsList(type){
      const res = await pptInterface.getCatalogsList()
      const currentKey = this.$refs[`${this.treeName}Tree`].getCurrentKey()
      if(res.Ret===200){
        const {PublicList,PrivateList,GrantList} = res.Data
        this.publicList = changeCatalogArr(PublicList)
        this.privateList = changeCatalogArr(PrivateList)
        this.sharedList = changeCatalogArr(GrantList)
        /* if(type==='load'){
          this.handleTabClick(1)
          this.handleTabClick(2)
        } */
        this.$nextTick(()=>{
          this.$refs[`${this.treeName}Tree`].setCurrentKey(currentKey)
          if(this.selectNode&&this.selectNode.GroupId){
            this.changeModel('list',this.selectNode)
          }else if(!this.selectNode){
            this.changeModel('list',{})
          }
        })
      }
    },
    //检测当前账号是否有私有目录
    handleOpenMergeDialog(){
      if(this.privateList.length===0){
        this.$message.warning('请先添加目录!')
      }else{
        this.mergePptShow = true
      }
    },

    /* 设置共享用户 */
    handleOpenShare({PptId,AdminIdStr,GrantType},type='set') {
      if(type === 'set') {
        this.shareObj = {
          ppt_id: PptId,
          users: AdminIdStr ? AdminIdStr.split(',') : '',
          type: GrantType || ''
        }
        this.openShareUserDia = true;

      }else {
        this.$confirm(
          '确定要取消共享吗',
          '提示',
          {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
          }
        ).then(()=>{
          pptInterface.cancelShareAuth({
            PptId
          }).then(res => {
            if(res.Ret !== 200) return

            this.$message.success('取消成功');
            this.getCatalogsList()
          })
        })
      }
    },

    /*  */
    async dealSharedHandle({key,item}) {
      const { Data } = key === 'set' && await pptInterface.getSharedDetail({ PptId: item.PptId })
      let params = key === 'set' ? {...item,...Data} : item;
      this.handleOpenShare(params,key);

    },
    //切换tab时,展开选中tab的全部目录
    handleTabClick(activeTab){
      const catalogMap = {
        1:'private',
        2:'shared',
        3:'public'
      }
      const List = this[catalogMap[activeTab]+'List']
      List.forEach((item)=>{
        if(item.children.length>0&&catalogMap[activeTab]!=='public'){
          this.handleNodeExpand(item,_,_,catalogMap[activeTab])
        }
      })

    },
    handleTransform(data){
      this.transData = data
      this.handleChooseCatalog('transform')
    },
    async transformPPTtoEn(selectedCatalog){
      const res  = await pptInterface.transPPTtoEn({
        PptId:this.transData.PptId,
        GroupId:selectedCatalog
      })
      if(res.Ret!==200) return
      this.$message.success('转英文PPT成功')
    },
    async transformCatalogtoEn(selectedCatalog){
      let PptIds = []
      this.catalogPPTList.forEach(item=>{
        PptIds.push(item.PptId)
      })
      const res  = await pptInterface.transCatalogtoEn({
        PptIds:PptIds.join(','),
        GroupId:selectedCatalog
      })
      if(res.Ret!==200) return
      this.$message.success('批量转英文PPT成功')
    }
  },
  mounted(){
    this.getCatalogsList('load')
  }
};
</script>

<style lang="scss">
@import './css/common.scss';
.catalog-wrap{
  .list-wrap{
    .el-tabs__nav-wrap::after {
      height: 0;
    }
    .el-tabs__item.is-active {
      border-bottom: 2px solid #409EFF;
    }
    .el-tabs__item { font-size: 16px; }
    .ppt-list-wrap{
      .target-tree {
        margin-top: 10px;
        font-size: 14px;
        color: #333;
        .custom-tree-node {
          display: flex !important;
          justify-content: space-between;
          align-items: center;
          display: block;
          flex: 1;
          width:calc(100% - 28px);
          .node_label {
            margin-right: 2px;
          }
          .tree-label{
            flex: 1;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis
          }
        }
        .el-tree__drop-indicator {
          height: 3px;
          background-color: #409eff;
        }
        .el-tree-node__content {
          margin-bottom: 7px !important;
          &:hover{
              background-color: #f0f4ff !important;
          }
        }
        .el-tree-node__children {
          .el-tree-node {
            margin-bottom: 0px !important;
            padding-left: 18px;
          }
          .el-tree-node__content {
            margin-bottom: 5px !important;
            padding-left: 0 !important;
            &:hover{
              background-color: #f0f4ff !important;
            }
          }
        }
        .expanded.el-icon-caret-right:before {
          content: url('~@/assets/img/set_m/down.png') !important;
        }
        .el-icon-caret-right:before {
          content: url('~@/assets/img/set_m/slide.png') !important;
        }
        .el-tree-node__expand-icon.is-leaf.el-icon-caret-right:before {
          content: '' !important;
        }
        .el-tree-node__expand-icon.expanded {
          -webkit-transform: rotate(0deg);
          transform: rotate(0deg);
        }
        .el-tree-node.is-current > .el-tree-node__content {
          background-color: #f0f4ff !important;
          color:#409eff ;
        }
        .el-tree-node__content {
          padding-right: 10px !important;
        }
      }
    }
  }
}
.treenode-dropdown-item{
   &:hover {
      background-color: #F5F7FA  !important;
      color: #606266 !important;
    }
}
.el-dropdown-menu .treenode-dropdown-item-act {
  background-color: #ecf5ff !important;
  color: #66b1ff !important;
}
</style>
<style scoped lang="scss">
.catalog-wrap{
  display: flex;
  width:100%;
  /* position: relative; */
  .list-wrap{
    width:300px;
    min-width: 300px;
    margin-right: 30px;
    padding:10px;
    position: relative;
    .add-btn{
      margin:-10px;
      padding: 10px;
      border-bottom: 1px solid rgb(225, 225, 225);
      box-shadow: 0px 3px 6px rgba(167, 167, 167, 0.09);
    }
    .select-wrap{
      margin-top:20px;
      .el-select{
        width:100%;
      }
    }
    .ppt-list-wrap{
      margin-top:20px;
      height: calc(100vh - 290px);
      overflow-y: scroll;
      &::-webkit-scrollbar-track{
        display: none;
      }
      h3{
        span{
          margin-left: 20px;
          color:#409EFF;
          font-size: 12px;
          font-weight: normal;
        }
      }
      .ppt-list{
        overflow: hidden;
      }
      .add-ppt{
        margin-top:20px;
        font-size: 16px;
        color: #409eff;
        cursor: pointer;
        display: flex;
        justify-content: center;
        align-items: center;
      } 
    }
    .move-btn {
      height: 100%;
      width: 4px;
      position: absolute;
      right: 0px;
      top: 0;
      &:hover {
        cursor: col-resize;
      }
    }
  }
  .detail-wrap{
    flex:1;
    background-color:transparent;
    box-shadow: none;
    .detail-list{
      .total{
        height: 20px;
        line-height: 20px;
        margin-bottom: 10px;
      }
      .ppt-list{
       /*  display: flex;
        flex-wrap: wrap; */
        min-width: 976px;
        height: calc(100vh - 150px);
        overflow-y: scroll;
        &::-webkit-scrollbar-track{
          display: none;
        }
        position: relative;
        .drag-cont {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
        }
        .list-item{
          width: 30%;
          background-color: white;
          border: 1px solid #ECECEC;
          border-radius: 4px;
          display: flex;
          flex-direction: column;
          margin: 0 20px 20px 0;
          padding:10px;
          box-sizing: border-box;
          .item-title{
            width:100%;
            height:20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            font-size: 16px;
            span{
              flex:1;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            }
            img{
              cursor: pointer;
            }
          }
          .item-image{
            margin:10px 0;
            width:100%;
            /* aspect-ratio:10/7; */
            height: 0;
            padding-bottom: 70%;
            background-color: pink;
            position:relative;
            background: no-repeat top/cover url('~@/assets/img/ppt_m/bg3.jpg');
            span{
              display: inline-block;
              width: 100%;
              text-align: center;
              position:absolute;
              top:50%;
              left:50%;
              transform: translate(-50%,-50%);
              font-size: 24px;
              color: #FFFFFF;
              font-weight: bold;
            }
          }
        }
        .empty{
          position: absolute;
          top:50%;
          left:50%;
          transform: translate(-50%,-50%);
          text-align: center;
        }
      }
    }
    .detail-ppt{
      display: flex;
      .ppt-show-box{
        flex: 1;
       /*  background-color: pink; */
      }
      .tool-side{
        margin-left: 20px;
        width:180px;
        background-color: white;
        height: calc(100vh - 120px);
        padding:20px;
        overflow-y: scroll;
        border-left: 1px solid #eaeaea;
        &::-webkit-scrollbar-track{
          display: none;
        }
        .tool-list{
          margin-top: 20px;
          display: flex;
          flex-direction: column;
          align-items: center;
          span{
            cursor: pointer;
            color:#409eff;
            display: inline-block;
            height: 35px;
            line-height: 35px;
            &.delete{
              color: red;
            }
          }
        }
      }
    }
  }
  .slide-icon {
      padding: 20px 0;
      box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3);
      border-radius: 5px;
      cursor: pointer;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      z-index: 99;
      &:hover {
        background-color: rgba(0, 0, 0, 0.05);
      }
      &.slide-left {
        right: 0;
      }
      &.slide-right {
        left: 0;
      }
  }
}
</style>

