<template>
  <div class="NoiseTemplateWrapper TemplateWrapper">
      <crumbs
              :title="txt"
              class="topBack"
              :param="$route.params"
              linkTo="labelGroup"
    ></crumbs>
    <PubTagGroup
      :editData="editData"
      :isEditOrCopy="isEditOrCopy"
      @changeVal="changeVal"
      @changeSex="changeSex"
      @changeType="changeType"
      @validatePass="validatePass"
      ref="submitForm"
    ></PubTagGroup>
    <div class="main">
      <p v-if="dataPub.region1 != 6 && dataPub.region1 != 7 && dataPub.region1 != 8 && dataPub.region1 != 9 && dataPub.region1 != 21 && dataPub.region1 != 22 && dataPub.region1 != 10" class="title"> <i>*</i> 标签明细：<span>{{dataPub.region2 == 2?'(操作界面:横栏默认互斥项,只能放入单选类型且明细为一条的标签;每列可以放入单选/多选类型)':dataPub.region2 == 6?'(操作界面:横栏默认互斥项,只能放入单选类型且明细为一条的标签;第一列只可放入带有同伴/无特殊标记的多选类型标签,其余列只可放入症状详情类型标签组)':''}}</span></p>
      <PubTagPartDetail
        :pool="dataPub.tagPool"
        :type="dataPub.region1"
        :sign="dataPub.region2"
        :isEditOrCopy="isEditOrCopy"
        :order="dataPub.order"
        :sexType="dataPub.region7"
        :tipLis="dataPub.tipLis"
        :choose="dataPub.region2 == 6?'multiple':'single'"
        :options="editData.questionMapping"
        v-if="dataPub.region2 == 2 || dataPub.region2 == 6"
        @changeActionData="changeActionData"
      ></PubTagPartDetail>
      <SymptomTagGroup 
        v-if="dataPub.region2 == 4" 
        :pool="dataPub.tagPool" 
        :isEditOrCopy="isEditOrCopy"
        :type="dataPub.region1"
        :isSymp="dataPub.region12"
        :sexType="dataPub.region7"
        :options="editData.questionMapping"
        @changeActionData="changeActionData"
        >
      </SymptomTagGroup>
      <InspactTagGroup 
        v-if="dataPub.region2 == 7" 
        :pool="dataPub.tagPool" 
        :isEditOrCopy="isEditOrCopy"
        :type="dataPub.region1"
        :sexType="dataPub.region7"
        :options="editData.questionMapping"
        @changeActionData="changeActionData"
        >
      </InspactTagGroup>
      <BloodPressTagGroup 
        v-if="dataPub.region2 == 3" 
        :pool="dataPub.tagPool" 
        :isEditOrCopy="isEditOrCopy"
        :type="dataPub.region1"
        :sexType="dataPub.region7"
        :options="editData.questionMapping"
        @changeActionData="changeActionData"
        >
      </BloodPressTagGroup>
      <SymptomPush
        v-if="dataPub.region2 == 11" 
        :pool="dataPub.tagPool" 
        :isEditOrCopy="isEditOrCopy"
        :type="dataPub.region1"
        :sexType="dataPub.region7"
        :options="editData.questionMapping"
        :tipLis="dataPub.tipLis"
         @changeActionData="changeActionData"
      >
      </SymptomPush>
      <el-form
        v-if="dataPub.region2 == 2"
        class="order"
        :rules="rules"
        :model="form"
        label-width="150px"
      >
        <el-form-item
          label="选择标签成文顺序："
          prop="currentOrder"
        >
          <el-select
            v-model="form.currentOrder"
            placeholder="选择标签成文顺序"
          >
            <el-option
              v-for="item in dataPub.order"
              :label="item.name"
              :value="item.val"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="btn">
        <el-button
          type="primary"
          @click="submitForm"
          :disabled="saveDisable"
        >确 定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
/**
 * dataPub.region2  判断底部显示哪些
 */
import PubTagGroup from './PubTagGroup';
import PubTagPartDetail from './PubTagPartDetail';
import SymptomTagGroup from './SymptomTagGroup';
import InspactTagGroup from './InspactTagGroup';
import BloodPressTagGroup from './BloodPressTagGroup';
import SymptomPush from './SymptomPush';
import api from '@api/icss.js';
import utils from '@api/utils.js';

