<template>
    <div class="NoiseTemplateWrapper TemplateWrapper">
        <crumbs
                :title="txt"
                class="topBack"
                :param="$route.params"
                linkTo="QuestionModules"
        ></crumbs>
        <div class="PubTagGroupWrapper">
        <el-form class="groups"
                :rules="rules"
                ref="groups"
                :model="form"
                label-width="150px">
            <el-form-item
                    label="模板类型："
                    prop="moduleType">
                <span class="changeTips">改变类型后，填写单明细将会恢复到默认状态</span>
                <el-select
                        v-model="form.moduleType"
                        :disabled="!!editData.id"
                        placeholder="请选择模板类型"
                        @change="changeType(1)"
                >
                    <el-option
                            v-for="item in moduleTypes"
                            :label="item.name"
                            :value="item.val"
                            :key="item.val"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                    v-if="form.moduleType==1"
                    label="选择科室："
                    prop="relationId">
                <span class="changeTips">改变类型后，填写单明细将会恢复到默认状态</span>
                <el-select
                        v-model="form.relationId"
                        :disabled="!!editData.id"
                        placeholder="请选择科室"
                >
                    <el-option
                            v-for="item in deptList"
                            :label="item.name"
                            :value="item.conceptId+''"
                            :key="item.conceptId+''"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                    label="模板归属："
                    prop="type"
            >
                <span class="changeTips">改变归属后，填写单明细将会恢复到默认状态</span>
                <el-select
                        v-model="form.type"
                        :clearable="false"
                        :disabled="!!editData.id||!form.moduleType||(form.moduleType==1&&!form.relationId)"
                        placeholder="请选择模板归属"
                        @change="changeType(0)"
                >
                    <el-option
                            v-for="item in typeList"
                            :label="item.name"
                            :value="item.val"
                            :key="item.val"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                    label="模板名称："
                    prop="name"
            >
                <el-input
                        v-model="form.name"
                        maxLength="30"
                        placeholder="请输入模板名称"
                ></el-input>
            </el-form-item>
            <el-form-item label="备注：" prop="remark">
                <el-input type="textarea" v-model="form.remark" style="width: 500px;"></el-input>
            </el-form-item>
        </el-form>
    </div>
        <div class="main">
            <p class="title" v-if="form.type&&form.moduleType">
                <i v-if="form.type!=1">*</i>填写单明细：
            </p>
            <QuestionTagGroup v-if="form.type&&form.moduleType&&form.type!=1" qaType="3" :ascription="form.type" :relationId="form.relationId" @changeActionData="pushValues" :options="editData.moduleDetail"></QuestionTagGroup>
            <div class="static" v-if="form.type==1">
                <p>请问您有哪些不适？</p>
                <div class="inner">科室常见症状</div>
            </div>
            <div class="btn">
                <el-button
                        type="primary"
                        @click="submitForm"
                >确 定</el-button>
            </div>
        </div>
    </div>
