index_calc.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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, relaParam) {
  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. this.relaParam = relaParam;
  26. }
  27. _splitByOperator(expr) {
  28. const exprStack = [];
  29. const result = [];
  30. for(let i = 0, len = expr.length; i < len; i++){
  31. const cur = expr[i];
  32. if(cur !== ' ' ){
  33. exprStack.push(cur);
  34. }
  35. }
  36. let param = '', isParamBefore = false;
  37. while(exprStack.length > 0){
  38. const cur = exprStack.shift();
  39. if (this.ctx.helper.isOperator(cur)) {
  40. if (isParamBefore) {
  41. result.push(param);
  42. param = '';
  43. }
  44. result.push(cur);
  45. isParamBefore = false;
  46. } else {
  47. param = param + cur;
  48. isParamBefore = true;
  49. if (exprStack.length === 0) {
  50. result.push(param);
  51. param = '';
  52. }
  53. }
  54. }
  55. return result;
  56. }
  57. _getEvalRule(rule) {
  58. const parts = this._splitByOperator(rule);
  59. const evalParts = [];
  60. for (const p of parts) {
  61. if (this.ctx.helper.isOperator(p)) {
  62. evalParts.push(p);
  63. } else if (this.globalParamsIndex[p]) {
  64. evalParts.push(this.globalParamsIndex[p]);
  65. } else if (this.nodeParamsIndex[p]) {
  66. evalParts.push(this.nodeParamsIndex[p]);
  67. }
  68. }
  69. return evalParts.join('');
  70. }
  71. calculate(indexes, globalParams, nodeParams, relaParam) {
  72. this._initCalc(indexes, globalParams, nodeParams, relaParam);
  73. for (const index of indexes) {
  74. if (!this.relaParam || index.calc_rule.match(this.relaParam.code)) {
  75. const eval_rule = this._getEvalRule(index.calc_rule);
  76. if (eval_rule !== index.eval_rule) {
  77. index.eval_rule = eval_rule;
  78. const value = this.ctx.helper.calcExprStr(index.eval_rule);
  79. index.value = value ? Number(value.toFixed(4)) : null;
  80. this.updateArr.push(index);
  81. }
  82. }
  83. }
  84. }
  85. }
  86. return IndexCalc;
  87. };