<template>
    <div>
        <crumbs :title="title" :param="$route.params" linkTo="ZskRuleManager"></crumbs>
        <div class="contents">
            <div class="content">
                <el-form ref="form" :label-position="labelPosition" class="add-new-form" label-width="130px" :model="form" :rules="rules">
                    <el-form-item label="规则名称：" prop="parDescription">
                        <el-input v-model.trim = "form.parDescription"></el-input>
                    </el-form-item>
                    <el-form-item label="规则类型：" prop="parRuleType">
                        <el-select v-model="form.parRuleType"
                                   placeholder="请选择"
                                   size="small"
                                   @change="ruleTypeChange"
                                   >
                            <el-option
                                    v-for="item in ruleTypeList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                        <span class="tip-text">注：更改术语类型，将会清空已填写的规则内容~</span>
                    </el-form-item>
                    <el-form-item label="规则术语类型：" prop="parLenCode">
                        <el-select v-model="form.parLenCode"
                                   placeholder="请选择"
                                   size="small" @change="ruleTermChange">
                            <el-option
                                    v-for="item in ruleTermTypeList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.code">
                            </el-option>
                        </el-select>
                        <span class="tip-text">注：更改规则术语类型，将会清空已填写的规则内容~</span>
                    </el-form-item>
                    <el-form-item  class="addDepartFormItem" label="医学标准术语：" prop="parConceptId">
                        <el-select clearable filterable remote :remote-method="searchConcept" v-model="form.parConceptId">
                            <el-option
                                    v-for="item in conceptList"
                                    :key="item.conceptId"
                                    :label="item.conceptName"
                                    :value="item.conceptId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!--<el-form-item label="有无子条件：" prop="parHasSub">
                        <el-select v-model="form.parHasSub"
                                   placeholder="请选择"
                                   size="small">
                            <el-option
                                    v-for="item in hasSub"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>-->
                    <el-form-item label="附加信息：" prop="remind" class="parMsg">
                        <el-input type="textarea" :rows="3" placeholder="请输入附加信息" v-model="form.parMsg" maxlength="121"></el-input>
                    </el-form-item>
                    <el-form-item v-if="form.parHasSub===1" label="规则内容：" prop="remind" class="discDesc">
                        <SubRulesGroup v-for="(group,i) in subGroups"
                                       ref="groups"
                                       :data="group"
                                       :firstPlace="firstPlace"
                                       :baseTypes="baseTypeList"
                                       :inx="i"
                                       :isLast="subGroups.length===1"
                                       @addGroup="addGroup"
                                       @delGroup="delGroup"></SubRulesGroup>
                    </el-form-item>
                    <el-button class="disclButn" size="small" type="primary" @click="confirm">保存</el-button>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script type="text/javascript">
    import api from '@api/knowledgeLib.js';
    import SubRulesGroup from './SubRulesGroup'
    export default {
        name:'AddRule',
        data(){
            return{
                labelPosition:'left',
                isFirst:true,
                isCopy:false,
                title:'规则维护-添加规则',
                ruleTermTypeList:[],
                ruleTypeList:[],
                conceptList:[],
                baseTypeList:[],
                conceptName:'',
                firstPlace:null,
                checkFirstPlace:false,
                subGroups:[[{
                    subDescription:'',
                    parRuleType:'',
                    subConceptId:'',
                    subType:'',
                    subMaxOperator:'',
                    subMaxUnit:'',
                    subMaxValue:'',
                    subMinOperator:'',
                    subMinUnit:'',
                    subMinValue:''
                }]],
                form:{
                    parDescription:'',
                    parRuleType:'',
                    parConceptId:'',
                    parlibName:'',
                    parHasSub:undefined,
                    parLenCode:'',
                    parMsg:'',
                    klRuleInfoSaveSub:[],
                },
                parId:null,
                rules:{
                    parDescription:[{ required: true, message: '请输入规则名称',trigger: ['blur'] },{
                        validator: (rule,value,callback)=>{
                            if(value.length>100){
                                callback(new Error('规则名称不能超过100字'));
                            }else{
                                callback();
                            }}, trigger: 'change'
                    }],
                    parRuleType:[{ required: true, message: '请选择规则类型',trigger: ['change'] }],
                    parLenCode:[{ required: true, message: '请选择规则术语类型',trigger: ['change'] }],
                    parConceptId:[{ required: true, message: '请输入医学标准术语',trigger: ['blur'] }],
                    parHasSub:[{ required: true, message: '请选择有无子条件',trigger: ['change'] }],
                    parMsg:[{
                        validator: (rule,value,callback)=>{
                            if(value.length>300){
                                callback(new Error('附加信息不能超过300字'));
                            }else{
                                callback();
                            }}, trigger: 'change'
                    }]
                },
                hasSub:[{name:'有',id:1},{name:'无',id:0},
                ]
            }
        },
        created(){
            this.getTypeList();
            const param = this.$route.params;
            let info = param.data;
            if(info){
                this.parId = info.parId;
                this.isCopy=param.copy;
                this.title = "规则维护-"+(this.isCopy?'复制':'修改')+"规则";
                this.form=Object.assign({},this.form,info);
                this.conceptList=[{conceptName:this.form.parlibName,conceptId:this.form.parConceptId}];
                this.subGroups=this.formatGroupDatas(info.klRuleByIdSub);

            }
        },
        watch:{
            'form.parRuleType':function(val){
                const obj = this.ruleTypeList.find((it)=>it.id===val);
                this.ruleTermTypeList = obj.subMenuList;
            },
            'form.parLenCode':function(val){
                if(!val){
                    this.baseTypeList = [];
                    return ;
                }
                const obj = this.ruleTermTypeList.find((it)=>it.code===val);
                this.baseTypeList = obj.subMenuList;
            },
            'form.parConceptId':function(val){
                if(this.checkFirstPlace) {
                    this.firstPlace = this.conceptList.find((it) => it.conceptId === val);
                }else{
                    this.firstPlace =null;
                }
            }
        },
        components:{
            SubRulesGroup
        },
        methods:{
            showConfirmDialog(msg,resolve){
                this.$alert(msg, '提示', {
                    confirmButtonText: '确定',
                    type: 'warning'
                }).then(() => {
                    resolve();
                }).catch(() => {});
            },
            formatGroupDatas(data){
                let arr=[];
                data.map((it)=>{
                    if(!arr[it.groupType]){arr[it.groupType]=[];}
                    arr[it.groupType].push(it);
                })
                return arr;
            },
            searchConcept(val){
                const param = {
                    excludedConceptIds:[this.form.parRuleType],
                    libType:this.form.parLenCode,
                    name:val,
                };
                api.searchConcept(param).then((res) => {
                    if (res.data.code == '0') {
                        const data = res.data.data;
                        this.conceptList = data;
                    }
                }).catch((error) => {
                    console.log(error);
                });
            },
            ruleTypeChange(val){       //规则类型选中
                this.form.parRuleType=val;
                this.form.parLenCode='';
                const obj = this.ruleTypeList.find((it)=>it.id===val);//console.log(val)
                this.ruleTermTypeList = obj.subMenuList;
                this.setInitGroupData();
            },
            ruleTermChange(val){        //规则术语类型选中
                this.form.parLenCode=val;
                const obj = this.ruleTermTypeList.find((it)=>it.code===val);
                this.baseTypeList = obj.subMenuList;
                this.setInitGroupData();
                this.form.parHasSub=obj.subMenuList.length?1:0;
                if(obj.firstPlace===1){
                    this.checkFirstPlace=true;
                }else{
                    this.checkFirstPlace=false;
                }
            },
            getTypeList(){
              const typeListData = JSON.parse(localStorage.getItem("zskTypesList"));
              this.ruleTypeList = typeListData;
            },
            setInitGroupData(){
              this.subGroups = [[{
                  subDescription:'',
                  parRuleType:'',
                  subConceptId:'',
                  subType:'',
                  subMaxOperator:'',
                  subMaxUnit:'',
                  subMaxValue:'',
                  subMinOperator:'',
                  subMinUnit:'',
                  subMinValue:''
              }]];
              this.form.parConceptId='';//医学标准术语清空
              this.conceptList=[];  //下拉列表清空
            },
            addGroup(){
                this.subGroups.push([{
                    subDescription:'',
                    parRuleType:'',
                    subConceptId:'',
                    subType:'',
                    subMaxOperator:'',
                    subMaxUnit:'',
                    subMaxValue:'',
                    subMinOperator:'',
                    subMinUnit:'',
                    subMinValue:''
                }]);
            },
            delGroup(i){
                this.subGroups.splice(i,1);
            },
            saveRule(params){
                api.saveRule(params).then((res)=>{
                    if(res.data.code==0){
                        this.$message({
                            message:"操作成功",
                            type:'success'
                        });
                        this.$router.push({name: 'ZskRuleManager'});
                    }else{
                        this.$message({
                            message:res.data.msg,
                            type:'warning'
                        });
                    }
                })
            },
            formatGroups(){
                let obj = [];
                this.subGroups.map((item,i)=>{
                   item.map((it)=>{
                       obj.push({groupType:i,...it});
                   })
                });
                return obj
            },
            validateForms(callBack){
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        const groupsRef = this.$refs['groups'];
                        let groupRef=null,goOn=true;
                        for(let i=0;i<groupsRef.length;i++){
                            groupRef=groupsRef[i].$refs['group'];
                            for(let j=0;j<groupRef.length;j++){
                                groupRef[j].$refs['groupData'].validate((valid)=>{
                                    if(!valid){
                                        goOn=false;
                                    }
                                })
                            }
                        }
                        if(goOn){
                            callBack();
                        }
                    } else {
                        return false;
                    }
                });
            },
            confirm(){
                const _this=this;
                this.validateForms(function(){
                    _this.form.klRuleByIdSub=undefined;
                    _this.form.klRuleInfoSaveSub = _this.form.parHasSub?_this.formatGroups():undefined;
                    let params = _this.form;
                    if(_this.parId){//修改/复制
                        params = Object.assign({},_this.form,{parId:_this.isCopy?undefined:_this.parId})
                    }
                    _this.saveRule(params);
                });
            },
        }
    }
