<!-- 添加常见科室症状  -->
<template>
    <div class="AddDiagBaseWrapper" @click="close">
        <crumbs
          :title="'诊断依据数据维护-'+titleText"
          class="topBack"
          :param="$route.params"
          linkTo="DiagBase"
        ></crumbs>
        <el-form  ref="ruleForm"  class="addDepartForm">
            <el-form-item  class="addDiagName"  label="选择添加疾病名称：" >
                <input class="searchInput"  @focus="focuInput" type="text" v-model = "searchDiagVal"> 
                <span class="searchName" @click="searchDiag">搜索</span>
                <ul class="itemList diagList" ref="diagList">
                    <li 
                    v-for="item in diagList" 
                    class="diagItem ellipsis"
                    :title="item.name"
                    @click="selectDiag(item)"
                    :key="item.conceptId">
                    {{item.name}}
                    </li>
                </ul>
            </el-form-item>
             <el-form-item class="isRequired" label="已选添加疾病名称：">
                {{disName}}
            </el-form-item>
        </el-form>
        <div class="symptomList">
            <p class="moduleTitle">疾病特征：</p>
            <table class="diagTable">
                <tr class="tableTitle">
                    <td class="FeatureSort">排序</td> 
                    <td class="FeatureType require">类型</td>
                    <td class="FeatureNumber require">序号</td>
                    <td class="FeatureStand require">标准词</td>
                    <td class="FeatureRelate">关联词</td>
                    <td class="FeatureResult">结果</td>
                    <td class="FeatureOpera"></td>
                </tr>
                <tr v-for="(item, index) in disFeatureList" :key="item.index"> 
                    <td class="FeatureSort" >{{index+1}}</td>
                    <td class="FeatureType" >
                        <el-select size="mini" :class="{selectType: item.typeNull}" v-model.trim="item.type" placeholder="标签类型" @change="clickItem(index,'FeatureType')" clearable>
                            <el-option v-for="item in featureTypeList" :label="item.name" :value="item.key" :key="item.key"></el-option>
                        </el-select>
                    </td>
                    <td class="FeatureNumber"  >
                        <el-tooltip :disabled="!item.verifyCode&&!item.codeNull&&!item.codeError" class="item" effect="dark" :content="item.verifyCode||item.codeNull||item.codeError" placement="top">
                            <input class="groupInput"  :class="{borderRed:item.verifyCode||item.codeNull, colorRed: item.codeError}" :title="item.code" type="text" v-model.trim="item.code" @input="handleInp(index,$event,'FeatureNumber')"  @click="clickItem(index,'FeatureNumber')">
                        </el-tooltip>
                    </td>
                    <td class="FeatureStand" >
                        <el-tooltip  :disabled="!item.verifyStandard&&!item.standardNull" class="item" effect="dark" :content="item.verifyStandard||item.standardNull" placement="top">
                            <input class="groupInput"  :class="{borderRed:item.verifyStandard||item.standardNull}" :title="item.standard" type="text" v-model.trim="item.standard" @input="handleInp(index,$event,'FeatureStand')"   @click="clickItem(index,'FeatureStand')">
                        </el-tooltip>                    
                    </td>
                    <td class="FeatureRelate">
                        <el-tooltip :disabled="!item.verifyRelation&&!item.relationNull"  class="item" effect="dark" :content="item.verifyRelation||item.relationNull" placement="top">
                            <input class="groupInput" :class="{borderRed:item.verifyRelation|| item.relationNull}" :title="item.relation" type="text" v-model.trim="item.relation" @input="handleInp(index,$event,'FeatureRelate',item.type)"  @click="clickItem(index,'FeatureRelate')">
                        </el-tooltip> 
                    </td>
                    <td class="FeatureResult">
                        <el-tooltip :disabled="!item.verifyResult"  class="item" effect="dark" :content="item.verifyResult" placement="top">
                            <input :readonly="item.type!=3" class="groupInput" :class="{borderRed:item.verifyResult, inpDisabled:item.type!=3}"  :title="item.result" type="text" v-model.trim="item.result" @input="handleInp(index,$event,'FeatureResult')" @click="clickItem(index,'FeatureResult')">
                        </el-tooltip> 
                    </td>
                    <td class="FeatureOpera">
                        <el-button type="text" size="small" class="delete" @click="addItem(index, 1)"><div class="btnOpera">+</div></el-button>
                        <el-button v-if="index !=0" type="text" size="small" class="delete" @click="delItem(index, 1)"><div class="btnOpera">-</div></el-button>
                    </td>
                </tr>
            </table>
            <p class="moduleTitle">诊断公式：</p>
            <p class="inpTips">可输入数字（0~9）规定内汉字：任、一、二、三、四、五、六、七、八、九、十，其余汉字不可输入；可输入的符号：“、”“\”“（）”</p>
            <table class="diagTable">
                <tr class="tableTitle"> 
                    <td class="FormulaSort">排序</td> 
                    <td class="FormulaType">类型</td>
                    <td class="FormulaNumber">公式</td>
                    <td class="FormulaOpera"></td>
                </tr>
                <tr v-for="(item, index) in disFormulaList"  :key="item.index"> 
                    <td class="FormulaSort">{{index +1}}</td>
                    <td class="FormulaType">
                        <el-select size="mini" :class="{selectType: item.verifyType}" v-model.trim="item.type" placeholder="标签类型"  @change="clickItem(index,'FormulaType')" clearable>
                            <el-option v-for="item in formulaTypeList" :label="item.name" :value="item.key" :key="item.key"></el-option>
                        </el-select>
                    </td>
                    <td class="FormulaNumber">
                        <el-tooltip :disabled="!item.verifyFormula"  class="item" effect="dark" :content="item.verifyFormula" placement="top">
                            <input class="groupInput" :class="{borderRed:item.verifyFormula}" :title="item.formula" type="text" v-model.trim="item.formula" @input="handleInp(index,$event,'FormulaNumber')"  @click="clickItem(index,'FormulaNumber')">
                        </el-tooltip> 
                    </td>
                   <td class="FeatureOpera">
                        <el-button type="text" size="small" class="delete" @click="addItem(index, 2)"><div class="btnOpera">+</div></el-button>
                        <el-button v-if="index !=0" type="text" size="small" class="delete" @click="delItem(index, 2)"><div class="btnOpera">-</div></el-button>
                    </td>
                    <!-- <td class="selectedContent ">{{item.indexUnique}}</td>
                    <td class="selectedContentGroup"><input class="groupInput" type="text" v-model="item.indexDesc" @input="handleInp(index,$event)"></td>
                    <td class="selectedContentOpera"><el-button type="text" size="small" class="delete" @click="delSelectedIndex(item, index)">删除</el-button></td> -->
                </tr>
                
            </table>
             <div class="btn clearfix">
                     <div class="btnBox">
                         <el-button
                                type="primary"
                                @click="submitForm()"
                                >校验并保存数据</el-button>
                            <el-button
                                type="primary"
                                :disabled = "hasQuestion == 1"
                                @click="exportDiagnosticAll"
                                >导出诊断依据</el-button>
                            <el-button
                                type="primary"
                                :disabled = "hasQuestion == 1"
                                @click="updateNeo"
                                >更新图谱</el-button>
                     </div>
                
                </div>
        </div>
        
    </div>
    
