/*
    *
    * Wijmo Library 5.20183.550
    * http://wijmo.com/
    *
    * Copyright(c) GrapeCity, Inc.  All rights reserved.
    *
    * Licensed under the GrapeCity Commercial License.
    * sales@wijmo.com
    * wijmo.com/products/wijmo-5/license/
    *
    */
function _getTagValue(e,t){let i=e.querySelector(t);return i?i.innerHTML||i.textContent:null}function _getLevelNumber(e){return Number(_getTagValue(e,"LNum"))}function _getCaptionValue(e){return _getLevelNumber(e)>0?_getTagValue(e,"Caption"):null}function _getCellValue(e,t){let i="Cell[CellOrdinal='"+t.toString()+"']",s=e.querySelector(i);if(s){let e=_getTagValue(s,"Value");if(e)return Number(e)}return null}function _findSubFieldByName(e,t){if(e.subFields)for(var i=0;i<e.subFields.length;i++){var s=e.subFields[i];if(s.header==t)return s}return e}function _containsFolder(e,t){if(e.subFields)for(var i=0;i<e.subFields.length;i++)if(e.subFields[i].header==t)return!0;return!1}import*as wjcCore from"wijmo/wijmo";import*as wjcGridFilter from"wijmo/wijmo.grid.filter";import*as wjcInput from"wijmo/wijmo.input";import*as wjcGrid from"wijmo/wijmo.grid";import*as wjcChart from"wijmo/wijmo.chart";var __glob="undefined"!=typeof window?window:self;import*as wjcSelfRef from"wijmo/wijmo.olap";var wjcSelf=wjcSelfRef||exports;__glob.wijmo=__glob.wijmo||{},__glob.wijmo.olap=wjcSelf;export class _Tally{constructor(){this._cnt=0,this._cntn=0,this._sum=0,this._sum2=0,this._min=null,this._max=null,this._first=null,this._last=null}add(e,t){e instanceof _Tally?(this._sum+=e._sum,this._sum2+=e._sum2,this._max=this._max&&e._max?Math.max(this._max,e._max):this._max||e._max,this._min=this._min&&e._min?Math.min(this._min,e._min):this._min||e._min,this._cnt+=e._cnt,this._cntn+=e._cntn):null!=e&&(this._cnt++,wjcCore.isBoolean(e)&&(e=e?1:0),(null==this._min||e<this._min)&&(this._min=e),(null==this._max||e>this._max)&&(this._max=e),null==this._first&&(this._first=e),this._last=e,wjcCore.isNumber(e)&&!isNaN(e)&&(wjcCore.isNumber(t)&&(e*=t),this._cntn++,this._sum+=e,this._sum2+=e*e))}getAggregate(e){if(0==this._cnt)return null;let t=0==this._cntn?0:this._sum/this._cntn;switch(e){case wjcCore.Aggregate.Avg:return t;case wjcCore.Aggregate.Cnt:return this._cnt;case wjcCore.Aggregate.Max:return this._max;case wjcCore.Aggregate.Min:return this._min;case wjcCore.Aggregate.Rng:return this._max-this._min;case wjcCore.Aggregate.Sum:return this._sum;case wjcCore.Aggregate.VarPop:return this._cntn<=1?0:this._sum2/this._cntn-t*t;case wjcCore.Aggregate.StdPop:return this._cntn<=1?0:Math.sqrt(this._sum2/this._cntn-t*t);case wjcCore.Aggregate.Var:return this._cntn<=1?0:(this._sum2/this._cntn-t*t)*this._cntn/(this._cntn-1);case wjcCore.Aggregate.Std:return this._cntn<=1?0:Math.sqrt((this._sum2/this._cntn-t*t)*this._cntn/(this._cntn-1));case wjcCore.Aggregate.First:return this._first;case wjcCore.Aggregate.Last:return this._last}throw"Invalid aggregate type."}};export class _PivotKey{constructor(e,t,i,s,l){this._fields=e,this._fieldCount=t,this._valueFields=i,this._valueFieldIndex=s,this._item=l}get fields(){return this._fields}get valueFields(){return this._valueFields}get valueField(){return this._valueFields[this._valueFieldIndex]}get values(){if(null==this._vals){this._vals=new Array(this._fieldCount);for(let e=0;e<this._fieldCount;e++){let t=this._fields[e];this._vals[e]=t._getValue(this._item,!1)}}return this._vals}get fieldNames(){if(!this._names){this._names=[];for(let e=0;e<this.fields.length;e++){let t=this._fields[e];this._names.push(t._getName())}}return this._names}get aggregate(){let e=this._valueFields,t=this._valueFieldIndex;return wjcCore.assert(e&&t>-1&&t<e.length,"aggregate not available for this key"),e[t].aggregate}getValue(e,t){if(0==this.values.length)return wjcCore.culture.olap.PivotEngine.grandTotal;if(e>this.values.length-1)return wjcCore.culture.olap.PivotEngine.subTotal;let i=this.values[e];if(t&&!wjcCore.isString(i)){let t=this.fields[e],s=t?t.format:"";i=wjcCore.Globalize.format(this.values[e],s)}return i}get level(){return this._fieldCount==this._fields.length?-1:this._fieldCount}compareTo(e){let t=0;if(null!=e&&e._fields==this._fields){let i=this.values,s=e.values,l=Math.min(i.length,s.length);for(let r=0;r<l;r++){let l=null!=i[r]?wjcCore.getType(i[r]):null,n=i[r],o=s[r],a=this._fields[r];if(a.sortComparer&&(t=a.sortComparer(n,o),wjcCore.isNumber(t))){if(0!=t)return a.descending?-t:t}else{if(l==wjcCore.DataType.Date){let t=a.format;if(t&&"d"!=t&&"D"!=t){let i=a._getValue(this._item,!0),s=a._getValue(e._item,!0),l=wjcCore.Globalize.parseDate(i,t),r=wjcCore.Globalize.parseDate(s,t);l&&r?(n=l,o=r):(n=i,o=s)}}if(!(n==o||wjcCore.DateTime.equals(n,o)))return null==n?1:null==o?-1:(t=n<o?-1:1,a.descending?-t:t)}}if(i.length==s.length&&0!=(t=this._valueFieldIndex-e._valueFieldIndex))return t;if(0!=(t=s.length-i.length))return t*(this.fields.engine.totalsBeforeData?-1:1)}return 0}matchesItem(e){for(let t=0;t<this._vals.length;t++)if(this.getValue(t,!0)!=this._fields[t]._getValue(e,!0))return!1;return!0}toString(e){if(!this._key||e){let t="";for(let e=0;e<this._fieldCount;e++){let i=this._fields[e];t+=i._getName()+":"+i._getValue(this._item,!0)+";"}if(this._valueFields?t+=this._valueFields[this._valueFieldIndex]._getName()+":0;":t+="{total}",e)return t+e.toString();this._key=t}return this._key}};_PivotKey._ROW_KEY_NAME="$rowKey";export class _PivotNode{constructor(e,t,i,s,l,r){this._key=new _PivotKey(e,t,i,s,l),this._nodes={},this._parent=r}getNode(e,t,i,s,l){let r=this;for(let n=0;n<t;n++){let t=e[n]._getValue(l,!0),o=r._nodes[t];o||(o=new _PivotNode(e,n+1,i,s,l,r),r._nodes[t]=o),r=o}if(i&&s>-1){let n=i[s].header,o=r._nodes[n];o||(o=new _PivotNode(e,t,i,s,l,r),r._nodes[n]=o),r=o}return r}get key(){return this._key}get parent(){return this._parent}get tree(){return this._tree||(this._tree=new _PivotNode(null,0,null,-1,null)),this._tree}};export class PivotCollectionView extends wjcCore.CollectionView{constructor(e){super(),this._ng=wjcCore.asType(e,PivotEngine,!1)}get engine(){return this._ng}_performSort(e){let t=this._ng;if(t.sortableGroups&&t._getShowRowTotals()==ShowTotals.Subtotals){let t=0,i=e.length-1;0==this._getItemLevel(e[t])&&t++,0==this._getItemLevel(e[i])&&i--,this._sortGroups(e,1,t,i)}else this._sortData(e)}_performFilter(e){return this._ng&&0==this._ng.valueFields.length&&0==this._ng.rowFields.length?[]:this.canFilter&&this._filter?e.filter(this._filter,this):e}_getGroupRange(e,t){let i=this._ng,s=e.indexOf(t),l=s,r=this._getItemLevel(e[s]);if(i.totalsBeforeData)for(l=s;l<e.length-1;l++){let t=this._getItemLevel(e[l+1]);if(t>-1&&t<=r)break}else for(s=l;s;s--){let t=this._getItemLevel(e[s-1]);if(t>-1&&t<=r)break}return[s,l]}_sortGroups(e,t,i,s){let l=[];for(let r=i;r<=s;r++)this._getItemLevel(e[r])==t&&l.push(e[r]);if(!l.length)return void this._sortData(e);super._performSort(l);let r=[];for(let s=0;s<l.length;s++){var n=this._getGroupRange(e,l[s]),o=r.length;for(let t=n[0];t<=n[1];t++)r.push(e[t]);t<this._ng.rowFields.length-1?this._sortGroups(r,t+1,i+o,r.length-1):this._sortSegment(r,i+o,r.length-1)}for(let t=0;t<r.length;t++)e[i+t]=r[t]}_sortSegment(e,t,i){let s=e.slice(t,i);super._performSort(s);for(let i=0;i<s.length;i++)e[t+i]=s[i]}_sortData(e){for(let t=0;t<e.length;t++){if(this._getItemLevel(e[t])>-1)continue;let i=t;for(;i<e.length-1&&!(this._getItemLevel(e[i+1])>-1);i++);if(i>t){let s=e.slice(t,i+1);super._performSort(s);for(let i=0;i<s.length;i++)e[t+i]=s[i]}t=i}}_getItemLevel(e){return e[_PivotKey._ROW_KEY_NAME].level}};export class PivotField{constructor(e,t,i,s){this.propertyChanged=new wjcCore.Event,this._ng=e,this._binding=new wjcCore.Binding(t),this._header=i||wjcCore.toHeaderCase(t),this._aggregate=wjcCore.Aggregate.Sum,this._showAs=ShowAs.NoCalculation,this._isContentHtml=!1,this._visible=!0,this._format="",this._filter=new PivotFilter(this),s&&wjcCore.copy(this,s)}get binding(){return this._binding?this._binding.path:null}set binding(e){if(e!=this.binding){let t=this.binding,i=wjcCore.asString(e);if(this._binding=i?new wjcCore.Binding(i):null,!this._dataType&&this._ng&&this._binding){let e=this._ng.collectionView;if(e&&e.sourceCollection&&e.sourceCollection.length){let t=e.sourceCollection[0];this._dataType=wjcCore.getType(this._binding.getValue(t))}}let s=new wjcCore.PropertyChangedEventArgs("binding",t,e);this.onPropertyChanged(s)}}get getValue(){return this._getValueFn}set getValue(e){this._getValueFn=wjcCore.asFunction(e,!0)}get header(){return this._header}set header(e){e=wjcCore.asString(e,!1);let t=this._ng.fields.getField(e);!e||t&&t!=this?wjcCore.assert(!1,"field headers must be unique and non-empty."):this._setProp("_header",wjcCore.asString(e))}get filter(){return this._filter}get aggregate(){return this._aggregate}set aggregate(e){this._setProp("_aggregate",wjcCore.asEnum(e,wjcCore.Aggregate))}get showAs(){return this._showAs}set showAs(e){this._setProp("_showAs",wjcCore.asEnum(e,ShowAs))}get weightField(){return this._weightField}set weightField(e){this._setProp("_weightField",wjcCore.asType(e,PivotField,!0))}get dataType(){return this._dataType}set dataType(e){this._setProp("_dataType",wjcCore.asEnum(e,wjcCore.DataType))}get isMeasure(){return this._dataType==wjcCore.DataType.Number}get subFields(){return this._subFields}get format(){return this._format}set format(e){this._setProp("_format",wjcCore.asString(e))}get width(){return this._width}set width(e){this._setProp("_width",wjcCore.asNumber(e,!0,!0))}get wordWrap(){return this._wordWrap}set wordWrap(e){this._setProp("_wordWrap",wjcCore.asBoolean(e))}get descending(){return!!this._descending}set descending(e){this._setProp("_descending",wjcCore.asBoolean(e))}get isContentHtml(){return this._isContentHtml}set isContentHtml(e){this._setProp("_isContentHtml",wjcCore.asBoolean(e))}get visible(){return this._visible}set visible(e){this._setProp("_visible",wjcCore.asBoolean(e))}get sortComparer(){return this._srtCmp}set sortComparer(e){e!=this.sortComparer&&(this._srtCmp=wjcCore.asFunction(e))}get engine(){return this._ng}get collectionView(){return this.engine?this.engine.collectionView:null}get isActive(){return this._getIsActive()}set isActive(e){this._setIsActive(e)}get parentField(){return this._parent}get key(){return this.header}onPropertyChanged(e){this.propertyChanged.raise(this,e),this._ng._fieldPropertyChanged(this,e)}_copy(e,t){return"subFields"==e&&(this._subFields?this._subFields.splice(0,this._subFields.length):this._subFields=[],t&&t.length&&t.forEach(e=>{let t=this.engine._createField(e,this._autoGenerated);this._subFields.push(t)}),!0)}_getIsActive(){if(this._ng&&!this._hasSubFields()){let e=this._ng._viewLists;for(let t=0;t<e.length;t++){let i=e[t];for(let e=0;e<i.length;e++)if(i[e].binding==this.binding)return!0}}return!1}_setIsActive(e){if(this._ng&&!this._hasSubFields()){let t=this.isActive;if((e=wjcCore.asBoolean(e))!=t)if(e)this.isMeasure?this._ng.valueFields.push(this):this._ng.rowFields.push(this);else{let e=this._ng._viewLists;for(let t=0;t<e.length;t++){let i=e[t];for(let e=0;e<i.length;e++){let t=i[e];t!=this&&t.parentField!=this||(i.removeAt(e),e--)}}let t=this._ng.fields;for(let e=t.length-1;e>=0;e--)t[e].parentField==this&&(t.removeAt(e),e--)}}}_hasSubFields(){return null!=this._subFields&&this._subFields.length>0}_clone(){let e=new PivotField(this._ng,this.binding);this._ng._copyProps(e,this,PivotField._props),e._autoGenerated=!0,e._parent=this;let t=this.header.replace(/\d+$/,"");for(let i=2;;i++){let s=t+i.toString();if(null==this._ng.fields.getField(s)){e._header=s;break}}return e}_setProp(e,t,i){let s=this[e];if(t!=s){this[e]=t;let i=new wjcCore.PropertyChangedEventArgs(e.substr(1),s,t);this.onPropertyChanged(i)}}_getName(){return this.header||this.binding}_getValue(e,t){let i,s=this._binding;return i=wjcCore.isFunction(this._getValueFn)?this._getValueFn.call(this,e):this._ng.isServer?e[this.key]:s._key?e[s._key]:s.getValue(e),t&&"string"!=typeof i?wjcCore.Globalize.format(i,this._format):i}_getWeight(e){let t=this._weightField?this._weightField._getValue(e,!1):null;return wjcCore.isNumber(t)?t:null}};PivotField._props=["dataType","format","width","wordWrap","aggregate","showAs","descending","isContentHtml","visible"];export class CubePivotField extends PivotField{constructor(e,t,i,s){super(e,t,i,s),wjcCore.assert(null!=this.dimensionType,"CubePivotField objects must specify the field's dimensionType")}get header(){return this._header}set header(e){this._setProp("_header",wjcCore.asString(e))}get dimensionType(){return this._dimensionType}set dimensionType(e){this._setProp("_dimensionType",wjcCore.asEnum(e,DimensionType,!1))}get isMeasure(){switch(this._dimensionType){case 1:case 8:return!0}return!1}get key(){return this.binding}_clone(){throw"CubePivotField objects cannot be cloned"}};export var DimensionType;!function(e){e[e.Dimension=0]="Dimension",e[e.Measure=1]="Measure",e[e.Kpi=2]="Kpi",e[e.NameSet=3]="NameSet",e[e.Attribute=4]="Attribute",e[e.Folder=5]="Folder",e[e.Hierarchy=6]="Hierarchy",e[e.Date=7]="Date",e[e.Currency=8]="Currency"}(DimensionType||(DimensionType={}));export class PivotFieldCollection extends wjcCore.ObservableArray{constructor(e){super(),this._ng=e}get maxItems(){return this._maxItems}set maxItems(e){this._maxItems=wjcCore.asInt(e,!0,!0)}get engine(){return this._ng}getField(e){return this._getField(this,e)}_getField(e,t){for(let i=0;i<e.length;i++){let s=e[i];if(s.key==t)return s;if(s._hasSubFields()&&(s=this._getField(s.subFields,t)))return s}return null}push(...e){let t=this._ng;for(let i=0;e&&i<e.length;i++){let s=e[i];if(wjcCore.isString(s)&&(s=this==t.fields?new PivotField(t,s):t.fields.getField(s)),wjcCore.assert(s instanceof PivotField,"This collection must contain PivotField objects only."),s.key&&this.getField(s.key))return wjcCore.assert(!1,"PivotField keys must be unique."),-1;if(null!=this._maxItems&&this.length>=this._maxItems)break;super.push(s)}return this.length}};export class PivotFilter{constructor(e){this._fld=e;let t=e;this._valueFilter=new wjcGridFilter.ValueFilter(t),this._conditionFilter=new wjcGridFilter.ConditionFilter(t)}get filterType(){return null!=this._filterType?this._filterType:this._fld.engine.defaultFilterType}set filterType(e){(e=wjcCore.asEnum(e,wjcGridFilter.FilterType,!0))!=this._filterType&&(this._filterType=e,this.clear())}apply(e){return this._conditionFilter.apply(e)&&this._valueFilter.apply(e)}get isActive(){return this._conditionFilter.isActive||this._valueFilter.isActive}clear(){let e=!1;this._valueFilter.isActive&&(this._valueFilter.clear(),e=!0),this._conditionFilter.isActive&&(this._valueFilter.clear(),e=!0),e&&this._fld.onPropertyChanged(new wjcCore.PropertyChangedEventArgs("filter",null,null))}get valueFilter(){return this._valueFilter}get conditionFilter(){return this._conditionFilter}};export class PivotFieldEditor extends wjcCore.Control{constructor(e,t){super(e,null,!0);wjcCore.assert(null!=wjcInput,"Missing dependency: PivotFieldEditor requires wijmo.input."),this.hostElement.tabIndex=-1;let i=this.getTemplate();this.applyTemplate("wj-control wj-pivotfieldeditor",i,{_dBnd:"sp-bnd",_dHdr:"div-hdr",_dAgg:"div-agg",_dShw:"div-shw",_dWFl:"div-wfl",_dSrt:"div-srt",_btnFltEdt:"btn-flt-edt",_btnFltClr:"btn-flt-clr",_dFmt:"div-fmt",_dSmp:"div-smp",_btnApply:"btn-apply",_btnCancel:"btn-cancel",_gDlg:"g-dlg",_gHdr:"g-hdr",_gAgg:"g-agg",_gShw:"g-shw",_gWfl:"g-wfl",_gSrt:"g-srt",_gFlt:"g-flt",_gFmt:"g-fmt",_gSmp:"g-smp"}),this._pvDate=new Date;let s=wjcCore.culture.olap.PivotFieldEditor;wjcCore.setText(this._gDlg,s.dialogHeader),wjcCore.setText(this._gHdr,s.header),wjcCore.setText(this._gAgg,s.summary),wjcCore.setText(this._gShw,s.showAs),wjcCore.setText(this._gWfl,s.weighBy),wjcCore.setText(this._gSrt,s.sort),wjcCore.setText(this._gFlt,s.filter),wjcCore.setText(this._gFmt,s.format),wjcCore.setText(this._gSmp,s.sample),wjcCore.setText(this._btnFltEdt,s.edit),wjcCore.setText(this._btnFltClr,s.clear),wjcCore.setText(this._btnApply,s.ok),wjcCore.setText(this._btnCancel,s.cancel),this._cmbHdr=new wjcInput.ComboBox(this._dHdr),this._cmbAgg=new wjcInput.ComboBox(this._dAgg),this._cmbShw=new wjcInput.ComboBox(this._dShw),this._cmbWFl=new wjcInput.ComboBox(this._dWFl),this._cmbSrt=new wjcInput.ComboBox(this._dSrt),this._cmbFmt=new wjcInput.ComboBox(this._dFmt),this._cmbSmp=new wjcInput.ComboBox(this._dSmp),this._initAggregateOptions(),this._initShowAsOptions(),this._initFormatOptions(),this._initSortOptions(),this._updatePreview(),this._cmbShw.textChanged.addHandler(this._updateFormat,this),this._cmbFmt.textChanged.addHandler(this._updatePreview,this),this.addEventListener(this._btnFltEdt,"click",e=>{this._editFilter(),e.preventDefault()}),this.addEventListener(this._btnFltClr,"click",e=>{this._createFilterEditor(),setTimeout(()=>{this._eFlt.clearEditor(),this._btnFltEdt.focus(),wjcCore.enable(this._btnFltClr,!1)}),e.preventDefault()}),this.addEventListener(this._btnApply,"click",e=>{this.updateField()}),this.initialize(t)}get field(){return this._fld}set field(e){e!=this._fld&&(this._fld=wjcCore.asType(e,PivotField),this.updateEditor())}updateEditor(){if(this._fld){this._dBnd.textContent=this._fld.binding,this._cmbHdr.text=this._fld.header,this._cmbAgg.collectionView.refresh(),this._cmbAgg.selectedValue=this._fld.aggregate,this._cmbSrt.selectedValue=this._fld.descending,this._cmbShw.selectedValue=this._fld.showAs,this._initWeighByOptions(),wjcCore.enable(this._btnFltClr,this._fld.filter.isActive),this._cmbFmt.collectionView.refresh(),this._cmbFmt.selectedValue=this._fld.format,this._cmbFmt.selectedValue||(this._cmbFmt.text=this._fld.format);let e=this._fld instanceof CubePivotField;this._cmbAgg.isDisabled=e,this._cmbWFl.isDisabled=e}}updateField(){if(this._fld){let e=this._cmbHdr.text.trim();this._fld.header=e||wjcCore.toHeaderCase(this._fld.binding),this._fld.aggregate=this._cmbAgg.selectedValue,this._fld.showAs=this._cmbShw.selectedValue,this._fld.weightField=this._cmbWFl.selectedValue,this._fld.descending=this._cmbSrt.selectedValue,this._eFlt&&this._eFlt.updateFilter(),this._fld.format=this._cmbFmt.selectedValue||this._cmbFmt.text}}_initAggregateOptions(){let e=wjcCore.culture.olap.PivotFieldEditor.aggs,t=wjcCore.Aggregate,i=[{key:e.sum,val:t.Sum,all:!1},{key:e.cnt,val:t.Cnt,all:!0},{key:e.avg,val:t.Avg,all:!1},{key:e.max,val:t.Max,all:!0},{key:e.min,val:t.Min,all:!0},{key:e.rng,val:t.Rng,all:!1},{key:e.std,val:t.Std,all:!1},{key:e.var,val:t.Var,all:!1},{key:e.stdp,val:t.StdPop,all:!1},{key:e.varp,val:t.VarPop,all:!1},{key:e.first,val:t.First,all:!0},{key:e.last,val:t.Last,all:!0}];this._cmbAgg.itemsSource=i,this._cmbAgg.collectionView.filter=(e=>{if(e&&e.all)return!0;if(this._fld){let e=this._fld.dataType;return e==wjcCore.DataType.Number||e==wjcCore.DataType.Boolean}return!1}),this._cmbAgg.initialize({displayMemberPath:"key",selectedValuePath:"val"})}_initShowAsOptions(){let e=wjcCore.culture.olap.PivotFieldEditor.calcs,t=[{key:e.noCalc,val:ShowAs.NoCalculation},{key:e.dRow,val:ShowAs.DiffRow},{key:e.dRowPct,val:ShowAs.DiffRowPct},{key:e.dCol,val:ShowAs.DiffCol},{key:e.dColPct,val:ShowAs.DiffColPct},{key:e.dPctGrand,val:ShowAs.PctGrand},{key:e.dPctRow,val:ShowAs.PctRow},{key:e.dPctCol,val:ShowAs.PctCol},{key:e.dRunTot,val:ShowAs.RunTot},{key:e.dRunTotPct,val:ShowAs.RunTotPct}];this._cmbShw.itemsSource=t,this._cmbShw.initialize({displayMemberPath:"key",selectedValuePath:"val"})}_initFormatOptions(){let e=wjcCore.culture.olap.PivotFieldEditor.formats,t=[{key:e.n0,val:"n0",all:!0},{key:e.n2,val:"n2",all:!0},{key:e.c,val:"c",all:!0},{key:e.p0,val:"p0",all:!0},{key:e.p2,val:"p2",all:!0},{key:e.n2c,val:"n2,",all:!0},{key:e.n2cc,val:"n2,,",all:!0},{key:e.n2ccc,val:"n2,,,",all:!0},{key:e.d,val:"d",all:!1},{key:e.MMMMddyyyy,val:"MMMM dd, yyyy",all:!1},{key:e.dMyy,val:"d/M/yy",all:!1},{key:e.ddMyy,val:"dd/M/yy",all:!1},{key:e.dMyyyy,val:"dd/M/yyyy",all:!1},{key:e.MMMyyyy,val:"MMM yyyy",all:!1},{key:e.MMMMyyyy,val:"MMMM yyyy",all:!1},{key:e.yyyy,val:"yyyy",all:!1},{key:e.yyyyQq,val:'yyyy "Q"q',all:!1},{key:e.FYEEEEQU,val:'"FY"EEEE "Q"U',all:!1}];this._cmbFmt.itemsSource=t,this._cmbFmt.isEditable=!0,this._cmbFmt.isRequired=!1,this._cmbFmt.collectionView.filter=(e=>!(!e||!e.all)||!!this._fld&&this._fld.dataType==wjcCore.DataType.Date),this._cmbFmt.initialize({displayMemberPath:"key",selectedValuePath:"val"})}_initWeighByOptions(){let e=[{key:wjcCore.culture.olap.PivotFieldEditor.none,val:null}];if(this._fld){let t=this._fld.engine;for(let i=0;i<t.fields.length;i++){let s=t.fields[i];s!=this._fld&&s.dataType==wjcCore.DataType.Number&&e.push({key:s.header,val:s})}}this._cmbWFl.initialize({displayMemberPath:"key",selectedValuePath:"val",itemsSource:e,selectedValue:this._fld.weightField})}_initSortOptions(){let e=wjcCore.culture.olap.PivotFieldEditor.sorts,t=[{key:e.asc,val:!1},{key:e.desc,val:!0}];this._cmbSrt.itemsSource=t,this._cmbSrt.initialize({displayMemberPath:"key",selectedValuePath:"val"})}_updateFormat(){switch(this._cmbShw.selectedValue){case ShowAs.DiffRowPct:case ShowAs.DiffColPct:this._cmbFmt.selectedValue="p0";break;default:this._cmbFmt.selectedValue="n0"}}_updatePreview(){let e=this._cmbFmt.selectedValue||this._cmbFmt.text,t=wjcCore.Globalize.format,i="";if(e){let s=e[0].toLowerCase();i="nfgxc".indexOf(s)>-1?t(1234.5678,e):"p"==s?t(.12345678,e):t(this._pvDate,e)}this._cmbSmp.text=i}_editFilter(){this._createFilterEditor(),wjcCore.showPopup(this._dFlt,this._btnFltEdt,!1,!1,!1),wjcCore.moveFocus(this._dFlt,0)}_createFilterEditor(){this._dFlt||(this._dFlt=document.createElement("div"),this._eFlt=new PivotFilterEditor(this._dFlt,this._fld),wjcCore.addClass(this._dFlt,"wj-dropdown-panel"),this._eFlt.lostFocus.addHandler(()=>{setTimeout(()=>{let e=wjcCore.Control.getControl(this._dFlt);e&&!e.containsFocus()&&this._closeFilter()},10)}),this._eFlt.finishEditing.addHandler(()=>{this._closeFilter(),wjcCore.enable(this._btnFltClr,!0)}))}_closeFilter(){this._dFlt&&(wjcCore.hidePopup(this._dFlt,!0),this.focus())}};PivotFieldEditor.controlTemplate='<div><div class="wj-dialog-header" tabindex="-1"><span wj-part="g-dlg"></span> <span wj-part="sp-bnd"></span></div><div class="wj-dialog-body"><table style="table-layout:fixed"><tr><td wj-part="g-hdr"></td><td><div wj-part="div-hdr"></div></td></tr><tr class="wj-separator"><td wj-part="g-agg"></td><td><div wj-part="div-agg"></div></td></tr><tr class="wj-separator"><td wj-part="g-shw"></td><td><div wj-part="div-shw"></div></td></tr><tr><td wj-part="g-wfl"></td><td><div wj-part="div-wfl"></div></td></tr><tr><td wj-part="g-srt"></td><td><div wj-part="div-srt"></div></td></tr><tr class="wj-separator"><td wj-part="g-flt"></td><td><div><button wj-part="btn-flt-edt" class="wj-btn"></button>&nbsp;&nbsp;<button wj-part="btn-flt-clr" class="wj-btn"></button></div></td></tr><tr class="wj-separator"><td wj-part="g-fmt"></td><td><div wj-part="div-fmt"></div></td></tr><tr><td wj-part="g-smp"></td><td><div wj-part="div-smp" readonly tabindex="-1"></div></td></tr></table></div><div class="wj-dialog-footer"><button wj-part="btn-apply" class="wj-btn wj-hide"></button>&nbsp;&nbsp;<button wj-part="btn-cancel" class="wj-btn wj-hide"></button></div></div>';export class PivotFilterEditor extends wjcCore.Control{constructor(e,t,i){super(e),this.finishEditing=new wjcCore.Event;wjcCore.assert(null!=wjcInput,"Missing dependency: PivotFilterEditor requires wijmo.input."),this.hostElement.tabIndex=-1;let s=this.getTemplate();this.applyTemplate("wj-control wj-content wj-pivotfiltereditor",s,{_divType:"div-type",_aVal:"a-val",_aCnd:"a-cnd",_divEdtVal:"div-edt-val",_divEdtCnd:"div-edt-cnd",_btnOk:"btn-ok"}),wjcCore.setText(this._aVal,wjcCore.culture.FlexGridFilter.values),wjcCore.setText(this._aCnd,wjcCore.culture.FlexGridFilter.conditions),wjcCore.setText(this._btnOk,wjcCore.culture.olap.PivotFieldEditor.ok);let l=this._btnClicked.bind(this);this.addEventListener(this._btnOk,"click",l),this.addEventListener(this._aVal,"click",l),this.addEventListener(this._aCnd,"click",l),this.addEventListener(this.hostElement,"keydown",e=>{switch(e.keyCode){case wjcCore.Key.Enter:switch(e.target.tagName){case"A":case"BUTTON":this._btnClicked(e);break;default:this.onFinishEditing(new wjcCore.CancelEventArgs)}e.preventDefault();break;case wjcCore.Key.Escape:this.onFinishEditing(new wjcCore.CancelEventArgs),e.preventDefault();break;case wjcCore.Key.Tab:wjcCore.moveFocus(this.hostElement,e.shiftKey?-1:1),e.preventDefault()}}),this._fld=t,this.initialize(i),this.updateEditor()}get field(){return this._fld}get filter(){return this._fld?this._fld.filter:null}updateEditor(){let e=wjcGridFilter.FilterType.None;this.filter&&(e=this.filter.conditionFilter.isActive||0==(this.filter.filterType&wjcGridFilter.FilterType.Value)?wjcGridFilter.FilterType.Condition:wjcGridFilter.FilterType.Value,this._showFilter(e)),this._edtVal&&this._edtVal.updateEditor(),this._edtCnd&&this._edtCnd.updateEditor()}updateFilter(){switch(this._getFilterType()){case wjcGridFilter.FilterType.Value:this._edtVal.updateFilter(),this.filter.conditionFilter.clear();break;case wjcGridFilter.FilterType.Condition:this._edtCnd.updateFilter(),this.filter.valueFilter.clear()}this.field.onPropertyChanged(new wjcCore.PropertyChangedEventArgs("filter",null,null))}clearEditor(){this._edtVal&&this._edtVal.clearEditor(),this._edtCnd&&this._edtCnd.clearEditor()}onFinishEditing(e){return this.finishEditing.raise(this,e),!e.cancel}_showFilter(e){switch(e==wjcGridFilter.FilterType.Value&&null==this._edtVal&&(this._edtVal=new wjcGridFilter.ValueFilterEditor(this._divEdtVal,this.filter.valueFilter)),e==wjcGridFilter.FilterType.Condition&&null==this._edtCnd&&(this._edtCnd=new wjcGridFilter.ConditionFilterEditor(this._divEdtCnd,this.filter.conditionFilter)),0!=(e&this.filter.filterType)&&(e==wjcGridFilter.FilterType.Value?(this._divEdtVal.style.display="",this._divEdtCnd.style.display="none",this._enableLink(this._aVal,!1),this._enableLink(this._aCnd,!0)):(this._divEdtVal.style.display="none",this._divEdtCnd.style.display="",this._enableLink(this._aVal,!0),this._enableLink(this._aCnd,!1))),this.filter.filterType){case wjcGridFilter.FilterType.None:case wjcGridFilter.FilterType.Condition:case wjcGridFilter.FilterType.Value:this._divType.style.display="none";break;default:this._divType.style.display=""}}_enableLink(e,t){e.style.textDecoration=t?"":"none",e.style.fontWeight=t?"":"bold",wjcCore.setAttribute(e,"href",t?"":null)}_getFilterType(){let e=wjcGridFilter.FilterType;return"none"!=this._divEdtVal.style.display?e.Value:e.Condition}_btnClicked(e){if(e.preventDefault(),e.stopPropagation(),!wjcCore.hasClass(e.target,"wj-state-disabled"))return e.target==this._aVal?(this._showFilter(wjcGridFilter.FilterType.Value),void wjcCore.moveFocus(this._edtVal.hostElement,0)):e.target==this._aCnd?(this._showFilter(wjcGridFilter.FilterType.Condition),void wjcCore.moveFocus(this._edtCnd.hostElement,0)):void this.onFinishEditing(new wjcCore.CancelEventArgs)}};PivotFilterEditor.controlTemplate='<div><div wj-part="div-type" style="text-align:center;margin-bottom:12px;font-size:80%"><a wj-part="a-cnd" href="" tabindex="-1" draggable="false"></a>&nbsp;|&nbsp;<a wj-part="a-val" href="" tabindex="-1" draggable="false"></a></div><div wj-part="div-edt-val" tabindex="-1"></div><div wj-part="div-edt-cnd" tabindex="-1"></div><div style="text-align:right;margin-top:10px"><button wj-part="btn-ok" class="wj-btn"></button></div>',wjcCore._addCultureInfo("olap",{PivotEngine:{grandTotal:"Grand Total",subTotal:"Subtotal"},PivotPanel:{fields:"Choose fields to add to report:",drag:"Drag fields between areas below:",filters:"Filters",cols:"Columns",rows:"Rows",vals:"Values",defer:"Defer Updates",update:"Update"},PivotFieldEditor:{dialogHeader:"Field settings:",header:"Header:",summary:"Summary:",showAs:"Show As:",weighBy:"Weigh by:",sort:"Sort:",filter:"Filter:",format:"Format:",sample:"Sample:",edit:"Edit...",clear:"Clear",ok:"OK",cancel:"Cancel",none:"(none)",sorts:{asc:"Ascending",desc:"Descending"},aggs:{sum:"Sum",cnt:"Count",avg:"Average",max:"Max",min:"Min",rng:"Range",std:"StdDev",var:"Var",stdp:"StdDevPop",varp:"VarPop",first:"First",last:"Last"},calcs:{noCalc:"No calculation",dRow:"Difference from previous row",dRowPct:"% Difference from previous row",dCol:"Difference from previous column",dColPct:"% Difference from previous column",dPctGrand:"% of grand total",dPctRow:"% of row total",dPctCol:"% of column total",dRunTot:"Running total",dRunTotPct:"% running total"},formats:{n0:"Integer (n0)",n2:"Float (n2)",c:"Currency (c)",p0:"Percentage (p0)",p2:"Percentage (p2)",n2c:"Thousands (n2,)",n2cc:"Millions (n2,,)",n2ccc:"Billions (n2,,,)",d:"Date (d)",MMMMddyyyy:"Month Day Year (MMMM dd, yyyy)",dMyy:"Day Month Year (d/M/yy)",ddMyy:"Day Month Year (dd/M/yy)",dMyyyy:"Day Month Year (dd/M/yyyy)",MMMyyyy:"Month Year (MMM yyyy)",MMMMyyyy:"Month Year (MMMM yyyy)",yyyy:"Year (yyyy)",yyyyQq:'Year Quarter (yyyy "Q"q)',FYEEEEQU:'Fiscal Year Quarter ("FY"EEEE "Q"U)'}},_ListContextMenu:{up:"Move Up",down:"Move Down",first:"Move to Beginning",last:"Move to End",filter:"Move to Report Filter",rows:"Move to Row Labels",cols:"Move to Column Labels",vals:"Move to Values",remove:"Remove Field",edit:"Field Settings...",detail:"Show Detail..."},DetailDialog:{header:"Detail View:",ok:"OK",items:"{cnt:n0} items",item:"{cnt} item",row:"Row",col:"Column"},PivotChart:{by:"by",and:"and"},Slicer:{multiSelect:"Multi-Select",clearFilter:"Clear Filter"}});export var ShowTotals;!function(e){e[e.None=0]="None",e[e.GrandTotals=1]="GrandTotals",e[e.Subtotals=2]="Subtotals"}(ShowTotals||(ShowTotals={}));export var ShowAs;!function(e){e[e.NoCalculation=0]="NoCalculation",e[e.DiffRow=1]="DiffRow",e[e.DiffRowPct=2]="DiffRowPct",e[e.DiffCol=3]="DiffCol",e[e.DiffColPct=4]="DiffColPct",e[e.PctGrand=5]="PctGrand",e[e.PctRow=6]="PctRow",e[e.PctCol=7]="PctCol",e[e.RunTot=8]="RunTot",e[e.RunTotPct=9]="RunTotPct"}(ShowAs||(ShowAs={}));export class PivotEngine{constructor(e){this._autoGenFields=!0,this._allowFieldEditing=!0,this._showRowTotals=ShowTotals.GrandTotals,this._showColTotals=ShowTotals.GrandTotals,this._totalsBefore=!1,this._sortableGroups=!0,this._showZeros=!1,this._updating=0,this._dirty=!1,this._cntTotal=0,this._cntFiltered=0,this._async=!0,this._serverParms={timeout:_ServerConnection._TIMEOUT,pollInterval:_ServerConnection._POLL_INTERVAL,maxDetail:_ServerConnection._MAXDETAIL},this.itemsSourceChanged=new wjcCore.Event,this.viewDefinitionChanged=new wjcCore.Event,this.updatingView=new wjcCore.Event,this.updatedView=new wjcCore.Event,this.error=new wjcCore.Event,this._pivotView=new PivotCollectionView(this),this._fields=new PivotFieldCollection(this),this._rowFields=new PivotFieldCollection(this),this._columnFields=new PivotFieldCollection(this),this._valueFields=new PivotFieldCollection(this),this._filterFields=new PivotFieldCollection(this),this._viewLists=[this._rowFields,this._columnFields,this._valueFields,this._filterFields];let t=this._fieldListChanged.bind(this);this._fields.collectionChanged.addHandler(t),this._viewLists.forEach(e=>{e.collectionChanged.addHandler(t)}),this._defaultFilterType=null,e&&wjcCore.copy(this,e)}get itemsSource(){return this._items}set itemsSource(e){this._items!=e&&(this._cv&&(this._cv.collectionChanged.removeHandler(this._cvCollectionChanged,this),this._cv=null),this._server&&(this._server.clearPendingRequests(),this._server=null),this._items=e,wjcCore.isString(e)?this._server=new _ServerConnection(this,e):wjcCore.isObject(e)&&!wjcCore.tryCast(e,"ICollectionView")?this._server=new _SqlServerConnection(this,e):this._cv=wjcCore.asCollectionView(e),null!=this._cv&&this._cv.collectionChanged.addHandler(this._cvCollectionChanged,this),this.deferUpdate(()=>{this.autoGenerateFields&&this._generateFields(),this._updateFieldTypes()}),this.onItemsSourceChanged())}get isServer(){return null!=this._server}get collectionView(){return this._cv}get pivotView(){return this._pivotView}get showRowTotals(){return this._showRowTotals}set showRowTotals(e){(e=wjcCore.asEnum(e,ShowTotals))!=this.showRowTotals&&(this._showRowTotals=e,this.onViewDefinitionChanged(),this.invalidate())}get showColumnTotals(){return this._showColTotals}set showColumnTotals(e){(e=wjcCore.asEnum(e,ShowTotals))!=this.showColumnTotals&&(this._showColTotals=e,this.onViewDefinitionChanged(),this.invalidate())}get totalsBeforeData(){return this._totalsBefore}set totalsBeforeData(e){e!=this._totalsBefore&&(this._totalsBefore=wjcCore.asBoolean(e),this.onViewDefinitionChanged(),this._updatePivotView())}get sortableGroups(){return this._sortableGroups}set sortableGroups(e){e!=this._sortableGroups&&(this._sortableGroups=wjcCore.asBoolean(e),this.onViewDefinitionChanged())}get sortOnServer(){return this._sortOnServer}set sortOnServer(e){this._sortOnServer=wjcCore.asBoolean(e)}get showZeros(){return this._showZeros}set showZeros(e){e!=this._showZeros&&(this._showZeros=wjcCore.asBoolean(e),this.onViewDefinitionChanged(),this._updatePivotView())}get defaultFilterType(){return null!=this._defaultFilterType?this._defaultFilterType:this._server?wjcGridFilter.FilterType.Condition:wjcGridFilter.FilterType.Both}set defaultFilterType(e){this._defaultFilterType=wjcCore.asEnum(e,wjcGridFilter.FilterType)}get autoGenerateFields(){return this._autoGenFields}set autoGenerateFields(e){this._autoGenFields=wjcCore.asBoolean(e)}get allowFieldEditing(){return this._allowFieldEditing}set allowFieldEditing(e){this._allowFieldEditing=wjcCore.asBoolean(e)}get fields(){return this._fields}get rowFields(){return this._rowFields}get columnFields(){return this._columnFields}get filterFields(){return this._filterFields}get valueFields(){return this._valueFields}get viewDefinition(){let e={showZeros:this.showZeros,showColumnTotals:this.showColumnTotals,showRowTotals:this.showRowTotals,defaultFilterType:this.defaultFilterType,totalsBeforeData:this.totalsBeforeData,sortableGroups:this.sortableGroups,fields:[],rowFields:this._getFieldCollectionProxy(this.rowFields),columnFields:this._getFieldCollectionProxy(this.columnFields),filterFields:this._getFieldCollectionProxy(this.filterFields),valueFields:this._getFieldCollectionProxy(this.valueFields)};return this.fields.forEach(t=>{let i=this._getFieldDefinition(t);e.fields.push(i)}),JSON.stringify(e)}set viewDefinition(e){let t=JSON.parse(e);t&&this.deferUpdate(()=>{this._copyProps(this,t,PivotEngine._props),this.fields.clear(),t.fields.forEach(e=>{let t=this._getFieldFromDefinition(e);this.fields.push(t)}),t.fields.forEach((e,t)=>{wjcCore.isString(e.weightField)&&(this.fields[t].weightField=this.fields.getField(e.weightField))}),this._setFieldCollectionProxy(this.rowFields,t.rowFields),this._setFieldCollectionProxy(this.columnFields,t.columnFields),this._setFieldCollectionProxy(this.filterFields,t.filterFields),this._setFieldCollectionProxy(this.valueFields,t.valueFields)})}get isViewDefined(){let e=this._valueFields.length,t=this._rowFields.length,i=this._columnFields.length;return this._server?e>0&&(t>0||i>0):e>0||t>0||i>0}beginUpdate(){this.cancelPendingUpdates(),this._updating++}endUpdate(){this._updating--,this._updating<=0&&(this.onViewDefinitionChanged(),this.refresh())}get isUpdating(){return this._updating>0}deferUpdate(e){try{this.beginUpdate(),e()}finally{this.endUpdate()}}refresh(e=!1){this.isUpdating&&!e||this._updateView()}invalidate(){this._toInv&&(this._toInv=clearTimeout(this._toInv)),this.isUpdating||(this._toInv=setTimeout(()=>{this.refresh()},wjcCore.Control._REFRESH_INTERVAL))}get async(){return this._async}set async(e){e!=this._async&&(this.cancelPendingUpdates(),this._async=wjcCore.asBoolean(e))}get serverTimeout(){return this._serverParms.timeout}set serverTimeout(e){this._serverParms.timeout=wjcCore.asNumber(e,!1,!0)}get serverPollInterval(){return this._serverParms.pollInterval}set serverPollInterval(e){this._serverParms.pollInterval=wjcCore.asNumber(e,!1,!0)}get serverMaxDetail(){return this._serverParms.maxDetail}set serverMaxDetail(e){this._serverParms.maxDetail=wjcCore.asNumber(e,!1,!0)}cancelPendingUpdates(){this._toUpdateTallies&&(clearTimeout(this._toUpdateTallies),this._toUpdateTallies=null)}getDetail(e,t){let i=e?e[_PivotKey._ROW_KEY_NAME]:null,s=this._getKey(t);if(this._server)return this._server.getDetail(i,s);let l=[];return this.collectionView.items.forEach(e=>{!this._applyFilter(e)||null!=i&&!i.matchesItem(e)||null!=s&&!s.matchesItem(e)||l.push(e)}),l}getDetailView(e,t){let i=this.getDetail(e,t);return new wjcCore.CollectionView(i)}getKeys(e,t){let i=e?e[_PivotKey._ROW_KEY_NAME]:null,s=this._getKey(t);return{rowKey:{fields:i?i.fieldNames:[],values:i?i.values:[]},colKey:{fields:s?s.fieldNames:[],values:s?s.values:[]}}}editField(e){if(this.allowFieldEditing){let t=new PivotFieldEditor(document.createElement("div"),{field:e});new wjcInput.Popup(document.createElement("div"),{content:t.hostElement}).show(!0)}}removeField(e){for(let t=0;t<this._viewLists.length;t++){let i=this._viewLists[t],s=i.indexOf(e);if(s>-1)return void i.removeAt(s)}}onItemsSourceChanged(e){this.itemsSourceChanged.raise(this,e)}onViewDefinitionChanged(e){this._updating||this.viewDefinitionChanged.raise(this,e)}onUpdatingView(e){this.updatingView.raise(this,e)}onUpdatedView(e){this.updatedView.raise(this,e)}onError(e){return this.error.raise(this,e),!e.cancel}_copy(e,t){let i;switch(e){case"fields":return this.fields.clear(),this._viewLists.forEach(e=>{e.clear()}),(i=wjcCore.asArray(t)).forEach(e=>{let t=this._createField(e,!1);this.fields.push(t)}),this._updateFieldTypes(),!0;case"rowFields":case"columnFields":case"valueFields":case"filterFields":return this[e].clear(),wjcCore.isArray(t)||(this[e].maxItems=t.maxItems,t=t.items),(i=wjcCore.asArray(t)).forEach(t=>{let i=this.fields.getField(t);this[e].push(i)}),!0}return!1}_getKey(e){return this._keys[e]}_getRowLevel(e){if(wjcCore.isNumber(e)){let t=this._pivotView.items[e];e=t?t[_PivotKey._ROW_KEY_NAME]:null}return e?e.level:-1}_getColLevel(e){return wjcCore.isNumber(e)&&(e=this._colBindings[e]),wjcCore.isString(e)&&(e=this._getKey(e)),wjcCore.assert(null==e||e instanceof _PivotKey,"invalid parameter in call to _getColLevel"),e?e.level:-1}_applyFilter(e){let t=this._activeFilterFields;for(let i=0;i<t.length;i++)if(!t[i].filter.apply(e))return!1;return!0}_updateView(){this.cancelPendingUpdates(),this._cntTotal=this._cntFiltered=0,this._tallies={},this._keys={},this._activeFilterFields=[],this._server&&this.isViewDefined?this._server.getOutputView(e=>{this.isViewDefined&&(this._server.updateTallies(e),this._updatePivotView())}):(this._viewLists.forEach(e=>{e.forEach(e=>{e.filter.isActive&&this._activeFilterFields.push(e)})}),this.isViewDefined&&wjcCore.hasItems(this._cv)?(this._batchStart=Date.now(),this._updateTallies(this._cv.items,0)):this._updatePivotView())}_updateTallies(e,t){let i=e.length,s=new _PivotNode(this._rowFields,0,null,-1,null),l=this.valueFields;0==l.length&&this.columnFields.length>0&&(l=new PivotFieldCollection(this)).push(new PivotField(this,""));let r=ShowTotals,n=this._rowFields.length,o=this._getShowRowTotals(),a=o==r.None?n:0,h=o==r.GrandTotals?Math.max(1,n):1,d=this._columnFields.length,c=this._getShowColTotals(),u=c==r.None?d:0,_=c==r.GrandTotals?Math.max(1,d):1,g=l.length;for(let r=t;r<i;r++){if(this._async&&r-t>=PivotEngine._BATCH_SIZE&&Date.now()-this._batchStart>PivotEngine._BATCH_DELAY)return void(this._toUpdateTallies=setTimeout(()=>{this.onUpdatingView(new ProgressEventArgs(Math.round(r/e.length*100))),this._batchStart=Date.now(),this._updateTallies(e,r)},PivotEngine._BATCH_TIMEOUT));this._cntTotal++;let i=e[r];if(!this._activeFilterFields.length||this._applyFilter(i)){this._cntFiltered++;for(let e=a;e<=n;e+=h){let t=s.getNode(this._rowFields,e,null,-1,i),r=t.key,n=r.toString(),o=this._tallies[n];o||(this._keys[n]=r,this._tallies[n]=o={});for(let e=u;e<=d;e+=_)for(let s=0;s<g;s++){let r=t.tree.getNode(this._columnFields,e,l,s,i).key,n=r.toString(),a=o[n];a||(this._keys[n]=r,a=o[n]=new _Tally);let h=l[s],d=h._getValue(i,!1),c=h._weightField?h._getWeight(i):null;a.add(d,c)}}}}this._toUpdateTallies=null,this._updatePivotView()}_updatePivotView(){this._pivotView.deferUpdate(()=>{this.onUpdatingView(new ProgressEventArgs(100));let e=this._pivotView.sourceCollection;e.length=0;let t={};for(let e in this._tallies)t[e]=!0;let i={};for(let e in this._tallies){let t=this._tallies[e];for(let e in t)i[e]=!0}let s=this._server&&this.sortOnServer,l=this._getSortedKeys(t,s),r=this._getSortedKeys(i,s);for(let t=0;t<l.length;t++){let i=l[t],s=this._tallies[i],n={};n[_PivotKey._ROW_KEY_NAME]=this._getKey(i);for(let e=0;e<r.length;e++){let t=r[e],i=s[t],l=this._getKey(t),o=i?i.getAggregate(l.aggregate):null;0!=o||this._showZeros||(o=null),n[t]=o}e.push(n)}this._colBindings=r,this._updateFieldValues(e),this._pivotView.sortDescriptions.clear(),this.onUpdatedView()})}_getSortedKeys(e,t){let i=Object.keys(e);return t||i.sort((e,t)=>this._keys[e].compareTo(this._keys[t])),i}_updateFieldValues(e){let t=this.valueFields.length;for(let i=0;i<t;i++){let s=this.valueFields[i];switch(s.showAs){case ShowAs.RunTot:case ShowAs.RunTotPct:for(let l=i;l<this._colBindings.length;l+=t){for(let t=0;t<e.length;t++)e[t][this._colBindings[l]]=this._getRunningTotal(e,t,l,s.showAs);if(s.showAs==ShowAs.RunTotPct)for(let t=0;t<e.length;t++){let i=e[t],s=this._colBindings[l],r=i[s];if(wjcCore.isNumber(r)){let n=this._getLastValueInRowGroup(e,t,l);0!=n&&(i[s]=r/n)}}}break;case ShowAs.PctGrand:case ShowAs.PctCol:let l=0;if(s.showAs==ShowAs.PctGrand)for(let s=i;s<this._colBindings.length;s+=t)-1==this._getColLevel(s)&&(l+=this._getColTotal(e,s));for(let r=i;r<this._colBindings.length;r+=t){s.showAs==ShowAs.PctCol&&(l=this._getColTotal(e,r));let t=this._colBindings[r];e.forEach((e,i)=>{let s=e[t];wjcCore.isNumber(s)&&(e[t]=0!=l?s/l:null)})}break;case ShowAs.PctRow:for(let s=0;s<e.length;s++){let l=e[s],r=0;for(let e=i;e<this._colBindings.length;e+=t)if(-1==this._getColLevel(e)){let t=l[this._colBindings[e]];wjcCore.isNumber(t)&&(r+=t)}for(let e=i;e<this._colBindings.length;e+=t){let t=this._colBindings[e],i=l[t];wjcCore.isNumber(i)&&(l[t]=0!=r?i/r:null)}}break;case ShowAs.DiffRow:case ShowAs.DiffRowPct:for(let l=i;l<this._colBindings.length;l+=t)for(let t=e.length-1;t>=0;t--)e[t][this._colBindings[l]]=this._getRowDifference(e,t,l,s.showAs);break;case ShowAs.DiffCol:case ShowAs.DiffColPct:for(let l=0;l<e.length;l++)for(let r=this._colBindings.length-t+i;r>=0;r-=t)e[l][this._colBindings[r]]=this._getColDifference(e,l,r,s.showAs)}}}_getColTotal(e,t){let i=this._colBindings[t],s=0;return e.forEach((e,t)=>{if(-1==this._getRowLevel(t)){let t=e[i];wjcCore.isNumber(t)&&(s+=t)}}),s}_getRunningTotal(e,t,i,s){let l=this._getRowLevel(t);if(0==l)return null;let r=this._colBindings[i],n=e[t][r],o=this._getShowRowTotals(),a=this.rowFields.length-2;for(let i=t-1;i>=0;i--){let s=this._getRowLevel(i);if(s==l){if(a>-1&&l<0&&o!=ShowTotals.Subtotals){let s=e[t].$rowKey,l=e[i].$rowKey;if(s.values[a]!=l.values[a])return null}n+=e[i][r];break}if(s>l)break}return n}_getLastValueInRowGroup(e,t,i){let s=this._colBindings[i],l=e[t][s],r=this._getRowLevel(t),n=this.rowFields.length-2,o=this._getShowRowTotals();for(let i=t+1;i<e.length;i++){let a=this._getRowLevel(i);if(a==r){if(n>-1&&r<0&&o!=ShowTotals.Subtotals){let s=e[t].$rowKey,r=e[i].$rowKey;if(s.values[n]!=r.values[n])return l}l=e[i][s]}if(a>r)break}return l}_getRowDifference(e,t,i,s){let l=this._getRowLevel(t);if(0==l)return null;let r=this.rowFields.length-2,n=this._getShowRowTotals();for(let o=t-1;o>=0;o--){let a=this._getRowLevel(o);if(a==l){if(r>-1&&l<0&&n!=ShowTotals.Subtotals){let i=e[t].$rowKey,s=e[o].$rowKey;if(i.values[r]!=s.values[r])return null}let a=this._colBindings[i],h=e[t][a],d=e[o][a],c=h-d;return s==ShowAs.DiffRowPct&&(c/=d),c}if(a>l)break}return null}_getColDifference(e,t,i,s){let l=this._getColLevel(i);if(0==l)return null;let r=this.valueFields.length,n=this.columnFields.length-2,o=this._getShowColTotals();for(let a=i-r;a>=0;a-=r){let r=this._getColLevel(a);if(r==l){if(n>-1&&l<0&&o!=ShowTotals.Subtotals){let e=this._getKey(this._colBindings[i]),t=this._getKey(this._colBindings[a]);if(e.values[n]!=t.values[n])return null}let r=e[t],h=r[this._colBindings[i]],d=r[this._colBindings[a]],c=h-d;return s==ShowAs.DiffColPct&&(c/=d),c}if(r>l)break}return null}_getShowRowTotals(){return this._valueFields.length?this._showRowTotals:ShowTotals.None}_getShowColTotals(){return this._valueFields.length?this._showColTotals:ShowTotals.None}_generateFields(){this._viewLists.forEach(e=>{e.clear()});for(let e=0;e<this.fields.length;e++)this.fields[e]._autoGenerated&&(this.fields.removeAt(e),e--);if(this._server)return void this._server.getFields().forEach(e=>{let t=this._createField(e,!0);this.fields.getField(t.header)||this.fields.push(t)});let e=this.collectionView,t=e?e.sourceCollection:null,i=t?t[0]:null;if(i&&this.autoGenerateFields)for(let e in i){let i=null;for(let s=0;s<t.length&&s<1e3&&null==i;s++)if(i=t[s][e],wjcCore.isPrimitive(i)){let t=this._createField({binding:e,header:wjcCore.toHeaderCase(e),dataType:wjcCore.getType(i)},!0);this.fields.getField(t.header)||this.fields.push(t)}}}_updateFieldTypes(){let e=this.collectionView,t=e?e.sourceCollection:null;t&&t.length&&this.fields.forEach(e=>{this._updateFieldType(e,t)})}_updateFieldType(e,t){if(e._hasSubFields())e.subFields.forEach(e=>{this._updateFieldType(e,t)});else if(null==e.dataType&&e.binding)for(let i=0;i<t.length&&i<1e3;i++){let s=e._binding.getValue(t[i]);if(null!=s){e.dataType=wjcCore.isPrimitive(s)?wjcCore.getType(s):null;break}}}_createField(e,t){let i;return wjcCore.isString(e)?i=new PivotField(this,e):e&&(e.key&&delete e.key,i=null!=e.dimensionType?new CubePivotField(this,e.binding,e.header,e):new PivotField(this,e.binding,e.header,e),null!=e.dataType&&(i.dataType=e.dataType)),i._autoGenerated=t,(t||wjcCore.isString(e))&&(i.format=i.dataType==wjcCore.DataType.Date?"d":"n0",i.aggregate=i.dataType==wjcCore.DataType.Number?wjcCore.Aggregate.Sum:wjcCore.Aggregate.Cnt),e&&!wjcCore.isString(e)&&wjcCore.copy(i,e),i}_cvCollectionChanged(e,t){this.invalidate()}_fieldListChanged(e,t){if(t.action==wjcCore.NotifyCollectionChangedAction.Add){let i=e;for(let e=0;e<i.length-1;e++)if(i[e].key)for(let t=e+1;t<i.length;t++)i[e].key==i[t].key&&(i.removeAt(t),t--);if(i!=this._fields)if(this._fields.getField(t.item.key)){for(let e=0;e<this._viewLists.length;e++)if(this._viewLists[e]!=i){let i=this._viewLists[e],s=i.indexOf(t.item);s>-1&&i.removeAt(s)}}else i.removeAt(t.index);if(wjcCore.isNumber(i.maxItems)&&i.maxItems>-1)for(;i.length>i.maxItems;){let e=i.length-1;i[e]==t.item&&e>0&&e--,i.removeAt(e)}}this.onViewDefinitionChanged(),this.invalidate()}_fieldPropertyChanged(e,t){if(this.onViewDefinitionChanged(),!e.isActive)return;let i=t.propertyName;"visible"!=i&&("width"!=i&&"wordWrap"!=i&&"isContentHtml"!=i?"format"==i&&this.valueFields.indexOf(e)>-1?this._pivotView.refresh():"showAs"!=i?"descending"!=i?"aggregate"!=i?this.invalidate():this.valueFields.indexOf(e)>-1&&!this.isUpdating&&(this._server?this._updateView():this._updatePivotView()):this._updatePivotView():this.valueFields.indexOf(e)>-1&&!this.isUpdating&&this._updatePivotView():this._pivotView.refresh())}_copyProps(e,t,i){for(let s=0;s<i.length;s++){let l=i[s];null!=t[l]&&(e[l]=t[l])}}_getFieldFromDefinition(e){let t=e.filter;e.filter&&delete e.filter;let i=this._createField(e,!0);return t&&(this._setFilterProxy(i,t),e.filter=t),i}_getFieldDefinition(e){let t={binding:e.binding,header:e.header,dataType:e.dataType,aggregate:e.aggregate,showAs:e.showAs,descending:e.descending,format:e.format,width:e.width,wordWrap:e.wordWrap,isContentHtml:e.isContentHtml};return e.weightField&&(t.weightField=e.weightField._getName()),e.key&&(t.key=e.key),e.filter.isActive&&(t.filter=this._getFilterProxy(e)),e._hasSubFields()&&(t.subFields=[],e.subFields.forEach(e=>{t.subFields.push(this._getFieldDefinition(e))})),e instanceof CubePivotField&&(t.dimensionType=e.dimensionType),t}_getFieldCollectionProxy(e){let t={items:[]};wjcCore.isNumber(e.maxItems)&&e.maxItems>-1&&(t.maxItems=e.maxItems);for(let i=0;i<e.length;i++){let s=e[i];t.items.push(s.key)}return t}_setFieldCollectionProxy(e,t){e.clear(),e.maxItems=wjcCore.isNumber(t.maxItems)?t.maxItems:null;for(let i=0;i<t.items.length;i++)e.push(t.items[i])}_getFilterProxy(e){let t=e.filter;if(t.conditionFilter.isActive){let e=t.conditionFilter,i={type:"condition",condition1:{operator:e.condition1.operator,value:e.condition1.value},and:e.and,condition2:{operator:e.condition2.operator,value:e.condition2.value}};return e.condition1.isActive||delete i.condition1,e.condition2.isActive||delete i.condition2,i}if(t.valueFilter.isActive){let e=t.valueFilter;return{type:"value",filterText:e.filterText,showValues:e.showValues}}return wjcCore.assert(!1,"inactive filters shouldn't be persisted."),null}_setFilterProxy(e,t){let i=e.filter;switch(i.clear(),t.type){case"condition":let s=i.conditionFilter;if(t.condition1){let i=wjcCore.changeType(t.condition1.value,e.dataType,e.format);s.condition1.value=i||t.condition1.value,s.condition1.operator=t.condition1.operator}if(wjcCore.isBoolean(t.and)&&(s.and=t.and),t.condition2){let i=wjcCore.changeType(t.condition2.value,e.dataType,e.format);s.condition2.value=i||t.condition2.value,s.condition2.operator=t.condition2.operator}break;case"value":let l=i.valueFilter;l.filterText=t.filterText,l.showValues=t.showValues}}};PivotEngine._BATCH_SIZE=1e4,PivotEngine._BATCH_TIMEOUT=0,PivotEngine._BATCH_DELAY=100,PivotEngine._props=["showZeros","showRowTotals","showColumnTotals","totalsBeforeData","sortableGroups","defaultFilterType"];export class ProgressEventArgs extends wjcCore.EventArgs{constructor(e){super(),this._progress=wjcCore.asNumber(e)}get progress(){return this._progress}};export class _MdxQueryBuilder{constructor(e,t){this._ng=null,this._cubeName=null,this._ng=e,this._cubeName=t}buildQuery(){let e=new _TextBuilder,t=this.buildWhereSection(this._ng.valueFields);return e.append("SELECT ",this.buildAxes()," FROM ",this.buildCubeName(),t),e.append(" CELL PROPERTIES VALUE, FORMAT_STRING"),e.toString()}buildWhereSection(e){let t=new _TextBuilder;return 1==e.length&&(t.append(this.buildSetForMeasuresShelf(e)),t.wrap(" WHERE ","")),t.toString()}buildCubeName(){let e=new _TextBuilder;e.append(this.buildSubcubeExpression());let t=e.length>0;return t&&e.wrap("SELECT "," FROM "),e.append("[",this._cubeName,"]"),t&&e.wrap("(",")"),e.toString()}buildSubcubeExpression(){let e=new _TextBuilder,t=this.getMeasureFilterExpressions(this._ng.valueFields),i=this.buildFilterAttributeSet(this._ng.filterFields),s=this.buildFilterAttributeSet(this._ng.rowFields,t),l=this.buildFilterAttributeSet(this._ng.columnFields,0==s.length?t:null);return e.joinItemToList(i),e.joinItemToList(s),e.joinItemToList(l),e.length>0&&(e.wrap("(",")"),e.append(" ON COLUMNS")),e.toString()}buildFilterAttributeSet(e,t){let i=new _TextBuilder;for(let s=0;s<e.length;s++){let l=e[s],r=this.buildFilterString(l,0==s?t:null);i.joinItemToList(r)}return i.toString()}buildFilterString(e,t){let i=new _TextBuilder;return e.filter.isActive?e.filter.filterType==wjcGridFilter.FilterType.Condition&&i.append(this.getConditionFilterString(e,t)):t&&i.append(this.getConditionFilterString(e,t)),i.toString()}getConditionFilterString(e,t){let i=new _TextBuilder,s=e.key+".LEVELS(1).ALLMEMBERS",l=e.filter.conditionFilter.condition1,r=e.filter.conditionFilter.condition2;return l.isActive&&(i.append(this.getConditionFilterExpression(e,l)),r.isActive&&i.append(e.filter.conditionFilter.and?" AND ":" OR ")),r.isActive&&i.append(this.getConditionFilterExpression(e,r)),t&&t.length>0&&(i.length>0&&i.append(" AND "),i.append(t.join(" AND "))),i.length>0&&i.wrap("Filter("+s+",(","))"),i.toString()}getMeasureFilterExpressions(e){let t=[];for(let i=0;i<e.length;i++){let s=new _TextBuilder,l=e[i],r=(l.dimensionType,DimensionType.Measure,l.filter.conditionFilter.condition1),n=l.filter.conditionFilter.condition2;r.isActive&&(s.append(this.getConditionFilterExpression(l,r)),n.isActive&&s.append(l.filter.conditionFilter.and?" AND ":" OR ")),n.isActive&&s.append(this.getConditionFilterExpression(l,n)),s.length>0&&(s.wrap("(",")"),t.push(s.toString()))}return t}getConditionFilterExpression(e,t){if(!t.isActive)return"";let i=e.dimensionType==DimensionType.Measure,s=e.dataType==wjcCore.DataType.Number,l=e.dataType==wjcCore.DataType.Date,r=s||l?"member_value":"member_caption",n=i?e.key:e.key+".CurrentMember."+r,o=l?"CDate('"+wjcCore.Globalize.formatDate(t.value,"d")+"')":t.value.toString(),a=new _TextBuilder;switch(t.operator){case wjcGridFilter.Operator.BW:a.append("(Left(",n,",",o.length.toString(),')="',o,'")');break;case wjcGridFilter.Operator.EW:a.append("(Right(",n,",",o.length.toString(),')="',o,'")');break;case wjcGridFilter.Operator.EQ:i||s||l?a.append("(",n,")=",o):a.append("(",n,')="',o,'"');break;case wjcGridFilter.Operator.NE:i||s||l?a.append("(",n,")<>",o):a.append("(",n,')<>"',o,'"');break;case wjcGridFilter.Operator.CT:a.append("(InStr(1,",n,',"',o,'")>0)');break;case wjcGridFilter.Operator.NC:a.append("(InStr(1,",n,',"',o,'")=0))');break;case wjcGridFilter.Operator.GT:a.append("(",n,")>",o);break;case wjcGridFilter.Operator.LT:a.append("(",n,")<",o);break;case wjcGridFilter.Operator.GE:a.append("(",n,")>=",o);break;case wjcGridFilter.Operator.LE:a.append("(",n,")<=",o)}return a.toString()}buildAxes(){let e=new _TextBuilder,t=this.buildSetForAttributesShelf(this._ng.rowFields);return e.joinItemToList(t),this._ng.rowFields.length>0&&(this._ng.columnFields.length>0||this._ng.valueFields.length>1?e.append(" ON ROWS"):e.append(" ON COLUMNS")),t=this.buildSetForAttributesColumnShelf(this._ng.columnFields),e.joinItemToList(t),this._ng.columnFields.length>0&&e.append(" ON COLUMNS"),this._ng.valueFields.length>1&&0==this._ng.columnFields.length&&(t=this.buildSetForMeasuresShelf(this._ng.valueFields),e.joinItemToList(t),e.append(" ON COLUMNS")),e.toString()}buildSetForAttributesShelf(e){let t=new _TextBuilder;for(let s=0;s<e.length;s++){var i=e[s];i.dimensionType!=DimensionType.Attribute&&i.dimensionType!=DimensionType.Hierarchy||t.joinItemToList(this.buildAttributeSetForAxis(i)),s>0&&t.wrap("CrossJoin(",")")}return t.wrap("NON EMPTY ",""),t.toString()}buildSetForAttributesColumnShelf(e){let t=new _TextBuilder;for(let s=0;s<e.length;s++){var i=e[s];i.dimensionType!=DimensionType.Attribute&&i.dimensionType!=DimensionType.Hierarchy||t.joinItemToList(this.buildAttributeSetForAxis(i))}return this._ng.valueFields.length>1&&e.length>0&&t.joinItemToList(this.buildSetForMeasuresShelf(this._ng.valueFields)),(this._ng.valueFields.length>1&&e.length>0||e.length>1)&&t.wrap("CrossJoin(",")"),t.wrap("NON EMPTY ",""),t.toString()}buildSetForMeasuresShelf(e){let t=new _TextBuilder;for(let s=0;s<e.length;s++){var i=e[s];i.dimensionType!=DimensionType.Measure&&i.dimensionType!=DimensionType.Kpi||t.joinItemToList(this.buildMeasureSetForAxis(i))}return t.wrap("{","}"),t.toString()}buildAttributeSetForAxis(e){let t=new _TextBuilder;return e.dimensionType==DimensionType.Hierarchy&&(t.append(e.key),t.append(".ALLMEMBERS"),t.wrap("{","}"),t.wrap("HIERARCHIZE(",")")),t.toString()}buildMeasureSetForAxis(e){let t=new _TextBuilder;return e.dimensionType!=DimensionType.Measure&&e.dimensionType!=DimensionType.Kpi||t.append(e.key),t.toString()}};export class _ServerConnection{constructor(e,t){this._ng=wjcCore.asType(e,PivotEngine),wjcCore.assert(this._isValidUrl(t),"Invalid service Url: "+t+")")}getFields(){let e=null;return wjcCore.httpRequest(this._getUrl("Fields"),{async:!1,success:t=>{e=JSON.parse(t.responseText),wjcCore.isArray(e)||console.error("Failed to get fields from server: "+t.responseText)},error:e=>{this._handleError("Getting Fields",e)}}),e}getOutputView(e){this.clearPendingRequests(),this._sendHttpRequest("Analyses",{method:"POST",data:{view:this._ng.viewDefinition},success:t=>{let i=JSON.parse(t.responseText);this._token=i.token,this._start=Date.now(),this._handleResult(i.status,e)},error:e=>{this._handleError("Analyses",e)}})}getDetail(e,t){let i,s=[],l=this._ng.rowFields.length,r=e?e.values.length:0;for(let t=0;t<l;t++)t<r?s.push(_ServerConnection._getRequestedValue(e.values[t])):s.push(null);l=this._ng.columnFields.length,r=t?t.values.length:0;for(let e=0;e<l;e++)e<r?s.push(_ServerConnection._getRequestedValue(t.values[e])):s.push(null);return i=new wjcCore.ObservableArray,this._loadArray("Detail",i,{method:"POST",view:this._ng.viewDefinition,keys:s,max:this._ng.serverMaxDetail}),i}static _getRequestedValue(e){if(wjcCore.isDate(e)){let t=e;return new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()))}return e}clearPendingRequests(){this._clearRequest(),this._clearTimeout(),this._clearToken()}updateTallies(e){let t=this._ng,i=t.rowFields.length,s=t.columnFields.length,l=t.valueFields.length,r=new _PivotNode(t.rowFields,0,null,-1,null),n=null,o=0,a=(e,a,h)=>{let d=this._getAggregatedFieldCount(e,t.rowFields),c=r.getNode(t.rowFields,i-d,null,-1,e),u=c.key,_=u.toString(),g=u.toString(o>0?o:null),p=t._tallies[g];p||(_!==n&&(o=0,g=_),n=_,t._keys[g]=u,t._tallies[g]=p={}),d=this._getAggregatedFieldCount(e,t.columnFields);for(let i=0;i<l;i++){let l=c.tree.getNode(t.columnFields,s-d,t.valueFields,i,e).key,r=l.toString(),n=t.valueFields[i],o=p[r];if(o)return!1;t._keys[r]=l,(o=p[r]=new _ServerTally).add(this._getFieldValue(n,e,!1))}return!0};e.forEach((e,t,i)=>{a(e)||(o++,a(e))})}_getFieldValue(e,t,i){let s=t[e.key];return i&&"string"!=typeof s?wjcCore.Globalize.format(s,e.format):s}_getAggregatedFieldCount(e,t){let i=t.length,s=0;for(let l=0;l<i;l++){let i=t[l];null==this._getFieldValue(i,e,!1)&&s++}return s}_loadArray(e,t,i){i||(i={}),null==i.skip&&(i.skip=0),null==i.top&&(i.top=100);let s=wjcCore.isNumber(i.max)?i.max:1e6;this._request=wjcCore.httpRequest(this._getUrl(e),{data:i,method:i.method||"GET",success:l=>{let r=JSON.parse(l.responseText);t.deferUpdate(()=>{r.value.forEach(e=>{t.push(e)})}),r.value.length==i.top&&t.length<s&&(i.skip+=i.top,this._loadArray(e,t,i))},error:t=>{this._handleError(e,t)}})}_getUrl(e,t=this._token,i){let s=this._ng.itemsSource.toString(),l=s.lastIndexOf("/");s.substr(0,l);switch(e=e.toLowerCase()){case"rawdata":case"detail":return s;case"fields":case"analyses":return s+"/"+e;case"clear":return s+"/analyses/"+t+"/";case"result":case"status":return s+"/analyses/"+t+"/"+e;case"uniquevalues":return s+"/fields/"+i+"/"+e}wjcCore.assert(!1,"Unrecognized command")}_isValidUrl(e){let t=document.createElement("a");return t.href=wjcCore.asString(e),t.href=t.href,t.protocol&&t.hostname&&t.pathname&&"/"!=e[e.length-1]}_handleResult(e,t){switch(e.executingStatus.toLowerCase()){case"executing":case"notset":if(Date.now()-this._start>this._ng.serverTimeout)return void this._handleError("Analyses",{status:500,statusText:"Analysis timed out"});this._progress=e.progress,this._ng.onUpdatingView(new ProgressEventArgs(this._progress)),this._clearTimeout(),this._toGetStatus=setTimeout(()=>{this._waitUntilComplete(t)},this._ng.serverPollInterval);break;case"completed":this._progress=100,this._ng.onUpdatingView(new ProgressEventArgs(this._progress)),this._getResults(t);break;case"exception":this._getResults(t);break;default:this._handleError("Analyses",{status:500,statusText:"Unexpected result..."})}}_waitUntilComplete(e){this._sendHttpRequest("Status",{success:t=>{let i=JSON.parse(t.responseText);this._handleResult(i,e)},error:e=>{this._handleError("Status",e)}})}_getResults(e){this._sendHttpRequest("Result",{success:t=>{this._clearToken();let i=JSON.parse(t.responseText);wjcCore.assert(wjcCore.isArray(i),"Result array Expected.");let s=[];this._ng._viewLists.forEach(e=>{s=s.concat(e.filter(e=>e.dataType==wjcCore.DataType.Date))}),s.length>0&&i.forEach(e=>{s.forEach(t=>{let i=t._binding,s=i.getValue(e);wjcCore.isString(s)&&i.setValue(e,new Date(s))})}),wjcCore.asFunction(e)(i)},error:e=>{this._handleError("Result",e)}})}_handleError(e,t){this.clearPendingRequests(),e='** HttpRequest error on command "'+e+'"',this._ng.onError(new wjcCore.RequestErrorEventArgs(t,e))&&this._throwResponseError(e,t)}_throwResponseError(e,t){e=e+"\r\n"+t.status+"\r\n";let i=t.responseText||"";throw 500==t.status&&t.responseText&&(i=JSON.parse(t.responseText).ExceptionMessage),e+=i||t.statusText}_sendHttpRequest(e,t){let i=this._getUrl(e);this._request=wjcCore.httpRequest(i,t)}_clearToken(){this._token&&(this._clearRequest(),this._clearTimeout(),this._sendHttpRequest("Clear",{method:"DELETE"}),this._token=null)}_clearRequest(){this._request&&4!=this._request.readyState&&(this._request.abort(),this._request=null)}_clearTimeout(){this._toGetStatus&&(clearTimeout(this._toGetStatus),this._toGetStatus=null)}};_ServerConnection._TIMEOUT=6e4,_ServerConnection._POLL_INTERVAL=500,_ServerConnection._MAXDETAIL=1e3;class _ServerTally extends _Tally{add(e,t){wjcCore.assert(0==this._cnt,"Server tallies have a single value."),this._aggregatedValue=e}getAggregate(e){return this._aggregatedValue}}export class _SqlServerConnection extends _ServerConnection{constructor(e,t){super(e,t.url),this._jsonResult=null,this._dataTypes=null,this._debug=!1,wjcCore.assert(wjcCore.isString(t.cube)&&!wjcCore.isNullOrWhiteSpace(t.cube),"Cube name required."),this._cubeName=t.cube,this._url=t.url}getFields(){this._getSession();return this._jsonResult=null,this._dataTypes=null,this._getProperties(this._token),this._getDimensions(this._token),this._endSession(),this._jsonResult}getOutputView(e){this._ng.onUpdatingView(new ProgressEventArgs(0));let t=this,i=new _MdxQueryBuilder(this._ng,this._cubeName).buildQuery();this._jsonResult=[],this._getSession(),this._execQuery(this._token,i,function(i){wjcCore.asFunction(e)(t._jsonResult),t._ng.onUpdatingView(new ProgressEventArgs(100))})}getDetail(e,t){throw"getDetail method not supported"}_getSession(){let e=this,t=this._url;return wjcCore.httpRequest(t,{async:!1,data:_ENV_SESSION,method:"POST",requestHeaders:{"Content-Type":"text/xml"},success:function(t){let i=t.responseXML.getElementsByTagName("Session");e._token=i[0].getAttribute("SessionId")},error:function(t){e._handleError("Begin Session",t)}})}_endSession(){let e=this,t=this._url;return wjcCore.httpRequest(t,{async:!1,data:_ENV_ENDSESSION(e._token),method:"POST",requestHeaders:{"Content-Type":"text/xml"},error:function(t){e._handleError("End Session",t)},complete:function(t){e._token=void 0}})}_getProperties(e){let t=this,i=this._url;return wjcCore.httpRequest(i,{async:!1,data:_ENV_PROPERTIES(e,t._cubeName),method:"POST",requestHeaders:{"Content-Type":"text/xml"},success:function(e){for(var i={},s=e.responseXML.getElementsByTagName("row"),l=0;l<s.length;l++){var r=_getTagValue(s[l],"HIERARCHY_UNIQUE_NAME");switch(Number(_getTagValue(s[l],"DATA_TYPE"))){case 2:case 3:case 4:case 5:case 6:i[r]=wjcCore.DataType.Number;break;case 7:i[r]=wjcCore.DataType.Date}}t._dataTypes=i},error:function(e){t._handleError("Get Properties",e)}})}_getDimensions(e){let t=this,i=this._url;return wjcCore.httpRequest(i,{async:!1,data:_ENV_DIMENSIONS(e,t._cubeName),method:"POST",requestHeaders:{"Content-Type":"text/xml"},success:function(i){for(var s=[],l=i.responseXML.getElementsByTagName("row"),r=0;r<l.length;r++)if("2"!==_getTagValue(l[r],"DIMENSION_TYPE")){var n=_getTagValue(l[r],"DIMENSION_UNIQUE_NAME"),o={header:_getTagValue(l[r],"DIMENSION_CAPTION"),dataType:wjcCore.DataType.Object,dimensionType:DimensionType.Dimension,subFields:[]};t._getSubFolders(e,n,o),s.push(o)}else t._getMeasures(e,s);var a={header:"KPIs",dataType:wjcCore.DataType.Object,dimensionType:DimensionType.Kpi,subFields:[]};t._getKPIs(e,a),s.push(a),t._jsonResult=s},error:function(e){t._handleError("Get Dimensions",e)}})}_getSubFolders(e,t,i){let s=this,l=this._url;wjcCore.httpRequest(l,{async:!1,data:_ENV_HIERARCHIES(e,s._cubeName,t),method:"POST",requestHeaders:{"Content-Type":"text/xml"},success:function(e){for(var t=e.responseXML.getElementsByTagName("row"),l=0;l<t.length;l++){var r={header:_getTagValue(t[l],"HIERARCHY_NAME"),binding:_getTagValue(t[l],"HIERARCHY_UNIQUE_NAME"),dataType:wjcCore.DataType.String,dimensionType:DimensionType.Hierarchy};s._dataTypes[r.binding]&&(r.dataType=s._dataTypes[r.binding]);for(var n=_getTagValue(t[l],"HIERARCHY_DISPLAY_FOLDER").split("\\"),o=i,a=0;a<n.length;a++)if(""!=n[a]){var h={header:n[a],dataType:wjcCore.DataType.Object,dimensionType:DimensionType.Folder,subFields:[]};_containsFolder(o,n[a])?o=_findSubFieldByName(o,n[a]):(o.subFields.push(h),o=h)}o.subFields.push(r)}},error:function(e){s._handleError("Get Hierarchies",e)}})}_getMeasures(e,t){let i=this,s=this._url;return wjcCore.httpRequest(s,{async:!1,data:_ENV_MEASURES(e,i._cubeName),method:"POST",requestHeaders:{"Content-Type":"text/xml"},success:function(e){for(var i=e.responseXML.getElementsByTagName("row"),s={},l=0;l<i.length;l++){var r=_getTagValue(i[l],"MEASUREGROUP_NAME"),n={header:_getTagValue(i[l],"MEASURE_CAPTION"),binding:_getTagValue(i[l],"MEASURE_UNIQUE_NAME"),dataType:wjcCore.DataType.Number,dimensionType:DimensionType.Measure};if(Object.keys(s).indexOf(r)<0){var o={header:r,dataType:wjcCore.DataType.Number,dimensionType:DimensionType.Measure,subFields:[]};o.subFields.push(n),t.push(o),s[r]=o}else s[r].subFields.push(n)}},error:function(e){i._handleError("Get Measures",e)}})}_getKPIs(e,t){let i=this,s=this._url;return wjcCore.httpRequest(s,{async:!1,data:_ENV_KPIS(e,i._cubeName),method:"POST",requestHeaders:{"Content-Type":"text/xml"},success:function(e){for(var i=e.responseXML.getElementsByTagName("row"),s=0;s<i.length;s++){for(var l=_getTagValue(i[s],"KPI_DISPLAY_FOLDER").split("\\"),r=t,n=0;n<l.length;n++){var o={header:l[n],dataType:wjcCore.DataType.Object,dimensionType:DimensionType.Folder,subFields:[]};_containsFolder(r,l[n])?r=_findSubFieldByName(r,l[n]):(r.subFields.push(o),r=o)}var a={header:_getTagValue(i[s],"KPI_CAPTION"),binding:_getTagValue(i[s],"KPI_VALUE"),dataType:wjcCore.DataType.Number,dimensionType:DimensionType.Kpi};r.subFields.push(a)}},error:function(e){i._handleError("Get KPIs",e)}})}_execQuery(e,t,i){let s=this,l=this._url;return wjcCore.httpRequest(l,{async:!0,data:_ENV_QUERY(e,t),method:"POST",requestHeaders:{"Content-Type":"text/xml"},success:function(e){let l=e.responseXML,r=l.querySelector("Error");if(r)throw"SSAS Error\r\n"+r.getAttribute("Description")+"\r\n"+t;s._createPivotKeys(l),wjcCore.asFunction(i)(e)},error:function(e){s._handleError("Execute Query",e)},complete:function(e){s._endSession()}})}_createPivotKeys(e){let t=null,i=null,s=e.querySelector("CellData");this._ng.columnFields.length>0||this._ng.valueFields.length>1?(i=e.querySelector("Axis[name='Axis0']"),this._ng.rowFields.length>0&&(t=e.querySelector("Axis[name='Axis1']"))):this._ng.rowFields.length>0&&(t=e.querySelector("Axis[name='Axis0']"));let l=t&&this._ng.rowFields.length>0,r=i&&this._ng.columnFields.length>0;l&&r?this._createRowKeys(s,t,i):l?this._createRowOnlyKeys(s,t):r&&this._createColumnOnlyKeys(s,i)}_createRowKeys(e,t,i){let s=0,l=t.getElementsByTagName("Tuple"),r=i.getElementsByTagName("Tuple").length;for(let t=0;t<l.length;t++){let n=l[t],o=this._validateTuple(n);o?s=this._createColumnKeys(e,i,o,s):s+=r}}_createRowOnlyKeys(e,t){let i=0,s=t.getElementsByTagName("Tuple"),l=this._ng.valueFields.length;for(let t=0;t<s.length;t++){let r=s[t],n=this._validateTuple(r);if(n){for(let t=0;t<this._ng.valueFields.length;t++)n[this._ng.valueFields[t].key]=_getCellValue(e,i++);this._jsonResult.push(n)}else i+=l}}_createColumnKeys(e,t,i,s){let l=t.getElementsByTagName("Tuple"),r=this._ng.valueFields.length;for(let t=0;t<l.length;t+=r){let n=l[t],o=this._validateTuple(n);if(o){for(let e in i)o[e]=i[e];for(let t=0;t<this._ng.valueFields.length;t++)o[this._ng.valueFields[t].key]=_getCellValue(e,s++);this._jsonResult.push(o)}else s+=r}return s}_createColumnOnlyKeys(e,t){let i=0,s=t.getElementsByTagName("Tuple"),l=this._ng.valueFields.length;for(let t=0;t<s.length;t+=l){let l=s[t],r=this._validateTuple(l);if(r){for(let t=0;t<this._ng.valueFields.length;t++)r[this._ng.valueFields[t].key]=_getCellValue(e,i++);this._jsonResult.push(r)}}}_validateTuple(e){let t=e.getElementsByTagName("Member"),i=void 0,s={};for(let e=0;e<t.length;e++){let l=t[e],r=_getLevelNumber(l),n=l.getAttribute("Hierarchy"),o=_getCaptionValue(l);if(0==e)i=r;else if(r>i)return null;n.indexOf(".")>=0&&(s[n]=o)}return s}};const _ENV_SESSION=`\n    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">\n        <Header>\n            <BeginSession soap:mustUnderstand="1" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:schemas-microsoft-com:xml-analysis" />\n        </Header>\n        <Body>\n            <Execute xmlns="urn:schemas-microsoft-com:xml-analysis">\n                <Command>\n                    <Statement />\n                </Command>\n                <Properties>\n                </Properties>\n            </Execute>\n        </Body>\n    </Envelope>`,_ENV_ENDSESSION=e=>`\n    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">\n        <Header>\n            <XA:EndSession soap:mustUnderstand="1" SessionId="${e}" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:XA="urn:schemas-microsoft-com:xml-analysis" />\n        </Header>\n        <Body>\n            <Execute xmlns="urn:schemas-microsoft-com:xml-analysis">\n                <Command>\n                    <Statement />\n                </Command>\n                <Properties>\n                </Properties>\n            </Execute>\n        </Body>\n    </Envelope>`,_ENV_DIMENSIONS=(e,t)=>`\n    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">\n        <Header>\n            <XA:Session soap:mustUnderstand="1" SessionId="${e}" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:XA="urn:schemas-microsoft-com:xml-analysis" />\n        </Header>\n        <Body>\n            <Discover xmlns="urn:schemas-microsoft-com:xml-analysis">\n                <RequestType>MDSCHEMA_DIMENSIONS</RequestType>\n                <Restrictions>\n                    <RestrictionList>\n                        <CUBE_NAME>${t}</CUBE_NAME>\n                    </RestrictionList>\n                </Restrictions>\n                <Properties>\n                </Properties>\n            </Discover>\n        </Body>\n    </Envelope>`,_ENV_HIERARCHIES=(e,t,i)=>`\n    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">\n        <Header>\n            <XA:Session soap:mustUnderstand="1" SessionId="${e}" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:XA="urn:schemas-microsoft-com:xml-analysis" />\n        </Header>\n        <Body>\n            <Discover xmlns="urn:schemas-microsoft-com:xml-analysis">\n                <RequestType>MDSCHEMA_HIERARCHIES</RequestType>\n                <Restrictions>\n                    <RestrictionList>\n                        <CUBE_NAME>${t}</CUBE_NAME>\n                        <DIMENSION_UNIQUE_NAME>${i}</DIMENSION_UNIQUE_NAME>\n                    </RestrictionList>\n                </Restrictions>\n                <Properties>\n                </Properties>\n            </Discover>\n        </Body>\n    </Envelope>`,_ENV_MEASURES=(e,t)=>`\n    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">\n        <Header>\n            <XA:Session soap:mustUnderstand="1" SessionId="${e}" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:XA="urn:schemas-microsoft-com:xml-analysis" />\n        </Header>\n        <Body>\n            <Discover xmlns="urn:schemas-microsoft-com:xml-analysis">\n                <RequestType>MDSCHEMA_MEASURES</RequestType>\n                <Restrictions>\n                    <RestrictionList>\n                        <CUBE_NAME>${t}</CUBE_NAME>\n                    </RestrictionList>\n                </Restrictions>\n                <Properties>\n                </Properties>\n            </Discover>\n        </Body>\n    </Envelope>`,_ENV_KPIS=(e,t)=>`\n    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">\n        <Header>\n            <XA:Session soap:mustUnderstand="1" SessionId="${e}" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:XA="urn:schemas-microsoft-com:xml-analysis" />\n        </Header>\n        <Body>\n            <Discover xmlns="urn:schemas-microsoft-com:xml-analysis">\n                <RequestType>MDSCHEMA_KPIS</RequestType>\n                <Restrictions>\n                    <RestrictionList>\n                        <CUBE_NAME>${t}</CUBE_NAME>\n                    </RestrictionList>\n                </Restrictions>\n                <Properties>\n                </Properties>\n            </Discover>\n        </Body>\n    </Envelope>`,_ENV_LEVELS=(e,t)=>`\n    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">\n        <Header>\n            <XA:Session soap:mustUnderstand="1" SessionId="${e}" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:XA="urn:schemas-microsoft-com:xml-analysis" />\n        </Header>\n        <Body>\n            <Discover xmlns="urn:schemas-microsoft-com:xml-analysis">\n                <RequestType>MDSCHEMA_LEVELS</RequestType>\n                <Restrictions>\n                    <RestrictionList>\n                        <CUBE_NAME>${t}</CUBE_NAME>\n                    </RestrictionList>\n                </Restrictions>\n                <Properties>\n                </Properties>\n            </Discover>\n        </Body>\n    </Envelope>`,_ENV_PROPERTIES=(e,t)=>`\n    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">\n        <Header>\n            <XA:Session soap:mustUnderstand="1" SessionId="${e}" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:XA="urn:schemas-microsoft-com:xml-analysis" />\n        </Header>\n        <Body>\n            <Discover xmlns="urn:schemas-microsoft-com:xml-analysis">\n                <RequestType>MDSCHEMA_PROPERTIES</RequestType>\n                <Restrictions>\n                    <RestrictionList>\n                        <CUBE_NAME>${t}</CUBE_NAME>\n                        <PROPERTY_NAME>MEMBER_VALUE</PROPERTY_NAME>\n                    </RestrictionList>\n                </Restrictions>\n                <Properties>\n                </Properties>\n            </Discover>\n        </Body>\n    </Envelope>`,_ENV_QUERY=(e,t)=>`\n    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">\n        <Header>\n            <XA:Session soap:mustUnderstand="1" SessionId="${e}" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:XA="urn:schemas-microsoft-com:xml-analysis" />\n        </Header>\n        <Body>\n            <Execute xmlns="urn:schemas-microsoft-com:xml-analysis">\n                <Command>\n                    <Statement>\n                        <![CDATA[\n                        ${t}\n                        ]]>\n                    </Statement>\n                </Command>\n                <Properties>\n                    <PropertyList>\n                        <Content>Data</Content>\n                    </PropertyList>\n                </Properties>\n            </Execute>\n        </Body>\n    </Envelope>`;export class _TextBuilder{constructor(){this._text=""}get length(){return this._text.length}toString(){return this._text}append(...e){this._text=this._text.concat(...e)}joinToList(e,...t){let i=t.join();this.length>0&&i.length>0?this._text=this._text.concat(e,...t):i.length>0&&(this._text=i)}joinItemToList(e){this.joinToList(",",e)}wrap(e,t){this.length>0&&(this._text=e.concat(this._text,t))}static wrap(e,t,i){return t.length>0?e.concat(t,i):""}};export class _ListContextMenu extends wjcInput.Menu{constructor(e){super(document.createElement("div"),{header:"Field Context Menu",displayMemberPath:"text",commandParameterPath:"parm",command:{executeCommand:e=>{this._execute(e)},canExecuteCommand:e=>this._canExecute(e)}}),this._full=e,this.itemsSource=this._getMenuItems(e),wjcCore.addClass(this.dropDown,"context-menu wj-olap-context-menu")}refresh(e=!0){this.itemsSource=this._getMenuItems(this._full),super.refresh(e)}attach(e){wjcCore.assert(e instanceof wjcGrid.FlexGrid,"Expecting a FlexGrid control...");let t=e.hostElement;t.addEventListener("contextmenu",i=>{this._selectField(e,i)&&(i.preventDefault(),this.owner=t,this.show(i))})}_selectField(e,t){let i=e.hitTest(t);if(i.panel!=e.cells||!i.range.isValid)return!1;let s=e.rows[i.row].dataItem;return!(s instanceof CubePivotField&&s.subFields&&s.subFields.length)&&(e.select(i.range,!0),!0)}_getMenuItems(e){let t;t=e?[{text:'<div class="menu-icon"></div>*',parm:"up"},{text:'<div class="menu-icon"></div>*',parm:"down"},{text:'<div class="menu-icon"></div>*',parm:"first"},{text:'<div class="menu-icon"></div>*',parm:"last"},{text:'<div class="wj-separator"></div>'},{text:'<div class="menu-icon"><span class="wj-glyph-filter"></span></div>*',parm:"filter"},{text:'<div class="menu-icon">&#8801;</div>*',parm:"rows"},{text:'<div class="menu-icon">&#10996;</div>*',parm:"cols"},{text:'<div class="menu-icon">&#931;</div>*',parm:"vals"},{text:'<div class="wj-separator"></div>'},{text:'<div class="menu-icon menu-icon-remove">&#10006;</div>*',parm:"remove"},{text:'<div class="wj-separator"></div>'},{text:'<div class="menu-icon">&#9965;</div>*',parm:"edit"}]:[{text:'<div class="menu-icon"><span class="wj-glyph-filter"></span></div>*',parm:"filter"},{text:'<div class="menu-icon">&#8801;</div>*',parm:"rows"},{text:'<div class="menu-icon">&#10996;</div>*',parm:"cols"},{text:'<div class="menu-icon">&#931;</div>*',parm:"vals"},{text:'<div class="wj-separator"></div>'},{text:'<div class="menu-icon">&#9965;</div>*',parm:"edit"}];for(let e=0;e<t.length;e++){let i=t[e];if(i.parm){let e=wjcCore.culture.olap._ListContextMenu[i.parm];wjcCore.assert(e,"missing localized text for item "+i.parm),i.text=i.text.replace(/([^>]+$)/,e)}}return t}_execute(e){let t=wjcCore.Control.getControl(this.owner),i=t.itemsSource,s=t.selection.row,l=t.rows[s].dataItem,r=l?l.engine:null,n=this._getTargetList(r,e);switch(e){case"up":case"first":case"down":case"last":if(r){let t=i.indexOf(l),s="up"==e?t-1:"first"==e?0:"down"==e?t+1:"last"==e?i.length:-1;r.deferUpdate(()=>{i.removeAt(t),i.insert(s,l)})}break;case"filter":case"rows":case"cols":case"vals":n&&l&&n.push(l);break;case"remove":l&&r.removeField(l);break;case"edit":l&&r.editField(l)}}_canExecute(e){let t=wjcCore.Control.getControl(this.owner);if(!t)return!1;let i=t.selection.row,s=i>-1?t.rows[i].dataItem:null,l=s?s.engine:null,r=this._getTargetList(l,e),n=!!s&&s instanceof CubePivotField,o=!!s&&s.isMeasure;switch(e){case"up":case"first":return i>0;case"down":case"last":return i<t.rows.length-1;case"filter":case"rows":case"cols":return!o&&r&&r.indexOf(s)<0;case"vals":return(!n||o)&&r&&r.indexOf(s)<0;case"edit":return l&&l.allowFieldEditing;case"detail":return s&&!n}return!0}_getTargetList(e,t){if(e)switch(t){case"filter":return e.filterFields;case"rows":return e.rowFields;case"cols":return e.columnFields;case"vals":return e.valueFields}return null}};export class PivotPanel extends wjcCore.Control{constructor(e,t){super(e,null,!0),this._showIcons=!0,this._restrictDrag=null,this.itemsSourceChanged=new wjcCore.Event,this.viewDefinitionChanged=new wjcCore.Event,this.updatingView=new wjcCore.Event,this.updatedView=new wjcCore.Event;let i="Missing dependency: PivotPanel requires ";wjcCore.assert(null!=wjcInput,i+"wijmo.input."),wjcCore.assert(null!=wjcGrid&&null!=wjcGridFilter,i+"wijmo.grid.filter.");let s=this.getTemplate();this.applyTemplate("wj-control wj-content wj-pivotpanel",s,{_dFields:"d-fields",_dFilters:"d-filters",_dRows:"d-rows",_dCols:"d-cols",_dVals:"d-vals",_dProgress:"d-prog",_btnUpdate:"btn-update",_chkDefer:"chk-defer",_gFlds:"g-flds",_gDrag:"g-drag",_gFlt:"g-flt",_gCols:"g-cols",_gRows:"g-rows",_gVals:"g-vals",_gDefer:"g-defer"}),this._globalize();let l=this.hostElement;this.addEventListener(l,"dragstart",this._dragstart.bind(this)),this.addEventListener(l,"dragover",this._dragover.bind(this)),this.addEventListener(l,"dragleave",this._dragover.bind(this)),this.addEventListener(l,"drop",this._drop.bind(this)),this.addEventListener(l,"dragend",this._dragend.bind(this)),this._lbFields=this._createFieldGrid(this._dFields),this._lbFilters=this._createFieldGrid(this._dFilters),this._lbRows=this._createFieldGrid(this._dRows),this._lbCols=this._createFieldGrid(this._dCols),this._lbVals=this._createFieldGrid(this._dVals);let r=this._ctxMenuShort=new _ListContextMenu(!1);r.attach(this._lbFields),(r=this._ctxMenuFull=new _ListContextMenu(!0)).attach(this._lbFilters),r.attach(this._lbRows),r.attach(this._lbCols),r.attach(this._lbVals),this._dMarker=wjcCore.createElement('<div class="wj-marker" style="display:none">&nbsp;</div>'),this.hostElement.appendChild(this._dMarker),this.addEventListener(this._btnUpdate,"click",e=>{this._ng.refresh(!0),e.preventDefault()}),this.addEventListener(this._chkDefer,"click",e=>{wjcCore.enable(this._btnUpdate,this._chkDefer.checked),this._chkDefer.checked?this._ng.beginUpdate():this._ng.endUpdate()}),this.engine=new PivotEngine,this.initialize(t)}_getProductInfo(){return"D6F4,PivotPanel"}get engine(){return this._ng}set engine(e){this._ng&&(this._ng.itemsSourceChanged.removeHandler(this._itemsSourceChanged),this._ng.viewDefinitionChanged.removeHandler(this._viewDefinitionChanged),this._ng.updatingView.removeHandler(this._updatingView),this._ng.updatedView.removeHandler(this._updatedView),this._ng.error.removeHandler(this._requestError)),e=wjcCore.asType(e,PivotEngine,!1),this._ng=e,this._ng.itemsSourceChanged.addHandler(this._itemsSourceChanged,this),this._ng.viewDefinitionChanged.addHandler(this._viewDefinitionChanged,this),this._ng.updatingView.addHandler(this._updatingView,this),this._ng.updatedView.addHandler(this._updatedView,this),this._ng.error.addHandler(this._requestError,this),this._lbFields.itemsSource=e.fields,this._lbFilters.itemsSource=e.filterFields,this._lbRows.itemsSource=e.rowFields,this._lbCols.itemsSource=e.columnFields,this._lbVals.itemsSource=e.valueFields,this._lbFields.collectionView.filter=(e=>e.visible&&null==e.parentField),"Filters,Rows,Cols,Vals".split(",").forEach(e=>{this["_lb"+e].collectionView.filter=(e=>e.visible)})}get itemsSource(){return this._ng.itemsSource}set itemsSource(e){e instanceof PivotEngine?this.engine=e:this._ng.itemsSource=e}get collectionView(){return this._ng.collectionView}get pivotView(){return this._ng.pivotView}get autoGenerateFields(){return this.engine.autoGenerateFields}set autoGenerateFields(e){this._ng.autoGenerateFields=e}get fields(){return this._ng.fields}get rowFields(){return this._ng.rowFields}get columnFields(){return this._ng.columnFields}get valueFields(){return this._ng.valueFields}get filterFields(){return this._ng.filterFields}get viewDefinition(){return this._ng.viewDefinition}set viewDefinition(e){this._ng.viewDefinition=e}get isViewDefined(){return this._ng.isViewDefined}get showFieldIcons(){return this._showIcons}set showFieldIcons(e){e!=this._showIcons&&(this._showIcons=wjcCore.asBoolean(e),this.invalidate())}get restrictDragging(){return this._restrictDrag}set restrictDragging(e){this._restrictDrag=wjcCore.asBoolean(e,!0)}onItemsSourceChanged(e){this.itemsSourceChanged.raise(this,e)}onViewDefinitionChanged(e){this.viewDefinitionChanged.raise(this,e)}onUpdatingView(e){this.updatingView.raise(this,e)}onUpdatedView(e){this.updatedView.raise(this,e)}refresh(e=!0){"Fields,Filters,Rows,Cols,Vals".split(",").forEach(e=>{let t=this["_lb"+e];t.refresh(),t.collectionView.refresh()}),e&&(this._globalize(),this._ctxMenuShort.refresh(),this._ctxMenuFull.refresh()),super.refresh(e)}_copy(e,t){switch(e){case"engine":return this.engine=t,!0}return!1}_globalize(){let e=wjcCore.culture.olap.PivotPanel;wjcCore.setText(this._gFlds,e.fields),wjcCore.setText(this._gDrag,e.drag),wjcCore.setText(this._gFlt,e.filters),wjcCore.setText(this._gCols,e.cols),wjcCore.setText(this._gRows,e.rows),wjcCore.setText(this._gVals,e.vals),wjcCore.setText(this._gDefer,e.defer),wjcCore.setText(this._btnUpdate,e.update)}_itemsSourceChanged(e,t){this.onItemsSourceChanged(t)}_viewDefinitionChanged(e,t){e.isUpdating||(this.invalidate(),this.onViewDefinitionChanged(t))}_updatingView(e,t){let i=wjcCore.clamp(t.progress,5,100)%100;this._dProgress.style.width=i+"%",this.onUpdatingView(t)}_updatedView(e,t){this.onUpdatedView(t)}_requestError(e,t){this._dProgress.style.width="0"}_createFieldGrid(e){let t=new wjcGrid.FlexGrid(e,{autoGenerateColumns:!1,childItemsPath:"subFields",columns:[{binding:"header",width:"*"}],headersVisibility:"None",selectionMode:"Cell",showAlternatingRows:!1});return t.cells.hostElement.parentElement.style.overflowX="hidden",t.formatItem.addHandler((e,t)=>{let i=e.rows[t.row].dataItem;wjcCore.assert(i instanceof PivotField,"PivotField expected...");let s=i._hasSubFields();wjcCore.toggleClass(t.cell,"wj-header",s),t.cell.setAttribute("draggable",(!s).toString());let l=t.cell.innerHTML;i.filter.isActive&&(l+='&nbsp;&nbsp;<span class="wj-glyph-filter"></span>'),e==this._lbVals&&(l+=' <span class="wj-aggregate">('+wjcCore.Aggregate[i.aggregate]+")</span>"),e!=this._lbFields||s||(this._showIcons&&(l='<span class="wj-glyph-'+(i.isMeasure?"measure":"dimension")+'"></span> '+l),l='<label><input type="checkbox"'+(i.isActive?" checked":"")+"> "+l+"</label>"),t.cell.innerHTML=l}),t.addEventListener(e,"click",e=>{let i=e.target;if(i instanceof HTMLInputElement&&"checkbox"==i.type){let s=this._hitTestField(t,e);s instanceof PivotField&&(s.isActive=i.checked)}}),t}_dragstart(e){let t=this._getFlexGridTarget(e);t&&(this._dragField=this._hitTestField(t,e),this._dragSource=this._dragField instanceof PivotField?t.hostElement:null,this._dragSource&&e.dataTransfer&&(wjcCore._startDrag(e.dataTransfer,"copyMove"),e.stopPropagation()))}_dragover(e){let t=!1,i=this._getFlexGridTarget(e);if(i&&this._dragField){if(this._dragSource==this._dFields&&i!=this._lbFields){let e=i.itemsSource;if(null==e.maxItems||e.length<e.maxItems){let e=this._dragField;i.itemsSource.indexOf(e)<0?t=!0:i==this._lbVals&&(t=!(e instanceof CubePivotField))}}this._dragSource&&this._dragSource!=this._dFields&&(t=!0)}if(t&&this._getRestrictDrag()&&this._dragSource!=i.hostElement){let e=this._dragField.isMeasure;i==this._lbVals?t=e:i!=this._lbRows&&i!=this._lbCols||(t=!e)}t?(this._updateDropMarker(i,e),e.dataTransfer.dropEffect=this._dragSource==this._dFields?"copy":"move",e.preventDefault(),e.stopPropagation()):this._updateDropMarker()}_drop(e){let t=this._getFlexGridTarget(e);if(t&&this._dragField){let e=wjcCore.Control.getControl(this._dragSource),i=this._dragField;e==this._lbFields&&t==this._lbVals&&t.itemsSource.indexOf(i)>-1&&(i=i._clone(),this.engine.fields.push(i)),t==this._lbFields?i.isActive=!1:this._ng.deferUpdate(()=>{let e=t.itemsSource,s=e.indexOf(i);s!=this._dropIndex&&(s>-1&&(e.removeAt(s),s<this._dropIndex&&this._dropIndex--),e.insert(this._dropIndex,i))})}this._resetMouseState()}_dragend(e){this._resetMouseState()}_hitTestField(e,t){let i=e.hitTest(t.target);return i.panel==e.cells&&i.range.isValid?(e.select(i.range,!0),e.rows[i.row].dataItem):null}_getRestrictDrag(){let e=this._restrictDrag;return null==e&&this.fields.length&&(e=this.fields[0]instanceof CubePivotField),e}_resetMouseState(){this._dragSource=null,this._updateDropMarker()}_getFlexGridTarget(e){let t=wjcCore.Control.getControl(wjcCore.closest(e.target,".wj-flexgrid"));return t instanceof wjcGrid.FlexGrid?t:null}_updateDropMarker(e,t){if(!t)return void(this._dMarker.style.display="none");let i;if(e.rows.length){let s=e.hitTest(t),l=s.row;l>-1?(i=e.getCellBoundingRect(l,0),s.point.y>i.top+i.height/2&&(i.top+=i.height,l++),this._dropIndex=l):(l=e.viewRange.bottomRow,(i=e.getCellBoundingRect(l,0)).top+=i.height,this._dropIndex=l+1)}else(i=wjcCore.Rect.fromBoundingRect(e.hostElement.getBoundingClientRect())).top+=4,this._dropIndex=0;let s=this.hostElement,l=s.getBoundingClientRect();wjcCore.setCss(this._dMarker,{left:Math.round(i.left-l.left)+s.scrollLeft,top:Math.round(i.top-l.top-2)+s.scrollTop,width:Math.round(i.width),height:4,display:""})}};PivotPanel.controlTemplate='<div><label wj-part="g-flds"></label><div wj-part="d-fields"></div><label wj-part="g-drag"></label><table><tr><td width="50%"><label><span class="wj-glyph wj-glyph-filter"></span> <span wj-part="g-flt"></span></label><div wj-part="d-filters"></div></td><td width= "50%" style= "border-left-style:solid"><label><span class="wj-glyph">&#10996;</span> <span wj-part="g-cols"></span></label><div wj-part="d-cols"></div></td></tr><tr style= "border-top-style:solid"><td width="50%"><label><span class="wj-glyph">&#8801;</span> <span wj-part="g-rows"></span></label><div wj-part="d-rows"></div></td><td width= "50%" style= "border-left-style:solid"><label><span class="wj-glyph">&#931;</span> <span wj-part="g-vals"></span></label><div wj-part="d-vals"></div></td></tr></table><div wj-part="d-prog" class="wj-state-selected" style="width:0px;height:3px"></div><div style="display:table"><label style="display:table-cell;vertical-align:middle"><input wj-part="chk-defer" type="checkbox"/> <span wj-part="g-defer"></span></label><button wj-part="btn-update" class="wj-btn wj-state-disabled" style="float:right;margin:6px" disabled></button></div></div>';export class _GridContextMenu extends wjcInput.Menu{constructor(){super(document.createElement("div"),{header:"PivotGrid Context Menu",displayMemberPath:"text",commandParameterPath:"parm",command:{executeCommand:e=>{this._execute(e)},canExecuteCommand:e=>this._canExecute(e)}}),this.itemsSource=this._getMenuItems(),wjcCore.addClass(this.dropDown,"context-menu wj-olap-context-menu")}refresh(e=!0){this.itemsSource=this._getMenuItems(),super.refresh(e)}attach(e){wjcCore.assert(e instanceof PivotGrid,"Expecting a PivotGrid control...");let t=e.hostElement;t.addEventListener("contextmenu",i=>{if(e.customContextMenu&&(i.preventDefault(),this.owner=t,this._selectField(i))){let e=this.dropDown;this.selectedIndex=-1,this.onIsDroppedDownChanging(new wjcCore.CancelEventArgs)&&(wjcCore.showPopup(e,i),this.onIsDroppedDownChanged(),e.focus())}})}_selectField(e){this._targetField=null,this._htDown=null;let t=wjcCore.Control.getControl(this.owner),i=t.engine,s=t.hitTest(e),l=wjcGrid.CellType;switch(s.cellType){case l.Cell:t.select(s.range),this._targetField=i.valueFields[s.col%i.valueFields.length],this._htDown=s;break;case l.ColumnHeader:this._targetField=i.columnFields[s.row];break;case l.RowHeader:this._targetField=i.rowFields[s.col];break;case l.TopLeft:s.row==s.panel.rows.length-1&&(this._targetField=i.rowFields[s.col])}return null!=this._targetField}_getMenuItems(){let e=[{text:'<div class="menu-icon menu-icon-remove">&#10006;</div>Remove Field',parm:"remove"},{text:'<div class="menu-icon">&#9965;</div>Field Settings...',parm:"edit"},{text:'<div class="wj-separator"></div>'},{text:'<div class="menu-icon">&#8981;</div>Show Detail...',parm:"detail"}];for(let t=0;t<e.length;t++){let i=e[t];if(i.parm){let e=wjcCore.culture.olap._ListContextMenu[i.parm];wjcCore.assert(e,"missing localized text for item "+i.parm),i.text=i.text.replace(/([^>]+$)/,e)}}return e}_execute(e){let t=wjcCore.Control.getControl(this.owner),i=this._targetField,s=this._htDown;switch(e){case"remove":t.engine.removeField(i);break;case"edit":t.engine.editField(i);break;case"detail":t.showDetail(s.row,s.col)}}_canExecute(e){let t=this._targetField,i=wjcCore.Control.getControl(this.owner),s=i?i.engine:null;switch(e){case"remove":return null!=t;case"edit":return null!=t&&s&&s.allowFieldEditing;case"detail":return null!=this._htDown&&s.valueFields.length&&null!=t&&!(t instanceof CubePivotField)}return!0}};export class _PivotMergeManager extends wjcGrid.MergeManager{getMergedRange(e,t,i,s=!0){let l=e.grid.collectionView;if(this._ng=l instanceof PivotCollectionView?l.engine:null,!this._ng)return super.getMergedRange(e,t,i,s);if(t<0||t>=e.rows.length||i<0||i>=e.columns.length)return null;switch(e.cellType){case wjcGrid.CellType.TopLeft:return this._getMergedTopLeftRange(e,t,i);case wjcGrid.CellType.RowHeader:return this._getMergedRowHeaderRange(e,t,i,s?e.viewRange:null);case wjcGrid.CellType.ColumnHeader:return this._getMergedColumnHeaderRange(e,t,i,s?e.viewRange:null)}return null}_getMergedTopLeftRange(e,t,i){let s=new wjcGrid.CellRange(t,i);for(;s.col>0&&!e.getCellData(t,s.col,!0);)s.col--;for(;s.col2<e.columns.length-1&&!e.getCellData(t,s.col2+1,!0);)s.col2++;return s}_getMergedRowHeaderRange(e,t,i,s){let l=this._ng._getRowLevel(t);if(l>-1&&i>=l){let l,r,n=e.getCellData(t,i,!1),o=s?s.col:0,a=s?s.col2:e.columns.length-1;for(l=i;l>o&&e.getCellData(t,l-1,!1)==n;l--);for(r=i;r<a&&e.getCellData(t,r+1,!1)==n;r++);return l!=r?new wjcGrid.CellRange(t,l,t,r):null}let r,n,o=s?s.row:0,a=s?s.row2:e.rows.length-1;for(r=t;r>o&&this._sameColumnValues(e,t,r-1,i);r--);for(n=t;n<a&&this._sameColumnValues(e,t,n+1,i);n++);return r!=n?new wjcGrid.CellRange(r,i,n,i):null}_sameColumnValues(e,t,i,s){for(;s>=0;s--)if(e.getCellData(t,s,!1)!=e.getCellData(i,s,!1))return!1;return!0}_getMergedColumnHeaderRange(e,t,i,s){let l=this._ng._getKey(e.columns[i].binding),r=e.getCellData(t,i,!1),n=this._ng._getColLevel(l);if(n>-1&&t>=n){let l,n,o=s?s.row:0,a=s?s.row2:e.rows.length-1;for(l=t;l>o&&e.getCellData(l-1,i,!1)==r;l--);for(n=t;n<a&&e.getCellData(n+1,i,!1)==r;n++);if(l!=n)return new wjcGrid.CellRange(l,i,n,i)}let o,a,h=s?s.col:0,d=s?s.col2:e.columns.length-1;for(o=i;o>h&&this._sameRowValues(e,t,i,o-1);o--);for(a=i;a<d&&this._sameRowValues(e,t,i,a+1);a++);return o!=a?new wjcGrid.CellRange(t,o,t,a):null}_sameRowValues(e,t,i,s){for(;t>=0;t--)if(e.getCellData(t,i,!1)!=e.getCellData(t,s,!1))return!1;return!0}};export class PivotGrid extends wjcGrid.FlexGrid{constructor(e,t){super(e),this._showDetailOnDoubleClick=!0,this._collapsibleSubtotals=!0,this._customCtxMenu=!0,this._showRowFldSort=!1,this._showRowFldHdrs=!0,this._showColFldHdrs=!0,this._centerVert=!0,this._collapsedKeys={},wjcCore.addClass(this.hostElement,"wj-pivotgrid"),this.isReadOnly=!0,this.deferResizing=!0,this.showAlternatingRows=!1,this.autoGenerateColumns=!1,this.allowDragging=wjcGrid.AllowDragging.None,this.mergeManager=new _PivotMergeManager(this),this.customContextMenu=!0,this.initialize(t),this.formatItem.addHandler(this._formatItem,this),this.addEventListener(this.hostElement,"mousedown",this._mousedown.bind(this),!0),this.addEventListener(this.hostElement,"mouseup",this._mouseup.bind(this),!0),this.addEventListener(this.hostElement,"dblclick",this._dblclick.bind(this),!0),this._ctxMenu=new _GridContextMenu,this._ctxMenu.attach(this)}_getProductInfo(){return"D6F4,PivotGrid"}get engine(){return this._ng}get showDetailOnDoubleClick(){return this._showDetailOnDoubleClick}set showDetailOnDoubleClick(e){this._showDetailOnDoubleClick=wjcCore.asBoolean(e)}get detailDialog(){return this._dlgDetail||(this._dlgDetail=new DetailDialog(document.createElement("div"))),this._dlgDetail}get showRowFieldHeaders(){return this._showRowFldHdrs}set showRowFieldHeaders(e){e!=this._showRowFldHdrs&&(this._showRowFldHdrs=wjcCore.asBoolean(e),this._updateFixedContent())}get showColumnFieldHeaders(){return this._showColFldHdrs}set showColumnFieldHeaders(e){e!=this._showColFldHdrs&&(this._showColFldHdrs=wjcCore.asBoolean(e),this._updateFixedContent())}get showRowFieldSort(){return this._showRowFldSort}set showRowFieldSort(e){e!=this._showRowFldSort&&(this._showRowFldSort=wjcCore.asBoolean(e),this._updateFixedContent())}get customContextMenu(){return this._customCtxMenu}set customContextMenu(e){this._customCtxMenu=wjcCore.asBoolean(e)}get collapsibleSubtotals(){return this._collapsibleSubtotals}set collapsibleSubtotals(e){e!=this._collapsibleSubtotals&&(this._collapsibleSubtotals=wjcCore.asBoolean(e),this.invalidate())}get centerHeadersVertically(){return this._centerVert}set centerHeadersVertically(e){e!=this._centerVert&&(this._centerVert=wjcCore.asBoolean(e),this.invalidate())}getDetail(e,t){let i=this.rows[wjcCore.asInt(e)].dataItem,s=this.columns[wjcCore.asInt(t)].binding;return this._ng.getDetail(i,s)}getKeys(e,t){let i=this.rows[wjcCore.asInt(e)],s=this.columns[wjcCore.asInt(t)],l=i?i.dataItem:null,r=s?s.binding:null;return this._ng.getKeys(l,r)}getDetailView(e,t){let i=this.rows[wjcCore.asInt(e)].dataItem,s=this.columns[wjcCore.asInt(t)].binding;return this._ng.getDetailView(i,s)}showDetail(e,t){if(this._ng.valueFields.length){let i=this.detailDialog;i.showDetail(this,new wjcGrid.CellRange(e,t)),i.show(!0)}}collapseRowsToLevel(e){this._collapseRowsToLevel(e)}collapseColumnsToLevel(e){this._collapseColsToLevel(e)}_getQuickAutoSize(){return wjcCore.isBoolean(this.quickAutoSize)?this.quickAutoSize:this.formatItem.handlerCount<=1&&null==this.itemFormatter}_bindGrid(e){this.deferUpdate(()=>{let t=this.preserveOutlineState,i=this._collapsedKeys,s=this.rows,l=this.columns;if(t||(i=this._collapsedKeys={}),super._bindGrid(e),this._ng&&t&&!wjcCore.isEmpty(i)){let e=this._ng.totalsBeforeData,t=e?s.length-1:0,r=e?-1:s.length,n=e?-1:1;for(let e=t;e!=r;e+=n){let t=s[e].dataItem,l=t?t[_PivotKey._ROW_KEY_NAME]:null;l&&l.level>0&&i[l.toString()]&&this._setRowCollapsed(new wjcGrid.CellRange(e,l.level-1),!0)}t=e?l.length-1:0,r=e?-1:l.length,n=e?-1:1;for(let e=t;e!=r;e+=n){let t=l[e].binding,s=this._ng._getKey(t);s&&s.level>0&&i[s.toString()]&&this._setColCollapsed(new wjcGrid.CellRange(s.level-1,e),!0)}}})}_getCollectionView(e){return e instanceof PivotPanel?e=e.engine.pivotView:e instanceof PivotEngine&&(e=e.pivotView),wjcCore.asCollectionView(e)}refresh(e=!0){this._ctxMenu.refresh(),super.refresh(e)}onItemsSourceChanged(e){this._ng&&(this._ng.updatedView.removeHandler(this._updatedView,this),this._ng.viewDefinitionChanged.removeHandler(this._viewDefinitionChanged,this)),this._collapsedKeys={};let t=this.collectionView;this._ng=t instanceof PivotCollectionView?t.engine:null,this._ng&&(this._ng.updatedView.addHandler(this._updatedView,this),this._ng.viewDefinitionChanged.addHandler(this._viewDefinitionChanged,this)),this._updatedView(),this._bindGrid(!0),super.onItemsSourceChanged(e)}onResizedColumn(e){let t=this._ng;if(t){if(e.panel.columns==this.rowHeaders.columns){let i=t.rowFields;e.col<i.length&&(i[e.col].width=e.panel.columns[e.col].renderWidth)}if(e.panel.columns==this.columnHeaders.columns){let i=t.valueFields;i.length>0&&(i[e.col%i.length].width=e.panel.columns[e.col].renderWidth)}}super.onResizedColumn(e)}onSortingColumn(e){let t=this._ng;return(!t||!t.isUpdating)&&super.onSortingColumn(e)}onDraggingColumn(e){let t=this._ng;return(!t||!t.isUpdating)&&super.onDraggingColumn(e)}onDraggedColumn(e){let t=this._ng;if(t&&e.panel.columns==this.topLeftCells.columns){let i=t.rowFields,s=i[e.data.col];t.deferUpdate(()=>{i.removeAt(e.data.col),i.insert(e.col,s)})}super.onDraggedColumn(e)}_updatedView(){this._updateFixedCounts(),this.columns.clear(),this.rows.clear()}_viewDefinitionChanged(){this._collapsedKeys={}}onLoadedRows(e){if(0==this.columns.length){let e=this.collectionView,t=e?e.sourceCollection:null;if(t&&t.length){let e=t[0];for(let t in e)if(t!=_PivotKey._ROW_KEY_NAME){let i=new wjcGrid.Column({binding:t,dataType:null!=e[t]?wjcCore.getType(e[t]):wjcCore.DataType.Number});this.columns.push(i)}}}this._updateFixedContent(),super.onLoadedRows(e)}_updateFixedCounts(){let e,t=this._ng,i=t&&t.isViewDefined;e=Math.max(1,i?t.rowFields.length:1),this._setLength(this.topLeftCells.columns,e),e=Math.max(1,i?t.columnFields.length:1),t&&t.columnFields.length&&t.valueFields.length>1&&e++,this._setLength(this.topLeftCells.rows,e)}_setLength(e,t){for(;e.length<t;)e.push(e instanceof wjcGrid.ColumnCollection?new wjcGrid.Column:new wjcGrid.Row);for(;e.length>t;)e.removeAt(e.length-1)}_updateFixedContent(){let e=this._ng;if(!(e&&e.isViewDefined))return void this.topLeftCells.setCellData(0,0,null);let t=this.topLeftCells;for(let i=0;i<t.rows.length;i++)for(let s=0;s<t.columns.length;s++){let l="";this.showRowFieldHeaders&&s<e.rowFields.length&&i==t.rows.length-1&&(l=e.rowFields[s].header),this.showColumnFieldHeaders&&!l&&i<e.columnFields.length&&0==s&&(l=e.columnFields[i].header+":"),t.setCellData(i,s,l,!1,!1)}t=this.rowHeaders;for(let e=0;e<t.rows.length;e++){let i=t.rows[e].dataItem[_PivotKey._ROW_KEY_NAME];wjcCore.assert(i instanceof _PivotKey,"missing PivotKey for row...");for(let s=0;s<t.columns.length;s++){let l=i.getValue(s,!0);t.setCellData(e,s,l,!1,!1)}}t=this.columnHeaders;for(let i=0;i<t.columns.length;i++){let s=e._getKey(t.columns[i].binding),l=e.valueFields,r=l.length>1||0==l.length||s.level>-1;wjcCore.assert(s instanceof _PivotKey,"missing PivotKey for column...");for(let e=0;e<t.rows.length;e++){let n=r&&e==t.rows.length-1&&l.length?l[i%l.length].header:s.getValue(e,!0);t.setCellData(e,i,n,!1,!1)}}t=this.topLeftCells;for(let i=0;i<t.columns.length;i++){let s=t.columns[i],l=i<e.rowFields.length?e.rowFields[i]:null;s.width=l&&wjcCore.isNumber(l.width)?l.width:this.columns.defaultSize,s.wordWrap=l?l.wordWrap:null,s.align=null}t=this.cells;for(let i=0;i<t.columns.length;i++){let s=t.columns[i],l=e.valueFields.length?e.valueFields[i%e.valueFields.length]:null;s.width=l&&wjcCore.isNumber(l.width)?l.width:this.columns.defaultSize,s.wordWrap=l?l.wordWrap:null,s.format=l?l.format:null}}_formatItem(e,t){let i=this._ng;if(!i)return;if(t.panel==this.topLeftCells){t.cell.style.textAlign="";let e=t.row<t.panel.rows.length-1||0==i.rowFields.length;wjcCore.toggleClass(t.cell,"wj-col-field-hdr",e),wjcCore.toggleClass(t.cell,"wj-row-field-hdr",!e)}t.panel==this.columnHeaders&&(i.valueFields.length<2||t.row<t.panel.rows.length-1)&&(t.cell.style.textAlign="");let s=null;t.panel==this.topLeftCells&&t.row==t.panel.rows.length-1&&this.allowDragging&wjcGrid.AllowDragging.Columns&&(s=!0),wjcCore.setAttribute(t.cell,"draggable",s);let l;switch(t.panel){case this.rowHeaders:l=i.rowFields[t.col%i.rowFields.length];break;case this.columnHeaders:l=i.columnFields[t.row];break;case this.cells:l=i.valueFields[t.col]}l&&l.isContentHtml&&(t.cell.innerHTML=t.cell.textContent);let r=i._getRowLevel(t.row),n=i._getColLevel(t.panel.columns[t.col].binding);if(wjcCore.toggleClass(t.cell,"wj-aggregate",r>-1||n>-1),this._collapsibleSubtotals){if(t.panel==this.rowHeaders&&i._getShowRowTotals()==ShowTotals.Subtotals){let e=this.getMergedRange(t.panel,t.row,t.col,!1)||t.range;t.col<i.rowFields.length-1&&e.rowSpan>1&&(t.cell.innerHTML=this._getCollapsedGlyph(this._getRowCollapsed(e))+t.cell.innerHTML)}if(t.panel==this.columnHeaders&&i._getShowColTotals()==ShowTotals.Subtotals){let e=this.getMergedRange(t.panel,t.row,t.col,!1)||t.range;t.row<i.columnFields.length-1&&e.columnSpan>1&&(t.cell.innerHTML=this._getCollapsedGlyph(this._getColCollapsed(e))+t.cell.innerHTML)}}if(t.panel==this.topLeftCells&&this.showRowFieldSort&&t.col<i.rowFields.length&&t.row==this._getSortRowIndex()&&(l=i.rowFields[t.col],wjcCore.toggleClass(t.cell,"wj-sort-asc",!l.descending),wjcCore.toggleClass(t.cell,"wj-sort-desc",l.descending),t.cell.innerHTML+=' <span class="wj-glyph-'+(l.descending?"down":"up")+'"></span>'),this._centerVert&&t.cell.hasChildNodes&&(t.panel==this.rowHeaders||t.panel==this.columnHeaders)){let e=wjcCore.createElement('<div style="display:table-cell;vertical-align:middle"></div>');this._docRange||(this._docRange=document.createRange()),this._docRange.selectNodeContents(t.cell),this._docRange.surroundContents(e),wjcCore.setCss(t.cell,{display:"table",tableLayout:"fixed",paddingTop:0,paddingBottom:0})}}_getCollapsedGlyph(e){return'<div style="display:inline-block;cursor:pointer" '+PivotGrid._WJA_COLLAPSE+'><span class="wj-glyph-'+(e?"plus":"minus")+'"></span></div>&nbsp'}_mousedown(e){if(e.defaultPrevented||0!=e.button)this._htDown=null;else if(this._htDown=this.hitTest(e),null!=wjcCore.closest(e.target,"["+PivotGrid._WJA_COLLAPSE+"]")&&null!=this._htDown.panel){let t,i=this._htDown.range;switch(this._htDown.panel.cellType){case wjcGrid.CellType.RowHeader:t=this._getRowCollapsed(i),e.shiftKey||e.ctrlKey?this._collapseRowsToLevel(i.col+(t?2:1)):this._setRowCollapsed(i,!t);break;case wjcGrid.CellType.ColumnHeader:t=this._getColCollapsed(i),e.shiftKey||e.ctrlKey?this._collapseColsToLevel(i.row+(t?2:1)):this._setColCollapsed(i,!t)}this._htDown=null,e.preventDefault()}}_mouseup(e){if(!this._htDown||e.defaultPrevented||"col-resize"==this.hostElement.style.cursor)return;let t=this.hitTest(e);if(this._htDown.panel!=t.panel||!t.range.equals(this._htDown.range))return;let i=this._ng,s=this.topLeftCells;if(t.panel==s&&t.row==s.rows.length-1&&t.col>-1){if(this.allowSorting&&t.panel.columns[t.col].allowSorting&&!i.isUpdating){let e=new wjcGrid.CellRangeEventArgs(t.panel,t.range);if(this.onSortingColumn(e)){i.pivotView.sortDescriptions.clear();let s=i.rowFields[t.col];s.descending=!s.descending,this.onSortedColumn(e)}}e.preventDefault()}}_dblclick(e){if(!e.defaultPrevented&&this._showDetailOnDoubleClick){let e=this._htDown;if(e&&e.panel==this.cells){let t=this._ng;t&&t.fields.length>0&&(t.fields[0]instanceof CubePivotField||this.showDetail(e.row,e.col))}}}_getRowLevel(e){return this._ng._getRowLevel(e)}_getGroupedRows(e){let t,i,s=this._getRowLevel.bind(this),l=e.col+1;if(this._ng.totalsBeforeData){for(i=e.row;i<this.rows.length-1;i++){let e=s(i+1);if(e>-1&&e<=l)break}for(t=i;t>0&&s(t)!=l;t--);}else{for(t=e.row;t>0;t--){let e=s(t-1);if(e>-1&&e<=l)break}for(i=t;i<this.rows.length-1&&s(i)!=l;i++);}return s(t)==l&&t++,s(i)==l&&i--,wjcCore.assert(i>=t,"group end < start?"),i>=t?new wjcGrid.CellRange(t,e.col,i,e.col2):e}_toggleRowCollapsed(e){this._setRowCollapsed(e,!this._getRowCollapsed(e))}_getRowCollapsed(e){e=this._getGroupedRows(e);let t=this._ng.totalsBeforeData?e.row-1:e.row2+1,i=this.rows[t]||this.rows[e.row],s=i?i.dataItem[_PivotKey._ROW_KEY_NAME]:null;return!!s&&this._collapsedKeys[s.toString()]}_setRowCollapsed(e,t){e=this._getGroupedRows(e);let i=this._ng.totalsBeforeData?e.row-1:e.row2+1,s=this.rows[i]||this.rows[e.row],l=s?s.dataItem[_PivotKey._ROW_KEY_NAME]:null;l&&(this._collapsedKeys[l.toString()]=t),this.deferUpdate(()=>{for(let i=e.row;i<=e.row2;i++)this.rows[i].visible=!t;if(s&&(s.visible=!0),!t){let t=this._getRowLevel(i),s=[];for(let i=e.row;i<=e.row2;i++)if(this._getRowLevel(i)>-1){let l=this._getGroupedRows(new wjcGrid.CellRange(i,t));wjcCore.assert(l.row>=e.row&&l.row2<=e.row2,"child range overflow"),s.push(l),i++}s.forEach(e=>{let t=this._getRowCollapsed(e);this._setRowCollapsed(e,t)})}})}_collapseRowsToLevel(e){e>=this._ng.rowFields.length&&(e=-1),this.deferUpdate(()=>{for(let t=0;t<this.rows.length;t++){let i=this._getRowLevel(t);if(i>0){let s=this.rows[t].dataItem[_PivotKey._ROW_KEY_NAME];this._collapsedKeys[s.toString()]=e>0&&i>=e}if(e<0)this.rows[t].visible=!0;else{let s=i>-1&&i<=e;s||(this._ng.totalsBeforeData?0==t&&(s=!0):t==this.rows.length-1&&(s=!0)),this.rows[t].visible=s}}})}_getColLevel(e){return this._ng._getColLevel(this.columns[e].binding)}_getGroupedCols(e){let t,i=this._getColLevel.bind(this),s=e.row+1,l=e.col;if(this._ng.totalsBeforeData)for(l=e.col2;l<this.columns.length&&i(l)==s;l++);for(;l>0;l--){let e=i(l-1);if(e>-1&&e<=s)break}for(t=l;t<this.columns.length-1;t++){let e=i(t+1);if(e>-1&&e<=s)break}return i(l)==s&&l++,i(t)==s&&t--,wjcCore.assert(t>=l,"group end < start?"),t>=l?new wjcGrid.CellRange(e.row,l,e.row2,t):e}_toggleColCollapsed(e){this._setColCollapsed(e,!this._getColCollapsed(e))}_getColCollapsed(e){e=this._getGroupedCols(e);let t=this._ng,i=t.totalsBeforeData?e.col-t.valueFields.length:e.col2+1,s=this.columns[i],l=s?s.binding:null;return!!l&&this._collapsedKeys[l.toString()]}_setColCollapsed(e,t){e=this._getGroupedCols(e);let i=this._ng,s=i.totalsBeforeData?e.col-i.valueFields.length:e.col2+1,l=this.columns[s],r=l?l.binding:null;r&&(this._collapsedKeys[r.toString()]=t),this.deferUpdate(()=>{for(let t=1;t<=i.valueFields.length;t++)this.columns[i.totalsBeforeData?e.col-t:e.col2+t].visible=!0;for(let i=e.col;i<=e.col2;i++)this.columns[i].visible=!t;if(!t){let t=this._getColLevel(s),l=[];for(let s=e.col;s<=e.col2;s++)if(this._getColLevel(s)>-1){let r=this._getGroupedCols(new wjcGrid.CellRange(t,s));wjcCore.assert(r.col>=e.col&&r.col2<=e.col2,"child range overflow"),l.push(r),s+=i.valueFields.length-1}l.forEach(e=>{let t=this._getColCollapsed(e);this._setColCollapsed(e,t)})}})}_collapseColsToLevel(e){e>=this._ng.columnFields.length&&(e=-1),this.deferUpdate(()=>{for(let t=0;t<this.columns.length;t++){let i=this._getColLevel(t);if(i>0){let s=this._ng._getKey(this.columns[t].binding);this._collapsedKeys[s.toString()]=e>0&&i>=e}if(e<0)this.columns[t].visible=!0;else{let s=i>-1&&i<=e;this.columns[t].visible=s}}})}};PivotGrid._WJA_COLLAPSE="wj-pivot-collapse";export class DetailDialog extends wjcInput.Popup{constructor(e,t){super(e,null);let i=this.getTemplate();this.applyTemplate("wj-control wj-detaildialog",i,{_sCnt:"sp-cnt",_dSummary:"div-summary",_dGrid:"div-grid",_btnOK:"btn-ok",_gHdr:"g-hdr"});let s=wjcCore.culture.olap.DetailDialog;this._gHdr.textContent=s.header,this._btnOK.textContent=s.ok,this._g=new wjcGrid.FlexGrid(this._dGrid,{isReadOnly:!0}),this.initialize(t)}showDetail(e,t){let i=e.getDetailView(t.row,t.col);this._g.itemsSource=i;let s=wjcCore.tryCast(i,"IPagedCollectionView");this._updateDetailCount(s?s.totalItemCount:i.items.length),i.collectionChanged.addHandler(()=>{this._updateDetailCount(i.items.length)});let l=e.engine,r=wjcCore.culture.olap.DetailDialog,n="",o=e.rows[t.row].dataItem[_PivotKey._ROW_KEY_NAME];this._rowHdr=wjcCore.escapeHtml(this._getHeader(o)),this._rowHdr&&(n+=r.row+": <b>"+this._rowHdr+"</b><br>");let a=l._getKey(e.columns[t.col].binding);this._colHdr=wjcCore.escapeHtml(this._getHeader(a)),this._colHdr&&(n+=r.col+": <b>"+this._colHdr+"</b><br>");let h=l.valueFields,d=h[t.col%h.length],c=e.getCellData(t.row,t.col,!0);this._cellHdr=wjcCore.escapeHtml(d.header),this._cellValue=wjcCore.escapeHtml(c),n+=this._cellHdr+": <b>"+this._cellValue+"</b>",this._dSummary.innerHTML=n}get rowHeader(){return this._rowHdr}get columnHeader(){return this._colHdr}get cellHeader(){return this._cellHdr}get cellValue(){return this._cellValue}get detailCount(){return this._detailCount}_updateDetailCount(e){let t=wjcCore.culture.olap.DetailDialog;this._sCnt.textContent=wjcCore.format(1==e?t.item:t.items,{cnt:e}),this._detailCount=e}_getHeader(e){if(e&&e.values&&e.values.length){let t=[];for(let i=0;i<e.values.length;i++)t.push(e.getValue(i,!0));return t.join(" - ")}return null}};DetailDialog.controlTemplate='<div><div class="wj-dialog-header"><span wj-part="g-hdr">Detail View:</span> <span wj-part="sp-cnt"></span></div><div class="wj-dialog-body"><div wj-part="div-summary" class="wj-summary"></div><div wj-part="div-grid"></div></div><div class="wj-dialog-footer"><button wj-part="btn-ok"class="wj-hide wj-btn">OK</button>&nbsp;&nbsp;</div></div>';export var PivotChartType;!function(e){e[e.Column=0]="Column",e[e.Bar=1]="Bar",e[e.Scatter=2]="Scatter",e[e.Line=3]="Line",e[e.Area=4]="Area",e[e.Pie=5]="Pie"}(PivotChartType||(PivotChartType={}));export var LegendVisibility;!function(e){e[e.Always=0]="Always",e[e.Never=1]="Never",e[e.Auto=2]="Auto"}(LegendVisibility||(LegendVisibility={}));export class PivotChart extends wjcCore.Control{constructor(e,t){super(e),this._chartType=PivotChartType.Column,this._showHierarchicalAxes=!0,this._showTotals=!1,this._showTitle=!0,this._showLegend=LegendVisibility.Always,this._legendPosition=wjcChart.Position.Right,this._maxSeries=PivotChart.MAX_SERIES,this._maxPoints=PivotChart.MAX_POINTS,this._stacking=wjcChart.Stacking.None,this._colItms=[],this._dataItms=[],this._lblsSrc=[],this._grpLblsSrc=[],wjcCore.addClass(this.hostElement,"wj-pivotchart"),this._isPieChart()?this._createFlexPie():this._createFlexChart(),super.initialize(t)}_getProductInfo(){return"D6F4,PivotChart"}get engine(){return this._ng}get itemsSource(){return this._itemsSource}set itemsSource(e){if(e&&this._itemsSource!==e){let t=this._itemsSource;e instanceof PivotPanel?e=e.engine.pivotView:e instanceof PivotEngine&&(e=e.pivotView),this._itemsSource=wjcCore.asCollectionView(e),this._onItemsSourceChanged(t)}}get chartType(){return this._chartType}set chartType(e){if((e=wjcCore.asEnum(e,PivotChartType))!=this._chartType){var t=this._chartType;this._chartType=e,this._changeChartType(),e!==PivotChartType.Bar&&t!==PivotChartType.Bar||this._updatePivotChart()}}get showHierarchicalAxes(){return this._showHierarchicalAxes}set showHierarchicalAxes(e){e!=this._showHierarchicalAxes&&(this._showHierarchicalAxes=wjcCore.asBoolean(e,!0),!this._isPieChart()&&this._flexChart&&this._updateFlexChart(this._dataItms,this._lblsSrc,this._grpLblsSrc))}get showTotals(){return this._showTotals}set showTotals(e){e!=this._showTotals&&(this._showTotals=wjcCore.asBoolean(e,!0),this._updatePivotChart())}get showTitle(){return this._showTitle}set showTitle(e){e!=this._showTitle&&(this._showTitle=wjcCore.asBoolean(e,!0),this._updatePivotChart())}get showLegend(){return this._showLegend}set showLegend(e){(e=wjcCore.asEnum(e,LegendVisibility))!=this.showLegend&&(this._showLegend=e,this._updatePivotChart())}get legendPosition(){return this._legendPosition}set legendPosition(e){(e=wjcCore.asEnum(e,wjcChart.Position))!=this.legendPosition&&(this._legendPosition=e,this._updatePivotChart())}get stacking(){return this._stacking}set stacking(e){(e=wjcCore.asEnum(e,wjcChart.Stacking))!=this._stacking&&(this._stacking=e,this._flexChart&&(this._flexChart.stacking=this._stacking,this._updatePivotChart()))}get maxSeries(){return this._maxSeries}set maxSeries(e){e!=this._maxSeries&&(this._maxSeries=wjcCore.asNumber(e),this._updatePivotChart())}get maxPoints(){return this._maxPoints}set maxPoints(e){e!=this._maxPoints&&(this._maxPoints=wjcCore.asNumber(e),this._updatePivotChart())}get flexChart(){return this._flexChart}get flexPie(){return this._flexPie}get header(){return this._header}set header(e){e!=this._header&&(this._header=wjcCore.asString(e,!0),this.invalidate())}get footer(){return this._footer}set footer(e){e!=this._footer&&(this._footer=wjcCore.asString(e,!0),this.invalidate())}get headerStyle(){return this._headerStyle}set headerStyle(e){e!=this._headerStyle&&(this._headerStyle=e,this.invalidate())}get footerStyle(){return this._footerStyle}set footerStyle(e){e!=this._footerStyle&&(this._footerStyle=e,this.invalidate())}refresh(e=!0){super.refresh(e),this._isPieChart()?this._flexPie&&this._flexPie.refresh(e):this._flexChart&&this._flexChart.refresh(e),this._updatePivotChart()}saveImageToDataUrl(e,t){this._isPieChart()?this._flexPie&&this._flexPie.saveImageToDataUrl(e,t):this._flexChart&&this._flexChart.saveImageToDataUrl(e,t)}saveImageToFile(e){this._isPieChart()?this._flexPie&&this._flexPie.saveImageToFile(e):this._flexChart&&this._flexChart.saveImageToFile(e)}_onItemsSourceChanged(e){this._ng&&this._ng.updatedView.removeHandler(this._updatePivotChart,this),e&&e.collectionChanged.removeHandler(this._updatePivotChart,this);let t=this._itemsSource;this._ng=t instanceof PivotCollectionView?t.engine:null,this._ng&&this._ng.updatedView.addHandler(this._updatePivotChart,this),this._itemsSource&&this._itemsSource.collectionChanged.addHandler(this._updatePivotChart,this),this._updatePivotChart()}_createFlexChart(){let e=document.createElement("div");this.hostElement.appendChild(e),this._flexChart=new wjcChart.FlexChart(e),this._flexChart._bindingSeparator=null,this._flexChart.legend.position=wjcChart.Position.Right,this._flexChart.bindingX=_PivotKey._ROW_KEY_NAME,this._flexChart.stacking=this._stacking,this._flexChart.tooltip.content=(e=>{let t=e.name?"<b>"+e.name+"</b> <br/>":"";return t+=this._getLabel(e.x)+" "+this._getValue(e)}),this._flexChart.hostElement.style.visibility="hidden"}_createFlexPie(){let e=document.createElement("div");this.hostElement.appendChild(e),this._colMenu=new wjcInput.Menu(e),this._colMenu.displayMemberPath="text",this._colMenu.selectedValuePath="prop",this._colMenu.hostElement.style.visibility="hidden";let t=document.createElement("div");this.hostElement.appendChild(t),this._flexPie=new wjcChart.FlexPie(t),this._flexPie.bindingName=_PivotKey._ROW_KEY_NAME,this._flexPie.tooltip.content=(e=>"<b>"+this._getLabel(this._dataItms[e.pointIndex][_PivotKey._ROW_KEY_NAME])+"</b> <br/>"+this._getValue(e)),this._flexPie.rendering.addHandler(this._updatePieInfo,this)}_updatePivotChart(){if(!this._ng||!this._ng.pivotView)return;let e,t=[],i=[],s=[],l=0,r=this._ng.pivotView,n=this._ng.rowFields;for(let o=0;o<r.items.length;o++){let a=r.items[o],h=a.$rowKey;if(0==o&&this._getColumns(a),t.length>=this._maxPoints)break;if(!this._isTotalRow(a[_PivotKey._ROW_KEY_NAME])){t.push(a),i.push({value:t.length-1,text:this._getLabel(a[_PivotKey._ROW_KEY_NAME])});for(let i=0;i<n.length;i++)if(s.length<=i&&s.push([]),this._getMergeIndex(h,e)<i){l=s[i].length-1;let e=s[i][l];if(0===l&&i<n.length-1&&(e.value=(e.width-1)/2),l>0&&i<n.length-1){let t=this._getOffsetWidth(s[i]);e.value=t+(e.width-1)/2}s[i].push({value:t.length-1,text:h.getValue(i,!0),width:1})}else l=s[i].length-1,s[i][l].width++;e=h}}for(let e=0;e<n.length;e++)e<s.length&&(l=s[e].length-1,s[e][l].value=this._getOffsetWidth(s[e])+(s[e][l].width-1)/2);this._dataItms=t,this._lblsSrc=i,this._grpLblsSrc=s,this._updateFlexChartOrPie()}_updateFlexChartOrPie(){let e=this._isPieChart();!e&&this._flexChart?this._updateFlexChart(this._dataItms,this._lblsSrc,this._grpLblsSrc):e&&this._flexPie&&this._updateFlexPie(this._dataItms,this._lblsSrc)}_updateFlexChart(e,t,i){let s,l=this._flexChart,r=l?l.hostElement:null;if(this._ng&&l&&r){if(l.beginUpdate(),l.itemsSource=e,this._createSeries(),l.series&&l.series.length>0&&e.length>0?r.style.visibility="visible":r.style.visibility="hidden",l.header=this.header||this._getChartTitle(),this.headerStyle&&(l.headerStyle=this.headerStyle),this.footer&&(l.footer=this.footer),this.footerStyle&&(l.footerStyle=this.footerStyle),this._isRotatedChart()){if(this._showHierarchicalAxes&&i.length>0){if(l.axisY.itemsSource=i[i.length-1],l.axisX.labelAngle=void 0,i.length>=2)for(let e=i.length-2;e>=0;e--)this._createGroupAxes(i[e])}else l.axisY.labelAngle=void 0,l.axisY.itemsSource=t;l.axisX.itemsSource=void 0}else{if(this._showHierarchicalAxes&&i.length>0){if(l.axisX.itemsSource=i[i.length-1],i.length>=2)for(let e=i.length-2;e>=0;e--)this._createGroupAxes(i[e])}else l.axisX.labelAngle=void 0,l.axisX.itemsSource=t;l.axisY.itemsSource=void 0}l.axisX.labelPadding=6,l.axisY.labelPadding=6,this._isRotatedChart()?(s=l.axisX,l.axisY.reversed=!0):(s=l.axisY,l.axisY.reversed=!1),l.stacking!==wjcChart.Stacking.Stacked100pc&&this._ng.valueFields.length>0&&this._ng.valueFields[0].format?s.format=this._ng.valueFields[0].format:s.format="",l.legend.position=this._getLegendPosition(),l.endUpdate()}}_updateFlexPie(e,t){let i=this._flexPie,s=i?i.hostElement:null,l=this._colMenu;if(!this._ng||!i||!s)return;this._colItms.length>0&&e.length>0?s.style.visibility="visible":s.style.visibility="hidden",i.beginUpdate(),i.itemsSource=e,i.bindingName=_PivotKey._ROW_KEY_NAME,this._colItms&&this._colItms.length>0&&(i.binding=this._colItms[0].prop),i.header=this.header||this._getChartTitle(),this.headerStyle&&(i.headerStyle=this.headerStyle),this.footer&&(i.footer=this.footer),this.footerStyle&&(i.footerStyle=this.footerStyle),i.legend.position=this._getLegendPosition(),i.endUpdate();let r=this._getTitle(this._ng.columnFields);""!==r&&(r="<b>"+r+": </b>"),this._colItms&&this._colItms.length>1&&e.length>0?(l.hostElement.style.visibility="visible",l.header=r+this._colItms[0].text,l.itemsSource=this._colItms,l.command={executeCommand:e=>{let t=l.selectedItem;l.header=r+t.text,i.binding=t.prop}},l.selectedIndex=0,l.invalidate(),l.listBox.invalidate()):l.hostElement.style.visibility="hidden"}_getLegendPosition(){let e=this.legendPosition;if(this.showLegend==LegendVisibility.Never)e=wjcChart.Position.None;else if(this.showLegend==LegendVisibility.Auto&&this.flexChart&&this.flexChart.series){let t=0;this.flexChart.series.forEach(e=>{let i=e.visibility;e.name&&i!=wjcChart.SeriesVisibility.Hidden&&i!=wjcChart.SeriesVisibility.Plot&&t++}),t<2&&(e=wjcChart.Position.None)}return e}_createSeries(){this._flexChart&&(this._flexChart.series.length=0);let e=1==this._ng.valueFields.length;for(let t=0;t<this._colItms.length;t++){let i=new wjcChart.Series,s=this._colItms[t].prop,l=this._colItms[t].text;if(e){let e=l.lastIndexOf(";");e>-1&&(l=l.substr(0,e))}i.binding=s,i.name=l,this._flexChart.series.push(i)}}_getColumns(e){let t,i,s=0;if(e){this._colItms=[];for(let l in e)e.hasOwnProperty(l)&&l!==_PivotKey._ROW_KEY_NAME&&s<this._maxSeries&&this._isValidColumn(l)&&(t=this._ng._getKey(l),i=this._getLabel(t),this._colItms.push({prop:l,text:this._getLabel(t)}),s++)}}_createGroupAxes(e){let t,i=this._flexChart,s=this._isRotatedChart()?i.axisY:i.axisX;if(!e)return;(t=new wjcChart.Axis).labelAngle=0,t.labelPadding=6,t.position=this._isRotatedChart()?wjcChart.Position.Left:wjcChart.Position.Bottom,t.majorTickMarks=wjcChart.TickMark.None,t.itemsSource=e,t.reversed=s.reversed,t.itemFormatter=((i,s)=>{let l=.5*e.filter(function(e){return e.value==s.val})[0].width;if(this._isRotatedChart()){let e=t.reversed?-1:1,r=t.convert(s.val+l)+5*e,n=t.convert(s.val-l)-5*e,o=t._axrect.left+t._axrect.width-5;i.drawLine(o,r,o,n,PivotChart.HRHAXISCSS),i.drawLine(o,r,o+5,r,PivotChart.HRHAXISCSS),i.drawLine(o,n,o+5,n,PivotChart.HRHAXISCSS),i.drawLine(o,s.pos.y,o-5,s.pos.y,PivotChart.HRHAXISCSS)}else{let e=t.convert(s.val-l)+5,r=t.convert(s.val+l)-5,n=t._axrect.top;i.drawLine(e,n,r,n,PivotChart.HRHAXISCSS),i.drawLine(e,n,e,n-5,PivotChart.HRHAXISCSS),i.drawLine(r,n,r,n-5,PivotChart.HRHAXISCSS),i.drawLine(s.pos.x,n,s.pos.x,n+5,PivotChart.HRHAXISCSS)}return s}),t.min=s.actualMin,t.max=s.actualMax,s.rangeChanged.addHandler(function(){isNaN(t.min)&&isNaN(s.actualMin)||t.min==s.actualMin||(t.min=s.actualMin),isNaN(t.max)&&isNaN(s.actualMax)||t.max==s.actualMax||(t.max=s.actualMax)});let l=new wjcChart.Series;l.visibility=wjcChart.SeriesVisibility.Hidden,this._isRotatedChart()?l.axisY=t:l.axisX=t,i.series.push(l)}_updateFlexPieBinding(){this._flexPie.binding=this._colMenu.selectedValue,this._flexPie.refresh()}_updatePieInfo(){this._flexPie&&(this._flexPie._labels=this._flexPie._labels.map((e,t)=>this._lblsSrc[t].text))}_changeChartType(){let e=null;if(this.chartType===PivotChartType.Pie)this._flexPie||this._createFlexPie(),this._updateFlexPie(this._dataItms,this._lblsSrc),this._swapChartAndPie(!1);else{switch(this.chartType){case PivotChartType.Column:e=wjcChart.ChartType.Column;break;case PivotChartType.Bar:e=wjcChart.ChartType.Bar;break;case PivotChartType.Scatter:e=wjcChart.ChartType.Scatter;break;case PivotChartType.Line:e=wjcChart.ChartType.Line;break;case PivotChartType.Area:e=wjcChart.ChartType.Area}this._flexChart?"none"!==this._flexChart.hostElement.style.display&&e!==PivotChartType.Bar&&this._flexChart.chartType!==wjcChart.ChartType.Bar||this._updateFlexChart(this._dataItms,this._lblsSrc,this._grpLblsSrc):(this._createFlexChart(),this._updateFlexChart(this._dataItms,this._lblsSrc,this._grpLblsSrc)),this._flexChart.chartType=e,this._swapChartAndPie(!0)}}_swapChartAndPie(e){this._flexChart&&(this._flexChart.hostElement.style.display=e?"block":"none"),this._flexPie&&(this._flexPie.hostElement.style.display=e?"none":"block"),this._colMenu&&this._colMenu.hostElement&&(this._colMenu.hostElement.style.display=e?"none":"block",this._colMenu.hostElement.style.top="0",setTimeout(()=>{this._colMenu.hostElement.style.top=""},0))}_getLabel(e){let t="";if(!e||!e.values)return t;let i=e.valueFields?e.valueField:null;switch(e.values.length){case 0:i&&(t+=i.header);break;case 1:t+=e.getValue(0,!0),i&&(t+="; "+i.header);break;default:for(let i=0;i<e.values.length;i++)i>0&&(t+="; "),t+=e.getValue(i,!0);i&&(t+="; "+i.header)}return t}_getValue(e){let t=this._ng.valueFields,i=e.series?e.series.chart.series.indexOf(e.series):0,s=i<t.length?t[i].format:t.length?t[0].format:"";return s?wjcCore.Globalize.format(e.y,s):e._yfmt}_getChartTitle(){if(!this.showTitle||!this._ng.valueFields.length)return null;let e=this._ng,t=this._getTitle(e.valueFields),i=this._getTitle(e.rowFields),s=this._getTitle(e.columnFields),l=t,r=wjcCore.culture.olap.PivotChart;return t&&this._dataItms.length>0&&(i&&(l+=wjcCore.format(" {by} {rows}",{by:r.by,rows:i})),s&&(l+=wjcCore.format(" {and} {cols}",{and:i?r.and:r.by,cols:s}))),l}_getTitle(e){let t="";for(let i=0;i<e.length;i++)t.length>0&&(t+="; "),t+=e[i].header;return t}_isValidColumn(e){let t=e.split(";"),i=this._showTotals;return 0===this._ng.columnFields.length||(t&&2===t.length?i:!(!t||t.length-2!==this._ng.columnFields.length)&&!i)}_isTotalRow(e){return e.values.length<this._ng.rowFields.length}_isPieChart(){return this._chartType==PivotChartType.Pie}_isRotatedChart(){return!this._isPieChart()&&this._chartType==PivotChartType.Bar!==this._flexChart.rotated}_getMergeIndex(e,t){let i=-1;if(null!=e&&null!=t&&e.values.length==t.values.length&&e.values.length==e.fields.length&&t.values.length==t.fields.length)for(let s=0;s<e.values.length;s++){if(e.getValue(s,!0)!=t.getValue(s,!0))return i;i=s}return i}_getOffsetWidth(e){let t=0;if(e.length<=1)return t;for(let i=0;i<e.length-1;i++)t+=e[i].width;return t}};PivotChart.MAX_SERIES=100,PivotChart.MAX_POINTS=100,PivotChart.HRHAXISCSS="wj-hierarchicalaxes-line";export class Slicer extends wjcCore.Control{constructor(e,t){super(e,null,wjcCore.isIE()&&!wjcCore.isEdge()),this._mSel=!1,this._fldPropChangeBnd=this._fldPropChange.bind(this);let i=this.getTemplate();this.applyTemplate("wj-slicer wj-nocheck wj-control wj-content",i,{_root:"root",_divHdr:"div-hdr",_divHdrText:"div-hdr-text",_btnMSel:"btn-msel",_btnClear:"btn-clear"});let s=wjcCore.culture.olap.Slicer,l=new wjcCore.Tooltip;wjcCore.setAttribute(this._btnMSel,"aria-label",s.multiSelect),wjcCore.setAttribute(this._btnClear,"aria-label",s.clearFilter),l.setTooltip(this._btnMSel,s.multiSelect),l.setTooltip(this._btnClear,s.clearFilter),this.addEventListener(this._btnClear,"click",e=>{this._clear()}),this.addEventListener(this._btnMSel,"click",e=>{this.multiSelect=!this.multiSelect}),this.initialize(t)}get field(){return this._fld}set field(e){if(e!=this._fld){this._divListBox&&(this.removeEventListener(this._divListBox,"click"),wjcCore.removeChild(this._divListBox),this._divListBox=null,this._lbx.dispose(),this._lbx=null),this._edt&&(this._clear(),this._edt.dispose());let t=this._fld;if(t&&t.propertyChanged.removeHandler(this._fldPropChangeBnd),(t=this._fld=wjcCore.asType(e,PivotField,!0)).propertyChanged.addHandler(this._fldPropChangeBnd),t&&!t.isActive&&t.engine.filterFields.push(t),t){let e=document.createElement("div");this._edt=new wjcGridFilter.ValueFilterEditor(e,t.filter.valueFilter)}this._edt&&(this._divListBox=this._edt.hostElement.querySelector(".wj-listbox"),this._root.appendChild(this._divListBox),this._lbx=wjcCore.Control.getControl(this._divListBox),this._lbx.checkedItemsChanged.addHandler((e,i)=>{this.multiSelect||(this._mSel=!0,this._lbx.checkedItems=[this._lbx.selectedItem],this._mSel=!1),this._edt&&t&&(this._edt.updateFilter(),t.engine.invalidate())})),this._updateHeader(),wjcCore.isIE()&&!wjcCore.isEdge()&&this.refresh()}}get header(){return this._hdr}set header(e){e!=this._hdr&&(this._hdr=wjcCore.asString(e),this._updateHeader())}get showHeader(){return"none"!=this._divHdr.style.display}set showHeader(e){this._divHdr.style.display=wjcCore.asBoolean(e)?"":"none"}get showCheckboxes(){return!wjcCore.hasClass(this.hostElement,"wj-nocheck")}set showCheckboxes(e){wjcCore.toggleClass(this.hostElement,"wj-nocheck",!wjcCore.asBoolean(e))}get multiSelect(){return this._mSel}set multiSelect(e){this._mSel=wjcCore.asBoolean(e),wjcCore.toggleClass(this._btnMSel,"wj-state-active",this._mSel)}refresh(e=!0){wjcCore.isIE()&&!wjcCore.isEdge()&&this.hostElement&&wjcCore.setCss(this._lbx.hostElement,{height:this.hostElement.clientHeight-this._divHdr.offsetHeight}),super.refresh(e)}_fldPropChange(e,t){switch(t.propertyName){case"header":this._updateHeader();break;case"format":case"binding":e.filter.clear(),this._edt.updateEditor()}}_updateHeader(){let e=this._hdr;e||null==this._fld||(e=this._fld.header),this._divHdrText.textContent=e}_clear(){this._edt&&(this._edt.clearEditor(),this._edt.updateFilter(),this._fld.engine.invalidate())}};Slicer.controlTemplate='<div wj-part="root"><div wj-part="div-hdr" class="wj-header"><div wj-part="div-hdr-text"></div><button wj-part="btn-msel" class="wj-btn btn-msel" tabindex="-1"><span class="wj-glyph">&#8801;</span></button><button wj-part="btn-clear" class="wj-btn btn-clear" tabindex="-1"><span class="wj-glyph">&times;</span></button></div></div>';