index_calc.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/4/27
  7. * @version
  8. */
  9. const Service = require('egg').Service;
  10. module.exports = app => {
  11. class IndexCalc extends Service {
  12. _initCalc (indexes, globalParams, nodeParams) {
  13. this.indexes = indexes;
  14. this.globalParams = globalParams;
  15. this.globalParamsIndex = {};
  16. for (const gp of this.globalParams) {
  17. this.globalParamsIndex[gp.code] = gp.calc_value;
  18. }
  19. this.nodeParams = nodeParams;
  20. this.nodeParamsIndex = {};
  21. for (const np of this.nodeParams) {
  22. this.nodeParamsIndex[np.code] = np.calc_value;
  23. }
  24. this.updateArr = [];
  25. }
  26. _splitByOperator(expr) {
  27. const exprStack = [];
  28. const result = [];
  29. for(let i = 0, len = expr.length; i < len; i++){
  30. const cur = expr[i];
  31. if(cur !== ' ' ){
  32. exprStack.push(cur);
  33. }
  34. }
  35. let param = '', isParamBefore = false;
  36. while(exprStack.length > 0){
  37. const cur = exprStack.shift();
  38. if(this.ctx.helper.isOperator(cur)){
  39. if (isParamBefore) {
  40. result.push(param);
  41. param = '';
  42. }
  43. result.push(cur);
  44. isParamBefore = false;
  45. }else{
  46. param = param + cur;
  47. isParamBefore = true;
  48. if (exprStack.length === 0) {
  49. result.push(param);
  50. param = '';
  51. }
  52. }
  53. }
  54. return result;
  55. }
  56. _getEvalRule(rule) {
  57. const parts = this._splitByOperator(rule);
  58. const evalParts = [];
  59. for (const p of parts) {
  60. if (this.ctx.helper.isOperator(p)) {
  61. evalParts.push(p);
  62. } else if (this.globalParamsIndex[p]) {
  63. evalParts.push(this.globalParamsIndex[p]);
  64. } else if (this.nodeParamsIndex[p]) {
  65. evalParts.push(this.globalParamsIndex[p]);
  66. }
  67. }
  68. return evalParts.join('');
  69. }
  70. calculate(indexes, globalParams, nodeParams) {
  71. this._initCalc(indexes, globalParams, nodeParams);
  72. for (const index of indexes) {
  73. index.eval_rule = this._getEvalRule(index.calc_rule);
  74. const value = this.ctx.helper.calcExprStr(index.eval_rule);
  75. if (value !== index.value) {
  76. index.value = value ? Number(value.toFixed(4)) : null;
  77. this.updateArr.push(index);
  78. }
  79. }
  80. }
  81. }
  82. return IndexCalc;
  83. };