<!-- 添加常见科室症状  -->
<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 v-if="showDiagList&&diagList.length > 0" 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="已选添加疾病名称：" :class="{colorRed: !disNameExist}">
                {{disName}}
            </el-form-item>
        </el-form>
        <div class="symptomList">
            <p class="moduleTitle">疾病特征：</p>
            <p class="inpTips">序号输入规则“序号+.”后可输入的范围0～99；标准词只能有一个词；化验类型关联只能出现一个词，其他类型可以输入多个词；化验类型可输入结果列，其他类型不可输入</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="FeatureuniqueName">化验公表项</td>
                    <td class="FeatureResult">结果</td>
                    <td class="FeatureOpera"></td>
                </tr>
                <DisFeatureItem
                    v-for="(item, index) in disFeatureList"
                    :key="index"
                    :item = "item"
                    :index = "index"
                    :featureTypeList = 'featureTypeList'
                    :showDiagList = 'showDiagList'
                    :searchIndex = 'searchIndex'
                    :searchFiled = 'searchFiled'
                    :searchResultList = 'searchResultList'
                     @handleInp="handleInp($event)"  
                     @clickItem="clickItem($event)"
                     @addItem ="addItem($event)"
                     @delItem ="delItem($event)"
                     @selectSearchItem = "selectSearchItem($event)"
                >

                </DisFeatureItem>
                
            </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>

                <DisFormulaItem
                    v-for="(item, index) in disFormulaList"
                    :key="index"
                    :item = "item"
                    :index = "index"
                    :formulaTypeList = 'formulaTypeList'
                     @handleInp="handleInp($event)"  
                     @clickItem="clickItem($event)"
                     @addItem ="addItem($event)"
                     @delItem ="delItem($event)"
                >
                </DisFormulaItem>
                
                
            </table>
             <div class="btn clearfix">
                     <div class="btnBox">
                          <el-button
                                type="primary"
                                :disabled = "isReady"
                                @click="saveTemp"
                                >临时保存</el-button>
                         <el-button
                                type="primary"
                                :disabled = "isReady"
                                @click="submitForm('save')"
                                >校验并保存数据</el-button>
                            <el-button
                                type="primary"
                                :disabled = "hasQuestion != 0"
                                @click="exportDiagnosticAll"
                                >导出诊断依据</el-button>
                            <el-button
                                type="primary"
                                :disabled = "hasQuestion != 0"
                                @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';
  import Textarea from './Textarea';
  import DisFeatureItem from './DisFeatureItem'
  import DisFormulaItem from './DisFormulaItem'
  

  export default {
    name: 'AddChronicAndIndexRelation',
    data() {
        return{
            
            id: '',  //诊断id
            disName:'',  //诊断名称
            modifier: '', //操作人
            titleText: '添加',
            diagList: [],
            featureTypeList: [],
            formulaTypeList: [],
            disFeatureList: [
                {
                    type:1,
                    code:'',
                    standard:'',
                    relation:'',
                    midResult:'',
                    formula:'',
                    result:'',
                    uniqueName:''
                }
            ],  //疾病特征列表
            disFeatureListResult:[], //疾病特征列表(保存用)
            disFormulaList:[
                {
                    type:92,
                    code:'',
                    standard:'',
                    relation:'',
                    midResult:'',
                    result:'',
                    formula:'',
                    uniqueName:''
                }
            ],
            disFormulaListResult:[], //诊断公式列表(保存用)
            searchDiagVal: '',
            isEdit: false,
            saveDisable: false ,
            hasQuestion: 1, //是否有问题词
            disNameExist: true, //诊断名称是否存在
            hasNoUniqueName: false, //是否存在没有公表项的化验
            isReady:false,
            showDiagList: false,
            searchIndex: -1,
            searchFiled: '',
            searchResultList: [],
            loading: undefined,
            showSearchList: true //是否展示搜索列表(解决引接口回来比较迟输入内容为空搜索内容还存在)
        }
    },
    created(){
        this.loading =  this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        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.disNameExist = data.disNameExist
                if(data.disFeature.length) {
                    this.disFeatureList = data.disFeature
                }   
                if(data.disformula.length) {
                    this.disFormulaList = data.disformula
                } 
                this.hasQuestion = data.hasQuestion
            } 
        } else {
            
        }
    },
   mounted(){
       this.$nextTick(()=>{
            if(Array.isArray(this.$refs.textarea)) {
                for(let i=0; i <this.$refs.textarea.length; i++) {
                    this.$refs.textarea[i].resizeTextarea()
                } 
            }else {
                this.$refs.textarea&&this.$refs.textarea.resizeTextarea()
            }
           this.loading.close()
       })
       
   },
    watch: {
        // searchTagVal(newVal, preVal) {
        //     if(newVal.trim() == ''){
        //         this.getTagList()
        //     }else if(newVal.trim() != preVal.trim()){
        //         this.getTagList()
        //     }
        // }
    },
    beforeRouteLeave(to, from, next) {
        this.showConfirmDialog('是否离开当前页面？（如果未校验并保存数据/暂存数据时请先保存）',()=>{
            next()
        })
       
    },
    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.showDiagList = false
            this.searchResultList = []
            this.diagList = []
        },
        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
                   this.showDiagList = true
                }
            })
        },
        selectDiag(item) {
            this.disName = item.name
            this.searchDiagVal = ''
            this.diagList=[]
        },
        selectSearchItem(event){
            const {index, item, searchType} = event
            if(searchType === 'FeatureStand') {
                const SelectResult =  this.getSelectResult(this.disFeatureList[index].standard, item)
                this.disFeatureList[index].standard = SelectResult
                this.disFeatureList = JSON.parse(JSON.stringify(this.disFeatureList))
                this.searchResultList = []
            } else if(searchType === 'FeatureRelate') {
                const SelectResult =  this.getSelectResult(this.disFeatureList[index].relation, item)
                this.disFeatureList[index].relation = SelectResult
                this.disFeatureList = JSON.parse(JSON.stringify(this.disFeatureList))
                this.searchResultList = []
            }
        },
        getSelectResult(val,item) {
            const index = val.lastIndexOf('、')
            if(index < 0) {
                return item
            } else {
                return val.slice(0,index+1)+item
            }
        },
        focuInput() {
            this.showDiagList = false            
        },
        clickItemBox(e) {
            e.target.children[0].focus()
        },
        getSearchVal(val) {
          const index = val.lastIndexOf('、')
          if(index < 0) {
            return val
          } else {
            return val.slice(index+1)
          }
        },
        diagBaseSearch(field, name, type) {
            this.showDiagList = true
            const param = {
                field,
                name,
                type
            }
            api.diagBaseSearch(param).then((res)=>{
                if(res.data.code == '0'&&this.showSearchList) {
                    this.searchResultList = res.data.data
                } else {
                     this.searchResultList = []
                }
            })
        },
        addItem(event) {
            const {index, type } = event
            if(type == 1) {
                const item = {
                    type:1,
                    code:'',
                    standard:'',
                    relation:'',
                    midResult:'',
                    result:'',
                    uniqueName:''
                }
                this.disFeatureList.splice(index+1, 0, item)
            }else if(type == 2) {
                 const item = {
                    type:92,
                    code:'',
                    standard:'',
                    relation:'',
                    midResult:'',
                    result:'',
                    uniqueName:''
                }
                this.disFormulaList.splice(index+1, 0, item)
            }
        },
        delItem(event) {
            const {index, type} = event
            if(type == 1) {
                this.disFeatureList.splice(index, 1)
            }else if(type == 2) {
                this.disFormulaList.splice(index, 1)
            }
        },
        //导入
        // uploadClick() {
        //     let inp = document.getElementById("upFile");
        //     inp.click();
        // },
        // uploadFile(e){
        //     let fileInfo = e.target.files[0];
        //     e.preventDefault();
        //     let formData = new FormData();
        //     formData.append('uploadfile', fileInfo);
        //     const header = {
        //         headers:{
        //         'Content-Type': 'multipart/form-data'
        //         }
        //     }
        //     api.importDiagnosticBasis(formData,header).then((res)=>{
        //        
        //         if(res.data.code==0){
        //             const data = res.data.data
        //             this.warning('上传成功','success')
        //             let feature = data.feature
        //             let equation = data.equation
        //             const featureList = []
        //             const formulaList = []

        //             if(feature&&feature.length > 0) {
        //                for(let i = 1; i <feature.length; i++) {
        //                    const item = {}
        //                    item.type = '';
        //                    for (let j = 0; j < this.featureTypeList.length; j++) {
        //                        if(feature[i].type.indexOf(this.featureTypeList[j].name) > -1) {
        //                            item.type = this.featureTypeList[j].key
        //                            break;
        //                        }
        //                    }
                           
        //                    item.code = feature[i].code
        //                    item.standard = feature[i].standard
        //                    item.relation = feature[i].associated
        //                    if(item.type === 4) {
        //                        item.midResult = ''
        //                    } else {
        //                         item.midResult = feature[i].midResult
        //                    }
        //                    featureList.push(item)
        //                }
        //             }
        //             if(equation&&equation.length > 0) {
        //                for(let i = 1; i <equation.length; i++) {
        //                    const item = {}
        //                    item.type = '';
        //                    for (let j = 0; j < this.formulaTypeList.length; j++) {
        //                        if(equation[i].type.indexOf(this.formulaTypeList[j].name) > -1) {
        //                            item.type = this.formulaTypeList[j].key
        //                            break;
        //                        }
        //                    }
        //                    item.formula = equation[i].associated
                           
        //                    formulaList.push(item)
        //                }
        //             }
        //             this.disFeatureList = featureList
        //             this.disFormulaList = formulaList
        //            
        //         }else{
        //         /*this.$message({
        //             dangerouslyUseHTMLString: true,
        //             message:res.data.msg,
        //             type:'warning'
        //         });*/
        //         this.$alert(res.data.msg,'错误信息',{
        //             dangerouslyUseHTMLString: true,
        //             confirmButtonText: '确定',
        //             callback: action => {
        //             /*this.$message({
        //                 type: 'info',
        //                 message: `action: ${ action }`
        //             });*/
        //             }
        //         });
        //         }
        //     })
            
        //     //解决上传相同文件不触发change
        //     let inp = document.getElementById("upFile");
        //     inp.value = "";   
        // },
        updateNeo() {
            const submitFormResult = this.submitForm('updateNeo')
            if(!submitFormResult) {
                return
            } else {
                submitFormResult.then((data) => {
                    if(data !== false) {
                         if(this.hasQuestion == 0) {
                            const param = {
                                id: this.id,
                                modifier: this.modifier
                            }
                            api.diagBaseUpdateNeo(param).then((res) => {
                                if(res.data.code == 0) {
                                    this.warning('更新成功', 'success');
                                } else {
                                    this.warning(res.data.msg)
                                }
                            })
                        } else {
                            this.warning('更新失败');
                        }

                        }
                })
            
            }
        },
        exportDiagnosticAll(){
            const submitFormResult = this.submitForm('export')
            if(!submitFormResult) {
                return
            } else {
                submitFormResult.then(() => {
                    if(this.hasQuestion == 0) {
                        const param = {
                            diagnoseId: this.id
                        }
                        api.exportDiagnosticAll(param).then((res) => {
                            utils.downloadExportedData(res.data,'诊断依据.xls');
                        })
                    }else {
                        if(!this.hasNoUniqueName) {
                            this.warning('导出失败');
                        }
                    }
                    
                }).catch((e)=>{
                })

            }
            
           
        },
        saveTemp(){
             if(!this.disName) {
                this.warning('请选择诊断');
                return
            }
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            this.hasQuestion= 1
            const param = {
                disFeature: this.disFeatureList,
                disName: this.disName,
                disformula: this.disFormulaList,
                id: this.id,
                modifier: this.modifier
            }
            api.tempSaveOrUpate(param).then((res)=>{
                loading.close()
                if(res.data.code === '0') {
                   this.id = res.data.data
                   this.warning('临时保存成功','success')
                }else {
                    this.warning(res.data.msg)
                }
            })
        },
        submitForm(type) {
            if(!this.disName) {
                this.warning('请选择诊断');
                return
            }
            this.disFeatureListResult = []
            this.disFormulaListResult = []
         
            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].midResult) {
                    this.disFeatureListResult.push(this.disFeatureList[i])
                }
            }
            
            let disFeatureList;
            if(this.disFeatureListResult.length) {
               disFeatureList = this.disFeatureListResult;
            } else {
               disFeatureList = [
                    {
                        type:'',
                        code:'',
                        standard:'',
                        relation:'',
                        midResult:'',
                        result:'',
                        formula:'',
                        uniqueName:''
                    }
                ];
            }
            this.disFeatureList = disFeatureList
            // this.showDelDialog()
            this.hasQuestion = 1
            return this.diagBaseVerifyData(type)
           
        },
        diagBaseVerifyData(type) {
           
            //判断诊断依据先判断化验有没有公表项
             const labArr= []
            for (let i = 0; i < this.disFeatureList.length; i++) {
                if(+this.disFeatureList[i].type === 3) {
                    labArr.push({index: i, mealName: this.disFeatureList[i].standard, itemName: this.disFeatureList[i].relation, uniqueName:''})
                } 
            }

            
           
            if(type == 'save'){
                this.isReady = true
            }
            if(labArr.length > 0) {
                const hasErrorData =  this.errorDataVerify()
                 if(!hasErrorData) {
                    return false
                } else {
                    this.hasNoUniqueName = false
                    const labVerifyData = this.labVerifyData(labArr,type)
                    if(labVerifyData) {
                         return labVerifyData.then((data) =>{
                            if(this.hasNoUniqueName||data===false) {
                                return false
                            }else {
                                return this.verifyDiagBase(type)
                            }
                        })
                    }
                   
                }
                
            } else {
                const hasErrorData =  this.errorDataVerify()
                if(!hasErrorData) {
                    return false
                } else {
                    return this.verifyDiagBase(type)
                }   
            }
        },
        errorDataVerify() {
            for(let i = 0; i < this.disFormulaList.length; i++) { //如果有任意一项有值，就检测，所有项都没值，则删掉这条数据
                if( this.disFormulaList[i].formula ) {
                    this.disFormulaListResult.push(this.disFormulaList[i])
                }
            }
            const disFeatureList = this.disFeatureList;
            const disFormulaList = this.disFormulaListResult;
            let codeErrorNum = 0;
            let errStrList = [];
            //必填项是否填写
            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)
                }
                let regex =new RegExp(`^${disFeatureList[i].type}\\.(0|[1-9]\\d?)$`,) 
                if(disFeatureList[i].code &&!regex.test(disFeatureList[i].code)) {  //序号和类型不匹配
                    codeErrorNum++
                    disFeatureList[i].codeError = "序号和类型不匹配"
                    const errStr = "疾病特征第" + (i+ 1) +"行序号和类型不匹配"
                    errStrList.push(errStr)
                } else { //序号和类型匹配但序号重复
                    let codeArr =  disFeatureList.filter(item => item.code ===disFeatureList[i].code) 
                    if(codeArr.length > 1) {
                        codeErrorNum++
                        disFeatureList[i].codeError = "序号重复"
                        const errStr = "疾病特征第" + (i+ 1) +"行序号重复"
                        errStrList.push(errStr)

                    }
                }

                //化验项有结果则必须有关联词
                if(disFeatureList[i].type == '3' && disFeatureList[i].midResult && !disFeatureList[i].relation) {
                     disFeatureList[i].relationNull = "未填写关联词"
                     const errStr = "第" + (i+ 1) +"行化验项数据填写不完整"
                    errStrList.push(errStr)
                }
               
                //导入后判断
                // let regexPause = new RegExp(`、`)      //判断标准词是否有顿号
                //  if(disFeatureList[i].standard &&regexPause.test(disFeatureList[i].standard)) {
                //     disFeatureList[i].verifyStandard ='数据异常'
                //     const errStr = "疾病特征第" + (i+ 1) +"行标准词数据异常"
                //     errStrList.push(errStr)
                // }

                // if(disFeatureList[i].type == '3'&&regexPause.test(disFeatureList[i].relation)) {
                //     disFeatureList[i].verifyRelation ='数据异常'
                //     const errStr = "疾病特征第" + (i+ 1) +"行化验关联词数据异常"
                //     errStrList.push(errStr)
                // }
                //导入后判断

                if(disFeatureList[i].type == '3') { 
                    disFeatureList[i].verifyRelation = ""
                    disFeatureList[i].verifyResult = ""
                    if(!disFeatureList[i].midResult ) {//化验项下面诊断公式如果有用到，判断是否填写结果项
                        const regex2 = new RegExp(`(?<=\\D|\\b)${disFeatureList[i].code.replace('.','\\.')}(?=\\D|\\b)`) //序号+前面是单词边界或者是非数字+后面是单词边界或者是非数字
                        //  const regex2 = new RegExp(`、\\s*、{1,}`) 
                        //  const regex2 = new RegExp(`([^0-9]|\\s{0,1})${disFeatureList[i].code}([^0-9]|\\s{0,1})`)
                        let hasError = disFormulaList.find(item => {return regex2.test(item.formula)})
                        if(hasError) {
                            if(!disFeatureList[i].relation) {
                                disFeatureList[i].verifyRelation = "数据异常"
                            }
                            disFeatureList[i].verifyResult = "数据异常"
                            const errStr = "第" + (i+ 1) +"行化验项数据异常"
                            errStrList.push(errStr)
                    }
                    }
                  
                }
                 if(disFeatureList[i].type == '4' && !disFeatureList[i].relation ) { //辅检项下面诊断公式如果有用到，判断是否填写结果项（辅检结果是填在关联词列）
                    const regex2 = new RegExp(`(?<=\\D|\\b)${disFeatureList[i].code.replace('.','\\.')}(?=\\D|\\b)`)
                    let hasError = disFormulaList.find(item => {return regex2.test(item.formula)})
                    if(hasError) {
                        disFeatureList[i].verifyRelation = "数据异常"
                        const errStr = "第" + (i+ 1) +"行辅捡项数据异常"
                        errStrList.push(errStr)
                    }
                }
                let regex1 =new RegExp(`、\\s*、{1,}|^、|、$`) 
                if(disFeatureList[i].relation &&regex1.test(disFeatureList[i].relation)) { //不能输入连续的、，前后也不能是、
                    disFeatureList[i].verifyRelation ='数据异常'
                    const errStr = "疾病特征第" + (i+ 1) +"行数据异常"
                    errStrList.push(errStr)
                }
                if(disFeatureList[i].midResult &&regex1.test(disFeatureList[i].midResult)) {
                    disFeatureList[i].verifyResult ='数据异常'
                    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[i].type == 91) { //确诊中有没有包含其他不可输入内容
                    //     let regexDisFormula = /[^\u4EFB\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341\u62df\u8bca0-9\/\.+\(\)\（\）]/g
                    //     if(regexDisFormula.test(disFormulaList[i].formula)) {
                    //          disFormulaList[i].verifyFormula = "公式格式错误"
                    //          const errStr = "诊断公式第" + (i+ 1) +"行公式格式错误,"
                    //         errStrList.push(errStr)
                    //         formulaListErrNum++;
                    //     }
                    // } else {   //其他诊断中有没有包含其他不可输入内容
                    // //计算公式只能输入以下内容： 任、一、二、三、四、五、六、七、八、九、十、0-9、/、.、(、)、（、）
                    //     let regexDisFormula = /[^\u4EFB\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u53410-9\/\.+\(\)\（\）]/g
                    //     if(regexDisFormula.test(disFormulaList[i].formula)) {
                    //          disFormulaList[i].verifyFormula = "公式格式错误"
                    //          const errStr = "诊断公式第" + (i+ 1) +"行公式格式错误"
                    //         errStrList.push(errStr)
                    //         formulaListErrNum++;
                    //     }
                    // }
                    //导入后判断

                   if(disFormulaList[i].type == 91 && disFormulaList[i].formula.indexOf("拟诊") > -1) { //确诊项如果有拟诊这两个字，判断公式列表中有没有拟诊这项
                       const noError = disFormulaList.filter(item => item.type == 92).length > 0
                       if(!noError) {
                           disFormulaList[i].verifyFormula = "公式格式错误"
                            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.disFeatureList = JSON.parse(JSON.stringify(disFeatureList))
                this.errorTips(errorStr)
                this.isReady=false
                return  false
            }
             return true
        },
        labVerifyData(labArr,type) {
            const labArrParam = {
                lisMappingSearchList : labArr
            }
             const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });

            return api.getUniqueNameWithList(labArrParam).then((res) => {
                this.isReady=false
                loading.close();
                if(res.data.code === '0') {
                    const data = res.data.data
                    let errorStr = ''
                    for (let i = 0; i < data.length; i++ ) {
                        if(!data[i].uniqueName) { //判断是否存在公表项
                            if(!this.hasNoUniqueName) {
                               

                                this.hasNoUniqueName = true
                            }
                            errorStr +=`<p>第${+data[i].index+1}行化验公表项不存在</p>`
                            this.disFeatureListResult[data[i].index].verifyUnique="公表项不存在"
                            this.disFeatureListResult[data[i].index].uniqueName=""
                        } else {
                            this.disFeatureListResult[data[i].index].verifyUnique=""
                        }
                        this.disFeatureListResult[data[i].index].uniqueName = data[i].uniqueName
                        if(data[i].uniqueName) { //有公表项和结果，则将公表项和结果拼接起来，结果用、分隔
                            if(this.disFeatureListResult[data[i].index].midResult) {
                                let midResult = this.disFeatureListResult[data[i].index].midResult.replace(' ', '').split('、')
                                for (let j = 0; j < midResult.length; j++) {
                                    if(midResult[j]) {
                                        midResult[j] = data[i].uniqueName+midResult[j]
                                    }
                                }
                                this.disFeatureListResult[data[i].index].result = midResult.join('、')
                            }
                           
                        }
                    }
                    this.disFeatureList = JSON.parse(JSON.stringify(this.disFeatureListResult))
                    this.disFeatureListResult = JSON.parse(JSON.stringify(this.disFeatureListResult))
                    if(errorStr) {
                       return this.errorTips(errorStr);
                        
                    }

                   
                    
                } else {
                    this.warning(res.data.msg)
                    return false
                }
            }).catch(()=>{ this.isReady=false;loading.close()})
        },
        verifyDiagBase(type) {
            const param = {
                disFeature: this.disFeatureListResult,
                disName: this.disName,
                disformula: this.disFormulaListResult,
                id: this.id,
                modifier: this.modifier
            }
            
            
           
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
        
                const diagBaseVerifyDataResult =  api.diagBaseVerifyData(param)

                return diagBaseVerifyDataResult.then((res) => {
                    if(+res.data.code === 0) {
                        const data = res.data.data
                        this.isReady=false
                        if(type =='save') {
                            if(data.hasQuestion) {
                                this.warning('校验完成请先调整错误数据,该数据已保存')
                            } else {
                                this.warning('校验成功', 'success')
                            }
                        }
                        
                        this.id = data.id
                        this.disNameExist = data.disNameExist
                        this.disFeatureList = data.disFeature                                                                           
                        if(data.disformula.length) {
                            this.disFormulaList = data.disformula
                        }else {
                            this.disFormulaList = [
                                {
                                    type:92,
                                    code:'',
                                    standard:'',
                                    relation:'',
                                    result:'',
                                    midResult:'',
                                    formula:'',
                                    uniqueName:''
                                }
                            ]
                        }  
                        this.hasQuestion = data.hasQuestion
                    } else {
                        this.hasQuestion = 1
                        this.warning(res.data.msg)
                    }
                    
                    loading.close()
                    
                    }).catch(()=>{ this.hasQuestion = false; this.isReady=false; loading.close()})


            
            
        },
        showConfirmDialog(msg, resolve) {
            this.$alert(msg, '提示', {
                confirmButtonText: '确定',
                type: 'warning'
            }).then(() => {
                resolve();
            }).catch(() => {});
        },
       
        // handleInp(index,e,type,itemType){ //分组不能输入负数
         handleInp(event){
            const {index,e,type,itemType} = event
            const value = e
            if(type === 'FeatureNumber') { //序号只能输入数字和.
                this.$nextTick(() => {
                    this.disFeatureList[index].code = value.replace(/[^\d.]/g,'')
                })
            } else if(type==='FeatureStand') {  //标准词不能输入顿号
                 this.$nextTick(() => {
                    const resultVal = value.replace(/、/g,'').replace(' ','')
                    this.disFeatureList[index].standard = resultVal
                    if(resultVal) {
                        const searchVal = this.getSearchVal(resultVal)
                        if(searchVal) {
                             this.showSearchList = true
                             this.searchIndex = index
                            this.searchFiled = 'FeatureStand'
                            this.diagBaseSearch(2,searchVal,itemType)
                        } else {
                            this.showSearchList = false
                            this.searchResultList = []
                        }
                    } else {
                         this.showSearchList = false
                        this.searchResultList = []
                    }
                    
                })
                // this.disFeatureList[index].standard = value.replace(/、/g,'')
            } else if ( type === 'FormulaNumber') {
                //计算公式确诊只能输入以下内容： 任、一、二、三、四、五、六、七、八、九、十、拟、诊、0-9、/、.、(、)、（、）
                if(itemType == 91) {
                    this.$nextTick(() => {

                        this.disFormulaList[index].formula =  value.replace(/[^\u4EFB\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341\u62df\u8bca0-9\/\.+\(\)\（\）]/g,'').replace(/[\（]/g, '(').replace(/[\）]/g, ')').replace(/' '/g, '')
                    })
                } else {    //计算公式其他只能输入以下内容： 任、一、二、三、四、五、六、七、八、九、十、0-9、/、.、(、)、（、）
                //计算公式只能输入以下内容： 任、一、二、三、四、五、六、七、八、九、十、0-9、/、.、(、)、（、）
                    this.$nextTick(() => {
                        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') {
                let resultVal;

                if(itemType == 3) {
                     resultVal = value.replace(/、/g,'').replace(' ','')
                } else {
                     resultVal = value.replace(' ','')
                }
                this.$nextTick(() => {
                    this.disFeatureList[index].relation = resultVal
                })
               if(resultVal) {
                    const searchVal = this.getSearchVal(resultVal)
                    if(searchVal) {
                         this.showSearchList = true
                        this.searchIndex = index
                        this.searchFiled = 'FeatureRelate'
                        this.diagBaseSearch(3,searchVal,itemType)
                    } else {
                        this.showSearchList = false
                        this.searchResultList = []
                    }

                } else {
                    this.showSearchList = false
                    this.searchResultList = []
                }

            }
            // const item = this.selectedIndexList[index].indexDesc;
            // e.target.value = value.replace(/[^\d]/g,'');
            // this.selectedIndexList[index].indexDesc = item.replace(/[^\d]/g,'');
        },
        clickItem(e) {
            const {index, type} = e
            this.showDiagList = false
            switch(type) {
                case 'FeatureType':
                    this.disFeatureList[index].typeNull = ''
                    this.disFeatureList[index].code = ''
                    this.disFeatureList[index].standard = ''
                    this.disFeatureList[index].relation = ''
                    this.disFeatureList[index].midResult = ''
                    this.disFeatureList[index].result = ''
                    this.disFeatureList[index].formula = ''
                    this.disFeatureList[index].uniqueName = ''
                    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 =''
                    this.disFeatureList[index].relationNull =''
                    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 =''
                     this.disFormulaList[index].formula =''
                    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,time) {
            this.$message({
                showClose: true,
                message: msg,
                type: type || 'warning',
                duration:time || '3000'
            })
        },
        errorTips(errorStr) {
            this.$alert(errorStr,'错误信息',{
                dangerouslyUseHTMLString: true,
                confirmButtonText: '确定',
                callback: action => {
                    /*this.$message({
                    type: 'info',
                    message: `action: ${ action }`
                    });*/
                }
            });
            return
        }
    },
    components: {
        Textarea,
        DisFeatureItem,
        DisFormulaItem
    }
  }
</script>
<style lang="less">
    @import '../../less/common.less';
    .AddDiagBaseWrapper {
        font-size: 14px;
        table,tr,td {
            list-style: none;
        }
        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;
            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 -35px 20px;
        }
        .addDiagName {
            position: relative;
        }
        .symptomList {
            position: relative;
            background-color: #fff;
             padding: 0px 20px 100px 20px;
             margin: 0px 20px 40px 20px;
             min-height: 400px;
        }
        
        .diagTable {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            tr {
                td {
                    /deep/textarea::-webkit-scrollbar{
                        display: none;
                    }
                    position: relative;
                    border: 1px solid #a9a9a9;
                    text-align: center;
                   /deep/textarea::-webkit-scrollbar {
                        display: none;
                    }
                   
                }
                .FormulaOpera, .FeatureOpera{
                    background: #fff;
                    border: none;
                    text-align: left;
                    padding-left: 30px;
                }
                /deep/.el-textarea__inner {
                    width: 100%;
                    line-height: 20px;
                    resize:none;
                    border: none;
                    border-radius: 0;
                    text-align: center;
                }
            }
            .selectedContent {
                width: 25%;
            }
            .selectedContentGroup {
                width: 55%;
            }
            .selectedContentOpera {
                width: 20%;
            }
        }
        .groupInput {
            text-align: center;
            color: #606266;
            width: 80%;
        }
        .groupTextarea {
             text-align: center;
            color: #606266;
            width: 100%;
        }
        .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);
            height: 40px;
        }
        .require::after{
            content:"*";
            color: red;
        }
        .borderRed {
            border: 3px solid red ;
            box-sizing: border-box;
        }
        .colorRed {
            color: red;
        }
        .FeatureSort {
            width: 5%;
        }
        .FeatureType {
            width: 7%;
            padding: 0 5px;
        }
        .FeatureNumber {
            width: 8%;
        }
        .FeatureStand {
            width: 20%;
        }
        .FeatureRelate {
            width: 30%;
        }
        .FeatureuniqueName {
            width: 10%;
        }
        .FeatureResult {
            width: 10%;
        } 
        .FeatureOpera{
            width: 10%;
        } 
        .FormulaSort{
            width: 5%;
        } 
        .FormulaType{
            width: 7%;
            padding: 0 5px;
        } 
        .FormulaNumber{
            width: 78%;
        } 
        .FormulaOpera{
            width: 10%;
        }
        .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: 3px solid red;
            }
            input:hover {
                border: 3px solid red;
            }
        }
        .moduleTitle {
            margin: 0 0 10px 0;
            font-weight: 600;
        }
        .inpDisabled{
            background: #ECECEC;
            cursor: not-allowed;
            textarea {
                background: #ECECEC;
                color: #AAAAAA;
                border: none;
                cursor: not-allowed;
                height: 100%;
            }
            
        }
        .inpTips {
            font-size: 14px;
            color: red;
            margin-bottom: 10px;
        }
        #upFile{
            display: none
        }
        .disableDiv {
            background: rgb(236, 236, 236);
            box-sizing: border-box;
            cursor: not-allowed;
            font-size: 14px;
            line-height: 20px;
            padding: 5px 0;
            min-height: 30px;
        }
        .searchItemBox{
            position: relative;
            bottom: 0px;
        }
        .searchItemList {
            position: absolute;
            border: 1px solid #a9a9a9;
            box-sizing: border-box;
            top: 4px;
            z-index: 2;
            width: 100%;
            max-height: 150px;
            overflow: auto; 
            background: #fff;
            margin: 0 0 20px 0;
        }   
    }
    
</style>