<template>
    <div class="NoiseTemplateWrapper TemplateWrapper">
        <crumbs
                :title="txt"
                class="topBack"
                :param="$route.params"
                linkTo="IndeptLabel"
        ></crumbs>
        <PubIndeptTag
                @changeVal="changeVal"
                @changeSex="changeSex"
                @changeType="changeType"
                @validatePass="validatePass"
                :editData="editData"
                :isEditOrCopy="isEditOrCopy"
                ref="submitForm"
        ></PubIndeptTag>
        <div class="main">
            <p class="title" v-if="dataPub.region2==1||dataPub.region2==2|| dataPub.region2==11">
                <i>*</i> 标签明细：
                <i v-if='dataPub.region2==2' style="margin-left:70px;color: #48C5D7; font-size: 12px;">所有选项必须都有或者都没有同“伴”/“无”标记</i>
            </p>
            <SingleSelect v-if="dataPub.region2==1 || dataPub.region2==2 || dataPub.region2==11" :ascription="dataPub.region1" :sexType="dataPub.region7" :type="dataPub.region2" @pushValues="pushValues" :isEditOrCopy="isEditOrCopy" :options="editData.questionDetailList"></SingleSelect>
            <div class="btn">
                <el-button
                        type="primary"
                        @click="submitForm"
                        :disabled="saveDisable"
                >确 定</el-button>
            </div>
        </div>
    </div>
</template>
<script>
  /**
   * dataPub.region2  判断底部显示哪些
   */
  import PubIndeptTag from './PubIndeptTag';
  import SingleSelect from './SingleSelect';
  import api from '@api/icss.js';
  import utils from '@api/utils.js';

  export default {
    name: 'NoiseTemplateWrapper',
    data() {
      return {
        txt:'独立标签维护-添加独立标签',
        dataPub: {},      //公用组件传的值都在这
        itemsTypes:[1,2],            //有明细的类型
        editData:{},                    //编辑数据
        form: {
          currentOrder: '0',     //标签成文顺序
        },
        rules: {
          currentOrder: [
            { required: true, message: '选择标签成文顺序', trigger: 'change' }
          ]
        },
        options: [],           //标签明细右侧操作数据
        saveDisable: false,
        isEditOrCopy: false //
      }
    },
    beforeMount:function(){
      const {isEdit,isCopy,data} = this.$route.params;
     
      if(isEdit){
      this.txt = '独立标签维护-修改独立标签';
      this.isEditOrCopy = true
      this.editData = data;
      } else if(isCopy) {
        this.txt = '独立标签维护-复制独立标签';
        this.isEditOrCopy = true
        const copyData = JSON.parse(JSON.stringify(data))
        copyData.id = ""
        copyData.name=""  
        copyData.tagName=""
        this.editData = copyData;
      }
    },
    computed: {
      newSign() {
        return this.dataPub.region2;
      },
    },
    watch: {
      newSign(nextVal, prevVal) {
         const {isEdit,isCopy} = this.$route.params;
        if (nextVal != prevVal && !isEdit&&!isCopy) {
          this.form.currentOrder = '0'
        }
      },
    },
    methods: {
      back() { this.$router.go(-1) },
      changeVal(val) {    //子组件数据改变传递到父组件
        this.dataPub = val
        console.log('公用组件传的值都在这', val)
      },
      changeSex(sex) {       //性别改变，清空标签明细
        //console.log(sex)
      },
      changeType(type) {        //填写单类型改变，标签明细左侧更新，右侧清空
        if(this.isEditOrCopy&&type=='2') {
          return
        }
        this.options = [];
      },
      pushValues(its){
        this.options = its;
      },
      submitForm() {      // 调用子组件的方法验证公用部分
        this.$refs.submitForm.submitForm('groups');
      },
      validatePass() {      //验证成功回调，调取接口
        //仍需验证标签明细是否选择
        let isNull = true
        let options2 = []
        const opts = this.options;
        for (let i = 0; i < this.options.length; i++) {
          if(this.options[i].name.trim() != '') {
            isNull = false
            options2.push(this.options[i])
          }
        }
        this.options = options2;
        if(this.itemsTypes.includes(+this.dataPub.region2)&&isNull) {
            this.warning('至少填一个选项')
            return;
        }
        let flag=true;
        if(opts[0] && opts[0].code){
          flag=opts.findIndex((it)=>{
            return !it.code;
          })==-1;
        }else{
          flag=opts.findIndex((it)=>{
            return it.code;
          })==-1;
        }
        if(!flag){
          this.warning('所有选项必须都有或者都没有同“伴”/“无”标记')
          return;
        }
        if(parseFloat(this.dataPub.region8) >= parseFloat(this.dataPub.region9)) {
          this.warning('最小年龄不能大于或等于最大年龄')
          return;
        }
        if(parseFloat(this.dataPub.minNormalVal) >= parseFloat(this.dataPub.maxNormalVal)) {
          this.warning('最小正常值不能大于或等于最大正常值')
          return;
        }
        const {isEdit,data} = this.$route.params;
        let param = {
          "questionWrapper": {
            "controlType": this.dataPub.region2,                            //控件类型(0：默认值 1：下拉单选 2：下拉多选 6：文本框 7：数字键盘文本框 99：联合推送)
            "id": isEdit?data.id:'',                                    //新增id置空
            "type": this.dataPub.region1,                //标签归属
            "tagType": 1,             //标签类型
            "tagName": this.dataPub.region3,             //系统名称
            "name": this.dataPub.region4,                //界面名称
            "joint": this.dataPub.region5,               //标签间的连接符
            // "subType": this.dataPub.region6,   	         //0:可以，1：不可以(当项目检索)  //这个字段暂时不用
            "sexType": this.dataPub.region7,             //1:男，2：女，3：通用
            "ageBegin": this.dataPub.region8,       		 //最小年龄
            "ageEnd": this.dataPub.region9,              //最大年龄
            "textGenerate": this.form.currentOrder,      //成文顺序 默认0
            "copyType": this.dataPub.region2 == 6 ? this.dataPub.region10 : (this.dataPub.region2 == 3 ? this.dataPub.region11 : ''),                               //是否复制
            "showAdd": 0,                                //是否显示加号血压
            "itemType" :this.dataPub.region12,    
            "showInfo": 0,
            "labelPrefix":this.dataPub.prefix,                                 //前缀
            "labelSuffix":this.dataPub.suffix,                                 //后缀
            "minValue": this.dataPub.minNormalVal,        //化验最小正常值
            "maxValue": this.dataPub.maxNormalVal,         //化验最大正常值
            "specFlag": this.dataPub.specFlag,  //标记状态（0：没有标记，1：主诉高亮，2：诱因记录, 4:生命体征）
            "selFlag": this.dataPub.selFlag,
            "questionDetails": this.options,
            "questionMappings": [],      //映射关系,
            "formulaCode": isEdit?data.formulaCode : ''
          }
        };
        this.showSaveDialog(param);
      },
      showSaveDialog(param) {
        this.showConfirmDialog('是否保存该标签？', () => {
          this.saveDisable = true
          api.saveOrUpdate(param).then((res) => {
            if (res.data.code === '0') {
              this.warning(res.data.msg || '保存成功', 'success');
              this.$router.push({name: 'IndeptLabel', params: Object.assign({}, this.$route.params, {currentPage: 1})});
            } else {
              this.warning(res.data.msg)
            }
            this.saveDisable = false

          }).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'
        })
      },
    },
    components: {
      PubIndeptTag,
      SingleSelect
    }
  }
</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>

