<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 v-if="!isEdit" label="选择术语：" prop="selectedTerm">
                    <el-select v-model="form.selectedTerm"
                               filterable
                               remote
                               clearable
                               value-key="id"
                               ref="termName"
                               placeholder="搜索术语"
                               :remote-method="searchTerms">
                        <el-option v-for="term in terms" :key="term.id" :label="term.name+'-('+term.type+')'" :value="term" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="已选择术语标签：">
                    {{form.selectedTermName}}
                </el-form-item>
                <el-form-item label="术语类型：">
                    {{form.selectedTermType}}
                    <!--<el-select  filterable
                                remote
                                clearable
                                v-model="form.termType"
                                placeholder="搜索术语类型">
                        <el-option v-for="it in termTypes" :label="it.name" :value="it.name" :key="it.id"></el-option>
                    </el-select>-->
                </el-form-item>
                <p class="line"></p>
                <el-form-item label="添加静态知识" style="font-weight: bold">
                </el-form-item>
                <el-form-item label="静态知识来源：" prop="source">
                    <el-input v-if="!isEdit" v-model="form.source" placeholder="输入静态知识来源"></el-input>
                    {{isEdit?form.source:''}}
                </el-form-item>
                <InfoParagraph :data="form.prags[0]"
                               :index="0"
                               :len="1"
                               :isEdit = "isEdit"
                               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 './MedicineInfoPg';

  export default {
    name: 'AddMedicinePrompt',
    components: {
      InfoParagraph
    },
    data() {
      return {
        isEdit:false,
        termTypes:[],
        terms:[],              //术语列表
        editData:{
          selectedTerm:'',
          prags:[]
        },
        form:{
          conceptId:'',             //术语id
          isTip:0,                 //是否要覆盖,0不覆盖，1覆盖
          selectedTerm:'',            //术语标签
          termType:'',
          source:'',
          selectedTermName:'',
          selectedTermType:'',
          prags:[{              //单个段落相关
            title:'',
            content:'',
            isReason:0,
            orderNo:0,
            position:[],
            text:''}]
        },
        rules: {
          source: [
            { required: true, message: '请输入静态知识来源', trigger: 'change' }
          ],
          selectedTerm: [
            { required: true, message: '请选择术语标签', trigger: 'change' }
          ]
        }
      }
    },
    watch:{
      'form.selectedTerm':function(newVal){
        const name = newVal.name;
        //this.editData.selectedTermName = name;
        this.form.selectedTermName = name;
        this.form.selectedTermType = newVal.type;
        this.form.conceptId = newVal.conceptId;
      }
    },
    created:function(){
      const {isEdit,data} = this.$route.params;
      //this.getTermTypes();
      if(isEdit){
        this.isEdit = isEdit;
        /*api.getTremList({term:data.name,type:data.type}).then((res) => {
          if (res.data.code == '0') {
            const data = res.data.data;
            this.form.prags=data.information&&data.information.map((it)=>{
              return {title:it.title,position:this.mapStringToNum(it.position),content:it.content,isReason:it.isReason};
            });
            console.log(data)
          }
        }).catch((error) => {
          console.log(error);
        });*/
        this.form.selectedTermName = data.conceptName;
        this.form.selectedTermType = data.conceptType;
        this.form.source = data.source;
        this.form.conceptId = data.conceptId;
        this.form.prags[0].content = data.content;
        this.form.prags[0].isReason = data.isReason;
        this.form.prags[0].position=this.mapStringToNum(data.position);
        this.form.prags[0].title = data.title;
      }
    },
    methods: {
      back() { this.$router.go(-1) },
      async getTermTypes(){
        let types = localStorage.getItem('termTypes');
        if(!types){
          types = await api.getAllType();
          if(types.data.code=='0'){
            this.termTypes = types.data.data.records;
          }
        }else{
          this.termTypes = JSON.parse(types).records;
        }
      },
      searchTerms(query){
        //搜索术语列表
        api.knowledgeName({term:query,type:''}).then((res) =>{
          if(res.data.code === '0') {
            this.terms = res.data.data.records;
          }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;
          it.$refs.form.validate((valid) =>{
            if(!valid){
              goOn = false;
            }
          });
        //};

        if(!goOn){
          return;
        }
        //通过必填验证，提交保存
        const item=this.form.prags[0];
        const param = Object.assign({},item,{
                                                position:typeof item.position=='string'?item.position:item.position.join(","),
                                                source:this.form.source,
                                                conceptId:this.form.conceptId,isTip:1,
                                              });
        this.showSaveDialog(param,'是否保存该静态知识？');
      },
      showSaveDialog(param,msg) {
        this.showConfirmDialog(msg, () => {
          api.saveTermPrompts(param).then((res) => {
            if (res.data.code === '0') {
              this.warning(res.data.msg || '保存成功', 'success');
              this.$router.push("/admin/LT-YXSYKWH-YXSYJTZSWH");
            } else if(res.data.code === '00000002'){
              //已存在，选择是否覆盖
              this.showSaveDialog(Object.assign({},param,{isTip:0}),res.data.msg);
            } else {
              this.warning(res.data.msg)
            }
          }).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";
    .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;
    }
    }
    .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>

