<!-- 新增修改-计算公式 -->
<template>
    <div class="examination alert_computationalFormula">
     <el-dialog @close="closeDialog" :close-on-press-escape='false' :close-on-click-modal='false' :visible.sync="dialogTableVisible" width='1050px'>
        <div slot="title" class="titleBox">
        <i :class="tableType === 0? 'el-icon-document':'el-icon-edit-outline'" style="font-size: 20px"></i>
        <!-- <img style="width: 25px; height: 25px" src='../../../../assets/img/imgScreen/more.png' /> -->
        <span style="margin-left:10px;font-size:18px">{{tableTypeDsc}}</span>
        </div>
        <div style="position: relative;">
          <div class="block_inline">
            <div class="block_inline">
              <div class="block_inline">
                <table class="common-table-style-com">
                  <tr>
                    <td>公式名称</td>
                    <td><el-input v-model="baseData.formulaName" size="small" placeholder="请输入" style="width: 120px;"></el-input></td>
                    <td>计算顺序</td>
                    <td><el-input v-model="baseData.cptIndex" size="small" placeholder="请输入" style="width: 120px;"></el-input></td>
                    <td>公式版本</td>
                    <td><el-input v-model="baseData.cptVer" size="small" placeholder="请输入" style="width: 120px;"></el-input></td>
                  </tr>
                   <tr>
                    <td>公式类型</td>
                    <td>
                      <el-select v-model="baseData.cptTypeCode" filterable collapse-tags size="small" style="width: 120px;">
                         <el-option v-for="(item,index) in cptTypeNameType" :key="index" :label="item.baseName"
                          :value="item.baseCode">
                         </el-option>
                      </el-select>
                    </td>
                    <td>公式备注</td>
                    <td><el-input v-model="baseData.memo" size="small" placeholder="请输入" style="width: 120px;"></el-input></td>
                    <td>输入值</td>
                    <td><el-input v-model="inputVal" size="small" :controls="false" @keyup.enter.native="addVal()" placeholder="请输入" style="width: 120px;"></el-input></td>
                  </tr>
                  <tr>
                    <td>公式</td>
                    <td colspan="5"><el-input v-model="baseData.formulaAmount" size="small" placeholder="请通过计算符填入公式" :readonly='true' style="width: 520px;" type="textarea" :rows="4"></el-input></td>
                  </tr>
                   <tr>
                    <td>公式说明</td>
                    <td colspan="5"><el-input v-model="baseData.formulaDsc" size="small" placeholder="请通过计算符填入公式" :readonly='true' style="width: 520px;" type="textarea" :rows="4"></el-input></td>
                  </tr>
                   <tr>
                    <td>公式API</td>
                    <td colspan="5"><el-input v-model="baseData.callApi" size="small" placeholder="请输入" style="width: 520px;"></el-input></td>
                  </tr>
                </table>
                </div>
              <div class="div-button-com block_inline" style="padding-bottom: 12px; width: 130px;">
                <div>计算符
                </div>
                <div>
                  <button @click="add">+</button>
                  <button @click="minus">-</button>
                  <button @click="division">/</button>
                </div>
                <div>
                  <button @click="multiple">*</button>
                  <button @click="leftBracket">(</button>
                  <button @click="rightBracket">)</button>
                </div>
                <div>
                  <button @click="addself">Y</button>
                  <button @click="addLog10">lg</button>
                  <button @click="addAvg">&</button>
                </div>
                <div>
