<template>
<!-- 新增/编辑 文章页 -->
  <div class="document-edit-page">
    <div class="document-info page-block-wrap">
      <el-form
        ref="formRef"
        label-position="left"
        hide-required-asterisk
        label-width="80px"
        :model="fileForm"
        :rules="fileFormRules"
      >
        <el-form-item label="文档名称" prop="Title">
          <el-input
            v-model="fileForm.Title"
            style="width: 240px"
            placeholder="请输入文档名称"
          />
        </el-form-item>
<!--         <el-form-item label="文档主题" prop="Theme">
          <el-input
            v-model="fileForm.Theme"
            style="width: 240px"
            placeholder="请输入文档主题"
          />
        </el-form-item> -->
        <el-form-item label="所属分类" prop="ClassifyId">
          <el-select placeholder="请选择所属分类" v-model="fileForm.ClassifyId">
            <el-option 
              v-for="item in classifyOptions" :key="item.SaDocClassifyId"
              :label="item.ClassifyName"
              :value="item.SaDocClassifyId"
              />
          </el-select>
        </el-form-item>
      </el-form>
      <el-button type="primary" style="margin-left:auto;" @click="saveFile">保存</el-button>
      <el-button @click="cancelModify">取消</el-button>
    </div>
    <div class="document-content page-block-wrap" v-if="$route.path.includes('add')">
      <froala :id="`froala-editor-documentContent`" 
        :ref="`froalaEditorDocumentContent`" 
        :tag="'textarea'" 
        :config="froalaConfig" 
        v-model="documentContent"></froala>
    </div>
    <div class="document-content page-block-wrap overflow-hide-scrollbar" v-else>
      <div class="content-block">
        <div class="block-item" v-for="(item,index) in fileBlockArr" :key="index">
            <!-- 若段落内有选定文字被打标签 item.UsePartNum 则不允许编辑段落内容 -->
          <textarea v-model="item.innerText" placeholder="请输入段落内容" :disabled="item.UsePartNum!==0"></textarea>
          <div class="block-item-tool">
            <div class="add-btn" @click="addBlock(index)">
              <img
                src="~@/assets/img/set_m/add_ico.png"
                alt=""
                style="width: 14px; height: 14px; margin-right: 10px"
              />
              <span>添加下一段</span>
            </div>
            <div class="dele-btn" style="margin-left:30px;margin-right:auto;"
              v-if="item.UseNum+item.UsePartNum===0" @click="deleteBlock(index)">
              <img
                src="~@/assets/img/set_m/del_icon.png"
                alt=""
                style="width: 14px; height: 14px; margin-right: 10px"
              />
              <span>删除</span>
            </div>
            <p class="hint-text">已打标签数：{{item.UseNum+item.UsePartNum}}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {froalaConfig} from '../utils/config';
import {formatFile} from '../utils/index';