</script>
<style lang="less">
    @import "../../less/admin.less";
    .content{
        background: #fff;
        // padding: 20px 20px 30px;
        padding: 20px 20px 50px;
        color: #545455;
        min-width: 980px;
        position: relative;
        .tip-text{
            color:#F56C6C;
            margin-left: 10px;
        }
        .conceptItem{
            padding: 0 10px;
            cursor: pointer;
            height: 32px;
            line-height: 32px;
            &:hover{
                background: #ebedf1;
            }
        }
        .discDesc{
            margin-bottom: 20px;
        }
        .disclButn{
            position: absolute;
            right: 80px;
            bottom: 10px;
        }
    }
    .add-new-form{
        .el-form-item__label{
            text-align: right;
        }
        .addDepartFormItem {
            position: relative;
        }
        .itemList {
            position: absolute;
            // display: none;
            background: #fff;
            width: 188px;
            max-height: 160px;
            border: 1px solid #DCDFE6;
            left: 0;
            top: 37px;
            z-index: 2;
            overflow-y: auto;
        }
        .indexList {
            left: 42px;
            top: 78px;
        }
        .el-input__prefix, .el-input__suffix{
            /*top:-2px;*/
            right: 3px;
        }
        .el-input--suffix .el-input__inner{
            padding-right: 22px;
        }
        .el-input,.el-input__inner{
            width: 190px;
            line-height: 32px;
            height: 32px;
        }
        .el-input__icon{
            line-height: 32px;
        }
    }

</style>