<template>
    <div class="NoiseTemplateWrapper TemplateWrapper knowledgeWrapper">
        <crumbs
          :title="'医学术语静态知识维护-'+title"
          class="topBack"
          :param="$route.params"
          linkTo="MedicinePrompt"
        ></crumbs>
        <div class="info-container">
            <el-form :rules="rules"
                     :model="form"
                     label-width="160px"
                     ref="groups">
                <el-form-item v-if="!isEdit" label="选择标准术语：" prop="selectedTerm">
                    <el-select v-model="form.selectedTerm"
                               filterable
                               remote
                               clearable
                               :loading="showDrop"
                               loading-text="加载中..."
                               @change="changeWord"
                               value-key="conceptId"
                               @clear="handleClear"
                               ref="termName"
                               placeholder="搜索"
                               :remote-method="searchTerms">
                        <el-option v-for="(term,idx) in terms" :key="idx" :label="term.name+(term.typeName?'('+term.typeName+')':'')" :value="term" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="已选择标准术语：" label-width="160px">
                    {{form.selectedTermName}}
                </el-form-item>
                <el-form-item v-if="form.selectedTerm&&(form.typeId==1||form.typeId==3||form.typeId==4||form.typeId==5)" :label="titleChange" prop="titleChange" label-width="160px">
                        <el-input v-model="form.titleChange"></el-input>
                </el-form-item>
                <p class="line"></p>
                <InfoParagraph v-for="(f,i) in form.prags"
                               v-if="!upload"
                               :key="i"
                               :data="f"
                               :index="i"
                               :total="form.prags.length"
                               :isEdit = "isEdit"
                               ref="subForm"
                               @add="addParagraph(i)"
                               @del="delParagraph"
                               @reOrder="reOrder"></InfoParagraph>
                <el-form-item   v-if="upload" label="标题名称：" prop="fileTitle" label-width="160px">
                        <el-input v-model="form.fileTitle"></el-input>
                </el-form-item>
                 <el-form-item  v-if="upload" label="上传文件：" ref="upload" prop="fileList" label-width="160px">
                      <el-upload 
                          @mouseenter.native="handleMouseenter"                        
                          @mouseleave.native="handleMouseleave"                        
                          class="upload-demo"
                          :action="config.urls.promptServer"
                          name="upfile"
                          :multiple=false
                          :limit="1"
                          :on-preview="handlePreview"
                          :on-remove="handleRemove"
                          :before-upload="handleBeforeUpLoad"
                          :before-remove="beforeRemove"
                          :on-change="handleChange"	
                          :on-success="handleSuccess"
                          :show-file-list="showFileList"
                          :file-list="form.fileList">
                          <el-button size="small" type="primary" v-if="showUpLoad">点击上传</el-button>
                             <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                      </el-upload>
                      <span class="tipInfo" v-show="isShowTip">{{form.fileList[0]&&form.fileList[0].name}}</span>
                      <!-- <el-button size="small" type="primary" >点击上传</el-button> -->
                </el-form-item>
                <el-form-item  label-width="160px"><div class="uploadInfo" v-if="isSuccessUpload===1">文件上传中，请稍等...</div></el-form-item>
                
            </el-form>
            <div class="btn">
                <el-button
                        type="primary"
                        :disabled = 'saveDisable'
                        @click="submitForm"
                >确 定</el-button>
            </div>
        </div>
    </div>