export default {
  name: 'NoiseTemplateWrapper',
  data() {
    return {
      txt:'标签组维护-添加标签组',
      dataPub: {},      //公用组件传的值都在这
      editData:{},                    //编辑数据
      form: {
        currentOrder: '0',     //标签成文顺序
      },
      rules: {
        currentOrder: [
          { required: true, message: '选择标签成文顺序', trigger: 'change' }
        ]
      },
      sendIds: [[], [], [], [], [], []],           //标签明细右侧操作数据
      saveDisable: false, //保存按钮是否可点击
      isEditOrCopy: false, //是否为修改或复制
      tmpArrAdd:[[], [], [], [], [], []],//既往史自动生成标签id
    }
  },
  beforeMount:function(){
    const {isEdit, isCopy, data} = this.$route.params;
    if(isEdit){
      this.txt = '标签组维护-修改标签组';
      this.isEditOrCopy = true
      this.editData = data;
      this.form.currentOrder = data.textGenerate+''
      // console.log('回读数据', 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;
      this.form.currentOrder = copyData.textGenerate+''
    }
  },
  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: {
    changeVal(val) {    //子组件数据改变传递到父组件
      this.dataPub = val
      // console.log('公用组件传的值都在这', val)
    },
    changeSex(sex) {       //性别改变，清空标签明细
      // console.log(sex)
    },
    changeType(type) {        //填写单类型改变，标签明细左侧更新，右侧清空
      // console.log(type)
    },
    changeActionData(arr,tmpArr) {          //标签明细右侧数据id
      this.sendIds = arr
      this.tmpArrAdd = tmpArr
    },
    submitForm() {       // 调用子组件的方法验证公用部分
      if(document.querySelectorAll('.redWordTip')[0]){
        // this.warning('当前数据有误是不可保存！')
        this.showConfirmDialog('当前数据有误是不可保存！');
        return
      }
      this.$refs.submitForm.submitForm('groups');
    },
    validatePass() {      //验证成功回调，调取接口
      //仍需验证标签明细是否选择
      let type = this.dataPub.region1;
      if (JSON.stringify(this.sendIds) == '[[],[],[],[],[],[]]' && type != 6 && type != 7 && type != 8 && type != 9 && type != 21 && type != 22 && type != 10 &&(type == 1&&this.dataPub.region2!=4)) {
        this.$message({
          message: '请选择标签明细',
          type: 'warning'
        });
        return;
      }
      if(parseFloat(this.dataPub.region8) >= parseFloat(this.dataPub.region9)) {
          this.$message({
            message: '最小年龄不能大于或等于最大年龄',
            type: 'warning'
          });
          return;
      }
      if(this.dataPub.region1==5 &&this.dataPub.region3 != this.dataPub.region4) {
        this.$message({
            message: '化验系统名称和界面名称必须相同',
            type: 'warning'
          });
          return;
      }
     
      let detailLis = utils.dataRecombination(this.sendIds, this.dataPub.region2,this.tmpArrAdd)

      let param = {
        "disTypeVO": {
          "type": ''
        },
        "questionWrapper": {
          "controlType": 0,                            //控件类型(0：默认值 1：下拉单选 2：下拉多选 6：文本框 7：数字键盘文本框 99：联合推送)
          "id": this.editData.id || '',                //新增id空
          "type": this.dataPub.region1,                //标签归属
          // "itemType":0,                                //0：是症状，1：不是症状
          "tagType": this.dataPub.region2,             //标签类型
          "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：通用
          "specFlag": this.dataPub.specFlag,           //生命体征
          "selFlag": this.dataPub.selFlag,           //一般情况/其他史标记
          "ageBegin": this.dataPub.region8,       		 //最小年龄
          "ageEnd": this.dataPub.region9,              //最大年龄
          "textGenerate": this.form.currentOrder,      //成文顺序 默认0
          "copyType": this.dataPub.region10,           //是否复制
          "showAdd": this.dataPub.region11,            //是否显示加号血压
          "itemType" :this.dataPub.region12,
          "showInfo": 0,
          "questionDetails": [],
          "questionMappings": detailLis       //映射关系,
        }
      }
      if((this.dataPub.region2 == 2 || this.dataPub.region2 == 3)&& detailLis.length == 0) {
         this.warning('请选择标签明细')
         return
      }
      this.showDelDialog(param)
    },
    showDelDialog(param) {
      this.showConfirmDialog('是否保存该标签组？', () => {
        this.saveDisable = true
        api.saveOrUpdate(param).then((res) => {
          if (res.data.code === '0') {
            this.warning(res.data.msg || '保存成功', 'success','1000')
            setTimeout(() => {
              //返回带搜索条件的首页
              this.$router.push({
                name: 'labelGroup',
                params: Object.assign({}, this.$route.params, {currentPage: 1})
              })
            }, 1000);
          } else {
            this.warning(res.data.msg)
          }
          this.saveDisable = false
        }).catch((err) => {
          this.warning(err);
        })
      });
      // const h = this.$createElement;
      // const {isEdit} = this.$route.params;
      // const addMsg = h('div',{style:'padding-bottom:10px'},[
      //       h('p',{style:'font-size:15px;margin-bottom:10px'},'是否保存该标签组？')
      //     ])
      // const modMsg = h('div',{style:'padding-bottom:10px'},[
      //       h('p',{style:'font-size:15px;margin-bottom:10px'},'是否保存该标签组？'),
      //       h('span',{style:'color:red;font-size:12px'},'若标签系统名称已经改变，请去别名维护中修改相关信息'),
      //     ])
      // this.$msgbox({
      //   title:'提示',
      //   message:isEdit?modMsg:addMsg,
      //   showCancelButton: true,
      //   distinguishCancelAndClose:true,
      //   confirmButtonText: '确认并前往别名维护',
      //   cancelButtonText:'确认',
      //   // type: 'warning',
      //   cancelButtonClass:'toast-cancel'
      // }).then(()=>{
      //   api.saveOrUpdate(param).then((res) => {
      //     if (res.data.code === '0') {
      //       this.warning(res.data.msg || '保存成功', 'success');
      //       // 判断是否已有别名--有（修改），无（新增）
      //       const item = {'questionId':param.questionWrapper.id,'questionName':param.questionWrapper.tagName};
      //       api.similarNameDetl(item).then((res)=>{
      //         if(res.data.code=='0'){
      //           this.$router.push({
      //             name:'AddSimilarName',
      //             params: {id:param.questionWrapper.id,name:param.questionWrapper.tagName}
      //           })
      //         }else{
      //           this.$router.push({
      //             name:'AddSimilarName',
      //             params: {}
      //           })
      //         }
      //       })
      //     } else {
      //       this.warning(res.data.msg)
      //     }
      //   }).catch((err) => {
      //     this.warning(err);
      //   })
      // }).catch((action)=>{
      //   // action :cancel--取消,close--关闭
      //   if(action=='cancel'){
      //     api.saveOrUpdate(param).then((res) => {
      //       if (res.data.code === '0') {
      //         this.warning(res.data.msg || '保存成功', 'success');
      //         setTimeout(() => {
      //           this.$router.push({
      //             path:'/admin/LT-YXSJWH-BQZWH'
      //           })
      //         }, 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: {
    PubTagGroup,
    PubTagPartDetail,
    SymptomTagGroup,
    BloodPressTagGroup,
    SymptomPush,
    InspactTagGroup,
  }
}
</script>
<style lang="less">
@import "../../less/common.less";
.NoiseTemplateWrapper {
  .topBack {
    top: 0;
  }
  .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;
    position: relative;
    .title {
      margin-bottom: 20px;
      min-width: 915px;
      i {
        color: #f56c6c;
      }
      span {
        color:@adminBase;
        font-size: 12px;
      }
    }
  }
  .btn {
    text-align: right;
    margin-top: 10px;
  }
  .order {
    margin-bottom: 20px;
    .el-input__inner {
      line-height: 30px;
      height: 30px;
    }
  }
}
</style>

