index_calc.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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.nodeParamsIndex[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. const eval_rule = this._getEvalRule(index.calc_rule);
  74. if (eval_rule !== index.eval_rule) {
  75. index.eval_rule = eval_rule;
  76. const value = this.ctx.helper.calcExprStr(index.eval_rule);
  77. index.value = value ? Number(value.toFixed(4)) : null;
  78. this.updateArr.push(index);
  79. }
  80. }
  81. }
  82. }
  83. return IndexCalc;
  84. };