</template>

<script>
  import api from '@api/diagBase.js';
  import utils from '@api/utils.js';
  import apis from '@api/icss.js';

  export default {
    name: 'AddChronicAndIndexRelation',
    data() {
        return{
            
            id: '',  //诊断id
            disName:'',  //诊断名称
            modifier: '', //操作人
            titleText: '添加',
            diagList: [],
            featureTypeList: [],
            formulaTypeList: [],
            disFeatureList: [
                {
                    type:'',
                    code:'',
                    standard:'',
                    relation:'',
                    result:'',
                    formula:''
                }
            ],  //疾病特征列表
            disFeatureListResult:[], //疾病特征列表(保存用)
            disFormulaList:[
                {
                    type:'',
                    code:'',
                    standard:'',
                    relation:'',
                    result:'',
                    formula:''
                }
            ],
            disFormulaListResult:[], //诊断公式列表(保存用)
            searchDiagVal: '',
            isEdit: false,
            saveDisable: false ,
            hasQuestion: 1, //是否有问题词
        }
    },
    created(){
        const userLoginDTO = JSON.parse(localStorage.getItem('userLoginDTO'))
        this.modifier = userLoginDTO && userLoginDTO.linkman
        this.getDropList()
        const { isEdit, data } = this.$route.params;
        if(isEdit) {
            if(isEdit) {
                this.isEdit = isEdit;
                this.titleText = '修改';
                this.disName = data.disName
                this.id = data.id
                this.disFeatureList = data.disFeature
                if(data.disformula.length) {
                    this.disFormulaList = data.disformula
                } 
                this.hasQuestion = data.hasQuestion

            } 
        } else {
            
        }
    },
    watch: {
        // searchTagVal(newVal, preVal) {
        //     if(newVal.trim() == ''){
        //         this.getTagList()
        //     }else if(newVal.trim() != preVal.trim()){
        //         this.getTagList()
        //     }
        // }
    },
    methods: {
        getDropList() {
          return apis.getKnowledgeEnums().then((res) =>{
              if(res.data.code === '0') {
                  this.featureTypeList = res.data.data.diagnoseFeatureTypeEnum.filter(item => item.key != 0)
                  this.formulaTypeList = res.data.data.diagnoseTypeEnum
              }
                 
          })
        },
        close() {
            this.diagList = [];
            if(this.diagList.length>0){this.$refs['diagList'].style.display = 'none';}
        },
        back(){
            this.$router.go(-1);
        },
        searchDiag() {
            if(!this.searchDiagVal) {
                return
            }
            const param = {
                "name": this.searchDiagVal,
            }
            
            api.diagBaseIndex(param).then((res)=>{
               if(res.data.code === '0') {
                   this.diagList = res.data.data
                   if(this.diagList.length>0) {this.$refs['diagList'].style.display = 'block'}
                }
            })
        },
        selectDiag(item) {
            this.disName = item.name
            this.$refs['diagList'].style.display='none'
            this.searchDiagVal = ''
            this.diagList=[]
        },
        focuInput() {
            this.$refs['diagList'].style.display='none'
            
        },
        addItem(index, type) {
            if(type == 1) {
                const item = {
                    type:'',
                    code:'',
                    standard:'',
                    relation:'',
                    result:'',
                }
                this.disFeatureList.splice(index+1, 0, item)
            }else if(type == 2) {
                 const item = {
                    type:'',
                    code:'',
                    standard:'',
                    relation:'',
                    result:'',
                }
                this.disFormulaList.splice(index+1, 0, item)
            }
        },
        delItem(index, type) {
            if(type == 1) {
                this.disFeatureList.splice(index, 1)
            }else if(type == 2) {
                this.disFormulaList.splice(index, 1)
            }
        },
        updateNeo() {
            this.submitForm().then(() => {
                if(this.hasQuestion == 0) {
                    const param = {
                        id: this.id,
                        modifier: this.modifier
                    }
                    api.diagBaseUpdateNeo(param).then((res) => {
                        if(res.data.code == 0) {
                            this.warning('更新成功')
                        } else {
                            this.warning(res.data.msg)
                        }
                    })
                }
                
            })
            // api.diagBaseUpdateNeo(param).then((res) =>{

            // })
        },
        exportDiagnosticAll(){
            
            this.submitForm().then(() => {
                if(this.hasQuestion == 0) {
                        const param = {
                        diagnoseId: this.id
                    }
                    api.exportDiagnosticAll(param).then((res) => {
                        utils.downloadExportedData(res.data,'诊断依据' )
                    })
                }
                
            })
           
        },
        submitForm() {
            if(!this.disName) {
                this.warning('请选择诊断')
                return
            }
            this.disFeatureListResult = []
            this.disFormulaListResult = []
            let errStrList = [];
            for(let i = 0; i < this.disFeatureList.length; i++) {
                if(this.disFeatureList[i].type || this.disFeatureList[i].code || this.disFeatureList[i].standard || this.disFeatureList[i].relation || this.disFeatureList[i].result) {
                    this.disFeatureListResult.push(this.disFeatureList[i])
                }
            }
            for(let i = 0; i < this.disFormulaList.length; i++) {
                if(this.disFormulaList[i].type || this.disFormulaList[i].formula ) {
                    this.disFormulaListResult.push(this.disFormulaList[i])
                }
            }
            let disFeatureList;
            if(this.disFeatureListResult.length) {
               disFeatureList = this.disFeatureListResult;
            } else {
               disFeatureList = [
                    {
                        type:'',
                        code:'',
                        standard:'',
                        relation:'',
                        result:'',
                        formula:''
                    }
                ];
            }
            const disFormulaList = this.disFormulaListResult;
            let codeErrorNum = 0;
            for(let i=0; i < disFeatureList.length; i++) {
                if(!disFeatureList[i].type) {
                     disFeatureList[i].typeNull = "未选择类型"
                }
                 if(!disFeatureList[i].code) {
                    disFeatureList[i].codeNull = "未填写编码"
                }
                 if(!disFeatureList[i].standard) {
                    disFeatureList[i].standardNull = "未填写标准词"
                }
                if(!disFeatureList[i].type||!disFeatureList[i].code||!disFeatureList[i].standard) {
                    const errStr = "第" + (i+ 1) +"行必填项未填写"
                    errStrList.push(errStr)
                }
                if(disFeatureList[i].type == '3' && disFeatureList[i].result && !disFeatureList[i].relation) {
                     disFeatureList[i].relationNull = "未填写关联词"
                     const errStr = "第" + (i+ 1) +"行化验项数据填写不完整"
                    errStrList.push(errStr)
                }
                let regex =new RegExp(`${disFeatureList[i].type}\\.[1-9]\\d?`) 
                if(disFeatureList[i].code &&!regex.test(disFeatureList[i].code)) {
                    codeErrorNum++
                    disFeatureList[i].codeError = "序号和类型不匹配"
                    const errStr = "疾病特征第" + (i+ 1) +"行序号和类型不匹配"
                    errStrList.push(errStr)
                } 
                
            }
            this.disFeatureList = JSON.parse(JSON.stringify(disFeatureList))
            let formulaListErrNum = 0
            for(let i=0; i < disFormulaList.length; i++) {
                   if(disFormulaList[i].type&&!disFormulaList[i].formula ) {
                       disFormulaList[i].verifyFormula = "诊断公式不能为空"
                       formulaListErrNum++;
                       const errStr = "诊断公式第" + (i+ 1) +"行诊断公式不能为空"
                       errStrList.push(errStr)
                   } else if(disFormulaList[i].formula&&!disFormulaList[i].type) {
                       disFormulaList[i].verifyType = "诊断类型不能为空"
                        const errStr = "诊断公式第" + (i+ 1) +"行诊断类型不能为空"
                       errStrList.push(errStr)
                       formulaListErrNum++;
                   }
            }
            if(disFormulaList.length) {
                this.disFormulaList = JSON.parse(JSON.stringify(disFormulaList))
            }
           
            let errorStr =''
            for(let i = 0; i <errStrList.length; i++) {
                errorStr += '<p>'+errStrList[i]+'</p>'
            }
           
            if(errStrList.length >0 ||codeErrorNum > 0 ||formulaListErrNum > 0) {
                 this.$alert(errorStr,'错误信息',{
                    dangerouslyUseHTMLString: true,
                    confirmButtonText: '确定',
                    callback: action => {
                        /*this.$message({
                        type: 'info',
                        message: `action: ${ action }`
                        });*/
                    }
                });
                return
            }
            // this.showDelDialog()
            return this.diagBaseVerifyData()
           
        },
        diagBaseVerifyData() {
             const param = {
                disFeature: this.disFeatureListResult,
                disName: this.disName,
                disformula: this.disFormulaListResult,
                id: this.id,
                modifier: this.modifier
            }
            return api.diagBaseVerifyData(param).then((res) => {
                const data = res.data.data
                if(data.hasQuestion) {
                    this.warning('校验完成请先调整问题词')
                } else {
                    this.warning('校验成功')
                }
                this.id = data.id
                this.disFeatureList = data.disFeature
                if(data.disformula.length) {
                    this.disFormulaList = data.disformula
                }else {
                    this.disFormulaList = [
                        {
                            type:'',
                            code:'',
                            standard:'',
                            relation:'',
                            result:'',
                            formula:''
                        }
                    ]
                }  
                this.hasQuestion = data.hasQuestion
                
            })
        },
        
        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'
            })
        },
        handleInp(index,e,type,itemType){ //分组不能输入负数
            const value =  e.target.value;
            if(type === 'FeatureNumber') { //序号只能输入数字和.
                this.disFeatureList[index].code = value.replace(/[^\d.]/g,'')
            } else if(type==='FeatureStand') {  //关联词不能输入顿号
                this.disFeatureList[index].standard = value.replace(/、/g,'')
            } else if ( type === 'FormulaNumber') {
                //计算公式只能输入以下内容： 任、一、二、三、四、五、六、七、八、九、十、0-9、/、.、(、)、（、）
                this.disFormulaList[index].formula =  value.replace(/[^\u4EFB\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u53410-9\/\.+\(\)\（\）]/g,'').replace(/[\（]/g, '(').replace(/[\）]/g, ')').replace(/' '/g, '')
            } else if ( type === 'FeatureRelate') {
                if(itemType == 3) {
                    this.disFeatureList[index].relation = value.replace(/、/g,'')
                }
            }
            // const item = this.selectedIndexList[index].indexDesc;
            // e.target.value = value.replace(/[^\d]/g,'');
            // this.selectedIndexList[index].indexDesc = item.replace(/[^\d]/g,'');
        },
        clickItem(index, type) {
            switch(type) {
                case 'FeatureType':
                    this.disFeatureList[index].typeNull = ''
                    this.disFeatureList[index].code = ''
                    this.disFeatureList[index].standard = ''
                    this.disFeatureList[index].relation = ''
                    this.disFeatureList[index].result = ''
                    this.disFeatureList[index].formula = ''
                    return this.disFeatureList = JSON.parse(JSON.stringify(this.disFeatureList))
                case 'FeatureNumber': 
                    this.disFeatureList[index].codeNull = ''
                    this.disFeatureList[index].verifyCode = ''
                    this.disFeatureList[index].codeError = ''
                    return this.disFeatureList = JSON.parse(JSON.stringify(this.disFeatureList))
                case 'FeatureStand':
                    this.disFeatureList[index].verifyStandard =''
                    this.disFeatureList[index].standardNull =''
                    return this.disFeatureList = JSON.parse(JSON.stringify(this.disFeatureList))
                case 'FeatureRelate':
                    this.disFeatureList[index].verifyRelation =''
                    return this.disFeatureList = JSON.parse(JSON.stringify(this.disFeatureList))
                case 'FeatureResult':
                    this.disFeatureList[index].verifyResult =''
                    return this.disFeatureList = JSON.parse(JSON.stringify(this.disFeatureList))
                case 'FeatureResult':
                    this.disFeatureList[index].verifyResult =''
                    return this.disFeatureList = JSON.parse(JSON.stringify(this.disFeatureList))
                case 'FormulaType':
                     this.disFormulaList[index].verifyType =''
                    return this.disFormulaList = JSON.parse(JSON.stringify(this.disFormulaList))
                case 'FormulaNumber':
                    this.disFormulaList[index].verifyFormula =''
                    return this.disFormulaList = JSON.parse(JSON.stringify(this.disFormulaList))
            }
        },
        warning(msg,type){
          this.$message({
            showClose: true,
            message:msg,
            type:type||'warning'
          })
        }
    }
  }