</template>
<script>
  /**
   *
   */
  import QuestionTagGroup from './QuestionTagGroup';
  import api from '@api/preTreat.js';

  export default {
    name: 'addCombinQuestion',
    props:[''],
    data() {
      return {
        txt:'模板维护-添加模板',
        form:{
          name:"",
          type:"",
          moduleType:"",
          relationId:"",
          moduleDetail:[],
          remark:''
        },
        typeList:[],
        moduleTypes:[],
        deptList:[],
        editData:{},                    //编辑数据
        options: [],           //标签明细右侧操作数据
        rules: {
          type: [
            { required: true, message: '请选择归属', trigger: 'change' }
          ],
          moduleType: [
            { required: true, message: '请选择类型', trigger: 'change' }
          ],
          name: [
            { required: true, message: '请输入模板名称', trigger: 'change' },
            { validator: (rule, value, callback)=>{
              if(value.length>7){
                callback(new Error('模板名称不能超过7个字'));
              }else{
                callback();
              }
              }, trigger: 'blur' },
          ],
          remark:[
            { validator: (rule, value, callback)=>{
                if((value&&value.trim().length>0)&&value.length>120){
                  callback(new Error('备注不能超过120个字'));
                }else{
                  callback();
                }
              }, trigger: 'blur' },
          ],
          relationId: [
            { required: true, message: '请选择模板归属科室', trigger: 'change' },
          ],
        },
      }
    },
    beforeMount:function(){
      const {isEdit,data} = this.$route.params;
      this.getDropDatas();
      if(isEdit){
        //this.getAvailibleType();
        this.txt = '模板维护-修改模板';
        this.form = Object.assign({},this.form,this.transFormData(data));
        this.editData = data;
      }
    },
    watch:{
      'form.moduleType':function(newVal,oldVal){
        if(+newVal!==1){
          this.form.relationId = '';
        }
        this.getAvailibleType();
      },
      'form.relationId':function(newVal,oldVal){
        this.getAvailibleType();
      },
    },
    methods: {
      getAvailibleType(){
        api.getModuleType({moduleType:this.form.moduleType,relationId:this.form.relationId}).then((res) =>{
          if(res.data.code === '0') {
            this.typeList = res.data.data;
          }else{
            this.warning(res.data.msg);
          }
        });
      },
      transFormData(org){
        const maps = {
          'moduleType':'moduleType',
          'moduleDetail':'moduleDetail',
          'relationId':'relationId',
          'type':'type',
          'name':'name',
          'id':'id',
          'remark':'remark'
        };
        let obj = {};
        for(let i in org){
          if(maps[i]){
            obj[maps[i]] = typeof org[i]=='object'?org[i]:''+org[i];
          }
        }
        return obj;
      },
      getDropDatas(){
        api.getPreTypeList().then((res) =>{
          if(res.data.code === '0') {
            this.typeList = res.data.data[1];
            this.moduleTypes =  res.data.data[4];
          }
        });
        this.getDeptList();
      },
      getDeptList(){
        const depts = localStorage.getItem("precDeptList");
        const list = depts?JSON.parse(depts):[];
        if(list&&list.length>0){
          this.deptList = list;
          return ;
        }
        api.getDeptList({moduleType:0,type:1}).then((res) =>{
          if(res.data.code === '0') {
            this.deptList = res.data.data&&res.data.data.deptDTOS||[];
            localStorage.setItem("precDeptList",JSON.stringify(this.deptList));
          }
        });
      },
      changeType(flag) {        //填写单类型改变，标签明细左侧更新，右侧清空
        // console.log('type',type)
        if(flag){
          this.form.type='';
        }
        this.options = [];
      },
      pushValues(its){
        const arr = its.map((it)=>{
          return {
            questionId:it.id,
          }
        });
        this.options = arr;
      },
      submitForm() {      // 调用子组件的方法验证公用部分
        this.$refs.groups.validate((valid) => {
          if (valid) {
            let param = this.form;
            param.moduleDetail = this.options;
            if(this.form.type!=1&&(!this.options||this.options.length==0)){
              this.warning('模版至少包含一个填写单');
              return;
            }
            this.showSaveDialog(param);
          }else{
            return false;
          }
        });
      },
      showSaveDialog(param) {
        this.showConfirmDialog('是否保存该模板？', () => {
          api.addModule(param).then((res) => {
            if (res.data.code === '0') {
              this.warning(res.data.msg || '保存成功', 'success');
              //返回带搜索条件的首页
              this.$router.push({name:'QuestionModules',params:Object.assign({},this.$route.params,{currentPage:1})});
            } 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'
        })
      },
    },
    components: {
      QuestionTagGroup
    }
  }
</script>
<style lang="less">
    @import "../../less/common.less";
    .NoiseTemplateWrapper .el-select .el-input__validateIcon.el-icon-circle-close{
        display: none!important;
    }
    .PubTagGroupWrapper .groups {
        padding: 20px 20px 30px;
        .el-form-item__error{
            top:unset;
        }
    }
    .NoiseTemplateWrapper .PubTagGroupWrapper{
        padding-bottom: 18px;
    }
    .static{
        width:360px;
        height:137px;
        background:#F0EEEE;
        padding: 20px 0 0 20px;
        .inner{
            background: #fff;
            width: 317px;
            height: 57px;
            line-height: 52px;
            margin-top:20px;
            text-align: center;
        }
        p{

        }
    }
    .PubTagGroupWrapper{
        padding-bottom: 10px;
    }
    .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;
    }
    }
    }
    .toast-cancel{
        color: #22ccc8 !important;
    // background: #22ccc8;
    }
</style>

