<template>
  <!-- 文档管理 -->
  <div class="document-file-page-wrap">
    <!-- 目录栏 -->
    <div class="catalog-wrap page-block-wrap catalog-block" id="left">
      <div class="btn-box">
        <el-button type="primary" @click="toPage('addFile')">添加文档</el-button>
      </div>
      <div class="select-wrap">
        <el-select
          filterable remote
          placeholder="请输入文件名称"
          v-model="searchTitle"
          :remote-method="searchHandle"
          value-key="SaDocId"
          clearable
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
          <el-option
            v-for="item in searchOptions"
            :key="item.SaDocId"
            :label="item.Title"
            :value="item"
          >
          </el-option>
        </el-select>
      </div>
      <div class="catalog-list-wrap">
        <div class="catalog-list">
          <el-tree
              ref="catalogTree"
              class="catalog-tree other-tree"
              empty-text="暂无分类"
              :data="listData"
              node-key="nodeKeyId"
              :expand-on-click-node="true"
              :default-expanded-keys="expandKeys"
              draggable 
              :allow-drag="checkAllowDrag"
              :allow-drop="checkAllowDrop"
              @node-drop="handleDropOver"
              @node-expand="handleNodeExpand"
              @node-collapse="handleNodeCollapse"
              @current-change="(data,node)=>{nodeChange(data,node)}"
            >
              <span class="custom-tree-node" slot-scope="{ data,node }"
              >
                <span class="tree-label">{{ data.label }}</span>
                <span style="display: flex; align-items: center"
                  v-if="data.nodeKeyId===selectNodeKey"
                >
                  <img
                    :src="require('@/assets/img/set_m/edit.png')"
                    alt="" v-if="node.level!==2"
                    style="width: 14px; height: 14px; margin-right: 5px"
                    @click.stop="clickNodeHandle('edit', data)"
                  />
                  <img
                    :src="require('@/assets/img/set_m/del.png')"
                    alt=""
                    style="width: 14px; height: 14px; margin-right: 5px"
                    @click.stop="clickNodeHandle('del', data)"
                  />
                </span>
              </span>
          </el-tree>
        </div>
      </div>
      <div class="catalog-tool">
        <div class="add-catalog" @click="isModifyClassifyShow=true">
          <img
            src="~@/assets/img/set_m/add_ico.png"
            alt=""
            style="width: 16px; height: 16px; margin-right: 6px"
          />
          <span>添加分类</span>
        </div>
        <span class="total-text" v-if="selectNode&&model==='list'">共{{catalogList.length}}个文档</span>
      </div>
      <span class="move-btn resize" v-drag id="resize"></span>
    </div>
    <div class="detail-wrap page-block-wrap catalog-block" id="right">
      <!-- 列表栏 -->
      <div class="detail-list overflow-hide-scrollbar" v-if="model==='list'">
          <!-- 选择一级分类不再展示列表 -->
        <!-- <draggable
          class="drag-cont"
          v-model="catalogList"
          animation="300"
          @start="dragStartHandler"
          @update="dragenter"
          @end="moveListItem"
          :disabled="true">
          <div class="list-item" 
            v-for="item in catalogList" :key="item.nodeKeyId"
            @click="changeModel('file',item)"
            >
            <div class="item-title">
              <span>{{item.label}}</span>
              <img
                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" :style="`background-image:url(${item.CoverImg?item.CoverImg:require('@/assets/img/document_m/default-img.png')})`"></div>
            <div style="height:1px;background:#ECECEC;margin:0 -10px;"></div>
            <div class="item-info">
              <span style="font-size:14px;">{{item.Theme}}</span>
              <span @click.stop>
                <el-dropdown @command="handleOperateCommand" trigger="click">
                  <span class="el-dropdown-link"> 
                    <i class="el-icon-more" style="font-size: 16px;cursor: pointer"/>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="{key:'edit',data:item}">编辑</el-dropdown-item>
                    <el-dropdown-item :command="{key:'del',data:item}">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </div>
          </div>
        </draggable> -->
          <div class="empty" v-if="catalogList.length===0">
            <tableNoData text="暂无数据"/>
          </div>
      </div>
      <!-- 文件详情 -->
      <div class="detail-file" v-else>
        <div class="file-info">
          <ul>
            <li class="name">文档名称:{{docInfo.Title}}</li>
            <!-- <li>文档主题:{{docInfo.Theme}}</li> -->
            <li>文档分类:{{docInfo.ClassifyName}}</li>
          </ul>
          <el-button type="primary" @click="handleEdit('file',selectNode)">编辑</el-button>
        </div>
        <div class="file-content overflow-hide-scrollbar">
          <p v-for="block in docInfo.SectionList" :key="block.SaDocSectionId">{{block.innerText}}</p>
        </div>
      </div>
    </div>
    <!-- 添加/编辑分类弹窗 -->
    <el-dialog
      :title="classifyForm.classify_id?'编辑分类':'添加分类'"
      :visible.sync="isModifyClassifyShow"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="clearForm"
      width="589px"
      v-dialogDrag
      center
    >
      <div class="dialog-container">
        <el-form
          ref="formRef"
          label-position="left"
          hide-required-asterisk
          label-width="80px"
          :model="classifyForm"
          :rules="classifyFormRules"
        >
          <el-form-item label="分类名称" prop="classify_name">
            <el-input
              v-model="classifyForm.classify_name"
              style="width: 80%"
              placeholder="请输入分类名称"
            />
          </el-form-item>
          <!-- 文档分类的封面图取消 -->
          <!-- <el-form-item label="封面图" prop="classify_img" ref="uploadImg">
            <el-upload
              action=""
              accept="image/png,image/jpg,image/jpeg"
              :http-request="handleUploadImg"
              :show-file-list="false"
              :key="uploadKey"
            >
              <div class="upload-box">
                <template v-if="!classifyForm.classify_img">
                  <i class="el-icon-plus" style="font-size: 24px;"></i>
                  <p class="form-hint">点击上传图片</p>
                </template>
                <template v-else>
                  <img
                    class="upload-img"
                    :src="classifyForm.classify_img" alt="封面图"
                  >
                  <span class="upload-mask">
                    <span
                      class="mask-icon"
                      @click.stop="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </template>  
              </div>
          </el-upload>
          <p class="form-hint">支持格式：PNG、JPEG</p>
          </el-form-item> -->
        </el-form>
      </div>
      <div class="foot-container">
        <el-button @click="clearForm">取 消</el-button>
        <el-button type="primary" @click="modifyClassify">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
