<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="name">
                    <el-input v-model="form.name" :disabled="isEdit"></el-input>
                </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>
                <p class="line"></p>
                <el-form-item label="关联标签：" prop="tags">
                    <el-form-item label="标签归属：">
                        <el-select placeholder="标签归属" v-model="form.tagFor" clearable>
                            <el-option v-for="item in Adscriptions" :label="item.name" :value="item.val" :key="item.id" ></el-option>
                        </el-select>
                    </el-form-item>
                    <TagPool :pool="tagPool"
                             :type="form.tagFor"
                             :selected="editData.selectedTags"
                             @changeActionData="changeActionData"></TagPool>
                </el-form-item>
                </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 utils from '@api/utils.js';
  import TagPool from './PromptTagPool';
  import schema from 'async-validator';
  import InfoParagraph from './InfoParagraph';

  export default {
    name: 'AddPromptInfo',
    components: {
      TagPool,
      InfoParagraph
    },
    data() {
      const validateTags = (rule,value,callback)=>{
        if(this.form.selectedTags.length==0){
          this.warning('请选择关联标签！');
          return;
        }
        callback();
      };
      return {
        isEdit:false,
        tagPool:[],                 //标签池数据
        Adscriptions:[],            //归属列表
        editData:{
          tagFor:'',
          selectedTags:[],
          prags:[]
        },
        form:{
          name:'',
          tagFor:'',
          selectedTags:[],            //关联标签
          prags:[{              //单个段落相关
            title:'',
            content:'',
            isReason:0,
            orderNo:0,
            position:[],
            text:''}]
        },
        rules: {
          name: [
            { required: true, message: '静态知识名称不能为空', trigger: 'change' }
          ],
          tags:[
            { required: true, validator: validateTags, trigger: 'submit' }
          ]
        }
      }
    },
    created:function(){
      const {isEdit,data} = this.$route.params;
      this.getDropList();           //标签归属列表获取
      if(isEdit){
        this.isEdit = isEdit;
        const id = data.id;
        api.getPrompDetail({id}).then((res) =>{
          if(res.data.code === '0') {
            this.form = this.parseData(res.data.data);
            this.editData = Object.assign({},this.form);
          }else{
            this.warning("数据获取失败");
          }
        })
      }
    },
    methods: {
      back() { this.$router.go(-1) },
      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);
      },
      getDropList() {
        return api.getDropList().then((res) =>{
          if(res.data.code === '0') {
            this.Adscriptions = res.data.data[1];
          }
        })
      },
      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.name,
          detailVOList:Object.assign(this.form.prags),
          mapVOList:Object.assign(this.form.selectedTags)
        };
        //console.log(param);
         this.showSaveDialog(param);
      },
      parseTagsForSubmit(data){
        return data.map((it)=>{
          return {questionId:it.id,introduceId:'',type:it.type};
        });
      },
      changeActionData(selectedTags){
        this.form.selectedTags = this.parseTagsForSubmit(selectedTags);
        //console.log(selectedTags)
      },
      showSaveDialog(param) {
        this.showConfirmDialog('是否保存该静态知识？', () => {
          api.savePrompts(param).then((res) => {
            if (res.data.code === '0') {
              this.warning(res.data.msg || '保存成功', 'success');
              this.$router.push("/admin/LT-YXSJWH-TSXXWH");
            } 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;
    }
</style>

