<template>
    <div class="NoiseTemplateWrapper TemplateWrapper">
        <crumbs :title="isEdit?'提示信息维护-修改':'提示信息维护-添加'"
                class="topBack"
                linkTo="PromptInfo"></crumbs>
        <div class="pinfo-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"
                               @add="addParagraph(i)"
                               @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="form.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 TagPool from './PromptTagPool';
  import InfoParagraph from './InfoParagraph';
  import config from '@api/config.js';

  export default {
    name: 'AddPromptInfo',
    components: {
      TagPool,
      InfoParagraph
    },
    data() {
      const validateTags = (rule,value,callback)=>{
        /*if(this.form.selectedTags.length==0){
          this.warning('请选择关联标签！');
          return false;
        }*/
        callback();
      };
      return {
        isEdit:false,
        tagPool:[],                 //标签池数据
        Adscriptions:[],            //归属列表
        editData:{
          id:'',
          tagFor:'',
          selectedTags:[],
          prags:[]
        },
        form:{
          name:'',
          tagFor:'',
          selectedTags:[],            //关联标签
          prags:[{              //单个段落相关
            title:'',
            content:'',
            isReason:0,
            orderNo:0,
            position:[],
            text:''}]
        },
        rules: {
          name: [
            { required: true, message: '静态知识名称不能为空', trigger: 'change' },
            { validator: (rule,value,callback)=>{
              if(value.length>120){
                callback(new Error('静态知识名称不能超过120字'));
            }else{
              callback();
              }}, trigger: 'change' }
          ],
          tags:[
            { required: true,validator:validateTags, message: '关联标签必填', trigger: 'change' }
          ]
        }
      }
    },
    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);
            //this.len=res.data.data.details&&res.data.data.details.length;
          }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),content:it.content.replace('{imageUrlPrefix}',config.imgHost),disabled:true}));
        });
        return {
          id:info.id,
          name:info.name,
          tagFor:info.questionList?info.questionList[0].type+'':'',
          selectedTags:info.questionList||[],
          prags:detail
        };
      },
      addParagraph(i){
        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);
        });
      },
      /*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;
        }
        if(!this.form.selectedTags||this.form.selectedTags.length==0){
          this.warning('请选择关联标签！');
          return;
        }
        //通过必填验证，提交保存
       const param = {
          id:this.editData.id||undefined,
          name:this.form.name,
          detailVOList:this.parsePosition(this.form.prags),
          mapVOList:this.parseTagsForSubmit(this.form.selectedTags)
        };
        this.showSaveDialog(param);
      },
      parsePosition(data){
        const arr = data.map((it)=>{
          return Object.assign({},it,{position:typeof it.position=='string'?it.position:it.position.join(","),content:it.content.replace(config.imgHost,'{imageUrlPrefix}')});
        });
        return arr;
      },
      parseTagsForSubmit(data){
        return data&&data.map((it)=>{
          return {questionId:it.id,introduceId:'',type:it.type};
        });
      },
      changeActionData(selectedTags){
        this.form.selectedTags = 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";
    .NoiseTemplateWrapper .pinfo-container{
        /*background: #fff;
        padding: 20px;*/
        margin: 70px 20px -20px 20px;
        form{
            padding: 20px;
            background: #fff;
        }
        .btn{
            padding: 10px 20px 20px 0;
            margin-top: 0;
            background: #fff;
            margin-bottom: 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>

