<template>
  <!-- 文档管理 -->
  <div class="document-file-page-wrap">
    <!-- 目录栏 -->
    <div class="catalog-wrap page-block-wrap catalog-block" id="left">
      <div class="btn-box">
        <el-button v-permission="permissionBtn.semanticPermission.docPage_save"
            type="primary" @click="toPage('addFile')">{{$t('SemanticsManage.DocumentManagement.add_document_btn')}}</el-button>
      </div>
      <div class="select-wrap">
        <el-select
          filterable remote
          :placeholder="$t('SemanticsManage.DocumentComparison.input_enter_fiel_content')"
          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&&isShowTreeBtn(node.level,'edit')"
                    style="width: 14px; height: 14px; margin-right: 5px"
                    @click.stop="clickNodeHandle('edit', data)"
                  />
                  <img
                    :src="require('@/assets/img/data_m/move_ico.png')"
                    alt="" v-if="node.level === 2"
                    style="width: 14px; height: 14px; margin-right: 5px"
                  />
                  <img
                    :src="require('@/assets/img/set_m/del.png')"
                    alt="" v-if="isShowTreeBtn(node.level,'delete')"
                    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" v-if="isShowTreeBtn(1,'edit')">
          <img
            src="~@/assets/img/set_m/add_ico.png"
            alt=""
            style="width: 16px; height: 16px; margin-right: 6px"
          />
          <span>{{$t('SemanticsManage.DocumentManagement.add_category')}}</span>
        </div>
        <span class="total-text" v-if="selectNode&&model==='list'">
          {{$t('SemanticsManage.DocumentManagement.all_num_document',{num: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="$t('Table.prompt_slogan')"/>
          </div>
      </div>
      <!-- 文件详情 -->
      <div class="detail-file" v-else>
        <div class="file-info">
          <ul>
            <li class="name">{{$t('SemanticsManage.DocumentComparison.document_name')}}:{{docInfo.Title}}</li>
            <!-- <li>文档主题:{{docInfo.Theme}}</li> -->
            <li>{{$t('SemanticsManage.DocumentComparison.document_category')}}:{{docInfo.ClassifyName}}</li>
          </ul>
          <el-button v-permission="permissionBtn.semanticPermission.docPage_save"
            type="primary" @click="handleEdit('file',selectNode)">{{$t('Table.edit_btn')}}</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? $t('SemanticsManage.DocumentManagement.edit_category') : $t('SemanticsManage.DocumentManagement.add_category') "
      :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
          :model="classifyForm"
          :rules="classifyFormRules"
        >
          <el-form-item label-width="118px" :label="$t('SemanticsManage.DocumentManagement.add_category_name')" prop="classify_name">
            <el-input
              v-model="classifyForm.classify_name"
              style="width: 80%"
              :placeholder="$t('SemanticsManage.DocumentManagement.add_category_input_name')"
            />
          </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">{{ $t('Dialog.cancel_btn')}}</el-button>
        <el-button type="primary" @click="modifyClassify">{{ $t('Dialog.confirm_btn')}}</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:{},//分类信息
      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 ? this.$t('MsgPrompt.edit_msg') : this.$t('MsgPrompt.add_msg') }`)
      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.$t('MsgPrompt.delete_msg'))
        this.clearForm()
      })
    },
    //删除文档
    async deleteDocument(data){
      await documentInterface.deleteDocument({
        SaDocId:Number(data.SaDocId)
      }).then(async res=>{
        if(res.Ret!==200) return
        this.$message.success(this.$t('MsgPrompt.delete_msg'))
        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(this.$t('SemanticsManage.DocumentManagement.select_img_mag') )
        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(this.$t('SemanticsManage.DocumentManagement.img_no_empty_msg') ))
      }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
            })
            this.$message.success(this.$t('ETable.Msg.move_success_msg') )
        })
    },
    //根据层级判断是否展示编辑/删除按钮
    isShowTreeBtn(level,btnType){
        return level===1
            ?this.permissionBtn.isShowBtn('semanticPermission',`docPage_classifyOpt_${btnType}`)
            :this.permissionBtn.isShowBtn('semanticPermission',`docPage_${btnType==='edit'?'save':btnType}`)
    }
  },
  computed:{
   classifyFormRules(){
    return {
        classify_name:[{ required: true, message:this.$t('Chart.Vailds.classify_msg') }],
      }//分类校验规则
   }
  }
};
</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>