<!--                  <button @click="addKb">K</button>-->
                  <button @click="absolute">A</button>
                  <button @click="addSqrt">√</button>
                  <button @click="addSup">^</button>
                </div>
                <div>
                  <button @click="addSum">H</button>
                  <button class="el-icon-back" type="danger" @click="deleteData"></button>
                </div>
              </div>
            </div>
          </div>
          <div class="div-search-com block_inline" style="position: absolute;right:-15px;width: 270px;">
             <el-form :inline='true' @submit.native.prevent>
              <el-row>
                <el-col>
                  <el-form-item label='分析项目名称' style="font-size: 13px;">
                    <el-input v-model="searchVal" @keyup.enter.native="searchData" size="mini" placeholder="请输入内容,按回车键查询" style="width: 170px;"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
             <!-- <table class="common-table-style-com">
                  <tr>
                    <td>项目类型</td>
                    <td><el-select v-model="itemTypeNameTypeIndex" filterable collapse-tags size="small" style="width: 120px;"  @change="selectTrigger(itemTypeNameTypeIndex)">
                         <el-option v-for="(item,index) in itemTypeNameType" :key="index" :label="item.baseName"
                          :value="index">
                         </el-option>
                      </el-select>
                    </td>
                  </tr>
             </table> -->
             <el-table ref="dataTable" border :height="220" :data="table.list" style="width: 270px"
            :header-cell-style="tableHeaderCellStyle" v-loading="dataLoading" highlight-current-row  @current-change="handleCurrentChange" :icore-filter-flag="icoreFilterFlag">
             <el-table-column type="index" label="NO" fixed="left" align="center">
             </el-table-column>
             <el-table-column min-width="100px" prop="anlyItemNo" label="分析项目编码" align="center"></el-table-column>
             <el-table-column min-width="120px" prop="anlyItemName" label="分析项目名称" align="center"></el-table-column>
             </el-table>
          </div>
        </div>
        <div class="clearfix">
          <div>
            &nbsp;&nbsp;&nbsp;提示:
            <span style="color:blue">&nbsp;&nbsp;&nbsp;A:绝对值 例:A(-10)=10</span>
            <span style="color:blue">&nbsp;&nbsp;&nbsp;K:空白浓度值</span>
            <span style="color:blue">&nbsp;&nbsp;&:平均值&nbsp;</span>
            <span style="color:blue">&nbsp;&nbsp;&nbsp;输入√会转化为√(,括号中填写开平方的值或表达式</span>
            <div>
              H:<img src="../../../../assets/img/imgScreen/求和运算.png">
              <span style="color:blue">&nbsp;&nbsp;Y:自身值&nbsp;</span>
              <span style="color:blue">&nbsp;&nbsp;^:次方。比如2^3，即2的3次方&nbsp;</span>
              <span style="color:blue">&nbsp;&nbsp;lg:10为底的对数&nbsp;</span>
            </div>
          </div>
         <div style="float:right">
         <el-pagination size='mini' small @size-change="pageSizeChange" @current-change="pageCurrentChange"
              :current-page="pageNum" :page-sizes="[10, 20, 50, 100, 200]" :page-size="pageSize" layout="total, sizes, prev, pager, next"
               :total="total" background>
         </el-pagination>
          </div>

        </div>
        <div class="div-el-button">
            <el-button type="goon" icon="el-icon-check" size="mini" @click="tableType === 0 ? addData():modifyData()">确定</el-button>
            <el-button size="mini" type="goon" icon="el-icon-remove-outline" @click="cancel">取消</el-button>
          </div>
    </el-dialog>
    </div>
</template>
<script>
import {
  getCookie
} from '@/utils/util.js';
import {
  cookieUserId,
  cookieUserName
} from '@/config/config.js';
let userName = getCookie(cookieUserName);
let userId = getCookie(cookieUserId);
export default {
  props: ['showFlag', 'Params'],
    data () {
        return {
            dialogTableVisible: false,
            tableTypeDsc: '新增计算信息',
            tableType: 0,
            seen: true,
            seenNo: true,
            beInvalid: false,
            itemTypeName: '',
            cptTypeNameTypeIndex: 0,
            itemTypeNameTypeIndex: 2,
            dataLoading: false,
            cptTypeNameType: [],
            table: {
              list:[]
            },
            icoreFilterFlag:true,
            inputVal:'',
            formula:[],
            explain:[],
            tableData: [],
            searchVal:'',
            pageNum:1,
            pageSize:50,
            total:0,
            baseData: {
              formulaNo: '',
              formulaName: '',
              formulaAmount: '',
              formulaDsc: '',
              cptIndex: '',
              cptTypeName: '',
              cptVer: '',
              callApi: ''
            },
            ruleValidate: {
              formulaNo: [{ required: true, message: '该项不能为空', trigger: 'change' }],
              formulaName: [{ required: true, message: '该项不能为空', trigger: 'change' }],
              formulaAmount: [{ required: true, message: '该项不能为空', trigger: 'change' }],
              formulaDsc: [{ required: true, message: '该项不能为空', trigger: 'change' }],
              cptIndex: [{ required: true, message: '该项不能为空', trigger: 'change' }],
              cptTypeName: [{ required: true, message: '该项不能为空', trigger: 'change' }],
              cptVer: [{ required: true, message: '该项不能为空', trigger: 'change' }],
              callApi: [{ required: true, message: '该项不能为空', trigger: 'change' }]
             }
        }
    },
    mounted () {
      this.getCptTypeNameList ()
      this.searchTableList()
    },
    methods: {
     searchData(){
       this.pageNum = 1
       this.searchTableList()
     },
    searchTableList(){
      this.dataLoading = true;
      this.axios.post('pass/baseManagement/v1/limsstdanlyitems/queryLimsStdAnlyItemPage',{object:{anlyItemName:this.searchVal,validFlag:1},pageIndex:this.pageNum,pageSize:this.pageSize}, {individualType: 'json'}).then(res => {
        this.dataLoading = false;
        this.table.list = res.data.list;
        this.total = res.data.total
      }).catch(e => {
        this.dataLoading = false;
      });
     },
     pageSizeChange (size) {
      this.pageSize = size;
      this.searchTableList();
    },
    pageCurrentChange (index) {
      this.pageNum = index;
      this.searchTableList();
    },
    saveVal(val){
      this.formula.push(val)
      this.explain.push(val)
      this.baseData.formulaAmount = this.formula.join('')
       this.baseData.formulaDsc = this.explain.join('')
    },
    //输入框新增值
    addVal(){
      let arr = ['+','-','*','/','(',')','^','lg(','<','>','=','<=','>=','?','&&']
      if (!this.inputVal) {
        this.$message.warning('添加的值为空值')
        return
      }
      if (this.inputVal < 0) {
        this.$message.warning('添加的值不能为负数')
        return
      }
      // if (this.formula.length > 0) {
      //   if (arr.indexOf(this.formula[this.formula.length-1]) == -1) {
      //     this.$message.warning('请先添加运算符')
      //     return
      //   }
      // }
      this.saveVal(this.inputVal)
    },
     handleCurrentChange (val) {
      let arr = ['+','-','*','/','(',')','√(','lg(','S(','H(','&(',':','^','>','<','=','>=','<=','?','&&']
      if (this.formula.length > 0) {
        if (arr.indexOf(this.formula[this.formula.length-1]) == -1) {
          this.$message.warning('请先添加运算符')
          return
        }
      }
      this.formula.push(val.anlyItemNo)
      this.explain.push(val.anlyItemName)
      this.baseData.formulaAmount = this.formula.join('')
      this.baseData.formulaDsc = this.explain.join('')
     },
     add () {
      let arr = ['+','-','*','/','(','P','A','<','>','=','<=','>=','?','&&']
      if (arr.indexOf(this.formula[this.formula.length-1]) > -1) {
        this.$message.warning('请先添加正确的公式值')
        return
      }
      this.saveVal('+')
     },
     minus () {
       let arr = ['+','-','*','/','P','A','<','>','=','<=','>=','?','&&']
      if (arr.indexOf(this.formula[this.formula.length-1]) > -1) {
        this.$message.warning('请先添加正确的公式值')
        return
      }
      this.saveVal('-')
     },
     multiple () {
       let arr = ['+','-','*','/','P','A','<','>','=','<=','>=','?','&&']
      if (arr.indexOf(this.formula[this.formula.length-1]) > -1) {
        this.$message.warning('请先添加正确的公式值')
        return
      }
      this.saveVal('*')
     },
     division () {
       let arr = ['+','-','*','/','P','A','<','>','=','<=','>=','?','&&']
      if (arr.indexOf(this.formula[this.formula.length-1]) > -1) {
        this.$message.warning('请先添加正确的公式值')
        return
      }
      this.saveVal('/')
     },
     leftBracket () {
       this.saveVal('(')
     },
     rightBracket () {
       this.saveVal(')')
     },
     addself(){
       let arr = ['+','-','*','/','(',')','lg(','<','>','=','<=','>=','?','&&']
      if (this.formula.length > 0) {
        if (arr.indexOf(this.formula[this.formula.length-1]) == -1) {
          this.$message.warning('请先添加运算符')
          return
        }
      }
      this.saveVal('Y')
     },absolute(){
        let arr = ['(',')','Y','P','<','>','=','<=','>=','?','&&']
        if (arr.indexOf(this.formula[this.formula.length-1]) > -1) {
          this.$message.warning('请先添加正确的公式值')
          return
        }
      this.saveVal('A')
     },
     zhishu () {
       let arr = ['(',')','Y','A','<','>','=','<=','>=','?','&&']
      if (arr.indexOf(this.formula[this.formula.length-1]) > -1) {
        this.$message.warning('请先添加正确的公式值')
        return
      }
      this.saveVal('P')
     },
      addKb(){
        let arr = ['+','-','*','/','(',')','lg(','<','>','=','<=','>=','?','&&']
        if (this.formula.length > 0) {
          if (arr.indexOf(this.formula[this.formula.length-1]) == -1) {
            this.$message.warning('请先添加运算符')
            return
          }
        }
       this.saveVal('K');
      },
      addAvg(){
        let arr = ['+','-','*','/','(',')','√(','&(','<','>','=','<=','>=','?','&&']
        if (this.formula.length > 0) {
          if (arr.indexOf(this.formula[this.formula.length-1]) == -1) {
            this.$message.warning('请先添加运算符')
            return
          }
        }
        this.formula.push('&(')
        this.explain.push('&(')
        this.baseData.formulaAmount = this.formula.join('')
        this.baseData.formulaDsc = this.explain.join('')
      },
      addSqrt(){
        let arr = ['+','-','*','/','(',')','√(','&(','<','>','=','<=','>=','?','&&']
        if (this.formula.length > 0) {
          if (arr.indexOf(this.formula[this.formula.length-1]) == -1) {
            this.$message.warning('请先添加运算符')
            return
          }
        }
        this.formula.push('√(')
        this.explain.push('√(')
        this.baseData.formulaAmount = this.formula.join('')
        this.baseData.formulaDsc = this.explain.join('')
      },
      // 次方
      addSup(){
        let arr = ['+','-','*','/','√(','&(','<','>','=','<=','>=','?','&&']
        if (this.formula.length > 0) {
          if (arr.indexOf(this.formula[this.formula.length-1]) != -1) {
            this.$message.warning('运算符后不能添加平方!')
            return
          }
        }else {
          return this.$message.warning('请先添加数字再添加平方!')
        }

        this.formula.push('^');
        this.explain.push('^');
        this.baseData.formulaAmount = this.formula.join('')
        this.baseData.formulaDsc = this.explain.join('')
      },
      addSum(){
        this.formula.push('H(');
        this.explain.push('H(');
        this.baseData.formulaAmount = this.formula.join('')
        this.baseData.formulaDsc = this.explain.join('')
      },
      addLog10(){
        let arr = ['+','-','*','/','<','>','=','<=','>=','?','&&']
        if (this.formula.length > 0) {
          if (arr.indexOf(this.formula[this.formula.length-1]) == -1) {
            this.$message.warning('只能在运算符后添加对数~!')
            return
          }
        }
        this.formula.push('lg(');
        this.explain.push('lg(');
        this.baseData.formulaAmount = this.formula.join('')
        this.baseData.formulaDsc = this.explain.join('')
      },
     //删除按钮
     deleteData(){
      this.formula.splice(this.formula.length-1,1)
      this.explain.splice(this.explain.length-1,1)
      this.baseData.formulaAmount = this.formula.join('')
      this.baseData.formulaDsc = this.explain.join('')
     },
     getCode (code, arr, codeKey, nameKey) {
        if (!code) {
          return '';
        }
        let targetRow = arr.find(item => {
          return item[codeKey] === code;
        });
        // console.log(targetRow, 'targetRow');
        return targetRow ? targetRow[nameKey] : '';
    },
      cancel () {
        let _this = this;
        _this.tableData = [];
         this.baseData= {
              formulaNo: '',
              formulaName: '',
              formulaAmount: '',
              formulaDsc: '',
              cptIndex: '',
              cptTypeName: '',
              cptVer: '',
              callApi: ''
            },
        this.inputVal = ''
        this.formula = []
        this.explain = []
        this.dialogTableVisible = false
      },
      addData () {
        this.baseData.formulaData = this.formula
        this.baseData.formulaDataExplain = this.explain
        // let verifyData = this.baseData.formulaAmount.replace('A', 1).replace('Y', 1)
        // console.log(verifyData);
        // try  {
        //   eval(verifyData);
        // }
        // catch(exception) {
        //   this.$message.warning('计算公式错误，请查验后再试')
        //   return
        // }
        if (!this.baseData.formulaName) {
          this.$message.warning('公式名称不能为空')
          return
        }
        if (!this.baseData.cptTypeCode) {
          this.$message.warning('公式类型不能为空')
          return
        }
        if (this.baseData.formulaData.length < 1) {
          this.$message.warning('公式不能为空')
          return
        }
        if (this.baseData.formulaDataExplain.length < 1) {
          this.$message.warning('公式说明不能为空')
          return
        }
        let _this = this;
         _this.tableData = [];
        //  _this.$refs['baseData'].validate((valid) => {
          // if (valid) {
            this.baseData.cptTypeName = this.getCode(this.baseData.cptTypeCode,this.cptTypeNameType,'baseCode','baseName')
            this.axios.post('pass/baseManagement/v1/limsbaseformulas/saveLimsBaseFormula', this.baseData, {individualType: 'json'}).then(res => {
                if (res.succeed) {
                  _this.dialogTableVisible = false;
                 this.$message.success('添加成功')
                 _this.$emit('refresh')
                } else {
                 this.$message.error(res.message)
                }
                }).catch(e => {
                 this.$message.error(e.message)
               })
      //    }
      //  })
      },
      modifyData () {
        this.baseData.formulaData = this.formula
        this.baseData.formulaDataExplain = this.explain
        if (!this.baseData.formulaName) {
          this.$message.warning('公式名称不能为空')
          return
        }
        if (!this.baseData.cptTypeCode) {
          this.$message.warning('公式类型不能为空')
          return
        }
        if (this.baseData.formulaData.length < 1) {
          this.$message.warning('公式不能为空')
          return
        }
        if (this.baseData.formulaDataExplain.length < 1) {
          this.$message.warning('公式说明不能为空')
          return
        }
        let _this = this;
        // _this.$refs['baseData'].validate((valid) => {
        // if (valid) {

       this.baseData.cptTypeName = this.getCode(this.baseData.cptTypeCode,this.cptTypeNameType,'baseCode','baseName')
        this.axios.post('pass/baseManagement/v1/limsbaseformulas/saveLimsBaseFormula', this.baseData, {individualType: 'json'}).then(res => {
           if (res.succeed) {
            _this.dialogTableVisible = false;
            this.$message.success('修改成功')
            _this.$emit('refresh')
           } else {
            this.$message.error(res.message)
           }
           }).catch(e => {
            this.$message.error(e.message)
          })
        // }
        // })
      },
      renderHeader (h) {
         return (
             <div style="cursor: pointer ;line-height:20px" onClick={() => this.addRow()}>
             <i class="el-icon-plus" style="font-size:20px; color:rgb(18, 52, 243)"></i>
             </div>
         )
      },
      getCptTypeNameList () {
      this.axios.post("pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode",{validFlag:1,baseCode:4815}, {individualType: 'json'}).then(res => {
              this.dataLoading = false;
              this.cptTypeNameType = res.data
            }).catch(e => {
              this.dataLoading = false;
            });
    },
     closeDialog () {
       let _this = this;
       _this.tableData = [];
       this.baseData= {
              formulaNo: '',
              formulaName: '',
              formulaAmount: '',
              formulaDsc: '',
              cptIndex: '',
              cptTypeName: '',
              cptVer: '',
              callApi: ''
            },
        this.inputVal = ''
        this.formula = []
        this.explain = []
        this.dialogTableVisible = false
     },
      tableHeaderCellStyle () {
      return 'background-color: rgb(249,249,249) !important;color: rgb(73, 72, 72);border-bottom: 1px solid #DCDFE7;border-top:3px solid #3ac1ea;'
      }
    },
    watch: {
      showFlag (arg) {
        let _this = this;
        if (_this.Params !== null) {
          _this.baseData = Object.assign({},this.Params[0]);
          this.formula = JSON.parse(this.baseData.formulaData)
          this.explain = JSON.parse(this.baseData.formulaDataExplain)
          _this.tableType = 1;
          _this.tableTypeDsc = '修改计算信息';
        } else {
          _this.tableType = 0;
          _this.seenNo = false;
          _this.tableTypeDsc = '新增计算信息';
        }
        this.dialogTableVisible = true
      }
    }
}
</script>
<style lang="less">
  .clearfix:after{/*伪元素是行内元素 正常浏览器清除浮动方法*/
      content: "";
      display: block;
      height: 0;
      clear:both;
      visibility: hidden;
  }
  .clearfix{
      *zoom: 1;/*ie6清除浮动的方式 *号只有IE6-IE7执行，其他浏览器不执行*/
  }
  .name{
    background-color: red;
  }
  .alert_computationalFormula {
    .div-button-com{
      div {
        margin-top: 15px;
      }
    }
  }
  .block_inline {
    display: inline-block;
    vertical-align: top;
  }
</style>
