UNPKG

tplus-pos

Version:

pos module

1,469 lines (1,335 loc) 48.1 kB
"use strict"; var _stringify = require("babel-runtime/core-js/json/stringify"); var _stringify2 = _interopRequireDefault(_stringify); var _typeof2 = require("babel-runtime/helpers/typeof"); var _typeof3 = _interopRequireDefault(_typeof2); var _mobx = require("mobx"); var _cloneDeep = require("lodash/cloneDeep"); var _cloneDeep2 = _interopRequireDefault(_cloneDeep); var _propTypes = require("prop-types"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* eslint-disable no-undef */ /** * Created by majianb on 2019/4/10. */ /*------------------对JS的扩展 begin-------------------------*/ String.prototype.trim = function () { return this.replace(/^\s*/, "").replace(/\s*$/, ""); }; /** * 对数字进行精度处理 * @param {number} [ACCUEAXY] 可选,控制精度的位数,默认为2位 */ String.prototype.Round = function (ACCUEAXY) { ///<summary>格式化精度</summary> var str = this.replace(/,/g, ''); return toFixed(str, ACCUEAXY); }; String.prototype.PadLeft = function (len, charStr) { var s = this + ''; return new Array(len - s.length + 1).join(charStr, '') + s; }; String.prototype.PadRight = function (len, charStr) { var s = this + ''; return s + new Array(len - s.length + 1).join(charStr, ''); }; /** * 格式化函数 */ String.prototype.Format = function (args) { if (arguments.length > 0) { var result = this; if (arguments.length == 1 && (typeof args === "undefined" ? "undefined" : (0, _typeof3.default)(args)) == "object") { for (var key in args) { var reg = new RegExp("({" + key + "})", "g"); result = result.replace(reg, args[key]); } } else { for (var i = 0; i < arguments.length; i++) { if (arguments[i] == undefined) { return ""; } else { var _reg = new RegExp("({[" + i + "]})", "g"); result = result.replace(_reg, arguments[i]); } } } return result; } else { return this; } }; String.prototype.isNullOrEmpty = String.isNullOrEmpty = function () { if (this === String && arguments.length === 0) { return true; } var str = this === String ? arguments[0] : this.toString(); if (typeof str === "string") { return (/^ *$/.test(str) ); } for (var key in str) { return false; } return typeof str !== "number" && typeof str !== "boolean"; }; //+--------------------------------------------------- //| 字符串转成日期类型 //| 格式 MM/dd/YYYY MM-dd-YYYY YYYY/MM/dd YYYY-MM-dd //+--------------------------------------------------- String.prototype.StringToDate = String.StringToDate = function () { if (this === String && arguments.length === 0) { return true; } var DateStr = this === String ? arguments[0] : this.toString(); var converted = Date.parse(DateStr); var myDate = new Date(converted); if (isNaN(myDate)) { //var delimCahar = DateStr.indexOf('/')!=-1?'/':'-'; var arys = DateStr.split('-'); myDate = new Date(arys[0], arys[1], arys[2]); } return myDate; }; //--------------------------------------------------- // 判断闰年 //--------------------------------------------------- Date.prototype.isLeapYear = function () { return 0 == this.getYear() % 4 && (this.getYear() % 100 != 0 || this.getYear() % 400 == 0); }; //--------------------------------------------------- // 日期格式化 // 格式 YYYY/yyyy/YY/yy 表示年份 // MM/M 月份 // W/w 星期 // dd/DD/d/D 日期 // hh/HH/h/H 时间 // mm/m 分钟 // ss/SS/s/S 秒 //--------------------------------------------------- Date.prototype.Format = function (formatStr) { var str = formatStr; var Week = ['日', '一', '二', '三', '四', '五', '六']; if (this.getFullYear() < 1900) { return ""; } str = str.replace(/yyyy|YYYY/, this.getFullYear()); str = str.replace(/yy|YY/, this.getYear() % 100 > 9 ? (this.getYear() % 100).toString() : '0' + this.getYear() % 100); str = str.replace(/MM/, this.getMonth() + 1 > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1)); str = str.replace(/M/g, this.getMonth() + 1); str = str.replace(/w|W/g, Week[this.getDay()]); str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate()); str = str.replace(/d|D/g, this.getDate()); str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours()); str = str.replace(/h|H/g, this.getHours()); str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes()); str = str.replace(/m/g, this.getMinutes()); str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds()); str = str.replace(/s|S/g, this.getSeconds()); return str; }; //+--------------------------------------------------- //| 求两个时间的天数差 日期格式为 YYYY-MM-dd //+--------------------------------------------------- Date.prototype.daysBetween = function (DateOne, DateTwo) { var OneMonth = DateOne.substring(5, DateOne.lastIndexOf('-')); var OneDay = DateOne.substring(DateOne.length, DateOne.lastIndexOf('-') + 1); var OneYear = DateOne.substring(0, DateOne.indexOf('-')); var TwoMonth = DateTwo.substring(5, DateTwo.lastIndexOf('-')); var TwoDay = DateTwo.substring(DateTwo.length, DateTwo.lastIndexOf('-') + 1); var TwoYear = DateTwo.substring(0, DateTwo.indexOf('-')); var cha = (Date.parse(OneMonth + '/' + OneDay + '/' + OneYear) - Date.parse(TwoMonth + '/' + TwoDay + '/' + TwoYear)) / 86400000; return Math.abs(cha); }; //+--------------------------------------------------- //| 日期计算 //+--------------------------------------------------- Date.prototype.DateAdd = function (strInterval, Number) { var dtTmp = this; switch (strInterval) { case 's': return new Date(Date.parse(dtTmp) + 1000 * Number); case 'n': return new Date(Date.parse(dtTmp) + 60000 * Number); case 'h': return new Date(Date.parse(dtTmp) + 3600000 * Number); case 'd': return new Date(Date.parse(dtTmp) + 86400000 * Number); case 'w': return new Date(Date.parse(dtTmp) + 86400000 * 7 * Number); case 'q': return new Date(dtTmp.getFullYear(), dtTmp.getMonth() + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds()); case 'm': return new Date(dtTmp.getFullYear(), dtTmp.getMonth() + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds()); case 'y': return new Date(dtTmp.getFullYear() + Number, dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds()); } }; //+--------------------------------------------------- //| 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串 //+--------------------------------------------------- Date.prototype.DateDiff = function (strInterval, dtEnd) { var dtStart = this; if (typeof dtEnd == 'string') //如果是字符串转换为日期型 { dtEnd = dtEnd.StringToDate(); } switch (strInterval) { case 's': return parseInt((dtEnd - dtStart) / 1000); case 'n': return parseInt((dtEnd - dtStart) / 60000); case 'h': return parseInt((dtEnd - dtStart) / 3600000); case 'd': return parseInt((dtEnd - dtStart) / 86400000); case 'w': return parseInt((dtEnd - dtStart) / (86400000 * 7)); case 'm': return dtEnd.getMonth() + 1 + (dtEnd.getFullYear() - dtStart.getFullYear()) * 12 - (dtStart.getMonth() + 1); case 'y': return dtEnd.getFullYear() - dtStart.getFullYear(); } }; //+--------------------------------------------------- //| 日期输出字符串,重载了系统的toString方法 //+--------------------------------------------------- Date.prototype.toWeekString = function (showWeek) { var myDate = this; var str = myDate.toLocaleDateString(); if (showWeek) { var Week = ['日', '一', '二', '三', '四', '五', '六']; str += ' 星期' + Week[myDate.getDay()]; } return str; }; //+--------------------------------------------------- //| 日期合法性验证 //| 格式为:YYYY-MM-DD或YYYY/MM/DD //+--------------------------------------------------- Date.prototype.IsValidDate = function (DateStr) { var sDate = DateStr.replace(/(^\s+|\s+$)/g, ''); //去两边空格; if (sDate == '') return true; //如果格式满足YYYY-(/)MM-(/)DD或YYYY-(/)M-(/)DD或YYYY-(/)M-(/)D或YYYY-(/)MM-(/)D就替换为'' //数据库中,合法日期可以是:YYYY-MM/DD(2003-3/21),数据库会自动转换为YYYY-MM-DD格式 var s = sDate.replace(/[\d]{ 4,4 }[\-/]{ 1 }[\d]{ 1,2 }[\-/]{ 1 }[\d]{ 1,2 }/g, ''); if (s == '') //说明格式满足YYYY-MM-DD或YYYY-M-DD或YYYY-M-D或YYYY-MM-D { var t = new Date(sDate.replace(/\-/g, '/')); var ar = sDate.split(/[-/:]/); if (ar[0] != t.getYear() || ar[1] != t.getMonth() + 1 || ar[2] != t.getDate()) { //alert('错误的日期格式!格式为:YYYY-MM-DD或YYYY/MM/DD。注意闰年。'); return false; } } else { //alert('错误的日期格式!格式为:YYYY-MM-DD或YYYY/MM/DD。注意闰年。'); return false; } return true; }; //+--------------------------------------------------- //| 日期时间检查 //| 格式为:YYYY-MM-DD HH:MM:SS //+--------------------------------------------------- Date.prototype.CheckDateTime = function (str) { var reg = /^(\d+)-(\d{ 1,2 })-(\d{ 1,2 }) (\d{ 1,2 }):(\d{ 1,2 }):(\d{ 1,2 })$/; var r = str.match(reg); if (r == null) return false; r[2] = r[2] - 1; var d = new Date(r[1], r[2], r[3], r[4], r[5], r[6]); if (d.getFullYear() != r[1]) return false; if (d.getMonth() != r[2]) return false; if (d.getDate() != r[3]) return false; if (d.getHours() != r[4]) return false; if (d.getMinutes() != r[5]) return false; if (d.getSeconds() != r[6]) return false; return true; }; //+--------------------------------------------------- //| 把日期分割成数组 //+--------------------------------------------------- Date.prototype.toArray = function () { var myDate = this; var myArray = Array(); myArray[0] = myDate.getFullYear(); myArray[1] = myDate.getMonth(); myArray[2] = myDate.getDate(); myArray[3] = myDate.getHours(); myArray[4] = myDate.getMinutes(); myArray[5] = myDate.getSeconds(); myArray[6] = myDate.getMilliseconds(); return myArray; }; //+--------------------------------------------------- //| 取得日期数据信息 //| 参数 interval 表示数据类型 //| y 年 m月 d日 w星期 ww周 h时 n分 s秒 //+--------------------------------------------------- Date.prototype.DatePart = function (interval) { var myDate = this; var partStr = ''; var Week = ['日', '一', '二', '三', '四', '五', '六']; switch (interval) { case 'y': partStr = myDate.getFullYear();break; case 'm': partStr = myDate.getMonth() + 1;break; case 'd': partStr = myDate.getDate();break; case 'w': partStr = Week[myDate.getDay()];break; case 'ww': partStr = myDate.WeekNumOfYear();break; case 'h': partStr = myDate.getHours();break; case 'n': partStr = myDate.getMinutes();break; case 's': partStr = myDate.getSeconds();break; } return partStr; }; //+--------------------------------------------------- //| 取得当前日期所在月的最大天数 //+--------------------------------------------------- Date.prototype.MaxDayOfDate = function () { var myDate = this; var ary = myDate.toArray(); var date1 = new Date(ary[0], ary[1] + 1, 1); var date2 = date1.dateAdd(1, 'm', 1); var result = dateDiff(date1.Format('yyyy-MM-dd'), date2.Format('yyyy-MM-dd')); return result; }; function isFreeItem(propertyName) { var itemName = 'freeitem'; for (var index = 0; index < 10; index++) { var freeitemName = itemName + index.toString(); if (propertyName.toLowerCase() == freeitemName) { return true; } } return false; } function getDynamicValue(jsonObj, propertyName) { if (!(jsonObj && jsonObj.hasOwnProperty)) { return; } var returnValue = void 0; if (jsonObj.hasOwnProperty('DynamicPropertyKeys') && jsonObj.hasOwnProperty('DynamicPropertyValues')) { var dynamicPropertyKeys = jsonObj["DynamicPropertyKeys"]; var dynamicPropertyValues = jsonObj["DynamicPropertyValues"]; var index = dynamicPropertyKeys.indexOf(propertyName.toLowerCase()); if (index > -1) { returnValue = dynamicPropertyValues[index]; } } return returnValue; } function setDynamicValue(jsonObj, propertyName, val) { if (!(jsonObj && jsonObj.hasOwnProperty)) { return; } if (jsonObj.hasOwnProperty('DynamicPropertyKeys') && jsonObj.hasOwnProperty('DynamicPropertyValues')) { var dynamicPropertyKeys = (0, _cloneDeep2.default)((0, _mobx.toJS)(jsonObj["DynamicPropertyKeys"])); var dynamicPropertyValues = (0, _cloneDeep2.default)((0, _mobx.toJS)(jsonObj["DynamicPropertyValues"])); var index = dynamicPropertyKeys.indexOf(propertyName.toLowerCase()); if (index > -1) { dynamicPropertyValues[index] = val; } else { dynamicPropertyKeys.push(propertyName.toLowerCase()); dynamicPropertyValues.push(val); } (0, _mobx.runInAction)(function () { jsonObj.DynamicPropertyKeys = dynamicPropertyKeys; jsonObj.DynamicPropertyValues = dynamicPropertyValues; }); } } JSON.getCellValue = function (jsonObj, propertyName) { if (propertyName.lastIndexOf(".") > 0) { var propertyNames = propertyName.split('.'); if (propertyNames.length > 1) { var tempObj = JSON.getCellValue(jsonObj, propertyNames.shift()); return JSON.getCellValue(tempObj, propertyNames.join('.')); } } var returnValue = null; if (!(jsonObj && jsonObj.hasOwnProperty)) { return; } if (jsonObj.hasOwnProperty(propertyName)) { returnValue = jsonObj[propertyName]; if (isFreeItem(propertyName)) { var ishasID = false; if (returnValue && returnValue.hasOwnProperty && returnValue.hasOwnProperty("Id") && returnValue.hasOwnProperty("Name")) { returnValue = JSON.getCellValue(jsonObj[propertyName], "Name"); } if (!returnValue) { returnValue = getDynamicValue(jsonObj, propertyName); } } } else if (jsonObj.hasOwnProperty('DynamicPropertyKeys') && jsonObj.hasOwnProperty('DynamicPropertyValues')) { returnValue = getDynamicValue(jsonObj, propertyName); } return returnValue; }; JSON.getDynamicValue = function (jsonObj, propertyName) { var returnValue = null; if (jsonObj.hasOwnProperty('DynamicPropertyKeys') && jsonObj.hasOwnProperty('DynamicPropertyValues')) { returnValue = getDynamicValue(jsonObj, propertyName); } return returnValue; }; JSON.setCellValue = function (jsonObj, propertyName, val) { if (!(jsonObj && jsonObj.hasOwnProperty)) { return; } if (jsonObj.hasOwnProperty(propertyName)) { if (isFreeItem(propertyName)) { setDynamicValue(jsonObj, propertyName, val); var freeitemObj = jsonObj[propertyName]; if (freeitemObj && freeitemObj.hasOwnProperty && freeitemObj.hasOwnProperty("Id") && freeitemObj.hasOwnProperty("Name")) { freeitemObj["Name"] = val; } } else { jsonObj[propertyName] = val; } } else if (jsonObj.hasOwnProperty('DynamicPropertyKeys') && jsonObj.hasOwnProperty('DynamicPropertyValues')) { setDynamicValue(jsonObj, propertyName, val); } }; JSON.setDynamicValue = function (jsonObj, propertyName, val) { if (!(jsonObj && jsonObj.hasOwnProperty)) { return; } if (jsonObj.hasOwnProperty('DynamicPropertyKeys') && jsonObj.hasOwnProperty('DynamicPropertyValues')) { setDynamicValue(jsonObj, propertyName, val); } }; JSON.ClearDynamicProperty = function (jsonObj, propertyName) { if (!(jsonObj && jsonObj.hasOwnProperty)) { return; } if (jsonObj.hasOwnProperty('DynamicPropertyKeys') && jsonObj.hasOwnProperty('DynamicPropertyValues')) { var dynamicPropertyKeys = jsonObj["DynamicPropertyKeys"]; var dynamicPropertyValues = jsonObj["DynamicPropertyValues"]; var index = dynamicPropertyKeys.indexOf(propertyName.toLowerCase()); if (index > -1) { dynamicPropertyKeys.splice(index, 1); dynamicPropertyValues.splice(index, 1); } } }; JSON.Clone = function (obj) { var txt = (0, _stringify2.default)(obj); return JSON.parse(txt); }; // 加 Math.Add = function (number1, number2) { // eslint-disable-next-line no-undef var math = new $T.Bap.TMath.NormalCalculator(); return math.Add(number1, number2); }; // 减 Math.Minus = function (number1, number2) { // eslint-disable-next-line no-undef var math = new $T.Bap.TMath.NormalCalculator(); return math.Minus(number1, number2); }; // 乘 Math.Multiply = function (number1, number2) { // eslint-disable-next-line no-undef var math = new $T.Bap.TMath.NormalCalculator(); return math.Multiply(number1, number2); }; // 除 Math.Divide = function (number1, number2) { // eslint-disable-next-line no-undef var math = new $T.Bap.TMath.NormalCalculator(); return math.Divide(number1, number2); }; /** 修改JavaScript的toFixed Bug */ Number.prototype.toFixed = function (d) { return toFixed(this, d); }; Array.prototype.Sum = function (fieldname) { var sum = 0; // eslint-disable-next-line no-undef var TMath = new $T.Bap.TMath.NormalCalculator(); this.forEach(function (value) { sum = TMath.Add(sum, value[fieldname]); }); return sum; }; Array.prototype.Contain = function (val) { for (var i = 0; i < this.length; i++) { if (this[i] == val) { return true; } } return false; }; function toFixed(val, d) { var s = val.toString(); if (s.indexOf('e') > 0) { var arr = s.split('e'); var realNumber = arr[0]; var other = arr[1]; var sign = other.charAt(0); if (sign != 'e') { other = Number(other.substring(1)); } var numberSign = realNumber.charAt(0); if (numberSign == '-') { realNumber = realNumber.substring(1); } else { numberSign = ''; } var intlen; var intNumber; var ret; var z; if (realNumber.indexOf('.') > 0) { var ma = realNumber.match(/(\d+)\.(\d+)/); intNumber = ma[1]; var decNumber = ma[2]; intlen = intNumber.length; if (intlen == other) { ret = '0.' + intNumber + decNumber; } else if (intlen > other) { var newInt = intNumber.substr(0, intlen - other); var newDec = intNumber.substr(intlen - other); ret = newInt + '.' + newDec + decNumber; } else { z = new Array(other - intlen + 1).join('0'); ret = '0.' + z + intNumber + decNumber; } } else { var len = realNumber.length; z = new Array(other - len + 1).join('0'); } s = numberSign + ret; } if (d === undefined || d === null || isNaN(d)) { d = 2; } if (typeof d == 'string') { d = parseInt(d); } if (s.indexOf('.') == -1) s += '.'; s += new Array(d + 1).join('0'); if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) { var _s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true; if (a == d + 2) { a = _s.match(/\d/g); if (parseInt(a[a.length - 1]) > 4) { for (var i = a.length - 2; i >= 0; i--) { a[i] = parseInt(a[i]) + 1; if (a[i] == 10) { a[i] = 0; b = i != 1; } else break; } } _s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2"); } if (b) _s = _s.substr(1); return (pm + _s).replace(/\.$/, ""); } return val + ""; } /** * 对数字进行精度处理 * @param {number} [ACCUEAXY] 可选,控制精度的位数,默认为2位 */ Number.prototype.Round = function (ACCUEAXY) { if (!isNaN(this) && this != Infinity) { return Number(this.toFixed(!isNaN(ACCUEAXY) ? ACCUEAXY : 2)); } return null; }; Number.isNumber = function (val) { var regPos = /^\d+(\.\d+)?$/; //非负浮点数 var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数 if (regPos.test(val) || regNeg.test(val)) { return true; } else { return false; } }; // String.prototype.Trim = String.trim; /** @ignore */ function $A(iterable) { if (!iterable) return []; if (iterable.toArray) return iterable.toArray(); var length = iterable.length, results = new Array(length); while (length--) { results[length] = iterable[length]; }return results; } Object.extend = function (destination, source) { for (var property in source) { destination[property] = source[property]; }return destination; }; Object.extend(Function.prototype, { wrap: function wrap(wrapper) { var __method = this; wrapper.__method = __method; return function () { return wrapper.apply(this, [__method.bind(this)].concat($A(arguments))); }; } }); /*------------------对JS的扩展 end-------------------------*/ if (!global["$T"]) { global.$T = {}; } else { global.$T = global.$T || {}; } // eslint-disable-next-line no-undef $T.Declare = function (ns) { ///<summary>���������ռ�</summary> ///<param name="ns" type="string">�����ռ䣬�磺Ufida.T.AA.Client</param> var ar = ns.split('.'); var root = global; for (var i = 0, len = ar.length; i < len; ++i) { var n = ar[i]; if (!root[n]) { root[n] = {}; root = root[n]; } else { root = root[n]; } } }; // eslint-disable-next-line no-undef $T.log = function (log) { console.log(log); }; // eslint-disable-next-line no-undef $T.debugger = function () { // debugger; }; /** * 获取当前函数的名称 */ Function.prototype.getName = function () { return this.name || this.toString().match(/function\s*([^(]*)\(/)[1]; }; // $T.Declare($T.Bap.Declare); // eslint-disable-next-line no-undef $T.Bap = {}; // eslint-disable-next-line no-undef $T.Bap.Declare = $T.Declare; // $T.Bap.Declare.__proto__ =$T.Declare.prototype; (function () { var _init = false; // eslint-disable-next-line no-undef $T.Object = function tempFun(prop) { var _base = this.prototype; _init = true; var proto = new this(); _init = false; for (var name in prop) { proto[name] = typeof prop[name] == "function" && typeof _base[name] == "function" ? function (name, fn) { return function () { var tmp = this.base; this.base = _base[name]; var ret = fn.apply(this, arguments); this.base = tmp; return ret; }; }(name, prop[name]) : prop[name]; } function cls() { if (!_init && this.init) { this.init.apply(this, arguments); } // this.extend=extend; // function extend(prop) // { // var supperClass=this; // var subClass=function(){}; // subClass.prototype=supperClass.prototype; // for (var name in prop) { // if (typeof prop[name] == "function") { // subClass.prototype.name=prop[name]; // } // else // { // subClass[name]=prop[name]; // } // } // return subClass; // } } cls.prototype = proto; cls.constructor = cls; cls.extend = tempFun; cls.fn = proto; cls.fn.extend = function (prop) { for (var name in prop) { if (typeof prop[name] == "function") { var basefn = function (fn) { return function () { if (fn) return fn.apply(this, arguments); }; }(this[name]); this[name] = function (fn, bfn) { return function () { var tmp = this.base; this.base = bfn; var ret = fn.apply(this, arguments); this.base = tmp; return ret; }; }(prop[name], basefn); } else { this[name] = prop[name]; } } return this; }; return cls; }.apply(Object, []); })(); /***********************************TMath begin*********************************************/ /*对JavaScript的扩展*/ // eslint-disable-next-line no-undef $T.Bap.Declare("$T.Bap.TMath"); // eslint-disable-next-line no-undef $T.Bap.TMath.ExpressionEngine = $T.Object.extend({ Convert: function Convert(exp) { var operStack = []; var out = []; var curly = 0; for (var i = 0, len = exp.length; i < len; ++i) { var ch = exp.charAt(i); var top; switch (ch) { case '(': operStack.push(ch); curly++; break; case ')': // eslint-disable-next-line no-constant-condition while (true) { top = operStack.pop(); if (top != '(' && operStack.length > 0) { out.push(top); } else { break; } } curly--; break; case '*': case '/': if (operStack.length == 0) { operStack.push(ch); break; } var flag = false; while (operStack.length > 0) { top = operStack.pop(); if (top == '(' || top == '+' || top == '-') { operStack.push(top); operStack.push(ch); flag = true; break; } else { out.push(top); } } if (flag) break; operStack.push(ch); break; case '+': case '-': if (operStack.length == 0) { operStack.push(ch); break; } top = operStack.pop(); if (top == '(') { operStack.push(top); operStack.push(ch); break; } else { out.push(top); while (operStack.length != 0) { top = operStack.pop(); if (top != "(") { out.push(top); } } if (top == "(") { operStack.push(top); } operStack.push(ch); } break; default: out.push(ch); break; } } if (curly > 0) throw new Error('curly not match'); while (operStack.length > 0) { out.push(operStack.pop()); } return out; } }); // eslint-disable-next-line no-undef $T.Bap.TMath.Evaluater = $T.Object.extend({ init: function init(cal) { this.calculator = cal; }, Eval: function Eval(ex) { var st = []; while (ex.length > 0) { var a = ex.shift(); if (typeof a == 'string' && a.indexOf('@') >= 0) { var d = parseInt(a.replace('@', '')); var v = st.pop().Round(d); st.push(v); continue; } switch (a) { case '+': st.push(this.calculator.Add(st.pop(), st.pop())); break; case '-': a = st.pop(); st.push(this.calculator.Minus(st.pop(), a)); break; case '*': st.push(this.calculator.Multiply(st.pop(), st.pop())); break; case '/': a = st.pop(); st.push(this.calculator.Divide(st.pop(), a)); break; default: st.push(a); break; } } return st[0]; } }); // eslint-disable-next-line no-undef $T.Bap.TMath.DefaultFormatter = $T.Object.extend({ init: function init() {}, Format: function Format(exp) { var arr = []; var ele = ''; var closed = false; while (exp.length > 0) { var ch = exp.shift(); switch (ch) { case '{': if (ele !== '') { arr.push(ele); ele = ''; } ele += ch; closed = false; break; case '}': ele += ch; arr.push(ele); ele = ''; closed = true; break; case '+': case '-': case '*': case '/': if (ele !== '') { arr.push(ele); ele = ''; } arr.push(ch); break; default: if (closed) { if (ch.toString().trim() !== '') { ele += ch; } } else { ele += ch; } break; } } return arr; } }); // eslint-disable-next-line no-undef $T.Bap.TMath.CalculatorFactory = { GetCalculator: function GetCalculator() { // eslint-disable-next-line no-undef return new $T.Bap.TMath.NormalCalculator(); } // eslint-disable-next-line no-undef };$T.Bap.TMath.NormalCalculator = $T.Object.extend({ init: function init() {}, Check: function Check(val) { if (typeof val == 'undefined' || val == null || typeof val == 'string' && (isNaN(val) || val === '')) { return false; } return true; }, GetPrecision: function GetPrecision(val) { if (val === undefined || val === null || isNaN(val)) return 0; var pattern = /\.(.*)/; var str = val.toString(); if (str.indexOf('.') >= 0) { var n = str.match(pattern)[1]; return n.length; } if (str.indexOf('e') > 0) { var r = str.match(/\d+e.?(\d)/i); if (r.length == 2) { return r[1]; } } return 0; }, ParseInt: function ParseInt(val, sp) { if (val === undefined || val === null || isNaN(val)) return 0; val = val.toString(); if (val.indexOf('.') >= 0) { if (!isNaN(sp)) { var d = val.match(/\d+\.(\d+)/)[1]; if (sp > d.length) { val += new Array(sp - d.length + 1).join('0'); } } val = val.replace('.', ''); val = Number(val); } else if (val.indexOf('e') > 0) { //未实现 val = Number(val.match(/\d+/i)); } else { if (!isNaN(sp)) { val += new Array(sp + 1).join('0'); } } return Number(val); }, ParseNum: function ParseNum(value) { function isEmpty(value) { value = value.replace(/[ ]/g, ''); if (value.length < 1) { return true; } return false; } //; //从新写一个ParseNum将5.12e-7的科学计数转换成普通数值的方法0.000000512 tangzheng value = value + ""; var rtnValue = value; if (!isEmpty(value)) { var num = 0; if ((num = value.indexOf('E')) != -1 || (num = value.indexOf('e')) != -1) { var doubleStr = value.substring(0, num); var eStr = value.substring(num + 1, value.length); eStr = parseInt(eStr); var doubleStrList = doubleStr.split('.'); var doubleStr1 = doubleStrList[0]; var doubleStr2 = doubleStrList[1]; if (eStr > 0) { //往后补0 var indexNum = Math.abs(eStr) - doubleStr2.length; //用0补齐 var str = ''; for (var i = 0; i < indexNum; i++) { str += '0'; } rtnValue = doubleStr1 + "." + doubleStr2 + str; } else { //往前补0 var _indexNum = Math.abs(eStr) - doubleStr1.length; //用0补齐 var _str = ''; for (var _i = 0; _i < _indexNum; _i++) { _str += '0'; } rtnValue = "0." + _str + doubleStr1 + doubleStr2; } } else { return value; } //如果是负数 if (parseFloat(value) < 0) rtnValue = "-" + rtnValue; } return rtnValue; }, ToString: function ToString(val) { var ret = val.toString(); var p = ret.match(/^(\d+)e([+-]?)(\d)$/i); if (!p) return val; var realNumber = p[1].toString(); var sign = p[2] == '+' || p[2] == '' ? true : false; var precision = p[3]; var out = ''; var leftover = precision - realNumber.length; var offset = new Array(leftover + 1).join('0'); if (sign) { out = offset + realNumber; } else { out = '0.' + offset + realNumber; } return out; }, /** * 加 * @param {*} a * @param {*} b */ Add: function Add(a, b) { if (!this.Check(a) && !this.Check(b)) return ''; a = Number(a); b = Number(b); var ap = this.GetPrecision(a); var bp = this.GetPrecision(b); var sp = Math.max(ap, bp); var a1 = this.ParseInt(a, sp); var b1 = this.ParseInt(b, sp); return (a1 + b1) / Math.pow(10, sp); }, /** * 减 * @param {*} a * @param {*} b */ Minus: function Minus(a, b) { if (!this.Check(a) && !this.Check(b)) return ''; a = Number(a); b = Number(b); var ap = this.GetPrecision(a); var bp = this.GetPrecision(b); var sp = Math.max(ap, bp); var a1 = this.ParseInt(a, sp); var b1 = this.ParseInt(b, sp); return (a1 - b1) / Math.pow(10, sp); }, /** * 乘 * @param {*} a * @param {*} b */ Multiply: function Multiply(a, b) { if (!this.Check(a) || !this.Check(b)) return ''; a = Number(a); b = Number(b); var ap = this.GetPrecision(a); var bp = this.GetPrecision(b); var sp = Number(ap) + Number(bp); var a1 = a, b1 = b; if (ap !== 0) { a1 = this.ParseInt(a1); } if (bp !== 0) { b1 = this.ParseInt(b1); } var s1 = Math.pow(10, sp); if (s1 === '' || s1 === 0 || s1 === null) { s1 = 1; } return Number(a1 * b1 / s1); }, /** * 除 * @param {*} a * @param {*} b * @param {*} notThrowDivideByZero */ Divide: function Divide(a, b, notThrowDivideByZero) { //; if (!this.Check(a) || !this.Check(b)) return ''; a = Number(a); b = Number(b); a = a.toString(); b = b.toString(); if (Number(b) === 0) { return 0; // if (notThrowDivideByZero) return ''; // else throw new DivideByZeroException(); } if (a.indexOf(".") >= 0) { a = a.replace(/[0]+$/, ''); } if (b.indexOf(".") >= 0) { b = b.replace(/[0]+$/, ''); } //获取绝对值 //zlj修改,将取绝对值的语句提前到去精度之前 var a1 = Math.abs(a), b1 = Math.abs(b); //获取小数位数 var ap = this.GetPrecision(a1); var bp = this.GetPrecision(b1); if (ap === 0 && bp === 0) return Number(a) / Number(b); var sign = ''; if (a < 0 || b < 0) sign = '-'; if (a < 0 && b < 0) sign = ''; //var a1 = Math.abs(a), b1 = Math.abs(b); if (ap !== 0) { a1 = this.ParseInt(a1); } if (bp !== 0) { b1 = this.ParseInt(b1); } var sp = ap - bp; var s1 = Math.pow(10, Math.abs(sp)); if (s1 === '' || s1 === 0 || s1 === null) { s1 = 1; } var v = a1 / b1; if (v != 0) { v = this.ParseNum(v); } if (sp === 0) return sign + v; var arr; if (sp > 0) { if (v.toString().indexOf(".") >= 0) { arr = v.toString().split("."); var first = arr[0]; var firstLen = first.length; if (firstLen == sp) return Number(sign + "0." + arr[0] + arr[1]); if (firstLen > sp) { var fi = first.substr(0, firstLen - sp); var se = first.substr(firstLen - sp, firstLen); if (fi == "") fi = 0; return Number(sign + fi + '.' + se + arr[1]); } else { return Number(sign + "0." + new Array(sp - firstLen + 1).join('0') + arr[0] + arr[1]); } } else { return Number(sign + v / s1); } } else { sp = Math.abs(sp); if (v.toString().indexOf(".") >= 0) { arr = v.toString().split("."); var second = arr[1]; var secondLen = second.length; if (secondLen == sp) return sign + arr[0] + arr[1]; if (secondLen > sp) { var _fi = second.substr(0, sp); var _se = second.substr(sp, secondLen); var ret = sign + arr[0] + _fi + '.' + _se; ret = ret.replace(/^[0]+/, ''); if (ret.charAt(0) == '.') ret = '0' + ret; return Number(ret); } else { //var ret = sign + arr[0] + arr[1] + new Array(sp - secondLen + 1).join('0'); //ret = ret.replace(/^[0]+/, ''); //zlj修改如果是负数,将-号后面的零去掉 var _ret = arr[0] + arr[1] + new Array(sp - secondLen + 1).join('0'); _ret = _ret.replace(/^[0]+/, ''); _ret = sign + _ret; if (_ret.charAt(0) == '.') _ret = '0' + _ret; return Number(_ret); } } else { var _ret2 = this.Multiply(v, s1); return sign + _ret2; } } }, ToFixed: function ToFixed(x) { if (Math.abs(x) < 1.0) { var e = parseInt(x.toString().split('e-')[1]); if (e) { x *= Math.pow(10, e - 1); x = '0.' + new Array(e).join('0') + x.toString().substring(2); } } else { var _e = parseInt(x.toString().split('+')[1]); if (_e > 20) { _e -= 20; x /= Math.pow(10, _e); x += new Array(_e + 1).join('0'); } } return x.toString(); } }); function DivideByZeroException() {} // eslint-disable-next-line no-undef $T.Bap.TMath.FormulaBase = $T.Object.extend({ init: function init(currentRowData) { // eslint-disable-next-line no-undef this.NS = $T.Bap.TMath; this.currentRowData = currentRowData; this.map = null; this.BeforeSetValue = null; this.BeforeGetValue = null; this.pattern = /{(.*)}/i; this.expressionList = []; this.precisionMap = null; this.result = {}; this.engine = new this.NS.ExpressionEngine(); this.calculator = this.NS.CalculatorFactory.GetCalculator(); this.evaluater = new this.NS.Evaluater(this.calculator); this.formatter = new this.NS.DefaultFormatter(); }, SetExpression: function SetExpression(exp) { this.expressionList.push(exp); }, RunParse: function RunParse() { try { for (var i = 0; i < this.expressionList.length; ++i) { this.ParseExpression(this.expressionList[i]); } } catch (exc) { console.error(exc); } this.Flush(); }, ParseExpression: function ParseExpression(exp) { var arr = exp.split('='); var ret = arr[0].trim(); var expression = arr[1].trim(); var out = this.engine.Convert(expression); out = this.formatter.Format(out); out = this.ParseArguments(out); try { out = this.evaluater.Eval(out); } catch (ex) { console.error(ex); return; } var m = ret.match(this.pattern); if (m && m.length >= 2) { console.log(exp); console.log(m[1] + "=" + out); this.SetValue(m[1], out); } }, ParseArguments: function ParseArguments(out) { var exp = out; var st = []; while (exp.length > 0) { var ele = out.shift(); var r = ele.match(this.pattern); if (r) { st.push(this.GetValue(r[1])); } else { st.push(ele); } } return st; }, SetPrecision: function SetPrecision(o) { this.precision = o; }, SetPattern: function SetPattern(p) { this.pattern = p; }, SetMapColumns: function SetMapColumns(m) { this.map = m; }, SetValue: function SetValue(colName, val) { var ret; if (this.BeforeSetValue) { ret = this.BeforeSetValue(colName, val); if (ret == false) return; } ret = val; var col = colName; if (this.map) { colName = this.map[colName]; } if (this.precision != null) { if (!isNaN(this.precision[col]) && this.precision[col] >= 0) { ret = val.Round(this.precision[col]); } } this.result[col] = ret; }, CheckData: function CheckData(colName, value) { if (typeof value == 'string') { if (value == '' || value == null || value == undefined) throw new Error(colName + ' is string and is empty!'); } else if (typeof value == 'number') { if (value === null || value === undefined || isNaN(value)) throw new Error(colName + ' is null error or not a number'); } else { throw new Error(colName + ' is not string or number'); } }, GetValue: function GetValue(colName) { if (this.BeforeGetValue) { var ret = this.BeforeGetValue(colName); if (ret != undefined) return ret; } var col = colName; var cellValue = this.result[col]; if (cellValue === undefined || cellValue === null) { if (this.map) { colName = this.map[col]; } cellValue = this.currentRowData[colName]; } try { this.CheckData(colName, cellValue); } catch (eexc) { return null; } $T.log("cellValue:" + cellValue); if (cellValue && this.precision != null) { if (!isNaN(this.precision[col]) && this.precision[col] >= 0) { return cellValue.Round(this.precision[col]); } } return cellValue; }, /** * */ Flush: function Flush() { if (this.result) { for (var col in this.result) { if (typeof this.result[col] == 'function') continue; var colName = this.map ? this.map[col] : col; if (this.result[col] !== undefined) { this.currentRowData[colName] = this.result[col]; } } } this.Dispose(); }, Dispose: function Dispose() { this.result = {}; } }); $T.ToFunction = function (value, calDirection, exchangeRate, isFormat) { var calc = $T.Bap.TMath.CalculatorFactory.GetCalculator(); var cc = $T.GetClientContext(); exchangeRate = exchangeRate.Round(cc.ExchangeRateDecimalDigits); var curBit = (value + "").indexOf(".") == -1 ? 0 : (value + "").match(/\.+(.*)/)[1].length; if (calDirection == '00') { //正算 if (!isFormat) { return calc.Multiply(value, exchangeRate); } return calc.Multiply(value, exchangeRate).Round(curBit); } else { if (!isFormat) { return calc.Divide(value, exchangeRate); } return calc.Divide(value, exchangeRate).Round(curBit); } }; /************************** TMath.js end *******************/ //# sourceMappingURL=Challenger.js.map