/* js */
import catalogMixin from "./mixins/catalogMixin";
import { formatArr,formatFile } from './utils/index';
/* components */
//import draggable from 'vuedraggable';
/* api */
import {customInterence} from '@/api/api.js'
import {documentInterface} from '@/api/modules/semanticsApi.js';

export default {
  mixins:[catalogMixin],
  data() {
    return {
      classifyForm:{},//分类信息
      classifyFormRules:{
        classify_name:[{ required: true, message: "分类名称不能为空"}],
        //classify_img:[{ required: true, message: "分类图片不能为空"}] //el-upload 触发校验后再校验不会更新这个
        //classify_img:[{validator:this.checkImg}],//使用自定义规则
      },//分类校验规则
      isModifyClassifyShow:false,//控制分类显示弹窗
      uploadKey:0,//刷新上传图片
      docInfo:{},//文档详情
    };
  },
  watch:{
    searchTitle(newVal){ //选中搜索结果
      const {SaDocId,ClassifyId} = newVal
      if(SaDocId&&ClassifyId){ //展开对应项
        this.handleNodeExpand({nodeKeyId:ClassifyId+''})
        this.nodeChange({SaDocId,nodeKeyId:`children_${SaDocId}`},{level:2})
        this.searchOptions = []
      }
    }
  },
  methods: {
    //搜索文档
    searchHandle(keyword){
      documentInterface.getDocumentList({
        PageSize:1000,
        CurrentIndex:1,
        Keyword:keyword
      }).then(res=>{
        if(res.Ret!==200) return 
        this.searchOptions = res.Data.List||[]
      })
    },
    //获取分类列表
    async getListData(){
      await documentInterface.getClassifyList().then(res=>{
        if(res.Ret!==200) return 
        this.listData = formatArr(res.Data||[])
      })
    },
    //获取文档详情
    getDetail(data){
      const {SaDocId} = data
      documentInterface.getDocumentDetail({
        DocId:Number(SaDocId)
      }).then(res=>{
        if(res.Ret!==200) return 
        this.docInfo = formatFile(res.Data)
      })
    },
    //新增/编辑分类
    async modifyClassify(){
      let res = null
      let flag = false
      const {classify_id,classify_name,/* classify_img */} = this.classifyForm
      this.$refs.formRef.validate((valid) => {
        flag = valid
      })
      if(!flag) return
      if(classify_id){
        res = await documentInterface.editClassify({
          SaDocClassifyId:Number(classify_id),
          ClassifyName:classify_name,
          /* CoverImg:classify_img */
        })
      }else{
        res = await documentInterface.addNewClassify({
          ClassifyName:classify_name,
          /* CoverImg:classify_img */
        })
      }
      if(res.Ret!==200) return
      this.$message.success(`${classify_id?'编辑':'新增'}成功`)
      await this.getListData()
      if(classify_id){//编辑后,重新选中该分类
        const catalog = this.listData.find(item=>{return item.nodeKeyId===classify_id})
        catalog&&this.nodeChange(catalog,{level:1})
      }
      this.clearForm()
    },
    //删除分类
    async deleteClassify(data){
      await documentInterface.deleteClassify({
        SaDocClassifyId:Number(data.SaDocClassifyId)
      }).then(res=>{
        if(res.Ret!==200) return 
        this.$message.success('删除成功')
        this.clearForm()
      })
    },
    //删除文档
    async deleteDocument(data){
      await documentInterface.deleteDocument({
        SaDocId:Number(data.SaDocId)
      }).then(async res=>{
        if(res.Ret!==200) return
        this.$message.success('删除成功')
        this.chooseDataClassify(data)
      })
    },
    /**
     * 文档分类封面图相关的代码,由于封面图取消这部分代码都没用到,不过还是留着吧
     */
    //删除已上传的图片
    handleRemove(e){
      this.classifyForm.classify_img=''
      this.uploadKey++
    },
    //上传图片
    async handleUploadImg(e){
      //console.log('upload',e.file);
      //验证图片类型
      if(!['image/png','image/jpg','image/jpeg'].includes(e.file.type)){
        this.$message.warning('请选择png、jpeg格式的图片')
        return
      }
      let form = new FormData()
      form.append("file", e.file)
      const res=await customInterence.upload(form)
      if(res.Ret===200){
        this.$refs.formRef&&this.$refs.formRef.clearValidate();
        this.classifyForm.classify_img=res.Data.ResourceUrl
        this.uploadKey++
      }
    },
    checkImg(rule,value,callback){
      if(!this.classifyForm.classify_img){
        return callback(new Error('分类图片不能为空'))
      }else{
        callback()
      }
    },
    /**------------------ */
    //切换页面
    toPage(pageName,params){
      const routerPathMap = {
        'addFile':'/addDocument',
        'editFile':'/editDocument',
        'tag':'/tagPage'
      }
      this.$router.push({
        path:routerPathMap[pageName],
        query:params||{}
      })
    },
    //移动文档
    moveDocument(moveParams){
        documentInterface.moveDocument(moveParams).then(async res=>{
            if(res.Ret!==200) return 
            await this.getListData()
            this.handleNodeExpand({
                nodeKeyId: moveParams.SaDocClassifyId
            })
            this.nodeChange({
                SaDocId:moveParams.SaDocId,
                nodeKeyId:`children_${moveParams.SaDocId}`},
                {
                    level:2
                })
        })
    },
  },
};
</script>

<style lang="scss">
@import "./css/catalogTree.scss";
.document-file-page-wrap{
  .file-content{
    p{
      font-size: 16px !important;
    }
  }
}

</style>

<style scoped lang="scss">
@import "./css/basePage.scss";
@import "./css/catalogPage.scss";
.document-file-page-wrap{
  display: flex;
  width: 100%;
  .dialog-container{
    padding: 0 35px;
    .upload-box{
      position:relative;
      width:120px;
      height: 120px;
      background-color: #F5F7F9;
      border: 1px dashed #DCDFE6;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      &:hover{
        border: 1px dashed #409EFF;
        .upload-mask{
          opacity: 1;
        }
      }
      .upload-img,.upload-mask{
        width:100%;
        height:100%;
      }
      .upload-mask{
        position:absolute;
        left: 0;
        top: 0;
        cursor: default;
        text-align: center;
        color: #fff;
        opacity: 0;
        font-size: 20px;
        background-color: rgba(0,0,0,.5);
        transition: opacity .3s;
        z-index: 2;
        line-height: 120px;
        .mask-icon{
          cursor: pointer;
        }
      }
    }
  }
  .file-info{
    padding:20px 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .file-content{
    padding:30px;
  }
}
</style>
