<template>
  <div class="NoiseTemplateWrapper TemplateWrapper">
    <crumbs
            :title="txt"
            class="topBack"
            :param="$route.params"
            linkTo="TemplateMaintenance"
    ></crumbs>
    <PubTemplateGroup
      :editData="editData"
      @changeVal="changeVal"
      @validatePass="validatePass"
      @staticOwn="staticOwn"
      ref="submitForm"
    ></PubTemplateGroup>
    <div class="main">
      <CommonTemplate
        v-if="dataPub.region1"
        :pool="dataPub.tagPool"
        :type="dataPub.region1"
        :signe="dataPub.region3"
        :copyed="dataPub.isCopy"
        :rela="dataPub.region4"
        :options="editData"
         @changeActionData="changeActionData"
      >
      </CommonTemplate>
      <div class="btn">
        <el-button
          type="primary"
          :disabled="(dataPub.isCopy && staticOwnTo == dataPub.region4) || saveDisable"
          :plain="dataPub.isCopy && staticOwnTo == dataPub.region4"
          @click="submitForm"
        >确 定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
/**
 * dataPub.region2  判断底部显示哪些
 */
import PubTemplateGroup from './PubTemplateGroup';
import CommonTemplate from './CommonTemplate';
import api from '@api/icss.js';
import utils from '@api/utils.js';

export default {
  name: 'TemplateMaintenanceWrap',
  data() {
    return {
      txt:'模板维护-添加模板',
      dataPub: {},                    //公用组件传的值都在这
      editData:{},                    //编辑数据
      sendIds: [],           //标签明细右侧操作数据
      staticOwnTo:'',
      saveDisable: false  //保存按钮禁止点击
    }
  },
  beforeMount:function(){
    const {isEdit,data} = this.$route.params;
    if(isEdit){
      this.txt = '模板维护-修改模板';
      this.editData = data;
      // console.log('回读数据', this.editData)
    }
  },
  methods: {
    staticOwn(val){
      this.staticOwnTo = val
    },
    changeVal(val) {    //子组件数据改变传递到父组件
      this.dataPub = val    // console.log('公用组件传的值都在这', val)
      if(val.isCopy){
        this.txt = '模板维护-复制模板'
      }
    },
    changeActionData(arr) {          //标签明细右侧数据id
      this.sendIds = arr
    },
    submitForm() {       // 调用子组件的方法验证公用部分
      this.$refs.submitForm.submitForm('groups');
    },
    validatePass() {      //验证成功回调，调取接口
      //仍需验证标签明细是否选择
      let type = this.dataPub.region1,name=this.dataPub.region2;
      let detailLis = utils.orderTemplateData(this.sendIds)
      if (JSON.stringify(this.sendIds) == '[]' || !detailLis) {
        this.$message({
          message: '模板至少包含一个标签池标签',
          type: 'warning'
        });
        return;
      }else if(detailLis[0].questionId == '' && detailLis.length == 1){
        let msg = ''
        if(detailLis[0].flag == 3){
          msg = '保存模版时，无法保存单独的子模板'
        }else{
          msg = '保存模版时，无法保存单独的输入栏'
        }
        this.$message({
          message: msg,
          type: 'warning'
        });
        return;
      }else if(detailLis.length == 2 && ((detailLis[0].questionId == '' && detailLis[1].flag == 3) || (detailLis[1].questionId == '' && detailLis[0].flag == 3))){
        this.$message({
          message: '保存模版时，只有输入栏和子模板无法保存',
          type: 'warning'
        });
        return;
      }
      // let numplus = 0;
      // for(let k = 0;k < detailLis.length;k++){
      //   if((detailLis[k].flag && detailLis[k].flag != 3) || (type == 322 || type == 32 || type == 31)){
      //     ++numplus
      //   }
      // }
      // if(numplus == 0){
      //   this.$message({
      //     message: '除子模板外，其他模板内容中至少给一个标签打上标记',
      //     type: 'warning'
      //   });
      //   return;
      // }
      function getTextType(){
        if(type == 322 || type == 22 || type == 32){
          return 2
        }else if(type == 31){
          return 1
        }
        return type
      }
      let param = {
        "modelDetils": detailLis,
        "name": name,
        "type": type,
        "flag": (type == 322 || type == 32 || type == 31)?3:'',
        "textType": getTextType(),
        "id":this.editData.id || '',
        "moduleType": this.dataPub.region3,
        "relationId": this.dataPub.region4
      }
      // console.log(param,'保存模板的参数')
      this.showDelDialog(param)
    },
    showDelDialog(param) {
      this.showConfirmDialog('是否保存该模板？', () => {
        if(this.editData.id){
          this.saveDisable = false  //提交保存按钮不可点击，返回结果时才可点击，防止频繁发送请求
          api.updateModuleInfo(param).then((res) => {
            if (res.data.code === '0') {
              this.warning(res.data.msg || '修改成功', 'success', '1000');
              //返回带搜索条件的首页
              setTimeout(() => {
                this.$router.push({
                  name: 'TemplateMaintenance',
                  params: Object.assign({}, this.$route.params, {currentPage: 1})
                })
              }, 1000);
            } else {
              this.warning(res.data.msg)
            }
            this.saveDisable = true
          }).catch((err) => {
            this.warning(err);
          })
        }else{
          api.saveModuleInfo(param).then((res) => {
          if (res.data.code === '0') {
            this.warning(res.data.msg || '保存成功', 'success','1000')
            setTimeout(() => {
              this.$router.push({
                path:'/admin/LT-YXSJWH-MBWH'
              })
            }, 1000);
          } 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,time) {
      this.$message({
        showClose: true,
        message: msg,
        type: type || 'warning',
        duration:time || '3000'
      })
    },
  },
  components: {
    PubTemplateGroup,
    CommonTemplate,
  }
}
</script>
<style lang="less">
@import "../../less/common.less";
.NoiseTemplateWrapper {
  .groupTitle {
    background-color: #fff;
    height: 40px;
    line-height: 40px;
    padding-left: 20px;
  }
  .main {
    background-color: #fff;
    margin: 0 20px 20px;
    padding: 20px;
    border-top: 1px solid @icssBorder;
    box-sizing: border-box;
    font-size: 14px;
    color: #606266;
    .title {
      margin-bottom: 20px;
      i {
        color: #f56c6c;
      }
    }
  }
  .btn {
    text-align: right;
  }
  .order {
    margin-bottom: 20px;
    .el-input__inner {
      line-height: 30px;
      height: 30px;
    }
  }
}
</style>

