import { parse } from './parse' ; import { INumberFormat , IOptions , IVars , IFunctions , IField } from './interfaces' ; import { getFieldSelector , numCleanse , numberFix } from './utils' ; export function autoCalc ( eq , fields , result , ctx , opts , vars , funcs ) { let resultValue = '' ; const numberFormat = { dec : '' , decPlaces : - 1 , thou : '' , sym : '' , symLoc : - 1 } ; $ . each ( $ . extend ( { } , funcs ) , function ( func , f ) { const r = new RegExp ( f . rgx , 'gi' ) ; let m ; while ( ( m = r . exec ( eq ) ) != null ) { const v = f . exec ( m [ 1 ] , ctx , opts , numberFormat ) ; eq = eq . replace ( new RegExp ( f . rgx , 'gi' ) , v ) ; } } ) ; for ( let i = 0 ; i < fields . length ; i ++ ) { const field = fields [ i ] ; const fieldValue = $ ( getFieldSelector ( field . fieldName ) , ctx ) . val ( ) ; const numValue = numCleanse ( fieldValue , opts , numberFormat ) ; if ( numValue . length == 0 ) { result . val ( '' ) . trigger ( "change" ) ; return ; } const parsedValue = parse ( numValue , { showParseError : false } ) ; if ( parsedValue == null ) { result . val ( '' ) . trigger ( "change" ) ; return ; } eq = eq . replace ( new RegExp ( '{' + field . eqName + '}' , 'g' ) , numValue ) ; } eq = eq . replace ( / /g , '' ) ; if ( numberFormat . dec == '' ) { numberFormat . dec = opts . decimalOpts [ 0 ] ; } if ( numberFormat . decPlaces == - 1 ) { numberFormat . decPlaces = 0 ; } if ( numberFormat . thou == '' ) { numberFormat . thou = opts . thousandOpts [ 0 ] ; } const tmp = parse ( eq , opts ) ; if ( tmp == null ) { resultValue = '' ; } else { resultValue = numberFix ( tmp , numberFormat . decPlaces ) ; } resultValue = resultValue . replace ( /\./g , '<c>' ) ; resultValue = resultValue . replace ( /\,/g , '<t>' ) ; resultValue = resultValue . replace ( /<c>/g , numberFormat . dec ) ; resultValue = resultValue . replace ( /<t>/g , numberFormat . thou ) ; if ( numberFormat . symLoc > - 1 ) { if ( numberFormat . symLoc == 0 ) { resultValue = numberFormat . sym + resultValue ; } else { resultValue = resultValue + numberFormat . sym ; } } if ( opts . smartIntegers ) { resultValue = resultValue . replace ( /[\,\.]0+$/ , '' ) ; } if ( typeof opts . onShowResult === "function" ) { resultValue = opts . onShowResult . call ( result , resultValue ) ; } result . val ( resultValue ) ; if ( opts . chainFire ) { const current = result . data ( 'current' ) ; if ( current === undefined || current !== resultValue ) { result . data ( 'current' , resultValue ) ; result . trigger ( "change" ) ; } } }