</template>
<script>
  /**
   *
   */
  import api from '@api/icss.js';
  import InfoParagraph from './MedicineInfoPg';
  import config from '@api/config';

  export default {
    name: 'AddMedicinePrompt',
    components: {
      InfoParagraph
    },
    data() {
      return {
        isEdit:false,
        isCopy:false,
        title:'添加',
        termTypes:[],
        terms:[],              //术语列表
        form:{
          conceptId:'',             //术语id
          isTip:0,                 //是否要覆盖,0不覆盖，1覆盖
          selectedTerm:'',            //术语标签
          termType:'',
          typeId:'',
          selectedTermName:'',
          selectedTermType:'',
          titleChange:'',
          fileList:[],
          name:'',
          prags:[{              //单个段落相关
            title:'',
            content:'',
            isReason:0,
            orderNo:0,
            position:[],
            text:''}
          ],
          fileTitle:'',
          titleChange:''          
        },
        rules: {
          selectedTerm: [
            { required: true, message: '请选择术语标签', trigger: 'change' }
          ],
           fileTitle: [
            { required: true, message: '请输入标题名称', trigger: 'change' },
            { validator: (rule,value,callback)=>{
                if(value.length>30){
                  callback(new Error('标题名称不能超过30字'));
                }else{
                  callback();
                }
                }, trigger: 'change' }
          ],
          fileList: [
             { required: true, message: '请上传文件', trigger: 'change' },             
          ]
        },
        saveDisable: false,  //保存按钮禁止点击
        showDrop:false,        //下拉框显示文字bug1774
        config:config,
        showUpLoad:true,
        showFileList: false,
        upload: false,
        showConfirm: true,
        isSuccessUpload: 0, //是否上传成功  0: 不在上传  1: 上传过程中  2: 上传成功
        isShowTip: false
      }
    },
    created:function(){
      const {isEdit,data,isCopy} = this.$route.params;
      if(isEdit||isCopy){
        this.isEdit = isEdit;
        this.isCopy = isCopy;
        this.title = isEdit?'编辑':(isCopy?'复制':'添加');
        isEdit&&this.changeWord(data);
        api.getTremList({id:data.id}).then((res) => {
          if (res.data.code == '0') {
            const data = res.data.data;
            if(this.form.typeId === 82 || this.form.typeId === 83){
              // console.log('data',data)
             this.form.fileList=data&&data.map((it)=>{
                return JSON.parse(it.content);
              });
              this.showFileList = true
              this.showUpLoad = false
            }else{
              this.conceptId = data.id
              this.form.typeId = data.type
              this.form.name = data.name
              this.form.titleChange = data.type==1?data.clinicalPathwayName:(data.type==3||data.type==4||data.type==5)?data.noticeName:''
              this.form.selectedTermName = data.name+(data.typeName?'('+data.typeName+')':'')
              this.form.selectedTerm = data.name+(data.typeName?'('+data.typeName+')':'')
              this.form.prags=data&&data.details.map((it)=>{
                return {
                    title:it.title,
                    position:this.mapStringToNum(it.contentType  ),
                    content:it.content.replace(/{imageUrlPrefix}/g,config.imgHost),
                    // isReason:it.isReason,
                    text:it.text,
                    disabled:true};
              });
            }

          }
        }).catch((error) => {
          console.log(error);
        });
      }
    },
    mounted(){
    },
    beforeRouteLeave (to, from, next) {     
       if(this.isSuccessUpload === 1 ) {
        this.$confirm('文件正在上传，是否确定返回？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass:'cancel',
          type: 'warning'
        }).then(() => {
           next()
        }).catch(() => {
                  
        });
        //  this.warning('还有未保存的文件，是否确定返回？');        
       }else if( this.isSuccessUpload === 2) {
         this.$confirm('还有未保存的文件，是否确定返回？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass:'cancel',
          type: 'warning'
          }).then(() => {
            next()
          }).catch(() => {                   
          });
       }else {
         next()
       }

    },
    methods: {
      handleClear(){
        this.form.selectedTermName = ''
        this.form.selectedTerm = ''
      },

      handleMouseenter(){
        if(this.form.fileList.length !== 0 ){
          this.isShowTip = true
        }
      },
      handleMouseleave(){
        this.isShowTip = false
      },
      changeWord(newVal){
        const name = newVal.name;
        const typeName = newVal.typeName;
        const type = newVal.type;
        this.form.selectedTermName = name+(typeName?'('+typeName+')':'');
        this.form.selectedTerm=name+(typeName?'('+typeName+')':'');
        this.form.name=name
        this.form.fileList=[]
        this.showFileList = false
        this.form.typeId = type || ""
        this.showUpLoad = true
        this.titleChange = type==1?'临床路径标题：':type==3||type==4||type==5?'注意事项标题：':''
        this.form.fileTitle = "" 
        if(newVal.typeId === 82 || newVal.typeId === 83){
          this.upload = true
          this.form.fileTitle = newVal.title
        }else{
          this.upload = false
        }
      },
      
      reOrder(isUp,i){
        let temp = {},it={};
        if(isUp===1){
          if(i===0){
            this.warning('已经是第一个，不能再升啦！');
            return ;
          }
          temp = Object.assign(this.form.prags[i-1]);
          it = Object.assign(this.form.prags[i]);
          this.form.prags.splice(i-1,2,it,temp);
        }else{
          if(i===this.form.prags.length-1){
            this.warning('已经是最后一个，不能再降啦！');
            return ;
          }
          temp = Object.assign(this.form.prags[i+1]);
          it = Object.assign(this.form.prags[i]);
          this.form.prags.splice(i,2,temp,it);
        }
      },
      addParagraph(i){
        this.form.prags.splice(i+1,0,{
          title:'',
          content:'',
          isReason:0,
          position:[],
          text:''});
        //添加段落光标自动落到新增的段落中
        setTimeout(()=>{
          this.$refs.subForm[i+1].$el.getElementsByClassName("el-input__inner")[0].focus()
        })
      },
      delParagraph(i){
        if(this.form.prags.length==1){
          this.warning('只剩一个段落，不能再删啦！');
          return;
        }
        this.showConfirmDialog('确定要删除该段落？', () => {
          this.form.prags.splice(i,1);
        });
      },
      back() { this.$router.go(-1) },
      searchTerms(query){
        if(!query.trim()){
            this.form.terms = []
            return;
        }
        //搜索术语列表
        this.showDrop = true;
        api.getAllConcept({inputStr:query.trim(),types:[0]}).then((res) =>{
          this.showDrop = false;
          if(res.data.code === '0') {
            this.terms = res.data.data;
          }else{
            this.warning("数据获取失败");
          }
        })
      },
      mapStringToNum(str){
        return str.split(",").map((it)=>{
          return +it;
        })
      },
      submitForm() {
        if(this.isSuccessUpload === 1) {
          this.warning('文件上传中，请稍等')
          return 
        }

        //验证外层表单
        let goOn=true,it=null;
        this.$refs.groups.validate((valid) =>{
          if(!valid){
            goOn = false;
            return false;
          }
        });
        //验证段落表单
        if(this.form.typeId !== 82 && this.form.typeId !== 83){
          for(let i=0;i<this.$refs.subForm.length;i++){
            it=this.$refs.subForm[i];
            it.$refs.form.validate((valid) =>{
              if(!valid){
                goOn = false;
              }
            });
          };
        }
        

        if(!goOn){
          return;
        }
        //通过必填验证，提交保存
        const item=this.form.prags;
        let param= []
        if(this.form.typeId === 82 || this.form.typeId === 83){
           if(this.form.fileList.length === 0){
             this.warning("文件未上传，不存储数据")
             return
           }
            param.push(Object.assign({},{
                    position: this.form.typeId === 82 ? "8" : "9",
                    conceptId:this.form.conceptId,
                    title: this.form.fileTitle,
                    orderNo:0,
                    content:JSON.stringify(this.form.fileList[0]),
          }))
         
        }else {
          let data = this.form.prags,tempArr=[],paramsAll={},types = this.form.typeId;
          for(let i = 0;i < data.length;i++){
            let obj = {}
            obj.content = data[i].content
            obj.text = data[i].text
            obj.conceptId = data[i].conceptId
            obj.orderNo = i
            obj.title = data[i].title
            obj.contentType = data[i].position.join(',')
            tempArr.push(obj)
          }
          paramsAll.clinicalPathwayName = types==1?this.form.titleChange:''
          paramsAll.id = this.conceptId
          paramsAll.name = this.form.name
          paramsAll.noticeName = types==3||types==4||types==5?this.form.titleChange:''
          paramsAll.type = this.form.typeId
          paramsAll.details = tempArr
          param = paramsAll

        }
        this.showSaveDialog(param,'是否'+(this.isEdit?'修改':'保存')+'该静态知识？');
      },
      showSaveDialog(param,msg) {
        this.showConfirmDialog(msg, () => {
          this.saveDisable = true  //提交保存按钮不可点击，返回结果时才可点击，防止频繁发送请求
          api.saveTermPrompts(param).then((res) => {
            if (res.data.code === '0') {
              this.isSuccessUpload = 0 // 修改文件上传状态为0
              this.warning(res.data.msg || '保存成功', 'success');
              //返回带搜索条件的首页
              this.$router.push({name:'MedicinePrompt',params:Object.assign({},this.$route.params,{currentPage:1})});
            } else {
              this.warning(res.data.msg)
            }
            this.saveDisable = false
          }).catch((err) => {
            this.saveDisable = false
            this.warning(err);
          })
        });
      },
      showConfirmDialog(msg, resolve) {
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass:'cancel',
          type: 'warning'
        }).then(() => {
          resolve();
        }).catch(() => {});
      },
      warning(msg, type) {
        this.$message({
          showClose: true,
          message: msg,
          type: type || 'warning'
        })
      },
      handleChange(file, fileList){
        // if(fileList&&fileList[0]&&fileList[0].response&&fileList[0].response.code==='0'){
        //   this.showUpLoad = false
        //   this.showFileList = true
        // }else{
        //    this.showUpLoad = true
        //    this.showFileList = false
        // }
        // console.log(fileList,this.form.fileList,'aa')
        
      },
      handleSuccess(response, file, fileList){
        if(response.code == "0"){
          this.showFileList=true
          this.form.fileList=[]
           this.form.fileList.push({
             name: response.data.title, 
             url: response.data.url,
             size: response.data.size
           })
             this.showUpLoad = false
           if(!this.form.fileTitle){
              
             this.form.fileTitle = response.data.title
           }
           this.isSuccessUpload = 2 // 上传成功状态
           this.$refs.upload && this.$refs.upload.clearValidate()  // 清除校验
        }else{
          this.warning(response.msg||'上传失败')
          // this.form.fileList = []
          this.showUpLoad = true
           this.showFileList=false
           this.form.fileList=[]
        }
      },
      handleRemove(file, fileList) {
           this.showUpLoad = true
            this.form.fileList=[]
            this.isSuccessUpload = 0
      },
      handleBeforeUpLoad(file){
        // 上传过程中   上传按钮 隐藏
        this.isSuccessUpload = 1  // 上传过程中
        this.showFileList = true  // 新增 进度条  显示
        this.$refs.upload && this.$refs.upload.clearValidate()  // 清除校验

        this.showUpLoad = false
        if(file.size/1024/1024 >= 500){
           this.warning('文件上传失败，超出大小限制500MB')
           this.form.fileList=[]
           this.showConfirm = false
           return false
        }else{
          this.showConfirm = true
        }
      },
      handlePreview(file) {

      },
      beforeRemove(file, fileList) {
        if(this.showConfirm ){
           return this.$confirm(`确定移除 ${ file.name }？`,'',{
             cancelButtonClass:"cacelBtn"
            });
        }
       
      }
    }
  }