import {documentInterface} from '@/api/modules/semanticsApi.js';
export default {
  data() {
    return {
      documentContent:'',//文档内容
      froalaConfig:froalaConfig,//富文本配置
      fileForm:{Title:'',/* Theme:'', */ClassifyId:''},//文档信息
      classifyOptions:[],//分类列表
      fileBlockArr:[],//文档段落列表
      fileFormRules:{
        Title: [
          { required: true, message: "文档名称不能为空"}
        ],
        /* Theme:[
          { required: true, message: "文档主题不能为空"}
        ], */
        ClassifyId:[
          { required: true, message: "请选择文档分类"}
        ]
      },
      fileId:0,//为0时是新增 不为0时是文档id
    };
  },
  methods: {
    //获取分类列表
    getClassifyList(){
      documentInterface.getClassifyList().then(res=>{
        if(res.Ret!==200) return 
        this.classifyOptions = res.Data||[]
      })
    },
    //获取文档详情
    getFileData(){
      const {fileId} = this.$route.query
      if(fileId&&Number(fileId.split('_')[1])){
        this.fileId = Number(fileId.split('_')[1])
        documentInterface.getDocumentDetail({DocId:this.fileId}).then(res=>{
          if(res.Ret!==200) return
          const {Title,/* Theme, */ClassifyId} = res.Data
          this.fileForm = {
            Title,/* Theme, */ClassifyId
          }
          this.fileBlockArr = formatFile(res.Data).SectionList
        })
      }else{
        this.fileForm = {Title:'',/* Theme:'', */ClassifyId:''}
      }
    },
    //添加一段
    addBlock(index){
      let block = {
        SaDocSectionId:0,
        DocId:this.fileId,
        Content:'',
        innerText:'',
        Sort:index+1,//其实这个无所谓
        UseNum:0,
        UsePartNum:0
      }
      this.fileBlockArr.splice(index+1,0,block)
    },
    //删除一段
    deleteBlock(index){
      if(index===0&&this.fileBlockArr.length===1){
        this.$message.warning('请至少保留一段')
        return
      }
      this.fileBlockArr.splice(index,1)
    },
    //点击保存按钮
    async saveFile(){
      //每个段落都有值
      if(!this.checkBlock()) return
      //文章有内容
      if(!this.fileId&&!this.documentContent.length){
        this.$message.warning('请输入文章内容')
        return
      }
      let flag = false
      this.$refs.formRef.validate((valid) => {
        flag = valid
      })
      //文档信息已填写
      if(!flag) return 
      if(this.fileId===0){
        this.addFile()
      }else{
        this.editFile()
      }
    },
    //新增文档
    addFile(){
      const {Title,/* Theme, */ClassifyId} = this.fileForm
      documentInterface.addDocument({
        Title,/* Theme, */ClassifyId,Content:this.documentContent
      }).then(res=>{
        if(res.Ret!==200) return 
        this.$message.success('新增成功')
        const SaDocId = res.Data?res.Data:''
        sessionStorage.setItem('fileClassify',ClassifyId+'')
        sessionStorage.setItem('fileId',SaDocId+'')
        this.$router.push('/documentPage')
      })
    },
    //编辑文档
    editFile(){
      const {Title,/* Theme, */ClassifyId} = this.fileForm
      //按index排序fileBlockArr
      this.fileBlockArr = this.fileBlockArr.map((item,index)=>{
        item.Sort = index+1
        item.Content = item.innerText
        return item
      })
      documentInterface.editDocument({
        SaDocId:this.fileId,
        Title,/* Theme, */ClassifyId,
        SectionList:this.fileBlockArr
      }).then(res=>{
        if(res.Ret!==200) return 
        this.$message.success('编辑成功')
        sessionStorage.setItem('fileClassify',ClassifyId+'')
        sessionStorage.setItem('fileId',this.fileId+'')
        this.$router.push('/documentPage')
      })
    },
    cancelModify(){
        if(this.fileId!==0){
            sessionStorage.setItem('fileClassify',this.fileForm.ClassifyId+'')
            sessionStorage.setItem('fileId',this.fileId+'')
        }
        this.$router.push('/documentPage')
    },
    checkBlock(){
      for(let i=0;i<this.fileBlockArr.length;i++){
        if(!this.fileBlockArr[i].innerText.length){
          this.$message.warning('请输入段落内容')
          return false
        }
      }
      return true
    },
  },
  mounted(){
    this.$refs.formRef.resetFields();
    this.getFileData()
    this.getClassifyList()
  }
};
</script>
<style lang="scss">
.document-fr-custom-class{
  height: 100%;
  display: flex;
  flex-direction: column;
  .fr-wrapper{
    flex: 1;
    .fr-element{
      height:100%
    }
  }
}
</style>
<style scoped lang="scss">
@import "../css/basePage.scss";
.document-edit-page{
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(100vh - 120px);
  .document-info{
    padding:20px 30px;
    display: flex;
    justify-content: space-between;
    .el-form{
      display: flex;
      .el-form-item{
        margin-right: 30px;
        margin-bottom: 0px;
      }
    }
  }
  .document-content{
    margin-top: 20px;
    flex: 1;
    padding: 30px;
    &.overflow-hide-scrollbar{
      overflow-y: scroll;
    }
    .content-block{
      .block-item{
        margin-bottom: 25px;
        textarea{
          width:100%;
          height:180px;
          border: 1px solid #DCDFE6;
          padding:5px 15px;
          border-radius: 4px;
          font-size: 18px;
          color:#666666;
          line-height: 28px;
          resize: vertical;
        }
        .block-item-tool{
          margin-top: 5px;
          color: #409eff;
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 14px;
          .add-btn,.dele-btn{
            cursor: pointer;
            display: flex;
            align-items: center;
          }
          .dele-btn{
            color:#C54322;
          }
          .hint-text{
            color:#999999;
          }
        }
      }
    }
  }
}
</style>
