<template>
    <div class="NoiseTemplateWrapper TemplateWrapper">
        <div class="groupTitle"><i
                class="el-icon-back"
                @click="back"
        ></i> 医学静态知识--{{isEdit?'修改':'添加'}}</div>
        <div class="info-container">
            <el-form :rules="rules"
                     :model="form"
                     label-width="130px"
                     ref="groups">
                <el-form-item label="选择术语标签：" prop="selectedTerm">
                    <el-select v-model="form.selectedTerm"
                               :disabled="isEdit"
                               filterable
                               remote
                               clearable
                               value-key="libId"
                               ref="termName"
                               placeholder="搜索术语"
                               :remote-method="searchTerms">
                        <el-option v-for="term in terms" :key="term.libId" :label="term.name" :value="term" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="已选择术语标签：">
                    {{form.selectedTermName}}
                </el-form-item>
                <el-form-item label="添加静态知识">
                </el-form-item>
                <InfoParagraph v-for="(f,i) in form.prags"
                               :data="f"
                               :index="i"
                               :isEdit = "isEdit"
                               @change="getPgValues"
                               @add="addParagraph"
                               @del="delParagraph" ref="subForm"></InfoParagraph>
            </el-form>
            <div class="btn">
                <el-button
                        type="primary"
                        @click="submitForm"
                >确 定</el-button>
            </div>
        </div>
    </div>
</template>
<script>
  /**
   *
   */
  import api from '@api/icss.js';
  import InfoParagraph from './InfoParagraph';

  export default {
    name: 'AddMedicinePrompt',
    components: {
      InfoParagraph
    },
    data() {
      return {
        isEdit:false,
        terms:[],              //术语列表
        editData:{
          selectedTerm:'',
          prags:[]
        },
        form:{
          selectedTerm:'',            //术语标签
          selectedTermName:'',
          prags:[{              //单个段落相关
            title:'',
            content:'',
            isReason:0,
            orderNo:0,
            position:[],
            text:''}]
        },
        rules: {
          selectedTerm: [
            { required: true, message: '请选择术语标签', trigger: 'change' }
          ]
        }
      }
    },
    watch:{
      'form.selectedTerm':function(newVal){
        const name = newVal.name;
        this.form.selectedTermName = name;
      }
    },
    created:function(){
      const {isEdit,data} = this.$route.params;
      if(isEdit){
        this.isEdit = isEdit;
      }
    },
    methods: {
      back() { this.$router.go(-1) },
      searchTerms(query){
        //搜索术语列表
        api.getConceptInfo({term:query,type:''}).then((res) =>{
          if(res.data.code === '0') {
            this.terms = res.data.data;
          }else{
            this.warning("数据获取失败");
          }
        })
      },
      mapStringToNum(str){
        return str.split(",").map((it)=>{
          return +it;
        })
      },
      parseData(info){
        let detail = [];
        info.details.forEach((it)=>{
          detail.push(Object.assign({},it,{position:this.mapStringToNum(it.position)}));
        });
        return {
          name:info.name,
          tagFor:info.questionList[0].type+'',
          selectedTags:info.questionList,
          prags:detail
        };
      },
      addParagraph(){
        this.form.prags.push({title:'',
          content:'',
          isReason:0,
          orderNo:0,
          position:[],
          text:''});
      },
      delParagraph(i){
        if(this.form.prags.length==1){
          this.warning('只剩一个段落，不能再删啦！');
          return;
        }
        this.showConfirmDialog('确定要删除该段落？', () => {
          this.form.prags.splice(i,1);
        });
      },
      getPgValues(i,data){
        this.form.prags[i] = data;
        //console.log(data,this.form.prags);
      },
      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 param = {
          name:this.form.selectedTerm.libId,
          detailVOList:Object.assign(this.form.prags)
        };
        console.log(param);
        this.showSaveDialog(param);
      },
      showSaveDialog(param) {
        this.showConfirmDialog('是否保存该静态知识？', () => {
          api.saveTermPrompts(param).then((res) => {
            if (res.data.code === '0') {
              this.warning(res.data.msg || '保存成功', 'success');
              this.$router.push("/admin/LT-YXSYKWH-YXSYJTZSWH");
            } else {
              this.warning(res.data.msg)
            }
          }).catch((err) => {
            this.warning(err);
          })
        });
      },
      showConfirmDialog(msg, resolve) {
        this.$alert(msg, '提示', {
          confirmButtonText: '确定',
          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";
    .info-container{
        background: #fff;
        padding: 20px;
        margin: 20px 20px -20px 20px;
    .el-input__inner{
        width: 200px;
    }
    .el-form-item__label{
        text-align: left;
    }
    .add-prg .el-form-item{
        margin-bottom: 20px;
    }
    }
    .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>

