<template>
    <div class="NoiseTemplateWrapper TemplateWrapper">
        <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"
                               ref="termName"
                               placeholder="搜索"
                               :remote-method="searchTerms">
                        <el-option v-for="term in terms" :key="term.conceptId" :label="term.nameType" :value="term" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="已选择标准术语：" label-width="160px">
                    {{form.selectedTermName}}
                </el-form-item>
                <p class="line"></p>
                <InfoParagraph v-for="(f,i) in form.prags"
                               :data="f"
                               :index="i"
                               :total="form.prags.length"
                               :isEdit = "isEdit"
                               ref="subForm"
                               @add="addParagraph(i)"
                               @del="delParagraph"
                               @reOrder="reOrder"></InfoParagraph>
            </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:'',
          selectedTermName:'',
          selectedTermType:'',
          prags:[{              //单个段落相关
            title:'',
            content:'',
            isReason:0,
            orderNo:0,
            position:[],
            text:''}]
        },
        rules: {
          selectedTerm: [
            { required: true, message: '请选择术语标签', trigger: 'change' }
          ]
        },
        saveDisable: false,  //保存按钮禁止点击
        showDrop:false,        //下拉框显示文字bug1774
      }
    },
    /*watch:{
      'form.selectedTerm':function(newVal){
        const name = newVal.nameType;console.log(newVal)
        this.form.selectedTermName = name;
        this.form.conceptId = newVal.conceptId;
      }
    },*/
    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);
        //this.form.selectedTerm = data;
        //this.form.selectedTermName = data.libName;
        //this.form.conceptId = data.conceptId;
        api.getTremList({conceptId:data.conceptId}).then((res) => {
          if (res.data.code == '0') {
            const data = res.data.data;
            this.form.prags=data&&data.map((it)=>{
              return {
                        title:it.title,
                        position:this.mapStringToNum(it.position),
                        content:it.content.replace(/{imageUrlPrefix}/g,config.imgHost),
                        isReason:it.isReason,
                        text:it.text,
                        disabled:true};
            });

          }
        }).catch((error) => {
          console.log(error);
        });
      }
    },
    methods: {
      changeWord(newVal){
        const name = newVal.nameType;
        this.form.selectedTermName = name;
        this.form.selectedTerm=name;
        this.form.conceptId = newVal.conceptId;
      },
      reOrder(isUp,i){
        let temp = {},it={};
        if(isUp===1){
          if(i===0){
            this.warning('已经是第一个，不能再升啦！');
            return ;
          }
          temp = Object.assign(this.form.prags[i-1]);
          temp.orderNo = temp.orderNo+1;
          it = Object.assign(this.form.prags[i]);
          it.orderNo = it.orderNo-1;
          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]);
          temp.orderNo = temp.orderNo-1;
          it = Object.assign(this.form.prags[i]);
          it.orderNo = it.orderNo+1;
          this.form.prags.splice(i,2,temp,it);
        }
      },
      addParagraph(i){
        this.form.prags.splice(i+1,0,{
          title:'',
          content:'',
          isReason:0,
          orderNo:i+1,
          position:[],
          text:''});
        //添加段落光标自动落到新增的段落中
        setTimeout(()=>{
          //console.log(this.$refs.subForm[i+1].$el.getElementsByClassName("el-input__inner")[0]);
          this.$refs.subForm[i+1].$el.getElementsByClassName("el-input__inner")[0].focus()
        })
        /*this.form.prags.push({
          title:'',
          content:'',
          isReason:0,
          orderNo:this.form.prags.length,
          position:[],
          text:''});*/
      },
      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()){
            return;
        }
        //搜索术语列表
        this.showDrop = true;
        api.getAllConcept({name:query.trim()}).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() {
        //验证外层表单
        let goOn=true,it=null;
        this.$refs.groups.validate((valid) =>{
          if(!valid){
            goOn = false;
            return false;
          }
        });
        //验证段落表单
        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;
        const param =item.map((it)=>{
          return Object.assign({},it,{
                                        position:typeof it.position=='string'?it.position:it.position.join(","),
                                        conceptId:this.form.conceptId,
                                        content:it.content.replace(new RegExp(config.imgHost,'g'),'{imageUrlPrefix}')});
        });
        this.showSaveDialog(param,'是否保存该静态知识？');
      },
      showSaveDialog(param,msg) {
        this.showConfirmDialog(msg, () => {
          this.saveDisable = true  //提交保存按钮不可点击，返回结果时才可点击，防止频繁发送请求
          api.saveTermPrompts(param).then((res) => {
            if (res.data.code === '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.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'
        })
      },
    }
  }
</script>
<style lang="less">
    @import "../../less/common.less";
    .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;
    }
</style>