</script>

<style lang="less">
    @import '../../less/common.less';
    .AddDiagBaseWrapper {
        color: #606266;
        .topBack {
            top: 0;
        }
        .groupTitle {
            background-color: #fff;
            height: 40px;
            line-height: 40px;
            padding-left: 20px;
        }
        .searchInput, .searchName {
            display: inline-block;
            height: 32px;
            line-height: 32px;
            border: 1px solid #a9a9a9;
            margin: 0px 0 0 0;
            padding: 0 5px;
            float: left;
            margin-top: 4px;
        }
        .isRequired .el-form-item__label::before {
            content: '*';
            color: red;
        }
        .searchName {
            border-left: none;
            cursor: pointer;
            font-size: 16px;
            padding: 0 14px;
        }
        .itemList {
            position: absolute;
            display: none;
            background: #fff;
            width: 162px;
            max-height: 150px;
            border: 1px solid #a9a9a9;
            left: 138px;
            top: 37px;
            z-index: 2;
            overflow-y: auto;
        }
        .diagItem {
            padding: 0 5px;
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            cursor: pointer;
        }
        .diagItem:hover {
            background: #f5f7fa;
        }
        .addDepartForm {
            position: relative;
            background-color: #fff;
            padding: 20px;
            margin: 70px 20px 0px 20px;
        }
        .addDiagName {
            position: relative;
        }
        .symptomList {
            position: relative;
            background-color: #fff;
             padding: 20px 20px 100px 20px;
             margin: 0px 20px 40px 20px;
             min-height: 400px;
        }
        
        .diagTable {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            tr {
                td {
                    padding: 5px 10px;
                    border: 1px solid #a9a9a9;
                    text-align: center;
                }
                .FormulaOpera, .FeatureOpera{
                    background: #fff;
                    border: none;
                    text-align: left;
                    padding-left: 30px;
                }
            }
            .selectedContent {
                width: 25%;
            }
            .selectedContentGroup {
                width: 55%;
            }
            .selectedContentOpera {
                width: 20%;
            }
        }
        .groupInput {
            text-align: center;
            height: 28px;
            color: #606266;
            width: 80%;
        }
        .btn {
            position: absolute;
            background-color: #fff;
            width: 100%;
            margin: 20px 0;
            height: 40px;
            bottom: 0px;
            right: 0px;
            .btnBox {
                position: absolute;
                right: 0px;
                
            }
            .el-button {
                margin-right: 20px;
               
            }
        }
        .tableTitle{
            background: rgba(239,243,249,1);
        }
        .require::after{
            content:"*";
            color: red;
        }
        .borderRed {
            border: 1px solid red !important;
        }
        .colorRed {
            color: red;
        }
        .FeatureSort {
            width: 5%;
        }
        .FeatureType {
            width: 7%;
        }
        .FeatureNumber {
            width: 8%;
        }
        .FeatureStand {
            width: 20%;
        }
        .FeatureRelate {
            width: 20%;
        }
        .FeatureResult {
            width: 20%;
        } 
        .FeatureOpera{
            width: 20%;
        } 
        .FormulaSort{
            width: 5%;
        } 
        .FormulaType{
            width: 7%;
        } 
        .FormulaNumber{
            width: 68%;
        } 
        .FormulaOpera{
            width: 20%;
        }
        .btnOpera {
            width:16px;
            height:16px;
            background:rgba(176,190,197,1);
            border-radius: 50%;
            color: #fff;
            line-height: 16px;
            text-align: center;
        }
        /deep/.el-input--mini .el-input__inner {
            width: 80px;
        }
        /deep/ .is-disabled {
                    background: #ECECEC;
                    color: #AAAAAA;
                    border: none;
                }
        .selectType {
            input {
                border: 1px solid red;
            }
            input:hover {
                border: 1px solid red;
            }
        }
        .moduleTitle {
            margin: 0 0 10px 0;
        }
        .inpDisabled{
            background: #ECECEC;
            color: #AAAAAA;
            border: none;
            cursor: not-allowed;
        }
        .inpTips {
            font-size: 13px;
            color: red;
            margin-bottom: 10px;
        }
    }
    
</style>