<template>
<!-- 新增/编辑 文章页 -->
  <div class="document-edit-page">
    <div class="document-info page-block-wrap">
      <el-form
        ref="formRef"
        label-position="left"
        hide-required-asterisk
       
        :model="fileForm"
        :rules="fileFormRules"
      >
        <el-form-item  label-width="118px" :label="$t('SemanticsManage.DocumentComparison.document_name')" prop="Title">
          <el-input
            v-model="fileForm.Title"
            style="width: 240px"
            :placeholder="$t('SemanticsManage.DocumentComparison.select_documents_input')"
          />
        </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-width="80px" :label="$t('SemanticsManage.DocumentComparison.select_category')" prop="ClassifyId">
          <el-select :placeholder="$t('SemanticsManage.DocumentComparison.please_select_category')" 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">{{$t('Dialog.confirm_save_btn')}}</el-button>
      <el-button @click="cancelModify">{{$t('Dialog.cancel_btn')}}</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,placeholderText:$t('SemanticsManage.DocumentComparison.article_content_enter')}" 
        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="$t('SemanticsManage.DocumentComparison.paragraph_content_ipt')" :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>{{$t('SemanticsManage.DocumentComparison.add_next_section')}}</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>{{$t('Table.delete_btn')}}</span>
            </div>
            <p class="hint-text">{{$t('SemanticsManage.DocumentComparison.number_tags_attached')}}：{{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:[],//文档段落列表

      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(this.$t('SemanticsManage.DocumentComparison.least_one_paragraph_msg') )
        return
      }
      this.fileBlockArr.splice(index,1)
    },
    //点击保存按钮
    async saveFile(){
      //每个段落都有值
      if(!this.checkBlock()) return
      //文章有内容
      if(!this.fileId&&!this.documentContent.length){
        this.$message.warning(this.$t('SemanticsManage.DocumentComparison.article_content_enter') )
        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(this.$t('MsgPrompt.add_msg'))
        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(this.$t('MsgPrompt.edit_msg'))
        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(this.$t('SemanticsManage.DocumentComparison.paragraph_content_ipt') )
          return false
        }
      }
      return true
    },
  },
  mounted(){
    this.$refs.formRef.resetFields();
    this.getFileData()
    this.getClassifyList()
  },
  computed: {
    fileFormRules() {
      return {
        Title: [{ required: true, message: this.$t('SemanticsManage.DocumentComparison.document_name_no_empty')  }],
        /* Theme:[
          { required: true, message: "文档主题不能为空"}
        ], */
        ClassifyId: [{ required: true, message: this.$t('SemanticsManage.DocumentManagement.select_document_category_msg')  }],
      };
    },
  },
};
</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>