</script>
<style lang="less">
    @import "../../less/common.less";
    .cell .el-button.delete:focus {
        color: red !important;
    }

    .topBack{
      top: 0;
    }
    .info-container{
        background: #fff;
        padding: 20px;
        margin: 70px 20px -20px 20px;
    .el-input__inner{
        width: 200px;
    }
    .el-form-item__label{
        text-align: left;
    }
    .add-prg .el-form-item{
        margin-bottom: 20px;
    }
    }
    .cancel span{
        color: #22ccc8;
    }
    .line{
        border-top:1px #dcdfe6 solid;
        margin-bottom: 25px;

    }
    .NoiseTemplateWrapper .info-container .el-input__inner{
       width: 250px;
    }
    // .NoiseTemplateWrapper .el-select .el-input .el-icon-circle-close{
    //     display: inherit!important;
    // }
    .cacelBtn{
      color: #22ccc8!important;
    }
    .upload-demo{
      width: 300px;
      /deep/.el-upload-list__item .el-icon-close-tip{
        display: none !important;
      } 

      /deep/.el-upload-list__item .el-upload-list__item-name {
        max-width: 250px;
        white-space:nowrap;
        overflow:hidden;
        text-overflow:ellipsis;
      }
      /deep/ .focusing{
        // border: 1px solid transparent !important;
        outline: transparent !important;
      }

    }
    .uploadInfo{
      margin-top: -20px;
      color: #606266;
    }
    .tipInfo{
      position: absolute;
      // position: relative;
      line-height: 24px;
      top: -56px;
      left: 20px;
      // background-color: transparent;
      // color: #606266;
      padding: 3px 10px;
      border-radius: 4px;
      margin: 100px auto;
      background-color: #4D4D4D;
      text-align: center;
      color: #fff;
      font-size: 14px;
    }
    .tipInfo:before{
      content: '';
      display: block;
      position: absolute;
      // bottom: 9px;
      top: -10px;
      left: 18px;
      border-bottom: 6px solid #4D4D4D;
      border-top: 6px solid transparent;
      border-left: 6px solid transparent;
      border-right: 6px solid transparent;
      // border-right: 6px solid #4D4D4D;
    }
    .btn {
      text-align: right;
      padding-right: 20px;
    }

 
</style>

