/*
    *
    * 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/
    *
    */
import*as wjcCore from"wijmo/wijmo";import*as wjcXlsx from"wijmo/wijmo.xlsx";import*as wjcGrid from"wijmo/wijmo.grid";import*as wjcInput from"wijmo/wijmo.input";import*as wjcGridXlsx from"wijmo/wijmo.grid.xlsx";import*as wjcGridFilter from"wijmo/wijmo.grid.filter";var __glob="undefined"!=typeof window?window:self;import*as wjcSelfRef from"wijmo/wijmo.grid.sheet";var wjcSelf=wjcSelfRef||exports;__glob.wijmo=__glob.wijmo||{},__glob.wijmo.grid=__glob.wijmo.grid||{},__glob.wijmo.grid.sheet=wjcSelf;export class _CalcEngine{constructor(e){this._expressionCache={},this._idChars="$:!",this._functionTable={},this._cacheSize=0,this._tableRefStart=!1,this.unknownFunction=new wjcCore.Event,this._owner=e,this._buildSymbolTable(),this._registerAggregateFunction(),this._registerMathFunction(),this._registerLogicalFunction(),this._registerTextFunction(),this._registerDateFunction(),this._registLookUpReferenceFunction(),this._registFinacialFunction(),this._registAddressRelatedFunction()}onUnknownFunction(e,t){var o,i;if(t&&t.length>0){o=[];for(var l=0;l<t.length;l++)o[l]=t[l].evaluate(this._rowIndex,this._columnIndex)}if(i=new UnknownFunctionEventArgs(e,o),this.unknownFunction.raise(this,i),null!=i.value)return new _Expression(i.value);throw'The function "'+e+'" has not supported in FlexSheet yet.'}evaluate(e,t,o,i,l){var n;if(!this._owner.enableFormulas)return e;try{if(e&&e.length>1&&"="===e[0]){for(this._containsCellRef=!1,this._rowIndex=i,this._columnIndex=l,this._sheet=o||this._owner.selectedSheet,n=this._checkCache(e).evaluate(i,l,o);n instanceof _Expression;)n=n.evaluate(i,l,o);return t&&wjcCore.isPrimitive(n)?wjcCore.Globalize.format(n,t):n}return e||""}catch(e){return"Error: "+e}}addCustomFunction(e,t,o,i){var l=this;e=e.toLowerCase(),this._functionTable[e]=new _FunctionDefinition(e=>{var o,i=[];if(e&&e.length>0)for(var n=0;n<e.length;n++)o=e[n],i[n]=o instanceof _CellRangeExpression?o.cells:o.evaluate(l._rowIndex,l._columnIndex);return t.apply(l,i)},i,o)}addFunction(e,t,o,i){var l=this;e=e.toLowerCase(),this._functionTable[e]=new _FunctionDefinition(e=>{var o,i=[];if(e&&e.length>0)for(var n=0;n<e.length;n++)o=e[n],i[n]=o instanceof _CellRangeExpression?o.getValuseWithTwoDimensions():[[o.evaluate(l._rowIndex,l._columnIndex)]];return t.apply(l,i)},i,o)}_clearExpressionCache(){this._expressionCache=null,this._expressionCache={},this._cacheSize=0}_parse(e){return this._expression=e,this._expressLength=e?e.length:0,this._pointer=0,this._expressLength>0&&"="===this._expression[0]&&this._pointer++,this._parseExpression()}_buildSymbolTable(){this._tokenTable||(this._tokenTable={},this._addToken("+",_TokenID.ADD,_TokenType.ADDSUB),this._addToken("-",_TokenID.SUB,_TokenType.ADDSUB),this._addToken("(",_TokenID.OPEN,_TokenType.GROUP),this._addToken(")",_TokenID.CLOSE,_TokenType.GROUP),this._addToken("*",_TokenID.MUL,_TokenType.MULDIV),this._addToken(",",_TokenID.COMMA,_TokenType.GROUP),this._addToken(".",_TokenID.PERIOD,_TokenType.GROUP),this._addToken("/",_TokenID.DIV,_TokenType.MULDIV),this._addToken("\\",_TokenID.DIVINT,_TokenType.MULDIV),this._addToken("=",_TokenID.EQ,_TokenType.COMPARE),this._addToken(">",_TokenID.GT,_TokenType.COMPARE),this._addToken("<",_TokenID.LT,_TokenType.COMPARE),this._addToken("^",_TokenID.POWER,_TokenType.POWER),this._addToken("<>",_TokenID.NE,_TokenType.COMPARE),this._addToken(">=",_TokenID.GE,_TokenType.COMPARE),this._addToken("<=",_TokenID.LE,_TokenType.COMPARE),this._addToken("&",_TokenID.CONCAT,_TokenType.CONCAT),this._addToken("[",_TokenID.OPEN,_TokenType.SQUAREBRACKETS),this._addToken("]",_TokenID.CLOSE,_TokenType.SQUAREBRACKETS))}_registerAggregateFunction(){var e=this;e._functionTable.sum=new _FunctionDefinition((t,o)=>e._getAggregateResult(wjcCore.Aggregate.Sum,t,o)),e._functionTable.average=new _FunctionDefinition((t,o)=>e._getAggregateResult(wjcCore.Aggregate.Avg,t,o)),e._functionTable.max=new _FunctionDefinition((t,o)=>e._getAggregateResult(wjcCore.Aggregate.Max,t,o)),e._functionTable.min=new _FunctionDefinition((t,o)=>e._getAggregateResult(wjcCore.Aggregate.Min,t,o)),e._functionTable.var=new _FunctionDefinition((t,o)=>e._getAggregateResult(wjcCore.Aggregate.Var,t,o)),e._functionTable.varp=new _FunctionDefinition((t,o)=>e._getAggregateResult(wjcCore.Aggregate.VarPop,t,o)),e._functionTable.stdev=new _FunctionDefinition((t,o)=>e._getAggregateResult(wjcCore.Aggregate.Std,t,o)),e._functionTable.stdevp=new _FunctionDefinition((t,o)=>e._getAggregateResult(wjcCore.Aggregate.StdPop,t,o)),e._functionTable.count=new _FunctionDefinition((t,o)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.Count,t,o)),e._functionTable.counta=new _FunctionDefinition((t,o)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.CountA,t,o)),e._functionTable.countblank=new _FunctionDefinition((t,o)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.ConutBlank,t,o)),e._functionTable.countif=new _FunctionDefinition((t,o)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.CountIf,t,o),2,2),e._functionTable.countifs=new _FunctionDefinition((t,o)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.CountIfs,t,o),254,2),e._functionTable.sumif=new _FunctionDefinition((t,o)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.SumIf,t,o),3,2),e._functionTable.sumifs=new _FunctionDefinition((t,o)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.SumIfs,t,o),255,2),e._functionTable.rank=new _FunctionDefinition((t,o)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.Rank,t,o),3,2),e._functionTable.product=new _FunctionDefinition((t,o)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.Product,t,o),255,1),e._functionTable.subtotal=new _FunctionDefinition((t,o)=>e._handleSubtotal(t,o),255,2),e._functionTable.dcount=new _FunctionDefinition((t,o)=>e._handleDCount(t,o),3,3),e._functionTable.sumproduct=new _FunctionDefinition((t,o)=>e._getSumProduct(t,o),255,1)}_registerMathFunction(){var e=this,t=["abs","acos","asin","atan","cos","exp","ln","sin","sqrt","tan"],o=["ceiling","floor"],i=["round","rounddown","roundup"];e._functionTable.pi=new _FunctionDefinition(()=>Math.PI,0,0),e._functionTable.rand=new _FunctionDefinition(()=>Math.random(),0,0),e._functionTable.power=new _FunctionDefinition((t,o)=>Math.pow(_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,o),_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o)),2,2),e._functionTable.atan2=new _FunctionDefinition((t,o)=>{var i=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,o),l=_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o);if(0===i&&0===l)throw"The x number and y number can't both be zero for the atan2 function";return Math.atan2(l,i)},2,2),e._functionTable.mod=new _FunctionDefinition((t,o)=>{let i=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,o),l=_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o),n=Math.abs(i)%Math.abs(l);return l<0&&(n=-n),n},2,2),e._functionTable.trunc=new _FunctionDefinition((t,o)=>{var i,l,n,s=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,o),r=2===t.length?_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o):0;if(0===r?(n="n0",l=s>=0?Math.floor(s):Math.ceil(s)):(n="n"+((r=r>0?Math.floor(r):Math.ceil(r))>0?r:0),i=Math.pow(10,r),l=s>=0?Math.floor(s*i)/i:Math.ceil(s*i)/i),null!=l)return{value:l,format:n}},2,1),o.forEach(t=>{e._functionTable[t]=new _FunctionDefinition((o,i)=>{var l,n,s,r=_Expression.toNumber(o[0],e._rowIndex,e._columnIndex,i),a=2===o.length?_Expression.toNumber(o[1],e._rowIndex,e._columnIndex,i):1;if(isNaN(r))throw"Invalid Number!";if(isNaN(a))throw"Invalid Significance!";if(r>0&&a<0)throw"The significance has to be positive, if the number is positive.";if(0===r||0===a)return 0;if(l=a-Math.floor(a),n=1,0!==l)for(;l<1;)n*=10,l*=10;return s="ceiling"===t?Math.ceil(r/a):Math.floor(r/a),a*n*s/n},2,1)}),i.forEach(t=>{e._functionTable[t]=new _FunctionDefinition((o,i)=>{var l,n,s,r,a=_Expression.toNumber(o[0],e._rowIndex,e._columnIndex,i),h=_Expression.toNumber(o[1],e._rowIndex,e._columnIndex,i);if(0===h){switch(t){case"rounddown":l=a>=0?Math.floor(a):Math.ceil(a);break;case"roundup":l=a>=0?Math.ceil(a):Math.floor(a);break;case"round":r=a>=0?0:.1,l=Math.round(a-r);break;default:l=Math.floor(a)}n="n0"}else{switch(h=h>0?Math.floor(h):Math.ceil(h),s=Math.pow(10,h),t){case"rounddown":l=a>=0?Math.floor(a*s)/s:Math.ceil(a*s)/s;break;case"roundup":l=a>=0?Math.ceil(a*s)/s:Math.floor(a*s)/s;break;case"round":r=a>=0?0:1*s/10,l=Math.round(a*s-r)/s}n="n"+(h>0?h:0)}if(null!=l)return{value:l,format:n}},2,2)}),t.forEach(t=>{e._functionTable[t]=new _FunctionDefinition((o,i)=>"ln"===t?Math.log(_Expression.toNumber(o[0],e._rowIndex,e._columnIndex,i)):Math[t](_Expression.toNumber(o[0],e._rowIndex,e._columnIndex,i)),1,1)})}_registerLogicalFunction(){var e=this;e._functionTable.and=new _FunctionDefinition((t,o)=>{var i,l=!0;for(i=0;i<t.length&&(l=l&&_Expression.toBoolean(t[i],e._rowIndex,e._columnIndex,o));i++);return l},Number.MAX_VALUE,1),e._functionTable.or=new _FunctionDefinition((t,o)=>{var i,l=!1;for(i=0;i<t.length&&!(l=l||_Expression.toBoolean(t[i],e._rowIndex,e._columnIndex,o));i++);return l},Number.MAX_VALUE,1),e._functionTable.not=new _FunctionDefinition((t,o)=>!_Expression.toBoolean(t[0],e._rowIndex,e._columnIndex,o),1,1),e._functionTable.if=new _FunctionDefinition((t,o)=>3===t.length?_Expression.toBoolean(t[0],e._rowIndex,e._columnIndex,o)?t[1].evaluate(e._rowIndex,e._columnIndex,o):t[2].evaluate(e._rowIndex,e._columnIndex,o):!!_Expression.toBoolean(t[0],e._rowIndex,e._columnIndex,o)&&t[1].evaluate(e._rowIndex,e._columnIndex,o),3,2),e._functionTable.true=new _FunctionDefinition(()=>!0,0,0),e._functionTable.false=new _FunctionDefinition(()=>!1,0,0)}_registerTextFunction(){var e=this;e._functionTable.char=new _FunctionDefinition((t,o)=>{var i,l="";for(i=0;i<t.length;i++)l+=String.fromCharCode(_Expression.toNumber(t[i],e._rowIndex,e._columnIndex,o));return l},Number.MAX_VALUE,1),e._functionTable.code=new _FunctionDefinition((t,o)=>{var i=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o);return i&&i.length>0?i.charCodeAt(0):-1},1,1),e._functionTable.concatenate=new _FunctionDefinition((t,o)=>{var i,l="";for(i=0;i<t.length;i++)l=l.concat(_Expression.toString(t[i],e._rowIndex,e._columnIndex,o));return l},Number.MAX_VALUE,1),e._functionTable.left=new _FunctionDefinition((t,o)=>{var i=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o),l=null==t[1]?1:Math.floor(_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o));return i&&i.length>0?i.slice(0,l):null},2,1),e._functionTable.right=new _FunctionDefinition((t,o)=>{var i=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o),l=null==t[1]?1:Math.floor(_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o));return i&&i.length>0?i.slice(-l):null},2,1),e._functionTable.find=new _FunctionDefinition((t,o)=>{var i,l=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o),n=_Expression.toString(t[1],e._rowIndex,e._columnIndex,o),s=null!=t[2]?wjcCore.asInt(_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,o)):0;return null!=n&&null!=l&&(i=!isNaN(s)&&s>0&&s<n.length?n.indexOf(l,s):n.indexOf(l))>-1?i+1:-1},3,2),e._functionTable.search=new _FunctionDefinition((t,o)=>{var i,l,n,s=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o),r=_Expression.toString(t[1],e._rowIndex,e._columnIndex,o),a=null!=t[2]?wjcCore.asInt(_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,o)):0;return null!=r&&null!=s&&(l=new RegExp(s,"i"),!isNaN(a)&&a>0&&a<r.length?(r=r.substring(a),i=a+1):i=1,(n=r.search(l))>-1)?n+i:-1},3,2),e._functionTable.len=new _FunctionDefinition((t,o)=>{var i=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o);return i?i.length:-1},1,1),e._functionTable.mid=new _FunctionDefinition((t,o)=>{var i=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o),l=Math.floor(_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o)),n=Math.floor(_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,o));return i&&i.length>0&&l>0?i.substr(l-1,n):null},3,3),e._functionTable.lower=new _FunctionDefinition((t,o)=>{var i=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o);return i&&i.length>0?i.toLowerCase():null},1,1),e._functionTable.upper=new _FunctionDefinition((t,o)=>{var i=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o);return i&&i.length>0?i.toUpperCase():null},1,1),e._functionTable.proper=new _FunctionDefinition((t,o)=>{var i=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o);return i&&i.length>0?i.replace(/\b[\w']+\b/g,e=>e&&e.length>0?e[0].toUpperCase()+e.substring(1).toLowerCase():e):null},1,1),e._functionTable.trim=new _FunctionDefinition((t,o)=>{var i=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o);return i&&i.length>0?i.trim():null},1,1),e._functionTable.replace=new _FunctionDefinition((t,o)=>{var i=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o),l=Math.floor(_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o)),n=Math.floor(_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,o)),s=_Expression.toString(t[3],e._rowIndex,e._columnIndex,o);return i&&i.length>0&&l>0?i.substring(0,l-1)+s+i.slice(l-1+n):null},4,4),e._functionTable.substitute=new _FunctionDefinition((t,o)=>{var i,l=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o),n=_Expression.toString(t[1],e._rowIndex,e._columnIndex,o),s=_Expression.toString(t[2],e._rowIndex,e._columnIndex,o),r=4===t.length?_Expression.toNumber(t[3],e._rowIndex,e._columnIndex,o):null,a=0;if(null!=r&&r<1||isNaN(r))throw"Invalid instance number.";return l&&l.length>0&&n&&n.length>0?(i=new RegExp(n,"g"),l.replace(i,e=>(a++,null!=r?(r=Math.floor(r),a===r?s:e):s))):null},4,3),e._functionTable.rept=new _FunctionDefinition((t,o)=>{var i,l=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o),n=Math.floor(_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o)),s="";if(l&&l.length>0&&n>0)for(i=0;i<n;i++)s=s.concat(l);return s},2,2),e._functionTable.text=new _FunctionDefinition((t,o)=>{var i,l=t[0].evaluate(e._rowIndex,e._columnIndex,o),n=_Expression.toString(t[1],e._rowIndex,e._columnIndex,o);if(!wjcCore.isPrimitive(l)&&l&&(l=l.value),wjcCore.isDate(l))n=n.replace(/\[\$\-.+\]/g,"").replace(/(\\)(.)/g,"$2").replace(/H+/g,e=>e.toLowerCase()).replace(/m+/g,e=>e.toUpperCase()).replace(/S+/g,e=>e.toLowerCase()).replace(/AM\/PM/gi,"tt").replace(/A\/P/gi,"t").replace(/\.000/g,".fff").replace(/\.00/g,".ff").replace(/\.0/g,".f").replace(/\\[\-\s,]/g,e=>e.substring(1)).replace(/Y+/g,e=>e.toLowerCase()).replace(/D+/g,e=>e.toLowerCase()).replace(/M+:?|:?M+/gi,e=>e.indexOf(":")>-1?e.toLowerCase():e).replace(/g+e/gi,e=>e.substring(0,e.length-1)+"yy");else{if(!wjcCore.isNumber(l))return l;if((i=n.match(/^(\d+)(\.\d+)?\E\+(\d+)(\.\d+)?$/))&&5===i.length)return e._parseToScientificValue(l,i[1],i[2],i[3],i[4]);/M{1,4}|d{1,4}|y{1,4}/.test(n)?l=new Date(1900,0,l-1):n&&(n=wjcXlsx.Workbook.fromXlsxFormat(n)[0])}if(wjcCore.isDate(l))switch(n){case"d":return l.getDate();case"M":return l.getMonth()+1;case"y":n="yy";break;case"yyy":n="yyyy"}return wjcCore.Globalize.format(l,n)},2,2),e._functionTable.value=new _FunctionDefinition((t,o)=>{var i,l=_Expression.toString(t[0],e._rowIndex,e._columnIndex,o);if((l=l.replace(/(\,\d{3})/g,e=>e.substring(1))).length>0){if(l[0]===wjcCore.culture.Globalize.numberFormat.currency.symbol)return+(l=l.substring(1));if("%"===l[l.length-1])return+(l=l.substring(0,l.length-1))/100}return i=+l,isNaN(i)?_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,o):i},1,1)}_registerDateFunction(){var e=this;e._functionTable.now=new _FunctionDefinition(()=>({value:new Date,format:"M/d/yyyy h:mm"}),0,0),e._functionTable.today=new _FunctionDefinition(()=>{var e=new Date;return{value:new Date(e.getFullYear(),e.getMonth(),e.getDate()),format:"M/d/yyyy"}},0,0),e._functionTable.year=new _FunctionDefinition((t,o)=>{var i=_Expression.toDate(t[0],e._rowIndex,e._columnIndex,o);return!wjcCore.isPrimitive(i)&&i?i.value:wjcCore.isDate(i)?i.getFullYear():1900},1,1),e._functionTable.month=new _FunctionDefinition((t,o)=>{var i=_Expression.toDate(t[0],e._rowIndex,e._columnIndex,o);return!wjcCore.isPrimitive(i)&&i?i.value:wjcCore.isDate(i)?i.getMonth()+1:1},1,1),e._functionTable.day=new _FunctionDefinition((t,o)=>{var i=_Expression.toDate(t[0],e._rowIndex,e._columnIndex,o);return!wjcCore.isPrimitive(i)&&i?i.value:wjcCore.isDate(i)?i.getDate():0},1,1),e._functionTable.hour=new _FunctionDefinition((t,o)=>{var i=t[0].evaluate(e._rowIndex,e._columnIndex,o);if(wjcCore.isNumber(i)&&!isNaN(i))return Math.floor(24*(i-Math.floor(i)));if(wjcCore.isDate(i))return i.getHours();if(i=_Expression.toDate(t[0],e._rowIndex,e._columnIndex,o),!wjcCore.isPrimitive(i)&&i&&(i=i.value),wjcCore.isDate(i))return i.getHours();throw"Invalid parameter."},1,1),e._functionTable.time=new _FunctionDefinition((t,o)=>{var i=t[0].evaluate(e._rowIndex,e._columnIndex,o),l=t[1].evaluate(e._rowIndex,e._columnIndex,o),n=t[2].evaluate(e._rowIndex,e._columnIndex,o);if(wjcCore.isNumber(i)&&wjcCore.isNumber(l)&&wjcCore.isNumber(n))return i%=24,l%=60,n%=60,{value:new Date(0,0,0,i,l,n),format:"h:mm tt"};throw"Invalid parameters."},3,3),e._functionTable.date=new _FunctionDefinition((t,o)=>{var i=t[0].evaluate(e._rowIndex,e._columnIndex,o),l=t[1].evaluate(e._rowIndex,e._columnIndex,o),n=t[2].evaluate(e._rowIndex,e._columnIndex,o);if(wjcCore.isNumber(i)&&wjcCore.isNumber(l)&&wjcCore.isNumber(n))return{value:new Date(i,l-1,n),format:"M/d/yyyy"};throw"Invalid parameters."},3,3),e._functionTable.datedif=new _FunctionDefinition((t,o)=>{var i,l,n,s,r,a=_Expression.toDate(t[0],e._rowIndex,e._columnIndex,o),h=_Expression.toDate(t[1],e._rowIndex,e._columnIndex,o),d=t[2].evaluate(e._rowIndex,e._columnIndex,o);if(!wjcCore.isPrimitive(a)&&a&&(a=a.value),!wjcCore.isPrimitive(h)&&h&&(h=h.value),wjcCore.isDate(a)&&wjcCore.isDate(h)&&wjcCore.isString(d)){if(i=a.getTime(),l=h.getTime(),i>l)throw"Start date is later than end date.";switch(n=h.getDate()-a.getDate(),s=h.getMonth()-a.getMonth(),r=h.getFullYear()-a.getFullYear(),d.toUpperCase()){case"Y":return s>0?r:s<0?r-1:n>=0?r:r-1;case"M":return n>=0?12*r+s:12*r+s-1;case"D":return(l-i)/864e5;case"YM":return(s=n>=0?12*r+s:12*r+s-1)%12;case"YD":return s>0?(new Date(a.getFullYear(),h.getMonth(),h.getDate()).getTime()-a.getTime())/864e5:s<0?(new Date(a.getFullYear()+1,h.getMonth(),h.getDate()).getTime()-a.getTime())/864e5:n>=0?n:(new Date(a.getFullYear()+1,h.getMonth(),h.getDate()).getTime()-a.getTime())/864e5;case"MD":return n>=0?n:n=new Date(h.getFullYear(),h.getMonth(),0).getDate()-new Date(h.getFullYear(),h.getMonth()-1,1).getDate()+1+n;default:throw"Invalid unit."}}throw"Invalid parameters."},3,3)}_registLookUpReferenceFunction(){var e=this;e._functionTable.column=new _FunctionDefinition((t,o,i,l)=>{var n;if(null==t)return l+1;if(n=t[0],(n=e._ensureNonFunctionExpression(n,o))instanceof _CellRangeExpression)return n.cells.col+1;throw"Invalid Cell Reference."},1,0),e._functionTable.columns=new _FunctionDefinition((t,o)=>{var i=t[0];if((i=e._ensureNonFunctionExpression(i,o))instanceof _CellRangeExpression)return i.cells.columnSpan;throw"Invalid Cell Reference."},1,1),e._functionTable.row=new _FunctionDefinition((t,o,i,l)=>{var n;if(null==t)return i+1;if(n=t[0],(n=e._ensureNonFunctionExpression(n,o))instanceof _CellRangeExpression)return n.cells.row+1;throw"Invalid Cell Reference."},1,0),e._functionTable.rows=new _FunctionDefinition((t,o)=>{var i=t[0];if((i=e._ensureNonFunctionExpression(i,o))instanceof _CellRangeExpression)return i.cells.rowSpan;throw"Invalid Cell Reference."},1,1),e._functionTable.choose=new _FunctionDefinition((t,o)=>{var i=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,o);if(isNaN(i))throw"Invalid index number.";if(i<1||i>=t.length)throw"The index number is out of the list range.";return i=Math.floor(i),t[i].evaluate(e._rowIndex,e._columnIndex,o)},255,2),e._functionTable.index=new _FunctionDefinition((t,o)=>{var i,l=t[0],n=_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o),s=null!=t[2]?_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,o):0;if(isNaN(n)||n<0)throw"Invalid Row Number.";if(isNaN(s)||s<0)throw"Invalid Column Number.";if((l=e._ensureNonFunctionExpression(l,o))instanceof _CellRangeExpression){if(i=l.cells,n>i.rowSpan||s>i.columnSpan)throw"Index is out of the cell range.";if(n>0&&s>0)return e._owner.getCellValue(i.topRow+n-1,i.leftCol+s-1,!0,o);if(0===n&&0===s)return l;if(0===n)return new _CellRangeExpression(new wjcGrid.CellRange(i.topRow,i.leftCol+s-1,i.bottomRow,i.leftCol+s-1),l.sheetRef,e._owner);if(0===s)return new _CellRangeExpression(new wjcGrid.CellRange(i.topRow+n-1,i.leftCol,i.topRow+n-1,i.rightCol),l.sheetRef,e._owner)}throw"Invalid Cell Reference."},4,2),e._functionTable.hlookup=new _FunctionDefinition((t,o)=>e._handleHLookup(t,o),4,3)}_registFinacialFunction(){var e=this;e._functionTable.rate=new _FunctionDefinition((t,o)=>({value:e._calculateRate(t,o),format:"p2"}),6,3)}_registAddressRelatedFunction(){let e=this;e._functionTable.indirect=new _FunctionDefinition((t,o)=>{let i,l,n,s,r,a,h,d,c=e._ensureNonFunctionExpression(t[0],o);if(c instanceof _CellRangeExpression?(i=c.cells,l=c.evaluate(i.row,i.col,o)):l=c.evaluate(e._rowIndex,e._columnIndex,o),wjcCore.isString(l)){if(2===(n=l.split("!")).length?(s=n[0].toLowerCase(),r=n[1].toLowerCase()):r=n[0].toLowerCase(),a=e._getDefinedName(r,s||e._sheet.name.toLowerCase()),o=o||e._owner.selectedSheet,a){if(a.sheetName&&a.sheetName.toLowerCase()!==o.name.toLowerCase())throw"Invalid Cell Reference.";l=a.value}if(h=e._getCellRange(l)){if(h.sheetRef){for(let t=0;t<e._owner.sheets.length;t++)if(e._owner.sheets[t].name.toLowerCase()===h.sheetRef.toLowerCase()){d=e._owner.sheets[t];break}}else d=e._owner.selectedSheet;if(d)return e._owner.getCellValue(h.cellRef.cellRange.row,h.cellRef.cellRange.col,!0,o)}}throw"Invalid Cell Reference."},2,1),e._functionTable.address=new _FunctionDefinition((t,o)=>{let i,l,n=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,o),s=_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,o),r=!1,a=!1;if(isNaN(n)||!wjcCore.isInt(n)||n<1||n>1048576)throw"Invalid row number.";if(isNaN(s)||!wjcCore.isInt(s)||s<1||s>16384)throw"Invalid column number.";if(null!=t[2]&&(i=_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,o),isNaN(i)||!wjcCore.isInt(i)||i<1||i>4))throw"Invalid absolute type.";return null!=t[4]&&(l=_Expression.toString(t[4],e._rowIndex,e._columnIndex,o)),null==i||1===i?(r=!0,a=!0):2===i?r=!0:3===i&&(a=!0),(null!=l?l+"!":"")+(a?"$":"")+e._numAlpha(s)+(r?"$":"")+n.toString()},5,2)}_addToken(e,t,o){var i=new _Token(e,t,o);this._tokenTable[e]=i}_parseExpression(){return this._getToken(),this._parseCompareOrConcat()}_parseCompareOrConcat(){for(var e,t,o=this._parseAddSub();this._token.tokenType===_TokenType.COMPARE||this._token.tokenType===_TokenType.CONCAT;)e=this._token,this._getToken(),t=this._parseAddSub(),o=new _BinaryExpression(e,o,t);return o}_parseAddSub(){for(var e,t,o=this._parseMulDiv();this._token.tokenType===_TokenType.ADDSUB;)e=this._token,this._getToken(),t=this._parseMulDiv(),o=new _BinaryExpression(e,o,t);return o}_parseMulDiv(){for(var e,t,o=this._parsePower();this._token.tokenType===_TokenType.MULDIV;)e=this._token,this._getToken(),t=this._parsePower(),o=new _BinaryExpression(e,o,t);return o}_parsePower(){for(var e,t,o=this._parseUnary();this._token.tokenType===_TokenType.POWER;)e=this._token,this._getToken(),t=this._parseUnary(),o=new _BinaryExpression(e,o,t);return o}_parseUnary(){var e,t;return this._token.tokenID===_TokenID.ADD||this._token.tokenID===_TokenID.SUB?(e=this._token,this._getToken(),t=this._parseAtom(),new _UnaryExpression(e,t)):this._parseAtom()}_parseAtom(){var e,t,o,i,l,n,s,r,a,h,d,c,_,u=null;switch(this._token.tokenType){case _TokenType.LITERAL:u=new _Expression(this._token);break;case _TokenType.IDENTIFIER:if(e=this._token.value.toString().toLowerCase(),t=this._functionTable[e]){if(o=this._getParameters(),this._token.tokenType===_TokenType.GROUP&&this._token.tokenID===_TokenID.CLOSE){if(i=o?o.length:0,-1!==t.paramMin&&i<t.paramMin)throw"Too few parameters.";if(-1!==t.paramMax&&i>t.paramMax)throw"Too many parameters.";"rand"===e&&(this._containsCellRef=!0),u=new _FunctionExpression(e,t,o);break}if("true"===e||"false"===e){u=new _FunctionExpression(e,t,o,!1);break}}if(2===(h=e.split("!")).length?(c=h[0],d=h[1]):d=h[0],n=this._getDefinedName(d,c||this._sheet.name.toLowerCase())){if(n.sheetName&&n.sheetName!==this._sheet.name&&n.sheetName.toLowerCase()!==c)throw"The defined name item works in "+n.sheetName+".  It does not work in current sheet.";a=this._pointer,r=this._expressLength,s=this._expression,this._pointer=0,u=this._checkCache(n.value),this._pointer=a,this._expressLength=r,this._expression=s;break}if(c="",null!=(_=this._owner._getTable(e))){if(""===(c=_.sheet.name))throw"The Table("+e+") is not located in any sheet.";if(this._getToken(),this._token.tokenType!==_TokenType.SQUAREBRACKETS||this._token.tokenID!==_TokenID.OPEN)throw"Invalid Table Reference.";this._tableRefStart=!0,u=this._getTableReference(_,c);break}if(l=this._getCellRange(e)){this._containsCellRef=!0,u=new _CellRangeExpression(l.cellRef.cellRange,l.sheetRef,this._owner,e.indexOf(":")>-1,l.cellRef.absRow,l.cellRef.absCol,l.cellRef.absRow2,l.cellRef.absCol2,l.isWholeRow);break}o=this._getParameters(),u=this.onUnknownFunction(e,o);break;case _TokenType.GROUP:if(this._token.tokenID!==_TokenID.OPEN)throw"Expression expected.";if(this._getToken(),u=this._parseCompareOrConcat(),this._token.tokenID!==_TokenID.CLOSE)throw"Unbalanced parenthesis.";break;case _TokenType.SQUAREBRACKETS:if(this._token.tokenID!==_TokenID.OPEN)throw"Table References expected.";null!=(_=this._sheet.findTable(this._rowIndex,this._columnIndex))&&(c=_.sheet.name,this._tableRefStart=!0,u=this._getTableReference(_,c,!1))}if(null===u)throw"";return this._getToken(),u}_getToken(){for(var e,t,o,i,l,n,s="",r="",a=new RegExp("[　-〿぀-ゟ゠-ヿ＀-ﾟ一-龯㐀-䶿]");this._pointer<this._expressLength&&" "===this._expression[this._pointer];)this._pointer++;if(this._pointer>=this._expressLength)this._token=new _Token(null,_TokenID.END,_TokenType.GROUP);else{if(t=this._expression[this._pointer],l=t>="a"&&t<="z"||t>="A"&&t<="Z"||a.test(t),n=t>="0"&&t<="9"||"."==t,!l&&!n){var h=this._tokenTable[t];if(h)return this._token=h,this._pointer++,void(this._pointer<this._expressLength&&(">"===t||"<"===t)&&(h=this._tokenTable[this._expression.substring(this._pointer-1,this._pointer+1)])&&(this._token=h,this._pointer++))}if(n){if(i=this._pointer,this._parseDigit(),":"!==this._expression[this._pointer])return;this._pointer=i}if('"'!==t){if("'"!==t||(r=this._parseSheetRef()))if("#"!==t){if(!l&&!n&&"_"!==t&&this._idChars.indexOf(t)<0&&!r)throw"Identifier expected.";for(e=1;e+this._pointer<this._expressLength;e++)if(t=this._expression[this._pointer+e],l=t>="a"&&t<="z"||t>="A"&&t<="Z"||a.test(t),n=t>="0"&&t<="9","'"!==t||":"!==o){if(o=t,!l&&!n&&"_"!==t&&this._idChars.indexOf(t)<0)break}else s=r+this._expression.substring(this._pointer,this._pointer+e),this._pointer+=e,r=this._parseSheetRef(),e=0;s+=r+this._expression.substring(this._pointer,this._pointer+e),this._pointer+=e,this._token=new _Token(s,_TokenID.ATOM,_TokenType.IDENTIFIER)}else this._parseDate()}else this._parseString()}}_getTableToken(){for(var e,t,o,i="",l=!1;this._pointer<this._expressLength&&" "===this._expression[this._pointer];)this._pointer++;for("@"===(t=this._expression[this._pointer])&&(i=t,this._pointer++),"["===(t=this._expression[this._pointer])&&(l=!0),e=1;e+this._pointer<this._expressLength;e++){if(t=this._expression[this._pointer+e],l&&","===t)throw"Invalid table reference.";if("]"===t)break}o=i+this._expression.substring(this._pointer+(l?1:0),this._pointer+e),this._pointer+=e+(l?1:0),this._token=new _Token(o,_TokenID.ATOM,_TokenType.IDENTIFIER)}_parseDigit(){var e,t,o=-1,i=!1,l=!1,n=0;for(e=0;e+this._pointer<this._expressLength;e++)if((t=this._expression[this._pointer+e])>="0"&&t<="9")n=10*n+(+t-0),o>-1&&(o*=10);else if("."===t&&o<0)o=1;else{if("E"!==t&&"e"!==t||i){if("%"===t){l=!0,e++;break}break}i=!0,"+"!==(t=this._expression[this._pointer+e+1])&&"-"!==t||e++}i?n=+this._expression.substring(this._pointer,this._pointer+e):(o>1&&(n/=o),l&&(n/=100)),this._token=new _Token(n,_TokenID.ATOM,_TokenType.LITERAL),this._pointer+=e}_parseString(){var e,t,o;for(e=1;e+this._pointer<this._expressLength;e++)if('"'===(t=this._expression[this._pointer+e])){if('"'!==(e+this._pointer<this._expressLength-1?this._expression[this._pointer+e+1]:" "))break;e++}if('"'!==t)throw"Can't find final quote.";if(o=this._expression.substring(this._pointer+1,this._pointer+e),this._pointer+=e+1,"!"===this._expression[this._pointer])throw"Illegal cross sheet reference.";this._token=new _Token(o.replace('""','"'),_TokenID.ATOM,_TokenType.LITERAL)}_parseDate(){var e,t,o;for(e=1;e+this._pointer<this._expressLength&&"#"!==(t=this._expression[this._pointer+e]);e++);if("#"!==t)throw'Can\'t find final date delimiter ("#").';o=this._expression.substring(this._pointer+1,this._pointer+e),this._pointer+=e+1,this._token=new _Token(Date.parse(o),_TokenID.ATOM,_TokenType.LITERAL)}_parseSheetRef(){var e,t,o;for(e=1;e+this._pointer<this._expressLength;e++)if("'"===(t=this._expression[this._pointer+e])){if("'"!==(e+this._pointer<this._expressLength-1?this._expression[this._pointer+e+1]:" "))break;e++}if("'"!==t)throw"Can't find final quote.";return o=this._expression.substring(this._pointer+1,this._pointer+e),this._pointer+=e+1,"!"===this._expression[this._pointer]?o.replace(/\'\'/g,"'"):""}_getCellRange(e){var t,o,i,l,n;if(e&&(t=e.split(":")).length>0&&t.length<3){if(null==(o=this._parseCell(t[0])).cellRef)return null;if(l=o.cellRef.cellRange,null!=o.cellRef.isWholeRow&&1===t.length)return null;if(l&&2===t.length){if(i=this._parseCell(t[1]),n=i.cellRef.cellRange,null!=o.cellRef.isWholeRow&&o.cellRef.isWholeRow!==i.cellRef.isWholeRow)return null;if(o.sheetRef&&!i.sheetRef&&(i.sheetRef=o.sheetRef),o.sheetRef!==i.sheetRef)throw"The cell reference must be in the same sheet!";n?(l.col2=n.col,l.row2=n.row):l=null}}return null==l?null:{cellRef:{cellRange:l,absRow:o.cellRef.absRow,absCol:o.cellRef.absCol,absRow2:i?i.cellRef.absRow:null,absCol2:i?i.cellRef.absCol:null},sheetRef:o.sheetRef,isWholeRow:o.cellRef.isWholeRow}}_parseCellRange(e){var t,o,i,l,n=-1,s=-1,r=!1,a=!1;for(t=0;t<e.length;t++)if("$"!==(i=e[t])||r){if(!(i>="a"&&i<="z"||i>="A"&&i<="Z"))break;n<0&&(n=0),n=26*n+(i.toUpperCase().charCodeAt(0)-"A".charCodeAt(0)+1)}else r=!0;for(;t<e.length;t++)if("$"!==(i=e[t])||a){if(!(i>="0"&&i<="9"))break;s<0&&(s=0),s=10*s+(+i-0)}else a=!0;return t<e.length?null:(s>-1&&n>-1?o=new wjcGrid.CellRange(s-1,n-1):-1===n?(l=!0,o=new wjcGrid.CellRange(s-1,0)):-1===s&&(l=!1,o=new wjcGrid.CellRange(0,n-1)),{cellRange:o,absRow:a,absCol:r,isWholeRow:l})}_parseCell(e){var t,o,i,l;if((o=e.lastIndexOf("!"))>0&&o<e.length-1)l=e.substring(0,o),i=e.substring(o+1);else{if(!(o<=0))return null;i=e}return t=this._parseCellRange(i),{cellRef:t,sheetRef:l}}_getParameters(){var e,t,o=this._pointer,i=this._token;if(this._getToken(),this._token.tokenType!==_TokenType.SQUAREBRACKETS||this._token.tokenID!==_TokenID.OPEN){if(this._token.tokenID!==_TokenID.OPEN)return this._pointer=o,this._token=i,null;if(o=this._pointer,this._getToken(),this._token.tokenID===_TokenID.CLOSE)return null;for(this._pointer=o,e=new Array,t=this._parseExpression(),e.push(t);this._token.tokenID===_TokenID.COMMA;)t=this._parseExpression(),e.push(t);if(this._token.tokenID!==_TokenID.CLOSE)throw"Syntax error.";return e}}_getTableReference(e,t,o=!0){var i,l,n=[],s=this._getTableParameter(),r=!1;if(null==s)throw"Invalid table reference.";for(n.push(s);this._tableRefStart&&(this._token.tokenID===_TokenID.COMMA||":"===this._token.value);){if(":"===this._token.value&&(r=!0),null==(s=this._getTableParameter()))throw"Invalid table reference.";r?(n[n.length-1]+=":"+s,r=!1):n.push(s)}if(this._token.tokenType!==_TokenType.SQUAREBRACKETS||this._token.tokenID!==_TokenID.CLOSE)throw"Unbalanced square brackets.";return this._tableRefStart=!1,i=this._getTableRange(e,n),this._containsCellRef=!0,l=new _CellRangeExpression(i,t.toLowerCase(),this._owner),l._tableParams=n,o&&(l._tableName=e.name),l}_getTableParameter(){var e;for(this._pointer;this._pointer<this._expressLength&&" "===this._expression[this._pointer];)this._pointer++;return"]"===this._expression[this._pointer]?(this._tableRefStart=!1,null):(this._getTableToken(),e=this._token.value,this._getToken(),e)}_getTableRange(e,t){for(var o,i,l,n,s,r,a=0;a<t.length;a++){if(i)throw"Invalid Table Refernce.";if(o=t[a].toLowerCase(),s=null,"#"===o[0]){switch(o){case"#all":s=e.getRange();break;case"#data":s=e.getRange(TableSection.Data);break;case"#headers":s=e.getRange(TableSection.Header);break;case"#totals":s=e.getRange(TableSection.Footer);break;case"#this row":if(n=e.getRange(),!(this._rowIndex>=n.topRow&&this._rowIndex<=n.bottomRow))throw"The row is out of the table ("+e.name+") range.";s=new wjcGrid.CellRange(this._rowIndex,n.leftCol,this._rowIndex,n.rightCol);break;default:throw"Invalid Table Refernce."}if(null==s)throw"Invalid Table Refernce.";null==l?l=s:(l.row=l.topRow<s.topRow?l.topRow:s.topRow,l.row2=l.bottomRow>s.bottomRow?l.bottomRow:s.bottomRow)}else{i=!0,r=o.split(":");for(var h=0;h<r.length;h++){if(r.length>2)throw"Invalid Table Column Refernce.";if("@"===(o=r[h])[0]){if(null==(s=e.getRange(TableSection.Data,o.substring(1))))throw"Invalid Table Refernce.";if(!(this._rowIndex>=s.topRow&&this._rowIndex<=s.bottomRow))throw"The row is out of the table ("+e.name+") range.";s.row=this._rowIndex,s.row2=this._rowIndex}else if(null==(s=e.getRange(TableSection.Data,o)))throw"Invalid Table Refernce.";0===h&&(null==l?l=s:l.col=s.col),l.col2=s.col,s=null}}}return l}_getAggregateResult(e,t,o){var i,l=this._getItemList(t,o);return i=wjcCore.getAggregate(e,l.items),l.isDate&&(i={value:i=new Date(i),format:l.format||"M/d/yyyy"}),i}_getFlexSheetAggregateResult(e,t,o){var i,l,n,s;switch(e){case _FlexSheetAggregate.Count:return i=this._getItemList(t,o,!0,!1),this._countNumberCells(i.items);case _FlexSheetAggregate.CountA:return(i=this._getItemList(t,o,!1,!1)).items.length;case _FlexSheetAggregate.ConutBlank:return i=this._getItemList(t,o,!1,!0),this._countBlankCells(i.items);case _FlexSheetAggregate.Rank:if(n=_Expression.toNumber(t[0],this._rowIndex,this._columnIndex,o),s=t[2]?_Expression.toNumber(t[2],this._rowIndex,this._columnIndex,o):0,isNaN(n))throw"Invalid number.";if(isNaN(s))throw"Invalid order.";if(t[1]=this._ensureNonFunctionExpression(t[1],o),t[1]instanceof _CellRangeExpression)return i=this._getItemList([t[1]],o),this._getRankOfCellRange(n,i.items,s);throw"Invalid Cell Reference.";case _FlexSheetAggregate.CountIf:if(t[0]=this._ensureNonFunctionExpression(t[0],o),t[0]instanceof _CellRangeExpression)return i=this._getItemList([t[0]],o,!1),this._countCellsByCriterias([i.items],[t[1]],o);throw"Invalid Cell Reference.";case _FlexSheetAggregate.CountIfs:return this._handleCountIfs(t,o);case _FlexSheetAggregate.SumIf:if(t[0]=this._ensureNonFunctionExpression(t[0],o),t[0]instanceof _CellRangeExpression)return i=this._getItemList([t[0]],o,!1),t[2]=this._ensureNonFunctionExpression(t[2],o),null!=t[2]&&t[2]instanceof _CellRangeExpression&&(l=this._getItemList([t[2]],o)),this._sumCellsByCriterias([i.items],[t[1]],l?l.items:null,o);throw"Invalid Cell Reference.";case _FlexSheetAggregate.SumIfs:return this._handleSumIfs(t,o);case _FlexSheetAggregate.Product:return i=this._getItemList(t,o),this._getProductOfNumbers(i.items)}throw"Invalid aggregate type."}_getItemList(e,t,o=!0,i=!1,l=!0,n){var s,r,a,h,d,c,_,u,g,w,m,f=new Array;for(r=0;r<e.length;r++)if(d=e[r],(d=this._ensureNonFunctionExpression(d,t))instanceof _CellRangeExpression){h=d.getValues(l,n,t),0===r&&((g=(u=d._getSheet()||t||this._sheet).getCellStyle(d.cells.topRow,d.cells.leftCol))&&(_=g.format),_||(w=u.grid.columns[d.cells.leftCol])&&(_=w.format));e:for(a=0;a<h.length;a++)if(s=h[a],null==c&&null!=s&&!wjcCore.isString(s)){c=wjcCore.isDate(s);break e}for(a=0;a<h.length;a++)if(s=h[a],i||null!=s&&""!==s){if(wjcCore.isString(s)&&0===s.indexOf("Error: ")){f=[0];break}m=wjcCore.isString(s)?c?wjcCore.changeType(s,wjcCore.DataType.Date,""):wjcCore.changeType(s,wjcCore.DataType.Number,""):s,o&&!wjcCore.isBoolean(m)?isNaN(+m)||f.push(+m):f.push(s)}}else{if(s=d instanceof _Expression?d.evaluate(this._rowIndex,this._columnIndex,t):d,wjcCore.isPrimitive(s)||(s=s.value),!i&&(null==s||""===s))continue;if(wjcCore.isString(s)&&0===s.indexOf("Error: ")){f=[0];break}o?isNaN(+s)||f.push(+s):f.push(s),null==c&&f.length>0&&(c=s instanceof Date)}return 0===f.length&&(c=!1),{isDate:c,items:f,format:_}}_countBlankCells(e){for(var t,o=0,i=0;o<e.length;o++)(null==(t=e[o])||wjcCore.isString(t)&&""===t||wjcCore.isNumber(t)&&isNaN(t))&&i++;return i}_countNumberCells(e){for(var t,o=0,i=0;o<e.length;o++)null!=(t=e[o])&&wjcCore.isNumber(t)&&!isNaN(t)&&i++;return i}_getRankOfCellRange(e,t,o=0){var i,l=0,n=0;for(o?t.sort((e,t)=>isNaN(e)||isNaN(t)?-1:e-t):t.sort((e,t)=>isNaN(e)||isNaN(t)?1:t-e);l<t.length;l++)if(i=t[l],!isNaN(i)&&(n++,e===i))return n;throw e+" is not in the cell range."}_handleCountIfs(e,t){var o,i,l,n,s=0,r=[],a=[];if(e.length%2!=0)throw"Invalid params.";for(;s<e.length/2;s++){if(i=e[2*s],!((i=this._ensureNonFunctionExpression(i,t))instanceof _CellRangeExpression))throw"Invalid Cell Reference.";if(0===s){if(!i.cells)throw"Invalid Cell Reference.";l=i.cells.rowSpan,n=i.cells.columnSpan}else{if(!i.cells)throw"Invalid Cell Reference.";if(i.cells.rowSpan!==l||i.cells.columnSpan!==n)throw"The row span and column span of each cell range has to be same with each other."}o=this._getItemList([i],t,!1),r[s]=o.items,a[s]=e[2*s+1]}return this._countCellsByCriterias(r,a,t)}_countCellsByCriterias(e,t,o,i){for(var l,n,s,r,a,h=0,d=0,c=0,_=e[0].length,u=[];d<t.length;d++)"*"===(a=_Expression.toString(t[d],this._rowIndex,this._columnIndex,o))?u.push(a):u.push(this._parseRightExpr(a));for(;h<_;h++){l=!1;e:for(d=0;d<e.length;d++)if(s=e[d],r=s[h],"string"==typeof(a=u[d])){if("*"!==a&&(null==r||""===r)){l=!1;break e}if(!(l="*"===a||this.evaluate(this._combineExpr(r,a),null,o,this._rowIndex,this._columnIndex)))break e}else if(!(l=l=a.reg.test(r.toString())===a.checkMathces))break e;l&&(i?null!=(n=i[h])&&wjcCore.isNumber(n)&&!isNaN(n)&&c++:c++)}return c}_handleSumIfs(e,t){var o,i,l,n,s,r,a=1,h=[],d=[];if(e.length%2!=1)throw"Invalid params.";if(l=e[0],!((l=this._ensureNonFunctionExpression(l,t))instanceof _CellRangeExpression))throw"Invalid Sum Cell Reference.";if(!l.cells)throw"Invalid Sum Cell Reference.";for(s=l.cells.rowSpan,r=l.cells.columnSpan,i=this._getItemList([l],t);a<(e.length+1)/2;a++){if(n=e[2*a-1],!((n=this._ensureNonFunctionExpression(n,t))instanceof _CellRangeExpression))throw"Invalid Criteria Cell Reference.";if(!n.cells)throw"Invalid Criteria Cell Reference.";if(n.cells.rowSpan!==s||n.cells.columnSpan!==r)throw"The row span and column span of each cell range has to be same with each other.";o=this._getItemList([n],t,!1),h[a-1]=o.items,d[a-1]=e[2*a]}return this._sumCellsByCriterias(h,d,i.items,t)}_sumCellsByCriterias(e,t,o,i){var l,n,s,r,a,h=0,d=0,c=0,_=e[0].length,u=[];for(null==o&&(o=e[0]);d<t.length;d++)"*"===(a=_Expression.toString(t[d],this._rowIndex,this._columnIndex,i))?u.push(a):u.push(this._parseRightExpr(a));for(;h<_;h++){n=!1,l=o[h];e:for(d=0;d<e.length;d++)if(s=e[d],r=s[h],"string"==typeof(a=u[d])){if("*"!==a&&(null==r||""===r)){n=!1;break e}if(!(n="*"===a||this.evaluate(this._combineExpr(r,a),null,i,this._rowIndex,this._columnIndex)))break e}else if(!(n=a.reg.test(r.toString())===a.checkMathces))break e;n&&wjcCore.isNumber(l)&&!isNaN(l)&&(c+=l)}return c}_getProductOfNumbers(e){var t,o=0,i=1,l=!1;if(e)for(;o<e.length;o++)t=e[o],wjcCore.isNumber(t)&&!isNaN(t)&&(i*=t,l=!0);return l?i:0}_handleSubtotal(e,t){var o,i,l,n,s=!0,r=!0;if((o=_Expression.toNumber(e[0],this._rowIndex,this._columnIndex,t))>=1&&o<=11||o>=101&&o<=111){switch(o>=101&&o<=111&&(s=!1),(o=wjcCore.asEnum(o,_SubtotalFunction))!==_SubtotalFunction.CountA&&o!==_SubtotalFunction.CountAWithoutHidden||(r=!1),i=this._getItemList(e.slice(1),t,r,!1,s),o){case _SubtotalFunction.Count:case _SubtotalFunction.CountWithoutHidden:return this._countNumberCells(i.items);case _SubtotalFunction.CountA:case _SubtotalFunction.CountAWithoutHidden:return i.items.length;case _SubtotalFunction.Product:case _SubtotalFunction.ProductWithoutHidden:return this._getProductOfNumbers(i.items);case _SubtotalFunction.Average:case _SubtotalFunction.AverageWithoutHidden:l=wjcCore.Aggregate.Avg;break;case _SubtotalFunction.Max:case _SubtotalFunction.MaxWithoutHidden:l=wjcCore.Aggregate.Max;break;case _SubtotalFunction.Min:case _SubtotalFunction.MinWithoutHidden:l=wjcCore.Aggregate.Min;break;case _SubtotalFunction.Std:case _SubtotalFunction.StdWithoutHidden:l=wjcCore.Aggregate.Std;break;case _SubtotalFunction.StdPop:case _SubtotalFunction.StdPopWithoutHidden:l=wjcCore.Aggregate.StdPop;break;case _SubtotalFunction.Sum:case _SubtotalFunction.SumWithoutHidden:l=wjcCore.Aggregate.Sum;break;case _SubtotalFunction.Var:case _SubtotalFunction.VarWithoutHidden:l=wjcCore.Aggregate.Var;break;case _SubtotalFunction.VarPop:case _SubtotalFunction.VarPopWithoutHidden:l=wjcCore.Aggregate.VarPop}return n=wjcCore.getAggregate(l,i.items),i.isDate&&(n=new Date(n)),n}throw"Invalid Subtotal function."}_handleDCount(e,t){var o,i,l,n=e[0],s=e[2];if(n=this._ensureNonFunctionExpression(n,t),s=this._ensureNonFunctionExpression(s,t),n instanceof _CellRangeExpression&&s instanceof _CellRangeExpression&&(o=e[1].evaluate(this._rowIndex,this._columnIndex,t),i=this._getColumnIndexByField(n,o),(l=this._getItemList([n],t,!0,!1,!0,i)).items&&l.items.length>1))return this._DCountWithCriterias(l.items.slice(1),n,s);throw"Invalid Count Cell Reference."}_DCountWithCriterias(e,t,o){var i,l,n,s,r,a,h,d,c,_,u,g=o.cells,w=0;if(i=this._getSheet(t.sheetRef),l=this._getSheet(o.sheetRef),g.rowSpan>1){for(n=g.topRow,s=g.bottomRow;s>g.topRow;s--){for(_=[],u=[],r=g.leftCol;r<=g.rightCol;r++)if(null!=(h=this._owner.getCellValue(s,r,!1,l))&&""!==h){if(u.push(new _Expression(h)),d=this._owner.getCellValue(n,r,!1,l),a=this._getColumnIndexByField(t,d),!(null!=(c=this._getItemList([t],i,!1,!1,!0,a)).items&&c.items.length>1))throw"Invalid Count Cell Reference.";_.push(c.items.slice(1))}w+=this._countCellsByCriterias(_,u,i,e)}return w}throw"Invalid Criteria Cell Reference."}_getColumnIndexByField(e,t){var o,i,l,n,s;if(o=e.cells,-1===(s=o.topRow))throw"Invalid Count Cell Reference.";if(wjcCore.isInt(t)&&!isNaN(t)){if(t>=1&&t<=o.columnSpan)return l=o.leftCol+t-1}else for(i=this._getSheet(e.sheetRef),l=o.leftCol;l<=o.rightCol;l++)if(n=this._owner.getCellValue(s,l,!1,i),t=wjcCore.isString(t)?t.toLowerCase():t,n=wjcCore.isString(n)?n.toLowerCase():n,t===n)return l;throw"Invalid field."}_getSumProduct(e,t){var o,i,l,n=0,s=this._getItemListForSumProduct(e,t);if(s.length>0){i=s[0].length,l=s.length;for(var r=0;r<i;r++){o=1;for(var a=0;a<l;a++)o*=s[a][r];n+=o}}return n}_getItemListForSumProduct(e,t){var o,i,l,n,s,r,a=[new Array];for(l=0;l<e.length;l++){if(r=e[l],o=new Array,(r=this._ensureNonFunctionExpression(r,t))instanceof _CellRangeExpression)for(s=r.getValues(!0,null,t),n=0;n<s.length;n++)i=s[n],o.push(+i);else i=r instanceof _Expression?r.evaluate(this._rowIndex,this._columnIndex,t):r,o.push(+i);if(l>0&&o.length!==a[0].length)throw"The cell ranges of the sumProduct formula must have the same dimensions.";a[l]=o}return a}_getSheet(e){var t,o=0;if(e)for(;o<this._owner.sheets.length&&(t=this._owner.sheets[o]).name!==e;o++);return t}_parseRightExpr(e){var t,o,i=!1;if(e.indexOf("?")>-1||e.indexOf("*")>-1){if(null==(t=e.match(/=?([\?\*]*)(\w*)([\?\*]*)(\w*)([\?\*]*)/))||6!==t.length)throw"Invalid Criteria.";return o=new RegExp("^"+(t[1].length>0?this._parseRegCriteria(t[1]):"")+t[2]+(t[3].length>0?this._parseRegCriteria(t[3]):"")+t[4]+(t[5].length>0?this._parseRegCriteria(t[5]):"")+"$","i"),/^[<>=]/.test(e)?"="===e.trim()[0]&&(i=!0):i=!0,{reg:o,checkMathces:i}}if(isNaN(+e))if(/^\w/.test(e))e='="'+e+'"';else{if(!/^[<>=]{1,2}\s*-?.+$/.test(e))throw"Invalid Criteria.";e=e.replace(/([<>=]{1,2})\s*(-?.+)/,'$1"$2"')}else e="="+ +e;return e}_combineExpr(e,t){return(wjcCore.isString(e)||wjcCore.isDate(e))&&(e='"'+e+'"'),(e="="+e)+t}_parseRegCriteria(e){for(var t=0,o=0,i="";t<e.length;t++)"*"===e[t]?(o>0&&(i+="\\w{"+o+"}",o=0),i+="\\w*"):"?"===e[t]&&o++;return o>0&&(i+="\\w{"+o+"}"),i}_calculateRate(e,t){var o,i,l,n,s,r,a,h,d,c,_=0,u=0;for(l=_Expression.toNumber(e[0],this._rowIndex,this._columnIndex,t),n=_Expression.toNumber(e[1],this._rowIndex,this._columnIndex,t),s=_Expression.toNumber(e[2],this._rowIndex,this._columnIndex,t),r=null!=e[3]?_Expression.toNumber(e[3],this._rowIndex,this._columnIndex,t):0,a=null!=e[4]?_Expression.toNumber(e[4],this._rowIndex,this._columnIndex,t):0,i=null!=e[5]?_Expression.toNumber(e[5],this._rowIndex,this._columnIndex,t):.1,Math.abs(i)<1e-7?s*(1+l*i)+n*(1+i*a)*l+r:s*(h=Math.exp(l*Math.log(1+i)))+n*(1/i+a)*(h-1)+r,d=s+n*l+r,c=s*h+n*(1/i+a)*(h-1)+r,o=i;Math.abs(d-c)>1e-7&&_<20;)i=(c*u-d*o)/(c-d),u=o,o=i,d=c,c=Math.abs(i)<1e-7?s*(1+l*i)+n*(1+i*a)*l+r:s*(h=Math.exp(l*Math.log(1+i)))+n*(1/i+a)*(h-1)+r,++_;if(Math.abs(d-c)>1e-7&&20===_)throw"It is not able to calculate the rate with current parameters.";return i}_handleHLookup(e,t){var o,i,l=e[0].evaluate(this._rowIndex,this._columnIndex,t),n=e[1],s=_Expression.toNumber(e[2],this._rowIndex,this._columnIndex,t),r=null==e[3]||_Expression.toBoolean(e[3],this._rowIndex,this._columnIndex,t);if(null==l||""==l)throw"Invalid lookup value.";if(isNaN(s)||s<0)throw"Invalid row index.";if((n=this._ensureNonFunctionExpression(n,t))instanceof _CellRangeExpression){if(o=n.cells,s>o.rowSpan)throw"Row index is out of the cell range.";if(r?-1===(i=this._exactMatch(l,o,t,!1))&&(i=this._approximateMatch(l,o,t)):i=this._exactMatch(l,o,t),-1===i)throw"Lookup Value is not found.";return this._owner.getCellValue(o.topRow+s-1,i,!1,t)}throw"Invalid Cell Reference."}_exactMatch(e,t,o,i=!0){var l,n,s,r,a=t.topRow;if(wjcCore.isString(e)&&(e=e.toLowerCase()),i&&wjcCore.isString(e)&&(e.indexOf("?")>-1||e.indexOf("*")>-1)){if(null==(s=e.match(/([\?\*]*)(\w+)([\?\*]*)(\w+)([\?\*]*)/))||6!==s.length)throw"Invalid lookup value.";r=new RegExp("^"+(s[1].length>0?this._parseRegCriteria(s[1]):"")+s[2]+(s[3].length>0?this._parseRegCriteria(s[3]):"")+s[4]+(s[5].length>0?this._parseRegCriteria(s[5]):"")+"$","i")}for(l=t.leftCol;l<=t.rightCol;l++)if(n=this._owner.getCellValue(a,l,!1,o),null!=r){if(r.test(n))return l}else if(wjcCore.isString(n)&&(n=n.toLowerCase()),e===n)return l;return-1}_approximateMatch(e,t,o){var i,l,n=t.topRow,s=[],r=0;for(wjcCore.isString(e)&&(e=e.toLowerCase()),l=t.leftCol;l<=t.rightCol;l++)i=this._owner.getCellValue(n,l,!1,o),i=isNaN(+i)?i:+i,s.push({value:i,index:l});for(s.sort((e,t)=>(wjcCore.isString(e.value)&&(e.value=e.value.toLowerCase()),wjcCore.isString(t.value)&&(t.value=t.value.toLowerCase()),e.value>t.value?-1:e.value===t.value?t.index-e.index:1));r<s.length;r++)if(i=s[r],wjcCore.isString(i.value)&&(i.value=i.value.toLowerCase()),e>i.value)return i.index;throw"Lookup Value is not found."}_parseToScientificValue(e,t,o,i,l){var n,s,r,a,h=0;if(Math.abs(e)>=1)for(s="+",n=Math.pow(10,t.length);e>n;)e/=n,h+=t.length;else for(s="-",n=Math.pow(10,t.length);e*n<n;)e*=n,h+=t.length;if(r=wjcCore.Globalize.format(e,"D"+t.length),o)for((r+=wjcCore.Globalize.format(e-Math.floor(e),t+o).substring(1)).indexOf(".")>-1?a=r.length-1-r.indexOf("."):(r+=".",a=0);a<o.length-1;)r+="0",a++;if(r+="E"+s+wjcCore.Globalize.format(h,"D"+i.length),l){r+=".";for(var d=1;d<l.length;d++)r+="0"}return r}_checkCache(e,t,o,i){null!=t&&(this._sheet=this._owner.sheets[t]),null!=o&&(this._rowIndex=o),null!=i&&(this._columnIndex=i);var l=this._expressionCache[e]||this._expressionCache[this._rowIndex+"_"+this._columnIndex+":"+e];if(l)return l;if(l=this._parse(e),this._token.tokenID!==_TokenID.END||this._token.tokenType!==_TokenType.GROUP)throw"Invalid Expression: "+e;return this._cacheSize>1e4&&this._clearExpressionCache(),this._expressionCache[(this._containsCellRef?this._rowIndex+"_"+this._columnIndex+":":"")+e]=l,this._cacheSize++,l}_ensureNonFunctionExpression(e,t){for(;e instanceof _FunctionExpression;)e=e.evaluate(this._rowIndex,this._columnIndex,t);return e}_getDefinedName(e,t){for(var o,i,l=0;l<this._owner.definedNames.length;l++)if((o=this._owner.definedNames[l]).name.toLowerCase()===e)if(o.sheetName){if(o.sheetName.toLowerCase()===t)return o}else i=o;return i}_numAlpha(e){let t=Math.floor((e-1)/26);return(t>0?this._numAlpha(t):"")+String.fromCharCode((e-1)%26+65)}};export class _Token{constructor(e,t,o){this._value=e,this._tokenID=t,this._tokenType=o}get value(){return this._value}get tokenID(){return this._tokenID}get tokenType(){return this._tokenType}};export class _FunctionDefinition{constructor(e,t,o){this._paramMax=Number.MAX_VALUE,this._paramMin=Number.MIN_VALUE,this._func=e,wjcCore.isNumber(t)&&!isNaN(t)&&(this._paramMax=t),wjcCore.isNumber(o)&&!isNaN(o)&&(this._paramMin=o)}get paramMax(){return this._paramMax}get paramMin(){return this._paramMin}get func(){return this._func}};export var _TokenType;!function(e){e[e.COMPARE=0]="COMPARE",e[e.ADDSUB=1]="ADDSUB",e[e.MULDIV=2]="MULDIV",e[e.POWER=3]="POWER",e[e.CONCAT=4]="CONCAT",e[e.GROUP=5]="GROUP",e[e.LITERAL=6]="LITERAL",e[e.IDENTIFIER=7]="IDENTIFIER",e[e.SQUAREBRACKETS=8]="SQUAREBRACKETS"}(_TokenType||(_TokenType={}));export var _TokenID;!function(e){e[e.GT=0]="GT",e[e.LT=1]="LT",e[e.GE=2]="GE",e[e.LE=3]="LE",e[e.EQ=4]="EQ",e[e.NE=5]="NE",e[e.ADD=6]="ADD",e[e.SUB=7]="SUB",e[e.MUL=8]="MUL",e[e.DIV=9]="DIV",e[e.DIVINT=10]="DIVINT",e[e.MOD=11]="MOD",e[e.POWER=12]="POWER",e[e.CONCAT=13]="CONCAT",e[e.OPEN=14]="OPEN",e[e.CLOSE=15]="CLOSE",e[e.END=16]="END",e[e.COMMA=17]="COMMA",e[e.PERIOD=18]="PERIOD",e[e.ATOM=19]="ATOM"}(_TokenID||(_TokenID={}));var _FlexSheetAggregate;!function(e){e[e.Count=0]="Count",e[e.CountA=1]="CountA",e[e.ConutBlank=2]="ConutBlank",e[e.CountIf=3]="CountIf",e[e.CountIfs=4]="CountIfs",e[e.Rank=5]="Rank",e[e.SumIf=6]="SumIf",e[e.SumIfs=7]="SumIfs",e[e.Product=8]="Product"}(_FlexSheetAggregate||(_FlexSheetAggregate={}));var _SubtotalFunction;!function(e){e[e.Average=1]="Average",e[e.Count=2]="Count",e[e.CountA=3]="CountA",e[e.Max=4]="Max",e[e.Min=5]="Min",e[e.Product=6]="Product",e[e.Std=7]="Std",e[e.StdPop=8]="StdPop",e[e.Sum=9]="Sum",e[e.Var=10]="Var",e[e.VarPop=11]="VarPop",e[e.AverageWithoutHidden=101]="AverageWithoutHidden",e[e.CountWithoutHidden=102]="CountWithoutHidden",e[e.CountAWithoutHidden=103]="CountAWithoutHidden",e[e.MaxWithoutHidden=104]="MaxWithoutHidden",e[e.MinWithoutHidden=105]="MinWithoutHidden",e[e.ProductWithoutHidden=106]="ProductWithoutHidden",e[e.StdWithoutHidden=107]="StdWithoutHidden",e[e.StdPopWithoutHidden=108]="StdPopWithoutHidden",e[e.SumWithoutHidden=109]="SumWithoutHidden",e[e.VarWithoutHidden=110]="VarWithoutHidden",e[e.VarPopWithoutHidden=111]="VarPopWithoutHidden"}(_SubtotalFunction||(_SubtotalFunction={}));export class _Expression{constructor(e){this._token=e?e instanceof _Token?e:new _Token(e,_TokenID.ATOM,_TokenType.LITERAL):new _Token(null,_TokenID.ATOM,_TokenType.IDENTIFIER)}get token(){return this._token}evaluate(e,t,o){if(this._token.tokenType!==_TokenType.LITERAL)throw"Bad expression.";return this._token.value}static toString(e,t,o,i){var l=e.evaluate(t,o,i);return wjcCore.isPrimitive(l)||(l=l.value),null!=l?l.toString():""}static toNumber(e,t,o,i){var l=e.evaluate(t,o,i);return wjcCore.isPrimitive(l)||(l=l.value),wjcCore.isNumber(l)?l:wjcCore.isBoolean(l)?l?1:0:wjcCore.isDate(l)?FlexSheet._toOADate(l):wjcCore.isString(l)?l?isNaN(+l)?this.isDateValue(l)?FlexSheet._toOADate(new Date(l)):wjcCore.changeType(l,wjcCore.DataType.Number,""):+l:0:wjcCore.changeType(l,wjcCore.DataType.Number,"")}static toBoolean(e,t,o,i){var l=e.evaluate(t,o,i);return wjcCore.isPrimitive(l)||(l=l.value),wjcCore.isBoolean(l)?l:wjcCore.isNumber(l)?0!==l:wjcCore.changeType(l,wjcCore.DataType.Boolean,"")}static toDate(e,t,o,i){var l=e.evaluate(t,o,i);return wjcCore.isPrimitive(l)||(l=l.value),wjcCore.isDate(l)?l:wjcCore.isNumber(l)?FlexSheet._fromOADate(l):wjcCore.changeType(l,wjcCore.DataType.Date,"")}static isDateValue(e){let t,o=["January","February","March","April","May","June","July","August","September","October","November","December","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];if(wjcCore.isPrimitive(e)||(e=e.value),!(t=wjcCore.isDate(e))&&wjcCore.isString(e))for(let i in o)if(e.indexOf(o[i])>-1){t=!0;break}return t}_updateCellRangeExp(e,t,o,i,l,n){return!1}_moveCellRangeExp(e,t,o,i=!1,l=!1){return!1}_updateCellRangeExpForReorderingRows(e){return!1}_updateCellBoundary(e,t){return!1}_getStringExpression(){return null==this._token.value?"":wjcCore.isString(this._token.value)?'"'+this._token.value+'"':this._token.value.toString()}};export class _UnaryExpression extends _Expression{constructor(e,t){super(e),this._expr=t}evaluate(e,t,o){if(this.token.tokenID===_TokenID.SUB)return null==this._evaluatedValue&&(this._evaluatedValue=-_Expression.toNumber(this._expr,e,t,o)),this._evaluatedValue;if(this.token.tokenID===_TokenID.ADD)return null==this._evaluatedValue&&(this._evaluatedValue=+_Expression.toNumber(this._expr,e,t,o)),this._evaluatedValue;throw"Bad expression."}_updateCellRangeExp(e,t,o,i,l,n){return this._expr._updateCellRangeExp(e,t,o,i,l,n)}_moveCellRangeExp(e,t,o,i=!1,l=!1){return this._expr._moveCellRangeExp(e,t,o,i,l)}_updateCellRangeExpForReorderingRows(e){return this._expr._updateCellRangeExpForReorderingRows(e)}_getStringExpression(){return this.token.tokenID===_TokenID.SUB?"-"+this._expr._getStringExpression():this.token.tokenID===_TokenID.ADD?"+"+this._expr._getStringExpression():""}};export class _BinaryExpression extends _Expression{constructor(e,t,o){super(e),this._leftExpr=t,this._rightExpr=o}evaluate(e,t,o){var i,l,n,s,r,a,h,d,c,_=!1;if(null!=this._evaluatedValue)return this._evaluatedValue;if(i=_Expression.toString(this._leftExpr,e,t,o),l=_Expression.toString(this._rightExpr,e,t,o),this.token.tokenType===_TokenType.CONCAT)return this._evaluatedValue=i+l,this._evaluatedValue;if(n=this._leftExpr.evaluate(e,t,o),wjcCore.isPrimitive(n)||(r=n.format,n=n.value),s=this._rightExpr.evaluate(e,t,o),wjcCore.isPrimitive(s)||(a=s.format,s=s.value),(_=_Expression.isDateValue(n)||_Expression.isDateValue(s))?(h=wjcCore.isDate(n)?FlexSheet._toOADate(n):wjcCore.isNumber(n)?n:FlexSheet._toOADate(new Date(n)),d=wjcCore.isDate(s)?FlexSheet._toOADate(s):wjcCore.isNumber(s)?s:FlexSheet._toOADate(new Date(s))):(h=_Expression.toNumber(this._leftExpr,e,t,o),d=_Expression.toNumber(this._rightExpr,e,t,o)),c=h-d,this.token.tokenType===_TokenType.COMPARE)switch(this.token.tokenID){case _TokenID.GT:return c>0;case _TokenID.LT:return c<0;case _TokenID.GE:return c>=0;case _TokenID.LE:return c<=0;case _TokenID.EQ:return isNaN(c)?(this._evaluatedValue=i.toLowerCase()===l.toLowerCase(),this._evaluatedValue):(this._evaluatedValue=0===c,this._evaluatedValue);case _TokenID.NE:return isNaN(c)?(this._evaluatedValue=i.toLowerCase()!==l.toLowerCase(),this._evaluatedValue):(this._evaluatedValue=0!==c,this._evaluatedValue)}switch(this.token.tokenID){case _TokenID.ADD:this._evaluatedValue=h+d;break;case _TokenID.SUB:this._evaluatedValue=h-d;break;case _TokenID.MUL:this._evaluatedValue=h*d;break;case _TokenID.DIV:this._evaluatedValue=h/d;break;case _TokenID.DIVINT:this._evaluatedValue=Math.floor(h/d);break;case _TokenID.MOD:this._evaluatedValue=Math.floor(h%d);break;case _TokenID.POWER:0===d&&(this._evaluatedValue=1),.5===d&&(this._evaluatedValue=Math.sqrt(h)),1===d&&(this._evaluatedValue=h),2===d&&(this._evaluatedValue=h*h),3===d&&(this._evaluatedValue=h*h*h),4===d&&(this._evaluatedValue=h*h*h*h),this._evaluatedValue=Math.pow(h,d);break;default:this._evaluatedValue=NaN}if(!isNaN(this._evaluatedValue))return _&&(this._evaluatedValue={value:FlexSheet._fromOADate(this._evaluatedValue),format:r||a}),this._evaluatedValue;throw"Bad expression."}_updateCellRangeExp(e,t,o,i,l,n){let s,r=!1;return s=this._leftExpr._updateCellRangeExp(e,t,o,i,l,n),r=r||s,s=this._rightExpr._updateCellRangeExp(e,t,o,i,l,n),r||s}_moveCellRangeExp(e,t,o,i=!1,l=!1){let n,s=!1;return n=this._leftExpr._moveCellRangeExp(e,t,o,i,l),s=s||n,n=this._rightExpr._moveCellRangeExp(e,t,o,i,l),s||n}_updateCellRangeExpForReorderingRows(e){let t,o=!1;return t=this._leftExpr._updateCellRangeExpForReorderingRows(e),o=o||t,t=this._rightExpr._updateCellRangeExpForReorderingRows(e),o||t}_getStringExpression(){let e;switch(this.token.tokenID){case _TokenID.GT:e=">";break;case _TokenID.LT:e="<";break;case _TokenID.GE:e=">=";break;case _TokenID.LE:e="<=";break;case _TokenID.EQ:e="=";break;case _TokenID.NE:e="<>";break;case _TokenID.ADD:e="+";break;case _TokenID.SUB:e="-";break;case _TokenID.MUL:e="*";break;case _TokenID.DIV:e="/";break;case _TokenID.DIVINT:e="\\";break;case _TokenID.POWER:e="^";break;default:return""}return this._leftExpr._getStringExpression()+e+this._rightExpr._getStringExpression()}};export class _CellRangeExpression extends _Expression{constructor(e,t,o,i=!0,l=!1,n=!1,s=!1,r=!1,a){super(),this._cells=new wjcGrid.CellRange(e.topRow,e.leftCol,e.bottomRow,e.rightCol),this._sheetRef=t,this._flex=o,this._evalutingRange={},this._isCellRange=i,this._absRow=l,this._absCol=n,this._absRow2=s,this._absCol2=r,this._isWholeRow=a}evaluate(e,t,o){let i=this._cells.clone();return null==this._evaluatedValue&&(null!=this._isWholeRow&&(this._isWholeRow?(i.col=0,i.col2=o?o.grid.columns.length-1:this._flex.columns.length-1):(i.row=0,i.row2=o?o.grid.rows.length-1:this._flex.rows.length-1)),this._evaluatedValue=this._getCellValue(i,o,e,t)),this._evaluatedValue}getValues(e=!0,t,o){var i,l,t,n,s,r,a=[],h=0;if(!(o=this._getSheet()||o||this._flex.selectedSheet))return null;for(r=this._cells.clone(),null!=this._isWholeRow&&(this._isWholeRow?(r.col=0,r.col2=o.grid.columns.length-1):(r.row=0,r.row2=o.grid.rows.length-1)),n=null==t||isNaN(+t)?r.leftCol:t,s=null==t||isNaN(+t)?r.rightCol:t,l=r.topRow;l<=r.bottomRow&&l<o.grid.rows.length;l++)if(e||!1!==o.grid.rows[l].isVisible)for(t=n;t<=s&&t<o.grid.columns.length;t++)i=this._getCellValue(new wjcGrid.CellRange(l,t),o),wjcCore.isPrimitive(i)||(i=i.value),a[h]=i,h++;return a}getValuseWithTwoDimensions(e=!0,t){var o,i,l,n,s,r=[],a=0,h=0;if(!(t=this._getSheet()||t||this._flex.selectedSheet))return null;for(s=this._cells.clone(),null!=this._isWholeRow&&(this._isWholeRow?(s.col=0,s.col2=t.grid.columns.length-1):(s.row=0,s.row2=t.grid.rows.length-1)),l=s.topRow;l<=s.bottomRow&&l<t.grid.rows.length;l++)if(e||!1!==t.grid.rows[l].isVisible){for(i=[],h=0,n=s.leftCol;n<=s.rightCol&&n<t.grid.columns.length;n++)e||!1!==t.grid.columns[n].isVisible?(o=this._getCellValue(new wjcGrid.CellRange(l,n),t),wjcCore.isPrimitive(o)||(o=o.value),i[h]=o,h++):h++;r[a]=i,a++}else a++;return r}get cells(){return this._cells}get sheetRef(){return this._sheetRef}_getCellValue(e,t,o,i){var t,l,n,s,r,a;if(!(t=this._getSheet()||t||this._flex.selectedSheet))return null;if(e.isSingleCell?(n=e.row,s=e.col):(null!=o&&o>=e.topRow&&o<=e.bottomRow&&e.col===e.col2&&(n=o,s=e.col),null!=i&&i>=e.leftCol&&i<=e.rightCol&&e.row===e.row2&&(n=e.row,s=i)),null==n||null==s)throw"Invalid Cell Reference.";if(l=t.name+":"+n+","+s+"-"+n+","+s,this._evalutingRange[l])throw"Circular Reference";try{if(this._flex)return this._evalutingRange[l]=!0,n<t.rowCount&&s<t.columnCount?(r=t.grid.columns[s],a=this._flex.getCellValue(n,s,!1,t),r.dataMap&&(a=r.dataMap.getDisplayValue(a)),a):0}finally{delete this._evalutingRange[l]}}_getSheet(){var e,t=0;if(!this._sheetRef)return null;for(;t<this._flex.sheets.length;t++)if((e=this._flex.sheets[t]).name.toLowerCase()===this._sheetRef)return e;throw"Invalid sheet reference"}_updateCellRangeExp(e,t,o,i,l,n){let s=this._cells,r=!1;if(this._tableParams&&this._tableParams.length>0)return!1;if(e===this._flex.selectedSheetIndex){if(this._sheetRef&&this._sheetRef.toLowerCase()!==this._flex.selectedSheet.name.toLowerCase())return!1}else if(!this._sheetRef||this._sheetRef.toLowerCase()!==this._flex.selectedSheet.name.toLowerCase())return!1;if(l){if(n&&(s.leftCol>n.rightCol||s.rightCol<n.leftCol))return!1;i?s.topRow>=t?(s.row+=o,s.row2+=o,r=!0):s.topRow<t&&s.bottomRow>=t&&(s.row2+=o,r=!0):s.topRow>t?(s.row-=o,s.row2-=o,r=!0):s.isSingleCell?s.row>=t-o+1&&(s.row=t-o+1,s.row2=t-o+1,r=!0):s.topRow>=t-o+1?(s.row=t-o+1,s.row2-=o,r=!0):s.topRow<t-o+1&&s.bottomRow>=t-o+1&&(s.bottomRow>t?s.row2-=o:s.row2=t-o,r=!0)}else{if(n&&(s.topRow>n.bottomRow||s.bottomRow<n.topRow))return!1;i?s.leftCol>=t?(s.col+=o,s.col2+=o,r=!0):s.leftCol<t&&s.rightCol>=t&&(s.col2+=o,r=!0):s.leftCol>t?(s.col-=o,s.col2-=o,r=!0):s.isSingleCell?s.col>=t-o+1&&(s.col=t-o+1,s.col2=t-o+1,r=!0):s.leftCol>=t-o+1?(s.col=t-o+1,s.col2-=o,r=!0):s.leftCol<t-o+1&&s.rightCol>=t-o+1&&(s.rightCol>t?s.col2-=o:s.col2=t-o,r=!0)}return r}_moveCellRangeExp(e,t,o,i=!1,l=!1){let n,s,r=this._cells,a=!1;return!(this._tableParams&&this._tableParams.length>0)&&(n=o.topRow-t.topRow,s=o.leftCol-t.leftCol,l?(0!==n&&(r.row+=l&&this._absRow?0:n,r.row2+=this._isCellRange?l&&this._absRow2?0:n:l&&this._absRow?0:n,a=!0),0!==s&&(r.col+=l&&this._absCol?0:s,r.col2+=this._isCellRange?l&&this._absCol2?0:s:l&&this._absCol?0:s,a=!0),a):(t.contains(r)?(0!==n&&(r.row+=n,r.row2+=n,a=!0),0!==s&&(r.col+=s,r.col2+=s,a=!0)):t.intersects(r)?(t.intersectsRow(r)&&0!==n&&(t.topRow<=r.topRow?n<0?(r.row+=n,a=!0):n>0&&i&&(t.topRow<r.topRow&&(r.row-=r.topRow-t.topRow),r.row2-=t.rowSpan,a=!0):t.bottomRow>=r.bottomRow?n>0?(r.row2+=n,a=!0):n<0&&i&&(t.bottomRow>r.bottomRow&&(r.row2+=t.bottomRow-r.bottomRow),r.row+=t.rowSpan,a=!0):i&&(n<0&&o.topRow<r.topRow&&(r.row+=t.rowSpan),n>0&&o.bottomRow>r.bottomRow&&(r.row2-=t.rowSpan),a=!0)),t.intersectsColumn(r)&&0!==s&&(t.leftCol<=r.leftCol?s<0?(r.col+=s,a=!0):s>0&&i&&(t.leftCol<r.leftCol&&(r.col-=r.leftCol-t.leftCol),r.col2-=t.columnSpan,a=!0):t.rightCol>=r.rightCol?s>0?(r.col2+=s,a=!0):s<0&&i&&(t.rightCol>r.rightCol&&(r.col2+=t.rightCol-r.rightCol),r.col+=t.columnSpan,a=!0):i&&(s<0?r.col+=t.columnSpan:r.col2-=t.columnSpan,a=!0))):i&&(r.topRow>=o.topRow&&r.topRow<t.topRow&&n<0&&(r.row+=o.rowSpan,r.row2+=o.rowSpan,a=!0),r.topRow>t.bottomRow&&r.bottomRow<=o.bottomRow&&n>0&&(r.row-=o.rowSpan,r.row2-=o.rowSpan,a=!0),r.leftCol>=o.leftCol&&r.leftCol<t.leftCol&&s<0&&(r.col+=o.columnSpan,r.col2+=o.columnSpan,a=!0),r.leftCol>t.rightCol&&r.rightCol<=o.rightCol&&s>0&&(r.col-=o.columnSpan,r.col2-=o.columnSpan,a=!0)),a))}_updateCellRangeExpForReorderingRows(e){let t,o=this._cells;return(t=this._cells.row+e)<0?t=0:t>=this._flex.rows.length&&(t=this._flex.rows.length-1),o.row=t,this._isCellRange&&((t=this._cells.row2+e)<0?t=0:t>=this._flex.rows.length&&(t=this._flex.rows.length-1)),o.row2=t,!0}_updateCellBoundary(e,t){let o=this._cells;return(!this._sheetRef||this._sheetRef.toLowerCase()===this._flex.selectedSheet.name.toLowerCase())&&(o.row===o.row2&&o.row===e&&t===o.col2+1?(o.col2+=1,!0):o.col===o.col2&&o.col===t&&e===o.row2+1&&(o.row2+=1,!0))}_getStringExpression(){return this._tableParams&&this._tableParams.length>0?this._getTableParamsStringExpression():(this._sheetRef?this._sheetRef+"!":"")+wjcXlsx.Workbook.xlsxAddress(this._cells.row,this._cells.col,this._absRow,this._absCol)+(this._isCellRange?":"+wjcXlsx.Workbook.xlsxAddress(this._cells.row2,this._cells.col2,this._absRow2,this._absCol2):"")}_getTableParamsStringExpression(){let e,t=0,o="",i=this._tableParams.length,l=!1;for(;t<i;t++)"#"===(e=this._tableParams[t])[0]?(o+="["+e+"]",t<i-1&&(o+=", ")):l?o+=": ["+e+"]":(o+="["+e+"]",l=!0);return i>1&&(o="["+o+"]"),this._tableName&&(o=this._tableName+o),o}};export class _FunctionExpression extends _Expression{constructor(e,t,o,i=!0){super(),this._funcId=e,this._funcDefinition=t,this._params=o,this._needCacheEvaluatedVal=i}evaluate(e,t,o){return this._needCacheEvaluatedVal?(null==this._evaluatedValue&&(this._evaluatedValue=this._funcDefinition.func(this._params,o,e,t)),this._evaluatedValue):this._funcDefinition.func(this._params,o,e,t)}_updateCellRangeExp(e,t,o,i,l,n){let s,r,a,h=!1;if(this._params&&this._params.length>0)for(s=0;s<this._params.length;s++)a=(r=this._params[s])._updateCellRangeExp(e,t,o,i,l,n),h||(h=h||a);return h}_moveCellRangeExp(e,t,o,i=!1,l=!1){let n,s,r,a=!1;if(this._params&&this._params.length>0)for(n=0;n<this._params.length;n++)r=(s=this._params[n])._moveCellRangeExp(e,t,o,i,l),a||(a=a||r);return a}_updateCellRangeExpForReorderingRows(e){let t,o,i,l=!1;if(this._params&&this._params.length>0)for(t=0;t<this._params.length;t++)i=(o=this._params[t])._updateCellRangeExpForReorderingRows(e),l||(l=l||i);return l}_updateCellBoundary(e,t){let o;return!!(this._params&&1===this._params.length&&(o=this._params[0])instanceof _CellRangeExpression)&&o._updateCellBoundary(e,t)}_getStringExpression(){return this._funcId+this._parseParamsExpToString()}_parseParamsExpToString(){let e,t,o;if(this._params&&this._params.length>0){for(o="",e=0;e<this._params.length;e++)t=this._params[e],0===e&&(o+="("),o+=t._getStringExpression(),e<this._params.length-1?o+=", ":o+=")";return o}return"()"}};export class _UndoAction{constructor(e){this._owner=e,this._sheetIndex=e.selectedSheetIndex}get sheetIndex(){return this._sheetIndex}undo(){throw"This abstract method must be overridden."}redo(){throw"This abstract method must be overridden."}saveNewState(){throw"This abstract method must be overridden."}};export class _EditAction extends _UndoAction{constructor(e,t){super(e),this._isPaste=!1,this._selections=t?[t]:e.selectedSheet.selectionRanges.length>0?e.selectedSheet.selectionRanges.slice():[e.selection.clone()],this._mergeAction=new _CellMergeAction(e),this._cellStyleAction=new _CellStyleAction(e),this._saveValues(!0)}get isPaste(){return this._isPaste}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return!!this._saveValues(!1)&&(this._mergeAction.saveNewState(),this._cellStyleAction.saveNewState(),this._checkActionState())}markIsPaste(){this._isPaste=!0}updateForPasting(e){var t=this._selections[this._selections.length-1],o=this._owner.getCellData(e.row,e.col,!!this._owner.columns[e.col].dataMap);t||(t=this._owner.selection,this._selections=[t]),o=null==o?"":o,this._oldValues["r"+e.row+"_c"+e.col]={row:e.row,col:e.col,value:o},t.row=Math.min(t.topRow,e.topRow),t.row2=Math.max(t.bottomRow,e.bottomRow),t.col=Math.min(t.leftCol,e.leftCol),t.col2=Math.max(t.rightCol,e.rightCol)}_storeDeletedTables(e){null==this._deletedTables&&(this._deletedTables=[]),this._deletedTables.push(e)}_checkActionState(){var e=this,t=!1;return Object.keys(e._oldValues).forEach(o=>{var i,l;t||(i=e._oldValues[o],l=e._newValues[o],i&&l&&i.value!==l.value&&(t=!0))}),t||e._mergeAction._checkActionState()||e._cellStyleAction._checkActionState()}_saveValues(e){var t,o,i,l,n,s,r={};for(t=0;t<this._selections.length;t++)for(l=(o=this._selections[t]).topRow;l<=o.bottomRow;l++)for(n=o.leftCol;n<=o.rightCol;n++){if(!(i=this._owner.columns[n]))return!1;s=null==(s=this._owner.getCellData(l,n,!!i.dataMap))?"":s,r["r"+l+"_c"+n]={row:l,col:n,value:s}}return e?this._oldValues=r:this._newValues=r,!0}_handleUndoRedo(e){var t=this;t._owner._clearCalcEngine(),t._owner.selectedSheet.selectionRanges.clear(),t._owner.deferUpdate(()=>{var o,i,l,n,s,r,a,h=e?t._oldValues:t._newValues;if(t._deletedTables&&t._deletedTables.length>0)for(o=0;o<t._deletedTables.length;o++)i=t._deletedTables[o],e?t._owner.selectedSheet.tables.push(i):t._owner.selectedSheet.tables.remove(i);for(l=0;l<t._selections.length;l++)n=t._selections[l],t._owner.selectedSheet.selectionRanges.push(n);if(Object.keys(h).forEach(e=>{var o=h[e];t._owner.setCellData(o.row,o.col,o.value)}),t._affectedFormulas&&(s=e?t._affectedFormulas.oldFormulas:t._affectedFormulas.newFormulas),s&&s.length>0)for(a=0;a<s.length;a++)r=s[a],t._owner.setCellData(r.point.x,r.point.y,r.formula);e?(t._mergeAction.undo(),t._cellStyleAction.undo()):(t._mergeAction.redo(),t._cellStyleAction.redo()),t._owner.refresh(!1)})}};export class _ColumnResizeAction extends _UndoAction{constructor(e,t,o){super(e),this._panel=t,this._colIndex=o,this._oldColWidth=t.columns[o].width}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return this._newColWidth=this._panel.columns[this._colIndex].width,this._oldColWidth!==this._newColWidth}_handleUndoRedo(e){var t=this._panel.columns[this._colIndex];t&&(t.width=e?this._oldColWidth:this._newColWidth)}};export class _RowResizeAction extends _UndoAction{constructor(e,t,o){super(e),this._panel=t,this._rowIndex=o,this._oldRowHeight=t.rows[o].height}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return this._newRowHeight=this._panel.rows[this._rowIndex].height,this._oldRowHeight!==this._newRowHeight}_handleUndoRedo(e){var t=this._panel.rows[this._rowIndex];t&&(t.height=e?this._oldRowHeight:this._newRowHeight)}};export class _ColumnsChangedAction extends _UndoAction{constructor(e,t,o,i){super(e),this._columnIndex=t,this._count=o,this._isAdding=i,this._saveValues(!0)}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return this._saveValues(!1),!0}_saveValues(e){var t,o,i,l,n=[],s=[];if(null==this._isAdding)for(t=0;t<this._owner.columns.length;t++)n.push(this._owner.columns[t]);else if(e&&!this._isAdding||!e&&this._isAdding)for(t=this._columnIndex;t<this._columnIndex+this._count&&t<this._owner.columns.length;t++)n.push(this._owner.columns[t]);if(this._owner.selectedSheet.tables&&this._owner.selectedSheet.tables.length>0)for(o=0;o<this._owner.selectedSheet.tables.length;o++)(i=this._owner.selectedSheet.tables[o])&&i.sheet.name===this._owner.selectedSheet.name&&s.push({name:i.name,range:i.getRange(),columns:i.getColumns()});l={columns:n,sortList:this._owner.sortManager._cloneSortList(this._owner.sortManager._committedList),styledCells:this._owner.selectedSheet?this._owner._cloneObject(this._owner.selectedSheet._styledCells):null,mergedCells:this._owner.selectedSheet?this._owner.selectedSheet._cloneMergedCells():null,tableRanges:s,selection:this._owner.selection,filterDef:this._owner.selectedSheet._filterDefinition},e?this._oldValue=l:this._newValue=l}_handleUndoRedo(e){var t,o,i,l,n,s,r,a,h,d,c,_,u=this,g=e?u._oldValue:u._newValue;u._owner.selectedSheet&&(u._owner.deferUpdate(()=>{let w;if(u._owner._isUndoing=!0,u._owner._clearCalcEngine(),u._owner.finishEditing(),null==u._isAdding&&(u._owner.columns.clear(),u._columnIndex=0),u._owner.selectedSheet._styledCells=null,u._owner.selectedSheet._mergedRanges.length=0,u._owner.columns.beginUpdate(),g.columns&&g.columns.length>0)for(t=0;t<g.columns.length;t++)(o=g.columns[t])&&o.isVisible&&(u._owner.columns.insert(u._columnIndex+t,o),u._owner.itemsSource&&(w=u._owner.allowAddNew&&u._owner.newRowAtTop?u._owner.rows[1]:u._owner.rows[0])&&(w._ubv||(w._ubv={}),w._ubv[o._hash]=o.header));else for(t=u._columnIndex+u._count-1;t>=u._columnIndex;t--)(o=u._owner.columns[t])&&o.isVisible&&u._owner.columns.removeAt(t);for(u._owner.columns.endUpdate(),u._owner.selectedSheet._styledCells=u._owner._cloneObject(g.styledCells),_=0;_<g.mergedCells.length;_++)u._owner.selectedSheet._mergedRanges[_]=g.mergedCells[_];for(l=0;l<g.tableRanges.length;l++)n=g.tableRanges[l],(s=u._owner._getTable(n.name))&&s._setTableRange(n.range,n.columns);if(u._affectedFormulas&&(a=e?u._affectedFormulas.oldFormulas:u._affectedFormulas.newFormulas),a&&a.length>0)for(i=0;i<a.length;i++)null!=(r=a[i]).point?r.sheet.name===u._owner.selectedSheet.name?u._owner.setCellData(r.point.x,r.point.y,r.formula):r.sheet.grid.setCellData(r.point.x,r.point.y,r.formula):r.row._ubv[r.column._hash]=r.formula;if(u._deletedTables&&u._deletedTables.length>0)for(l=0;l<u._deletedTables.length;l++)s=u._deletedTables[l],e?u._owner.selectedSheet.tables.push(s):u._owner.selectedSheet.tables.remove(s);if(u._affectedDefinedNameVals&&(h=e?u._affectedDefinedNameVals.oldDefinedNameVals:u._affectedDefinedNameVals.newDefinedNameVals),h&&h.length>0)for(i=0;i<h.length;i++)d=h[i],(c=u._owner._getDefinedNameIndexByName(d.name))>-1&&(u._owner.definedNames[c].value=d.value);u._owner.selectedSheet.grid.wj_sheetInfo.styledCells=u._owner.selectedSheet._styledCells,u._owner.selectedSheet.grid.wj_sheetInfo.mergedRanges=u._owner.selectedSheet._mergedRanges,u._owner._isUndoing=!1}),u._owner._copyColumnsToSelectedSheet(),u._owner.sortManager.sortDescriptions.sourceCollection=g.sortList.slice(),u._owner.selectedSheet._filterDefinition=g.filterDef,u._owner.sortManager.commitSort(!1),u._owner.selection=g.selection)}};export class _RowsChangedAction extends _UndoAction{constructor(e,t,o,i){super(e),this._rowIndex=t,this._count=o,this._isAdding=i,this._saveValues(!0)}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return this._saveValues(!1),!0}_saveValues(e){var t,o,i,l,n,s,r,a,h=[],d=[],c=[];if(null==this._isAdding)if(this._owner.itemsSource)for(s=this._owner.itemsSource instanceof wjcCore.CollectionView?this._owner.itemsSource.sourceCollection.slice():this._owner.itemsSource.slice(),i=0;i<this._owner.columns.length;i++)d.push(this._owner.columns[i]);else for(t=0;t<this._owner.rows.length;t++)h.push(this._owner.rows[t]);else{if(e&&!this._isAdding||!e&&this._isAdding)for(t=this._rowIndex;t<this._rowIndex+this._count&&t<this._owner.rows.length;t++)(o=this._owner.rows[t]).isVisible||this._isAdding?h.push(o):h.push(null);this._owner.collectionView&&this._owner.collectionView.sortDescriptions.length>0&&(r=this._owner.collectionView._view.slice())}if(this._owner.selectedSheet.tables&&this._owner.selectedSheet.tables.length>0)for(l=0;l<this._owner.selectedSheet.tables.length;l++)(n=this._owner.selectedSheet.tables[l])&&n.sheet.name===this._owner.selectedSheet.name&&c.push({name:n.name,range:n.getRange(),setting:{showHeaderRow:n.showHeaderRow,showTotalRow:n.showTotalRow}});a={rows:h,columns:d,itemsSource:s,styledCells:this._owner.selectedSheet?this._owner._cloneObject(this._owner.selectedSheet._styledCells):null,mergedCells:this._owner.selectedSheet?this._owner.selectedSheet._cloneMergedCells():null,tableSettings:c,selection:this._owner.selection,dataView:r,scrollPosition:this._owner.scrollPosition},e?this._oldValue=a:this._newValue=a}_handleUndoRedo(e){var t,o,i,l,n,s,r,a,h,d,c,_,u,g,w,m,f,C=this,p=!!C._owner.itemsSource,S=e?C._oldValue:C._newValue;C._owner.selectedSheet&&(C._owner.deferUpdate(()=>{if(C._owner._isUndoing=!0,C._owner._clearCalcEngine(),C._owner.finishEditing(),null==C._isAdding&&(C._owner.itemsSource&&C._owner.columns.clear(),C._owner.rows.clear(),C._rowIndex=0),C._owner.selectedSheet._styledCells=null,C._owner.selectedSheet._mergedRanges.length=0,null==this._isAdding&&p){for(w=C._owner.autoGenerateColumns,C._owner.autoGenerateColumns=!1,C._owner.collectionView.beginUpdate(),C._owner.itemsSource instanceof wjcCore.CollectionView?(g=[0,C._owner.itemsSource.sourceCollection.length].concat(S.itemsSource),Array.prototype.splice.apply(C._owner.itemsSource.sourceCollection,g)):C._owner.itemsSource=S.itemsSource.slice(),C._owner.columns.beginUpdate(),i=0;i<S.columns.length;i++)C._owner.columns.push(S.columns[i]);C._owner.columns.endUpdate(),C._owner.collectionView.endUpdate(),C._owner.autoGenerateColumns=w}else{if(p?(w=C._owner.autoGenerateColumns,C._owner.autoGenerateColumns=!1,m=C._rowIndex-(C._owner.allowAddNew&&C._owner.newRowAtTop?2:1),C._owner.collectionView.beginUpdate()):C._owner.rows.beginUpdate(),S.rows&&S.rows.length>0)for(t=0;t<S.rows.length;t++)(o=S.rows[t])&&(p&&o.dataItem?(f=null!=o.dataItem._itemIdx?o.dataItem._itemIdx:m+t,C._owner.itemsSource instanceof wjcCore.CollectionView?(C._owner._updateItemIndexForInsertingRow(C._owner.itemsSource.sourceCollection,f,1),C._owner.itemsSource.sourceCollection.splice(f,0,o.dataItem)):(C._owner._updateItemIndexForInsertingRow(C._owner.itemsSource,f,1),C._owner.itemsSource.splice(f,0,o.dataItem))):C._owner.rows.insert(C._rowIndex+t,o));else for(t=C._rowIndex+C._count-1;t>=C._rowIndex;t--)(o=C._owner.rows[t])&&(p&&o.dataItem?(f=null!=o.dataItem._itemIdx?o.dataItem._itemIdx:t-(C._owner.allowAddNew&&C._owner.newRowAtTop?2:1),C._owner.itemsSource instanceof wjcCore.CollectionView?(C._owner.itemsSource.sourceCollection.splice(f,1),C._owner._updateItemIndexForRemovingRow(C._owner.itemsSource.sourceCollection,f)):(C._owner.itemsSource.splice(f,1),C._owner._updateItemIndexForRemovingRow(C._owner.itemsSource,f))):C._owner.rows.removeAt(t));p?(C._owner._lastCount=C._owner.collectionView.itemCount,C._owner.collectionView.endUpdate(),S.dataView&&S.dataView.length>0&&(C._owner.collectionView._view=S.dataView,C._owner.collectionView._pgView=C._owner.collectionView._getPageView(),C._owner.itemsSource instanceof wjcCore.CollectionView||(C._owner.selectedSheet.grid.collectionView._view=S.dataView,C._owner.selectedSheet.grid.collectionView._pgView=C._owner.selectedSheet.grid.collectionView._getPageView()),C._owner._bindGrid(!1),C._owner.selectedSheet.grid._bindGrid(!1)),C._owner.autoGenerateColumns=w):C._owner.rows.endUpdate()}for(C._owner.selectedSheet._styledCells=C._owner._cloneObject(S.styledCells),u=0;u<S.mergedCells.length;u++)C._owner.selectedSheet._mergedRanges[u]=S.mergedCells[u];for(n=0;n<S.tableSettings.length;n++)s=S.tableSettings[n],(r=C._owner._getTable(s.name))&&(r._showHeaderRow=s.setting.showHeaderRow,r._showTotalRow=s.setting.showTotalRow,r._setTableRange(s.range));if(C._affectedFormulas&&(h=e?C._affectedFormulas.oldFormulas:C._affectedFormulas.newFormulas),h&&h.length>0)for(l=0;l<h.length;l++)null!=(a=h[l]).point?a.sheet.name===C._owner.selectedSheet.name?C._owner.setCellData(a.point.x,a.point.y,a.formula):a.sheet.grid.setCellData(a.point.x,a.point.y,a.formula):a.row._ubv[a.column._hash]=a.formula;if(C._deletedTables&&C._deletedTables.length>0)for(n=0;n<C._deletedTables.length;n++)r=C._deletedTables[n],e?C._owner.selectedSheet.tables.push(r):C._owner.selectedSheet.tables.remove(r);if(C._affectedDefinedNameVals&&(d=e?C._affectedDefinedNameVals.oldDefinedNameVals:C._affectedDefinedNameVals.newDefinedNameVals),d&&d.length>0)for(l=0;l<d.length;l++)c=d[l],(_=C._owner._getDefinedNameIndexByName(c.name))>-1&&(C._owner.definedNames[_].value=c.value);C._owner.selectedSheet.grid.wj_sheetInfo.styledCells=C._owner.selectedSheet._styledCells,C._owner.selectedSheet.grid.wj_sheetInfo.mergedRanges=C._owner.selectedSheet._mergedRanges,C._owner.selection=S.selection,C._owner.scrollPosition=S.scrollPosition,C._owner._isUndoing=!1}),C._owner._copyRowsToSelectedSheet())}};export class _CellStyleAction extends _UndoAction{constructor(e,t){super(e),this._oldStyledCells=t?e._cloneObject(t):e.selectedSheet?e._cloneObject(e.selectedSheet._styledCells):null}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return this._newStyledCells=this._owner.selectedSheet?this._owner._cloneObject(this._owner.selectedSheet._styledCells):null,!0}_checkActionState(){return null!=this._oldStyledCells&&null==this._newStyledCells||null==this._oldStyledCells&&null!=this._newStyledCells||null!=this._oldStyledCells&&null!=this._newStyledCells&&this._oldStyledCells.length!==this._newStyledCells.length}_handleUndoRedo(e){var t;this._owner.selectedSheet&&(t=e?this._oldStyledCells:this._newStyledCells,this._owner.selectedSheet._styledCells=this._owner._cloneObject(t),this._owner.selectedSheet.grid.wj_sheetInfo.styledCells=this._owner.selectedSheet._styledCells,this._owner.refresh(!1))}};export class _CellMergeAction extends _UndoAction{constructor(e){super(e),this._oldMergedCells=e.selectedSheet?e.selectedSheet._cloneMergedCells():null}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return this._newMergedCells=this._owner.selectedSheet?this._owner.selectedSheet._cloneMergedCells():null,!0}_handleUndoRedo(e){var t,o;if(this._owner.selectedSheet){if(t=e?this._oldMergedCells:this._newMergedCells,this._owner._clearCalcEngine(),t)for(this._owner.selectedSheet._mergedRanges.length=0,o=0;o<t.length;o++)this._owner.selectedSheet._mergedRanges[o]=t[o];this._owner.selectedSheet.grid.wj_sheetInfo.mergedRanges=this._owner.selectedSheet._mergedRanges,this._owner.refresh(!0)}}_checkActionState(){let e,t,o;if(null!=this._oldMergedCells&&null==this._newMergedCells||null==this._oldMergedCells&&null!=this._newMergedCells)return!0;if(null!=this._oldMergedCells&&null!=this._newMergedCells&&this._oldMergedCells.length!==this._newMergedCells.length)return!0;if(null!=this._oldMergedCells&&null!=this._newMergedCells&&this._oldMergedCells.length===this._newMergedCells.length)for(e=0;e<this._oldMergedCells.length;e++)if(o=this._oldMergedCells[e],t=this._oldMergedCells[e],!o.equals(t))return!0;return!1}};export class _SortColumnAction extends _UndoAction{constructor(e){super(e),this._saveValues(!0)}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return this._saveValues(!1),!0}_saveValues(e){var t,o,i,l,n,s,r,a,h,d=[];for(o=0;o<this._owner.columns.length;o++)d.push(this._owner.columns[o]);if(this._owner.itemsSource){l=this._owner.allowAddNew&&this._owner.newRowAtTop?2:1,n=[];for(let e=0;e<this._owner.rows.length-l;e++)(r=(s=this._owner.rows[e+l]).dataItem)&&(n[null!=r._itemIdx?r._itemIdx:e]=s.visible);e&&(h=this._owner.collectionView._view.slice())}else for(i=[],t=0;t<this._owner.rows.length;t++)i.push(this._owner.rows[t]);a={sortList:this._owner.sortManager._committedList.slice(),rows:i,columns:d,selection:this._owner.selection.clone(),formulas:this._owner._scanFormulas(),styledCells:this._owner.selectedSheet?this._owner._cloneObject(this._owner.selectedSheet._styledCells):null,rowsVisible:n,dataView:h},e?this._oldValue=a:this._newValue=a}_handleUndoRedo(e){var t,o,i,l,n=this,s=e?n._oldValue:n._newValue,r=!!n._owner.itemsSource,a=this._owner.itemsSource instanceof wjcCore.CollectionView;n._owner.selectedSheet&&(n._owner._isUndoing=!0,n._owner.deferUpdate(()=>{if(n._owner._clearCalcEngine(),n._owner.sortManager.sortDescriptions.sourceCollection=s.sortList.slice(),n._owner.sortManager.commitSort(!1),n._owner.selectedSheet._styledCells=n._owner._cloneObject(s.styledCells),r)s.dataView&&s.dataView.length>0&&(n._owner.collectionView._view=s.dataView,n._owner.collectionView._pgView=n._owner.collectionView._getPageView(),a||(n._owner.selectedSheet.grid.collectionView._view=s.dataView,n._owner.selectedSheet.grid.collectionView._pgView=n._owner.selectedSheet.grid.collectionView._getPageView()),n._owner._bindGrid(!1),n._owner.selectedSheet.grid._bindGrid(!1));else{for(n._owner.rows.clear(),n._owner.selectedSheet.grid.rows.clear(),t=0;t<s.rows.length;t++)i=s.rows[t],n._owner.selectedSheet.grid.rows.push(i),n._owner.rows.push(i);for(n._owner.columns.clear(),o=0;o<s.columns.length;o++)l=s.columns[o],n._owner.columns.push(l);n._owner._resetFormulas(s.formulas)}n._owner._isUndoing=!1}))}};export class _MoveCellsAction extends _UndoAction{constructor(e,t,o,i){super(e),e.selectedSheet&&(0===t.topRow&&t.bottomRow===e.rows.length-1?this._isDraggingColumns=!0:this._isDraggingColumns=!1,this._isCopyCells=i,this._dragRange=t,this._dropRange=o,this._saveValues(!0))}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return!!this._owner.selectedSheet&&(!!this._dropRange&&(this._saveValues(!1),!0))}_saveValues(e){var t,o,i,l,n,s,r,a,h,d,c,_;for(c=[],_={},t=this._dropRange.topRow;t<=this._dropRange.bottomRow;t++)for(o=this._dropRange.leftCol;o<=this._dropRange.rightCol;o++)this._isDraggingColumns&&(_[o]||(_[o]={dataType:this._owner.columns[o].dataType,align:this._owner.columns[o].align,format:this._owner.columns[o].format})),i=t*this._owner.columns.length+o,n=this._owner.selectedSheet._styledCells[i]?this._owner._cloneObject(this._owner.selectedSheet._styledCells[i]):null,l=this._owner.getCellData(t,o,!1),c.push({rowIndex:t,columnIndex:o,cellContent:l,cellStyle:n});if(e?(this._oldDroppingCells=c,this._oldDroppingColumnSetting=_):(this._newDroppingCells=c,this._newDroppingColumnSetting=_),this._isCopyCells){if(this._isDraggingColumns)if(e)for(t=this._dragRange.topRow;t<=this._dragRange.bottomRow;t++)for(o=this._dragRange.leftCol;o<=this._dragRange.rightCol;o++)(a=this._owner.selectedSheet.findTable(t,o))&&(h=a.getRange(),d=a.getColumns(),a.showHeaderRow&&t===h.topRow&&(this._draggingTableColumns||(this._draggingTableColumns=[]),this._draggingTableColumns.push({rowIndex:t,columnIndex:o,cellContent:d[o-h.leftCol].name})));else if(this._draggingTableColumns&&this._draggingTableColumns.length>0&&this._draggingTableColumns&&this._draggingTableColumns.length>0)for(s=0;s<this._draggingTableColumns.length;s++)r=this._draggingTableColumns[s],(a=this._owner.selectedSheet.findTable(r.rowIndex,r.columnIndex))&&(h=a.getRange(),d=a.getColumns(),a.showHeaderRow&&r.rowIndex===h.topRow&&(r.updatedCellContent=d[r.columnIndex-h.leftCol].name))}else if(e)for(this._draggingCells=[],this._draggingColumnSetting={},t=this._dragRange.topRow;t<=this._dragRange.bottomRow;t++)for(o=this._dragRange.leftCol;o<=this._dragRange.rightCol;o++)this._isDraggingColumns&&(this._draggingColumnSetting[o]||(this._draggingColumnSetting[o]={dataType:this._owner.columns[o].dataType,align:this._owner.columns[o].align,format:this._owner.columns[o].format})),i=t*this._owner.columns.length+o,n=this._owner.selectedSheet._styledCells[i]?this._owner._cloneObject(this._owner.selectedSheet._styledCells[i]):null,l=this._owner.getCellData(t,o,!1),this._draggingCells.push({rowIndex:t,columnIndex:o,cellContent:l,cellStyle:n});else if(this._isDraggingColumns&&this._draggingCells&&this._draggingCells.length>0)for(s=0;s<this._draggingCells.length;s++)r=this._draggingCells[s],(a=this._owner.selectedSheet.findTable(r.rowIndex,r.columnIndex))&&(h=a.getRange(),d=a.getColumns(),a.showHeaderRow&&r.rowIndex===h.topRow&&(r.updatedCellContent=d[r.columnIndex-h.leftCol].name))}_handleUndoRedo(e){var t,o,i,l,n,s,r,a,h,d,c=this,_=e?c._oldDroppingCells:c._newDroppingCells,u=e?c._oldDroppingColumnSetting:c._newDroppingColumnSetting;c._owner.selectedSheet&&(c._owner._clearCalcEngine(),c._owner.deferUpdate(()=>{var g,w,m;if(c._affectedFormulas&&(s=e?c._affectedFormulas.oldFormulas:c._affectedFormulas.newFormulas),s&&s.length>0)for(t=0;t<s.length;t++)(r=s[t]).sheet.name===c._owner.selectedSheet.name?c._owner.setCellData(r.point.x,r.point.y,r.formula):r.sheet.grid.setCellData(r.point.x,r.point.y,r.formula);if(c._affectedDefinedNameVals&&(a=e?c._affectedDefinedNameVals.oldDefinedNameVals:c._affectedDefinedNameVals.newDefinedNameVals),a&&a.length>0)for(t=0;t<a.length;t++)h=a[t],(d=c._owner._getDefinedNameIndexByName(h.name))>-1&&(c._owner.definedNames[d].value=h.value);for(t=0;t<_.length;t++)o=_[t],c._owner.setCellData(o.rowIndex,o.columnIndex,o.cellContent),(g=c._owner.selectedSheet.findTable(o.rowIndex,o.columnIndex))&&(w=g.getRange(),m=g.getColumns(),g.showHeaderRow&&o.rowIndex===w.topRow&&(m[o.columnIndex-w.leftCol].name=o.cellContent)),i=o.rowIndex*c._owner.columns.length+o.columnIndex,o.cellStyle?c._owner.selectedSheet._styledCells[i]=o.cellStyle:delete c._owner.selectedSheet._styledCells[i];if(c._isDraggingColumns&&u&&Object.keys(u).forEach(e=>{c._owner.columns[+e].dataType=u[+e].dataType?u[+e].dataType:wjcCore.DataType.Object,c._owner.columns[+e].align=u[+e].align,c._owner.columns[+e].format=u[+e].format}),c._isCopyCells){if(c._draggingTableColumns&&c._draggingTableColumns.length>0)for(t=0;t<c._draggingTableColumns.length;t++)o=c._draggingTableColumns[t],(g=c._owner.selectedSheet.findTable(o.rowIndex,o.columnIndex))&&(w=g.getRange(),m=g.getColumns(),g.showHeaderRow&&o.rowIndex===w.topRow&&(c._owner.setCellData(o.rowIndex,o.columnIndex,e?o.cellContent:o.updatedCellContent),m[o.columnIndex-w.leftCol].name=e?o.cellContent:o.updatedCellContent))}else{for(t=0;t<c._draggingCells.length;t++)o=c._draggingCells[t],(g=c._owner.selectedSheet.findTable(o.rowIndex,o.columnIndex))?(w=g.getRange(),m=g.getColumns(),g.showHeaderRow&&o.rowIndex===w.topRow?(c._owner.setCellData(o.rowIndex,o.columnIndex,e?o.cellContent:o.updatedCellContent),m[o.columnIndex-w.leftCol].name=e?o.cellContent:o.updatedCellContent):c._owner.setCellData(o.rowIndex,o.columnIndex,e?o.cellContent:null)):c._owner.setCellData(o.rowIndex,o.columnIndex,e?o.cellContent:null),i=o.rowIndex*c._owner.columns.length+o.columnIndex,e?o.cellStyle&&(c._owner.selectedSheet._styledCells[i]=o.cellStyle):c._owner.selectedSheet._styledCells[i]&&delete c._owner.selectedSheet._styledCells[i];if(c._isDraggingColumns&&c._draggingColumnSetting&&Object.keys(c._draggingColumnSetting).forEach(t=>{c._owner.columns[+t].dataType=e&&c._draggingColumnSetting[+t].dataType?c._draggingColumnSetting[+t].dataType:wjcCore.DataType.Object,c._owner.columns[+t].align=e?c._draggingColumnSetting[+t].align:null,c._owner.columns[+t].format=e?c._draggingColumnSetting[+t].format:null}),e){if(c._isDraggingColumns)if(c._dragRange.leftCol<c._dropRange.leftCol)for(n=c._dragRange.leftCol,l=c._dropRange.leftCol;l<=c._dropRange.rightCol;l++)c._owner._updateColumnFiler(l,n),n++;else for(n=c._dragRange.rightCol,l=c._dropRange.rightCol;l>=c._dropRange.leftCol;l--)c._owner._updateColumnFiler(l,n),n--}else if(c._isDraggingColumns)if(c._dragRange.leftCol>c._dropRange.leftCol)for(n=c._dropRange.leftCol,l=c._dragRange.leftCol;l<=c._dragRange.rightCol;l++)c._owner._updateColumnFiler(l,n),n++;else for(n=c._dropRange.rightCol,l=c._dragRange.rightCol;l>=c._dragRange.leftCol;l--)c._owner._updateColumnFiler(l,n),n--}}))}};export class _CutAction extends _UndoAction{constructor(e){super(e),this._oldValues=[],this._mergeAction=new _CellMergeAction(e),this._celltyleAction=new _CellStyleAction(e),this._cutSheet=e._copiedSheet,this._selection=e.selection,this._cutSelection=e.selectionMode===wjcGrid.SelectionMode.ListBox?e._getSelectionForListBoxMode(this._cutSheet.grid):e._copiedRanges[0],this._saveCutValues(!0)}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){var e,t,o;this._cutSheet===this._owner.selectedSheet?this._owner:this._cutSheet.grid;for(this._saveCutValues(!1),this._newValues=[],e=this._selection.topRow;e<=this._selection.bottomRow;e++)for(t=this._selection.leftCol;t<=this._selection.rightCol;t++){if(!this._owner.columns[t])return!1;o=null==(o=this._owner.getCellData(e,t,!!this._owner.columns[t].dataMap))?"":o,this._newValues.push({row:e,col:t,value:o})}return this._mergeAction.saveNewState(),this._celltyleAction.saveNewState(),!0}updateForPasting(e){var t=this._owner.getCellData(e.row,e.col,!!this._owner.columns[e.col].dataMap);t=null==t?"":t,this._oldValues.push({row:e.row,col:e.col,value:t}),this._selection.row=Math.min(this._selection.topRow,e.topRow),this._selection.row2=Math.max(this._selection.bottomRow,e.bottomRow),this._selection.col=Math.min(this._selection.leftCol,e.leftCol),this._selection.col2=Math.max(this._selection.rightCol,e.rightCol)}_saveCutValues(e){var t,o,i,l=this._cutSheet===this._owner.selectedSheet?this._owner:this._cutSheet.grid,n=[];for(t=this._cutSelection.topRow;t<=this._cutSelection.bottomRow;t++)if(null!=l.rows[t])for(o=this._cutSelection.leftCol;o<=this._cutSelection.rightCol;o++)i=null==(i=l.getCellData(t,o,!!l.columns[o].dataMap))?"":i,n.push({row:t,col:o,value:i});e?this._oldCutValues=n:this._newCutValues=n}_handleUndoRedo(e){var t=this,o=e?t._oldCutValues:t._newCutValues,i=e?t._oldValues:t._newValues;t._owner._clearCalcEngine(),t._owner.selectedSheet.selectionRanges.clear(),t._owner.deferUpdate(()=>{var l,n,s=t._cutSheet===t._owner.selectedSheet?t._owner:t._cutSheet.grid;for(t._owner.selectedSheet.selectionRanges.push(t._selection),l=0;l<o.length;l++)n=o[l],s.setCellData(n.row,n.col,n.value);for(l=0;l<i.length;l++)n=i[l],t._owner.setCellData(n.row,n.col,n.value);e?(t._mergeAction.undo(),t._celltyleAction.undo()):(t._mergeAction.redo(),t._celltyleAction.redo()),t._owner.refresh(!1)})}};export class _TableSettingAction extends _UndoAction{constructor(e,t){super(e),this._table=t,this._saveValues(!0)}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return this._saveValues(!1),!0}_saveValues(e){var t={name:this._table.name,style:this._table.style,showHeaderRow:this._table.showHeaderRow,showTotalRow:this._table.showTotalRow,showbandedRows:this._table.showBandedRows,showBandedColumns:this._table.showBandedColumns,alterFirstColumn:this._table.alterFirstColumn,alterLastColumn:this._table.alterLastColumn};e?this._oldTableSetting=t:this._newTableSetting=t}_handleUndoRedo(e){var t=e?this._oldTableSetting:this._newTableSetting;this._owner.beginUpdate(),this._owner._isUndoing=!0,this._table.name=t.name,this._table.style=t.style,this._table.showHeaderRow=t.showHeaderRow,this._table.showTotalRow=t.showTotalRow,this._table.showBandedRows=t.showbandedRows,this._table.showBandedColumns=t.showBandedColumns,this._table.alterFirstColumn=t.alterFirstColumn,this._table.alterLastColumn=t.alterLastColumn,this._owner._isUndoing=!1,this._owner.endUpdate()}};export class _TableAction extends _UndoAction{constructor(e,t){super(e),this._addedTable=t,t.showHeaderRow&&(this._orgHeaderCellsContent=t._orgHeaderCellsContent.slice())}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}_handleUndoRedo(e){var t,o,i;if(e?this._owner.selectedSheet.tables.remove(this._addedTable):this._owner.selectedSheet.tables.push(this._addedTable),this._addedTable.showHeaderRow)for(o=this._addedTable.getRange(),i=this._addedTable.getColumns(),t=0;t<o.columnSpan;t++)this._owner.setCellData(o.topRow,o.leftCol+t,e?this._orgHeaderCellsContent[t]:i[t].name);this._owner.refresh()}};export class _FilteringAction extends _UndoAction{constructor(e){super(e),this._oldFilterDefinition=e.filter.filterDefinition,this._oldRowsVisible=this._getRowsVisible()}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return this._newFilterDefinition=this._owner.filter.filterDefinition,this._newRowsVisible=this._getRowsVisible(),!0}_handleUndoRedo(e){let t=e?this._oldFilterDefinition:this._newFilterDefinition;this._owner.filter.filterDefinition!==t?(this._owner._isUndoing=!0,this._owner.selectedSheet._filterDefinition=t,this._owner.selectedSheet._applyFilterSetting(),this._owner._isUndoing=!1,this._owner.filter.apply()):this._setRowVisible(e)}_getRowsVisible(){let e,t=[],o=0;for(;o<this._owner.rows.length;o++)(e=this._owner.rows[o])&&t.push(e.visible);return t}_setRowVisible(e){let t,o=e?this._oldRowsVisible:this._newRowsVisible,i=0;for(;i<o.length;i++)(t=this._owner.rows[i])&&(t.visible=o[i])}};export class _FillAction extends _UndoAction{constructor(e,t){super(e),this._fillSource=t.clone(),this._oldCellSettings=e._orgCellSettings}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){return this._fillRange=this._owner.selection.clone(),this._newCellSettings=this._owner._getCellSettingsForFill(this._fillSource,this._fillRange),!0}_handleUndoRedo(e){let t,o,i,l,n,s,r=e?this._oldCellSettings:this._newCellSettings,a=e?this._fillSource:this._fillRange;if(this._owner.beginUpdate(),s=this._fillRange.topRow<this._fillSource.topRow?new wjcGrid.CellRange(this._fillRange.topRow,this._fillRange.col,this._fillSource.topRow-1,this._fillRange.col2):this._fillRange.leftCol===this._fillSource.leftCol&&this._fillRange.rightCol===this._fillSource.rightCol?new wjcGrid.CellRange(this._fillSource.bottomRow+1,this._fillRange.col,this._fillRange.bottomRow,this._fillRange.col2):this._fillRange.leftCol<this._fillSource.leftCol?new wjcGrid.CellRange(this._fillRange.row,this._fillRange.leftCol,this._fillRange.row2,this._fillSource.leftCol-1):new wjcGrid.CellRange(this._fillRange.row,this._fillSource.rightCol+1,this._fillRange.row2,this._fillRange.rightCol),this._owner._resetMergedRange(s),r&&r.length>0)for(t=0;t<r.length;t++)i=(o=r[t]).row,l=o.col,n=i*this._owner.columns.length+l,this._owner.selectedSheet._styledCells[n]=o.style,this._owner.setCellData(i,l,o.value),o.mergedCell&&this._owner.mergeRange(o.mergedCell);this._owner.selection=a,this._owner.endUpdate()}};export class _ContextMenu extends wjcCore.Control{constructor(e,t){super(e),this._idx=-1,this._isDisableDelRow=!1,this._isDisableConvertTable=!1,this._owner=t,this.applyTemplate("",this.getTemplate(),{_insRows:"insert-rows",_delRows:"delete-rows",_insCols:"insert-columns",_delCols:"delete-columns",_splitter:"splitter",_convertTable:"convert-table"}),this._init()}get visible(){return"none"!==this.hostElement.style.display}show(e,t){if(this._owner.selectedSheet){var o=(t?t.x:e.clientX)+(e?window.pageXOffset:0),i=(t?t.y:e.clientY)+(e?window.pageYOffset:0);this.hostElement.style.position="absolute",this.hostElement.style.display="inline",this._owner._isDisableDeleteRow(this._owner.selection.topRow,this._owner.selection.bottomRow)&&(this._isDisableDelRow=!0,wjcCore.addClass(this._delRows,"wj-state-disabled")),this._showTableOperation(),this._owner.selection.isValid||(this._isDisableConvertTable=!0,wjcCore.addClass(this._convertTable,"wj-state-disabled")),i+this.hostElement.clientHeight>window.innerHeight+(e?window.pageYOffset:0)&&(i-=this.hostElement.clientHeight),o+this.hostElement.clientWidth>window.innerWidth+(e?window.pageXOffset:0)&&(o-=this.hostElement.clientWidth),this.hostElement.style.top=i+"px",this.hostElement.style.left=o+"px"}}hide(){this._idx=-1;var e=this.hostElement.querySelectorAll(".wj-context-menu-item");this._removeSelectedState(e),this.hostElement.style.display="none",this._isDisableDelRow=!1,this._isDisableConvertTable=!1,wjcCore.removeClass(this._delRows,"wj-state-disabled"),wjcCore.removeClass(this._convertTable,"wj-state-disabled")}moveToNext(){var e=this.hostElement.querySelectorAll(".wj-context-menu-item");for(this._removeSelectedState(e),this._idx++,1===this._idx&&this._isDisableDelRow&&this._idx++;e[this._idx]&&"none"===e[this._idx].style.display;)this._idx++;this._idx>=e.length&&(this._idx=0),wjcCore.addClass(e[this._idx],"wj-context-menu-item-selected")}moveToPrev(){var e=this.hostElement.querySelectorAll(".wj-context-menu-item");for(this._removeSelectedState(e),this._idx--,1===this._idx&&this._isDisableDelRow&&this._idx--;this._idx>0&&"none"===e[this._idx].style.display;)this._idx--;this._idx<0&&(this._idx=e.length-1),wjcCore.addClass(e[this._idx],"wj-context-menu-item-selected")}moveToFirst(){var e=this.hostElement.querySelectorAll(".wj-context-menu-item");this._removeSelectedState(e),this._idx=0,wjcCore.addClass(e[this._idx],"wj-context-menu-item-selected")}moveToLast(){var e=this.hostElement.querySelectorAll(".wj-context-menu-item");this._removeSelectedState(e),this._idx=e.length-1,e[this._idx]&&"none"===e[this._idx].style.display&&this._idx--,wjcCore.addClass(e[this._idx],"wj-context-menu-item-selected")}handleContextMenu(){if(-1===this._idx)this.moveToNext();else{switch(this.hostElement.querySelectorAll(".wj-context-menu-item")[this._idx]){case this._insCols:this._owner.insertColumns();break;case this._insRows:this._owner.insertRows();break;case this._delCols:this._owner.deleteColumns();break;case this._delRows:this._isDisableDelRow||this._owner.deleteRows();break;case this._convertTable:this._addTable()}this.hide(),this._owner.hostElement.focus()}}_init(){var e=wjcCore.culture.FlexSheet,t=this,o=this.hostElement.querySelectorAll(".wj-context-menu-item");t._insRows.textContent=e.insertRow,t._delRows.textContent=e.deleteRow,t._insCols.textContent=e.insertCol,t._delCols.textContent=e.deleteCol,t._convertTable.textContent=e.convertTable,t.hostElement.style.zIndex="9999",document.querySelector("body").appendChild(t.hostElement),t.addEventListener(document.body,"mousemove",()=>{t._removeSelectedState(o)}),t.addEventListener(t.hostElement,"contextmenu",e=>{e.preventDefault()}),t.addEventListener(t._insRows,"click",e=>{t._owner.insertRows(),t.hide(),t._owner.hostElement.focus()}),t.addEventListener(t._delRows,"click",e=>{t._isDisableDelRow||t._owner.deleteRows(),t.hide(),t._owner.hostElement.focus()}),t.addEventListener(t._insCols,"click",e=>{t._owner.insertColumns(),t.hide(),t._owner.hostElement.focus()}),t.addEventListener(t._delCols,"click",e=>{t._owner.deleteColumns(),t.hide(),t._owner.hostElement.focus()}),t.addEventListener(t._convertTable,"click",e=>{t._isDisableConvertTable||t._addTable(),t.hide(),t._owner.hostElement.focus()})}_removeSelectedState(e){for(var t=0;t<e.length;t++)wjcCore.removeClass(e[t],"wj-context-menu-item-selected")}_showTableOperation(){var e,t,o=this._owner.selection;for(e=o.topRow;e<=o.bottomRow;e++)for(t=o.leftCol;t<=o.rightCol;t++)if(null!=this._owner.selectedSheet.findTable(e,t))return this._convertTable.style.display="none",void(this._splitter.style.display="none");o.isSingleCell||this._owner._containsMergedCells(o)?(this._convertTable.style.display="none",this._splitter.style.display="none"):(this._convertTable.style.display="",this._splitter.style.display="")}_addTable(){var e,t;if(e=this._owner.selectedSheet._addTable(this._owner.selection)){if(0===this._owner.undoStack.stackSize)return;t=new _TableAction(this._owner,e),this._owner.undoStack._addAction(t)}}};_ContextMenu.controlTemplate='<div class="wj-context-menu wj-control wj-flexsheet-context-menu" width="150px"><div class="wj-context-menu-item" wj-part="insert-rows"></div><div class="wj-context-menu-item" wj-part="delete-rows"></div><div class="wj-context-menu-item" wj-part="insert-columns"></div><div class="wj-context-menu-item" wj-part="delete-columns"></div><div class="wj-state-disabled" wj-part="splitter" style="width:100%;height:1px;background-color:lightgray;"></div><div class="wj-context-menu-item" wj-part="convert-table"></div></div>';export class _TabHolder extends wjcCore.Control{constructor(e,t){super(e),this._splitterMousedownHdl=this._splitterMousedownHandler.bind(this),this._owner=t,this.applyTemplate("",this.getTemplate(),{_divSheet:"left",_divSplitter:"splitter",_divRight:"right"}),this._init()}get sheetControl(){return this._sheetControl}get visible(){return"none"!==this.hostElement.style.display}set visible(e){this.hostElement.style.display=e?"block":"none",this._divSheet.style.display=e?"block":"none"}getSheetBlanketSize(){return 20}adjustSize(){var e=this._owner.scrollSize.width-this._owner.clientSize.width,t=(this._owner.scrollSize.height,this._owner.clientSize.height,this._divSplitter.parentElement);e<=0?(t.style.minWidth="100px",this._divSplitter.style.display="none",this._divRight.style.display="none",this._divSheet.style.width="100%",this._divSplitter.removeEventListener("mousedown",this._splitterMousedownHdl,!0)):(t.style.minWidth="300px",this._divSplitter.style.display="none",this._divRight.style.display="none",this._divSheet.style.width="100%",this._divSplitter.removeEventListener("mousedown",this._splitterMousedownHdl,!0),this._divSplitter.addEventListener("mousedown",this._splitterMousedownHdl,!0)),this._sheetControl._adjustSize()}_init(){var e=this;e._funSplitterMousedown=function(t){e._splitterMouseupHandler(t)},e._divSplitter.parentElement.style.height=e.getSheetBlanketSize()+"px",e._sheetControl=new _SheetTabs(e._divSheet,this._owner)}_splitterMousedownHandler(e){this._startPos=e.pageX,document.addEventListener("mousemove",this._splitterMousemoveHandler.bind(this),!0),document.addEventListener("mouseup",this._funSplitterMousedown,!0),e.preventDefault()}_splitterMousemoveHandler(e){null!==this._startPos&&void 0!==this._startPos&&this._adjustDis(e.pageX-this._startPos)}_splitterMouseupHandler(e){document.removeEventListener("mousemove",this._splitterMousemoveHandler,!0),document.removeEventListener("mouseup",this._funSplitterMousedown,!0),this._adjustDis(e.pageX-this._startPos),this._startPos=null}_adjustDis(e){var t=this._divRight.offsetWidth-e,o=this._divSheet.offsetWidth+e;t<=100?(t=100,e=this._divRight.offsetWidth-t,o=this._divSheet.offsetWidth+e):o<=100&&(e=(o=100)-this._divSheet.offsetWidth,t=this._divRight.offsetWidth-e),0!=e&&(this._divRight.style.width=t+"px",this._divSheet.style.width=o+"px",this._startPos=this._startPos+e)}};_TabHolder.controlTemplate='<div><div wj-part="left" style ="float:left;height:100%;overflow:hidden"></div><div wj-part="splitter" style="float:left;height:100%;width:6px;background-color:#e9eaee;padding:2px;cursor:e-resize"><div style="background-color:#8a9eb2;height:100%"></div></div><div wj-part="right" style="float:left;height:100%;background-color:#e9eaee"></div></div>';export class _FlexSheetCellFactory extends wjcGrid.CellFactory{updateCell(e,t,o,i,l){var n,s,r,a,h,d,c,_,u,g,w,m,f,C,p,S=e.grid;switch(e.cellType===wjcGrid.CellType.Cell&&this._resetCellStyle(i),super.updateCell(e,t,o,i,l),l&&!l.isSingleCell&&(t=l.row,o=l.col,l.row2,l.col2),p=S.selectedSheet,g=S._getBindingColumn(e,t,e.columns[o]),e.cellType){case wjcGrid.CellType.RowHeader:i.textContent=t+1+"";break;case wjcGrid.CellType.ColumnHeader:n=p&&p._showDefaultHeader||wjcCore.isNullOrWhiteSpace(g.header)||!wjcCore.isNullOrWhiteSpace(g.binding)&&(g.header===g.binding||g.header===wjcCore.toHeaderCase(g.binding))?FlexSheet.convertNumberToAlpha(o):g.header,i.textContent?i.innerHTML=i.innerHTML.replace(wjcCore.escapeHtml(i.textContent.trim()),n).replace(i.textContent,n):i.innerHTML+=n,i.style.textAlign="center";break;case wjcGrid.CellType.Cell:if(s=t*S.columns.length+o,c=p&&p._styledCells?p._styledCells[s]:null,l&&!l.isSingleCell&&(t=(m=this._getFirstVisibleCell(S,l)).row,o=m.col),e.rows[t]instanceof HeaderRow)e.columns[o].dataType===wjcCore.DataType.Boolean?1===i.childElementCount&&i.firstElementChild instanceof HTMLInputElement&&"checkbox"===i.firstElementChild.type&&(i.innerHTML=wjcCore.escapeHtml(S.getCellValue(t,o))):i.innerHTML||(i.innerHTML=wjcCore.escapeHtml(S.getCellValue(t,o))),wjcCore.addClass(i,"wj-header-row");else if(a=S.getCellValue(t,o,!1),h=S.getCellData(t,o,!1),d=null!=h&&"string"==typeof h&&"="===h[0],f=e.rows[t]instanceof wjcGrid.GroupRow,w=(c?c.format:null)||(f?null:g.format),S.editRange&&S.editRange.contains(t,o)?!wjcCore.isNumber(a)||g.dataMap||d||(w&&(a=this._getFormattedValue(a,w)),(u=i.querySelector("input"))&&(u.value=a)):e.columns[o].dataType===wjcCore.DataType.Boolean?(_=i.querySelector('[type="checkbox"]'))&&(_.checked=S.getCellValue(t,o),_.disabled=_.disabled||!S.canEditCell(t,o)):g.dataMap&&!f?(a=S.getCellValue(t,o,!0),(r=i.firstChild)&&3===r.nodeType&&r.nodeValue!==a&&(r.nodeValue=a)):0===i.childElementCount&&i.textContent===S.getCellData(t,o,!0)&&(""!==(a=S.getCellValue(t,o,!0))&&wjcCore.isNumber(+a)&&!isNaN(+a)&&/[hsmy\:]/i.test(w)&&(C=FlexSheet._fromOADate(+a),isNaN(C.getTime())||(a=wjcCore.Globalize.formatDate(C,w))),!w&&f||(a=wjcCore.isString(a)?a.replace(/^(\')(\s*[\w|=])/,"$2"):a,wjcCore.isString(a)?a&&this._isURL(a)?i.innerHTML='<a href="'+a+'" target="_blank">'+wjcCore.escapeHtml(a)+"</a>":i.innerHTML=wjcCore.escapeHtml(a):i.innerHTML=a)),c){var b,R=i.style;for(var y in c)"className"===y?c.className&&wjcCore.addClass(i,c.className):"format"!==y&&(b=c[y])&&(!wjcCore.hasClass(i,"wj-state-selected")&&!wjcCore.hasClass(i,"wj-state-multi-selected")||"color"!==y&&"backgroundColor"!==y?R[y]="whiteSpace"===y&&"normal"===b?"":b:R[y]="")}(i.style.backgroundColor||i.style.color)&&(c||(c={},p&&p._styledCells[s]),i.style.backgroundColor&&(c.backgroundColor=i.style.backgroundColor),i.style.color&&(c.color=i.style.color))}e.cellType===wjcGrid.CellType.Cell&&(t!==S._lastVisibleFrozenRow||wjcCore.hasClass(i,"wj-frozen-row")||wjcCore.addClass(i,"wj-frozen-row"),o!==S._lastVisibleFrozenColumn||wjcCore.hasClass(i,"wj-frozen-col")||wjcCore.addClass(i,"wj-frozen-col"))}_resetCellStyle(e){["fontFamily","fontSize","fontStyle","fontWeight","textDecoration","textAlign","verticalAlign","backgroundColor","color","whiteSpace","borderLeftStyle","borderLeftColor","borderLeftWidth","borderRightStyle","borderRightColor","borderRightWidth","borderTopStyle","borderTopColor","borderTopWidth","borderBottomStyle","borderBottomColor","borderBottomWidth"].forEach(t=>{e.style[t]=""})}_getFormattedValue(e,t){return e!==Math.round(e)&&(t=t.replace(/([a-z])(\d*)(.*)/gi,"$0112$3")),wjcCore.Globalize.formatNumber(e,t,!0)}_getFirstVisibleCell(e,t){var o,i;for(o=t.topRow;o<=t.bottomRow&&!e.rows[o].isVisible;o++);for(i=t.leftCol;i<=t.rightCol&&!e.columns[i].isVisible;i++);return new wjcGrid.CellRange(o,i)}_isURL(e){return new RegExp("^(https|http|ftp|rtsp|mms)://(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z].[a-z]{2,6})(:[0-9]{1,4})?(/($|[a-zA-Z0-9.,?'\\+&amp;%$#=~_-]+))*").test(e)}};wjcCore._addCultureInfo("FlexSheet",{insertRow:"Insert Row",deleteRow:"Delete Rows",insertCol:"Insert Column",deleteCol:"Delete Columns",convertTable:"Convert To Table",copyCells:"Copy Cells",fillSeries:"Fill Series",fillFormat:"Fill Formatting Only",fillWithoutFormat:"Fill Without Formatting"});var FlexSheetFunctions=[{name:"abs",description:"Returns the absolute value of a number."},{name:"acos",description:"Returns the arccosine of a number."},{name:"address",description:"Obtains the address of a cell in a worksheet by given specified row and column numbers."},{name:"and",description:"Returns TRUE if all of its arguments are TRUE."},{name:"asin",description:"Returns the arcsine of a number."},{name:"atan",description:"Returns the arctangent of a number."},{name:"atan2",description:"Returns the arctangent from x- and y-coordinates."},{name:"average",description:"Returns the average of its arguments."},{name:"ceiling",description:"Rounds a number to the nearest integer or to the nearest multiple of significance."},{name:"char",description:"Returns the character specified by the code number."},{name:"choose",description:"Chooses a value from a list of values."},{name:"code",description:"Returns a numeric code for the first character in a text string."},{name:"column",description:"Returns the column number of a reference."},{name:"columns",description:"Returns the number of columns in a reference."},{name:"concatenate",description:"Joins several text items into one text item."},{name:"cos",description:"Returns the cosine of a number."},{name:"count",description:"Counts how many numbers are in the list of arguments."},{name:"counta",description:"Counts how many values are in the list of arguments."},{name:"countblank",description:"Counts the number of blank cells within a range."},{name:"countif",description:"Counts the number of cells within a range that meet the given criteria."},{name:"countifs",description:"Counts the number of cells within a range that meet multiple criteria."},{name:"date",description:"Returns the serial number of a particular date."},{name:"datedif",description:"Calculates the number of days, months, or years between two dates."},{name:"day",description:"Converts a serial number to a day of the month."},{name:"dcount",description:"Counts the cells that contain numbers in a database."},{name:"exp",description:"Returns e raised to the power of a given number."},{name:"false",description:"Returns the logical value FALSE."},{name:"find",description:"Finds one text value within another (case-sensitive)."},{name:"floor",description:"Rounds a number down, toward zero."},{name:"hlookup",description:"Looks in the top row of an array and returns the value of the indicated cell."},{name:"hour",description:"Converts a serial number to an hour."},{name:"if",description:"Specifies a logical test to perform."},{name:"index",description:"Uses an index to choose a value from a reference."},{name:"indirect",description:"Returns the reference specified by a text string. References are immediately evaluated to display their contents."},{name:"left",description:"Returns the leftmost characters from a text value."},{name:"len",description:"Returns the number of characters in a text string."},{name:"ln",description:"Returns the natural logarithm of a number."},{name:"lower",description:"Converts text to lowercase."},{name:"max",description:"Returns the maximum value in a list of arguments."},{name:"mid",description:"Returns a specific number of characters from a text string starting at the position you specify."},{name:"min",description:"Returns the minimum value in a list of arguments."},{name:"mod",description:"Returns the remainder from division."},{name:"month",description:"Converts a serial number to a month."},{name:"not",description:"Reverses the logic of its argument."},{name:"now",description:"Returns the serial number of the current date and time."},{name:"or",description:"Returns TRUE if any argument is TRUE."},{name:"pi",description:"Returns the value of pi."},{name:"power",description:"Returns the result of a number raised to a power."},{name:"product",description:"Multiplies its arguments."},{name:"proper",description:"Capitalizes the first letter in each word of a text value."},{name:"rand",description:"Returns a random number between 0 and 1."},{name:"rank",description:"Returns the rank of a number in a list of numbers."},{name:"rate",description:"Returns the interest rate per period of an annuity."},{name:"replace",description:"Replaces characters within text."},{name:"rept",description:"Repeats text a given number of times."},{name:"right",description:"Returns the rightmost characters from a text value."},{name:"round",description:"Rounds a number to a specified number of digits."},{name:"rounddown",description:"Rounds a number down, toward zero."},{name:"roundup",description:"Rounds a number up, away from zero."},{name:"row",description:"Returns the row number of a reference."},{name:"rows",description:"Returns the number of rows in a reference."},{name:"search",description:"Finds one text value within another (not case-sensitive)."},{name:"sin",description:"Returns the sine of the given angle."},{name:"sqrt",description:"Returns a positive square root."},{name:"stdev",description:"Estimates standard deviation based on a sample."},{name:"stdevp",description:"Calculates standard deviation based on the entire population."},{name:"substitute",description:"Substitutes new text for old text in a text string."},{name:"subtotal",description:"Returns a subtotal in a list or database."},{name:"sum",description:"Adds its arguments."},{name:"sumif",description:"Adds the cells specified by a given criteria."},{name:"sumifs",description:"Adds the cells in a range that meet multiple criteria."},{name:"sumproduct",description:"Multiplies corresponding components in the given arrays, and returns the sum of those products."},{name:"tan",description:"Returns the tangent of a number."},{name:"text",description:"Formats a number and converts it to text."},{name:"time",description:"Returns the serial number of a particular time."},{name:"today",description:"Returns the serial number of today's date."},{name:"trim",description:"Removes spaces from text."},{name:"true",description:"Returns the logical value TRUE."},{name:"trunc",description:"Truncates a number to an integer."},{name:"upper",description:"Converts text to uppercase."},{name:"value",description:"Converts a text argument to a number."},{name:"var",description:"Estimates variance based on a sample."},{name:"varp",description:"Calculates variance based on the entire population."},{name:"year",description:"Converts a serial number to a year."}];export class FlexSheet extends wjcGrid.FlexGrid{constructor(e,t){super(e,t),this._selectedSheetIndex=-1,this._columnHeaderClicked=!1,this._addingSheet=!1,this._mouseMoveHdl=this._mouseMove.bind(this),this._clickHdl=this._click.bind(this),this._touchStartHdl=this._touchStart.bind(this),this._touchEndHdl=this._touchEnd.bind(this),this._keydownHdl=this._keydown.bind(this),this._isContextMenuKeyDown=!1,this._isClicking=!1,this._definedNames=new wjcCore.ObservableArray,this._builtInTableStylesCache=null,this._needCopyToSheet=!0,this._isSorting=!1,this._fillingData=!1,this._endDragFillOperationHdl=this._endDragFillOperation.bind(this),this._enableDragDrop=!0,this._enableFormulas=!0,this.selectedSheetChanged=new wjcCore.Event,this.draggingRowColumn=new wjcCore.Event,this.droppingRowColumn=new wjcCore.Event,this.loaded=new wjcCore.Event,this.unknownFunction=new wjcCore.Event,this.sheetCleared=new wjcCore.Event,this.prepareChangingRow=new wjcCore.Event,this.prepareChangingColumn=new wjcCore.Event,this.rowChanged=new wjcCore.Event,this.columnChanged=new wjcCore.Event,this._needCopyToSheet=!1,this._colorThemes=["FFFFFF","000000","EEECE1","1F497D","4F818D","C0504D","9BBB59","8064A2","4BACC6","F79646"],this._eCt.style.backgroundColor="white",wjcCore.addClass(this.hostElement,"wj-flexsheet"),wjcCore.setCss(this.hostElement,{fontFamily:"Arial"}),this._cf=new _FlexSheetCellFactory,this._bndSortConverter=this._sheetSortConverter.bind(this),this.quickAutoSize=!1,this._init(),this.showSort=!1,this.allowSorting=!1,this.showGroups=!1,this.showMarquee=!0,this.showSelectedHeaders=wjcGrid.HeadersVisibility.All,this.allowResizing=wjcGrid.AllowResizing.Both,this.allowDragging=wjcGrid.AllowDragging.None,this.keyActionTab=wjcGrid.KeyAction.CycleOut,this._needCopyToSheet=!0}_getProductInfo(){return"R20I,FlexSheet"}get sheets(){return this._sheets||(this._sheets=new SheetCollection,this._sheets.selectedSheetChanged.addHandler(this._selectedSheetChange,this),this._sheets.collectionChanged.addHandler(this._sourceChange,this),this._sheets.sheetVisibleChanged.addHandler(this._sheetVisibleChange,this),this._sheets.sheetCleared.addHandler(this.onSheetCleared,this)),this._sheets}get selectedSheetIndex(){return this._selectedSheetIndex}set selectedSheetIndex(e){e!==this._selectedSheetIndex&&(this._showSheet(e),this._sheets.selectedIndex=e)}get selectedSheet(){return this._sheets[this._selectedSheetIndex]}get isFunctionListOpen(){return this._functionListHost&&"none"!==this._functionListHost.style.display}get isTabHolderVisible(){return this._tabHolder.visible}set isTabHolderVisible(e){e!==this._tabHolder.visible&&(e?(this._divContainer.style.height=this._divContainer.parentElement.clientHeight-this._tabHolder.getSheetBlanketSize()+"px",this._eFocus.removeAttribute("tabindex")):(this._divContainer.style.height=this._divContainer.parentElement.clientHeight+"px",this._eFocus.tabIndex=this._orgTabIndex),this._tabHolder.visible=e)}get undoStack(){return this._undoStack}get sortManager(){return this._sortManager}get filter(){return this._filter}get showFilterIcons(){return!!this._filter&&this._filter.showFilterIcons}set showFilterIcons(e){this._filter&&this._filter.showFilterIcons!==e&&(this._filter.showFilterIcons=e)}get definedNames(){return this._definedNames}get enableDragDrop(){return this._enableDragDrop}set enableDragDrop(e){this._enableDragDrop=e}get enableFormulas(){return this._enableFormulas}set enableFormulas(e){this._enableFormulas!==e&&(this._enableFormulas=e,this.refresh())}onSelectedSheetChanged(e){this.selectedSheetChanged.raise(this,e)}onDraggingRowColumn(e){this.draggingRowColumn.raise(this,e)}onDroppingRowColumn(e){this.droppingRowColumn.raise(this,new wjcCore.EventArgs)}onLoaded(e){var t=this;t._toRefresh&&(clearTimeout(t._toRefresh),t._toRefresh=null),t._toRefresh=setTimeout(()=>{t._setFlexSheetToDirty(),t.invalidate()},10),t.loaded.raise(this,new wjcCore.EventArgs)}onUnknownFunction(e){this.unknownFunction.raise(this,e)}onSheetCleared(e){this.sheetCleared.raise(this,new wjcCore.EventArgs)}onPrepareChangingRow(e){this.prepareChangingRow.raise(this,e)}onPrepareChangingColumn(e){this.prepareChangingColumn.raise(this,e)}onRowChanged(e){this.rowChanged.raise(this,e)}onColumnChanged(e){this.columnChanged.raise(this,e)}refresh(e=!0){var t,o,i;if(this._divContainer.style.height=this._divContainer.parentElement.clientHeight-(this.isTabHolderVisible?this._tabHolder.getSheetBlanketSize():0)+"px",!this.preserveSelectedState&&this.selectedSheet&&(this.selectedSheet.selectionRanges.clear(),this.selectedSheet.selectionRanges.push(this.selection)),e&&this._clearCalcEngine(),this._lastVisibleFrozenRow=-1,this.frozenRows>0)for(var l=this.frozenRows-1;l>=0;l--)if(this.rows[l]&&this.rows[l].isVisible){this._lastVisibleFrozenRow=l;break}if(this._lastVisibleFrozenColumn=-1,this.frozenColumns>0)for(var n=this.frozenColumns-1;n>=0;n--)if(this.columns[n]&&this.columns[n].isVisible){this._lastVisibleFrozenColumn=n;break}if(this.selectedSheet){if(this.selectedSheet._freezeHiddenRows&&this.selectedSheet._freezeHiddenRows.length>0)for(t=0;t<this.selectedSheet._freezeHiddenRows.length;t++)(o=this.rows[t])instanceof HeaderRow||!this.selectedSheet._freezeHiddenRows[t]||(o.visible=!1);if(this.selectedSheet._freezeHiddenCols&&this.selectedSheet._freezeHiddenCols.length>0)for(i=0;i<this.selectedSheet._freezeHiddenCols.length;i++)this.selectedSheet._freezeHiddenCols[i]&&(this.columns[i].visible=!1)}super.refresh(e),this._tabHolder.adjustSize()}setCellData(e,t,o,i=!1,l=!0){var n=wjcCore.isString(o)&&o.length>1&&"="===o[0];return this._clearCalcEngine(),this.cells.setCellData(e,t,o,i&&!n,l)}containsFocus(){return this.isFunctionListOpen||super.containsFocus()}addUnboundSheet(e,t,o,i,l){var n=this._addSheet(e,t,o,i,l);return 0===n.selectionRanges.length&&n.selectionRanges.push(this.selection),n}addBoundSheet(e,t,o,i){var l=this._addSheet(e,0,0,o,i);return t&&(l.itemsSource=t,this.childItemsPath&&(l.grid.childItemsPath=this.childItemsPath)),0===l.selectionRanges.length&&l.selectionRanges.push(this.selection),l}applyCellsStyle(e,t,o=!1){var i,l,n,s,r,a=null!=t&&t.length>0,h=t||[this.selection];if(this.selectedSheet){if(!e&&this._cloneStyle)return this.selectedSheet._styledCells=this._cloneObject(this._cloneStyle),this._cloneStyle=null,void this.refresh(!1);if(h){for(t||o?o&&!this._cloneStyle&&(this._cloneStyle=this._cloneObject(this.selectedSheet._styledCells)):(this.undoStack.stackSize>0&&(r=new _CellStyleAction(this,this._cloneStyle)),this._cloneStyle=null),s=0;s<h.length;s++)for(i=(n=h[s]).topRow;i<=n.bottomRow;i++)for(l=n.leftCol;l<=n.rightCol;l++)this._applyStyleForCell(i,l,e,a);r&&(r.saveNewState(),this._undoStack._addAction(r))}t||this.refresh(!1)}}freezeAtCursor(){var e,t,o,i,l,n,s=this;if(s.selectedSheet){if(this.selectedSheet._freezeHiddenRows=null,this.selectedSheet._freezeHiddenCols=null,s.selection&&0===s.frozenRows&&0===s.frozenColumns){if(s._ptScrl.y<0)for(this.selectedSheet._freezeHiddenRows=[],e=0;e<s.selection.topRow-1;e++)if(!((l=s.rows[e])instanceof HeaderRow)){if(!(l._pos+s._ptScrl.y<0&&l.visible))break;l.visible=!1,this.selectedSheet._freezeHiddenRows[e]=!0}if(s._ptScrl.x<0)for(this.selectedSheet._freezeHiddenCols=[],t=0;t<s.selection.leftCol-1&&((n=s.columns[t])._pos+s._ptScrl.x<0&&n.visible);t++)n.visible=!1,this.selectedSheet._freezeHiddenCols[t]=!0;o=s.selection.leftCol>0?s.selection.leftCol:0,i=s.selection.topRow>0?s.selection.topRow:0}else{for(e=0;e<s.frozenRows-1;e++)s.rows[e].visible=!0;for(t=0;t<s.frozenColumns-1;t++)s.columns[t].visible=!0;s._filter.apply(),o=0,i=0}s.frozenRows=s.selectedSheet.grid.frozenRows=i,s.frozenColumns=s.selectedSheet.grid.frozenColumns=o,setTimeout(()=>{s._setFlexSheetToDirty(),s.invalidate(),s.scrollIntoView(s.selection.topRow,s.selection.leftCol)},10)}}showColumnFilter(){var e=this.selection.col>0?this.selection.col:0;this.columns.length>0&&this._filter.editColumnFilter(this.columns[e])}clear(){this.beginUpdate(),this.selection=new wjcGrid.CellRange,this.sheets.clear(),this._selectedSheetIndex=-1,this.columns.clear(),this.rows.clear(),this.columnHeaders.columns.clear(),this.rowHeaders.rows.clear(),this._undoStack.clear(),this._ptScrl=new wjcCore.Point,this._clearCalcEngine(),this._definedNames.clear(),this._builtInTableStylesCache=null,this._copiedRanges=null,this._copiedSheet=null,this._isCutting=!1,this._cutValue=null,this._reservedContent=null,this._lastVisibleFrozenRow=-1,this._lastVisibleFrozenColumn=-1,this.addUnboundSheet(),this.endUpdate()}getSelectionFormatState(){var e,t,o=this.rows.length,i=this.columns.length,l={isBold:!1,isItalic:!1,isUnderline:!1,textAlign:"left",isMergedCell:!1};if(0===o||0===i)return l;if(this.selection){if(this.selection.row>=o||this.selection.row2>=o||this.selection.col>=i||this.selection.col2>=i)return l;for(e=this.selection.topRow;e<=this.selection.bottomRow;e++)for(t=this.selection.leftCol;t<=this.selection.rightCol;t++)this._checkCellFormat(e,t,l)}return l}insertRows(e,t){var o,i,l,n,s,r,a,h,d,c=this,_=wjcCore.isNumber(e)&&e>=0?e:c.selection&&c.selection.topRow>-1?c.selection.topRow:0,u=wjcCore.isNumber(t)?t:1,g=c.rows[_],w=!1;if(c.selectedSheet){if(c.rows.length>0?_>=c.rows.length&&(_=c.rows.length-1):_=0,c._clearCalcEngine(),c.finishEditing(),0===_&&g&&g.constructor===HeaderRow&&(_=1),c.onPrepareChangingRow(new RowColumnChangedEventArgs(_,u,!0)),c.undoStack.stackSize>0&&(o=new _RowsChangedAction(c,_,u,!0)),c._updateCellsForUpdatingRow(c.rows.length,_,u),(!c.collectionView||0===c.collectionView.sortDescriptions.length)&&(i=c._updateAffectedFormula(_,u,!0,!0),l=c._updateAffectedNamedRanges(_,u,!0,!0)),o&&(o._affectedFormulas=i,o._affectedDefinedNameVals=l),c.collectionView){for(c.selectedSheet._dataView=c.collectionView._view.slice(),w=!0,s=c.itemsSource instanceof wjcCore.CollectionView,h=c.autoGenerateColumns,c.autoGenerateColumns=!1,c.collectionView.beginUpdate(),s||(d=c.selectedSheet.grid.autoGenerateColumns,c.selectedSheet.grid.autoGenerateColumns=!1,c.selectedSheet.grid.collectionView.beginUpdate()),n=0;n<u;n++)a=_-(c.allowAddNew&&c.newRowAtTop?2:1),s?(r=c.itemsSource.newItemCreator?c.itemsSource.newItemCreator():{},c.itemsSource.sourceCollection.splice(a,0,r)):(r={},c.itemsSource.splice(a,0,r),c.itemsSource!==c.selectedSheet.grid.itemsSource&&c.selectedSheet.grid.itemsSource.splice(a,0,r)),c.selectedSheet._dataView.splice(a,0,r);c._updateItemIndexForInsertingRow(c.collectionView.sourceCollection,a,u),s||(c.selectedSheet.grid.collectionView.endUpdate(),c.selectedSheet.grid.autoGenerateColumns=d),c.collectionView.endUpdate(),c.collectionView.sortDescriptions.length>0&&(c.collectionView._view=c.selectedSheet._dataView,c.collectionView._pgView=c.collectionView._getPageView(),s||(c.selectedSheet.grid.collectionView._view=c.selectedSheet._dataView,c.selectedSheet.grid.collectionView._pgView=c.selectedSheet.grid.collectionView._getPageView()),c._bindGrid(!1),c.selectedSheet.grid._bindGrid(!1)),setTimeout(()=>{c._filter.apply()}),c.autoGenerateColumns=h}else{for(c.rows.beginUpdate(),n=0;n<u;n++)c.rows.insert(_,new wjcGrid.Row);c.rows.endUpdate()}c._updateTablesForUpdatingRow(_,u),c.selection&&-1!==c.selection.row&&-1!==c.selection.col||(c.selection=new wjcGrid.CellRange(0,0)),o&&(o.saveNewState(),c._undoStack._addAction(o)),c.onRowChanged(new RowColumnChangedEventArgs(_,u,!0)),w&&c.refresh()}}deleteRows(e,t){var o,i,l,n,s,r,a,h,d,c,_,u,g,w=wjcCore.isNumber(t)&&t>=0?t:this.selection&&this.selection.topRow>-1?this.selection.bottomRow-this.selection.topRow+1:1,m=wjcCore.isNumber(e)&&e>=0?e:this.selection&&this.selection.topRow>-1?this.selection.topRow:-1,f=wjcCore.isNumber(e)&&e>=0?e+w-1:this.selection&&this.selection.topRow>-1?this.selection.bottomRow:-1,C=!1;if(this.selectedSheet&&!(m>=this.rows.length)&&(f=Math.min(f,this.rows.length-1),this._clearCalcEngine(),this.finishEditing(),m>-1&&f>-1)){for(this.onPrepareChangingRow(new RowColumnChangedEventArgs(m,w,!1)),this.undoStack.stackSize>0&&(o=new _RowsChangedAction(this,m,w,!1)),this._updateCellsForUpdatingRow(this.rows.length,m,w,!0),l=this._updateAffectedFormula(f,f-m+1,!1,!0),n=this._updateAffectedNamedRanges(f,f-m+1,!1,!0),s=this._updateTablesForUpdatingRow(m,w,!0),o&&(o._affectedFormulas=l,o._affectedDefinedNameVals=n,o._deletedTables=s),i=w===this.rows.length,_=(C=!!this.collectionView)&&this.itemsSource instanceof wjcCore.CollectionView,this.rows.beginUpdate(),C&&(this.selectedSheet._dataView=this.collectionView._view.slice(),u=this.autoGenerateColumns,this.autoGenerateColumns=!1,this.collectionView.beginUpdate(),_||(g=this.selectedSheet.grid.autoGenerateColumns,this.selectedSheet.grid.autoGenerateColumns=!1,this.selectedSheet.grid.collectionView.beginUpdate()));f>=m;f--)(!(r=this.rows[f])||(r.constructor!==HeaderRow||i)&&r.isVisible)&&(r.dataItem&&this.collectionView?(a=this._getCvIndex(f))>-1&&(h=this.collectionView.items[a],_?(d=this.itemsSource.sourceCollection.indexOf(h),this.itemsSource.sourceCollection.splice(d,1)):(d=this.itemsSource.indexOf(h),this.itemsSource.splice(d,1),this.itemsSource!==this.selectedSheet.grid.itemsSource&&this.selectedSheet.grid.itemsSource.splice(d,1)),this.selectedSheet._dataView.splice(this.selectedSheet._dataView.indexOf(h),1),this._updateItemIndexForRemovingRow(this.collectionView.sourceCollection,d)):this.rows.removeAt(f));C&&(_||(this.selectedSheet.grid.collectionView.endUpdate(),this.selectedSheet.grid.autoGenerateColumns=g),this.collectionView.endUpdate(),this.collectionView.sortDescriptions.length>0&&(this.collectionView._view=this.selectedSheet._dataView,this.collectionView._pgView=this.collectionView._getPageView(),_||(this.selectedSheet.grid.collectionView._view=this.selectedSheet._dataView,this.selectedSheet.grid.collectionView._pgView=this.selectedSheet.grid.collectionView._getPageView()),this._bindGrid(!1),this.selectedSheet.grid._bindGrid(!1)),this.autoGenerateColumns=u),this.rows.endUpdate(),c=this.rows.length,this.selectedSheet.selectionRanges.clear(),0===c?(this.select(new wjcGrid.CellRange),"move"===this.hostElement.style.cursor&&(this.hostElement.style.cursor="default")):f===c-1?this.select(new wjcGrid.CellRange(f,0,f,this.columns.length-1)):this.select(new wjcGrid.CellRange(this.selection.topRow,this.selection.col,this.selection.topRow,this.selection.col2)),o&&(o.saveNewState(),this._undoStack._addAction(o)),this.onRowChanged(new RowColumnChangedEventArgs(m,w,!1)),C&&this.refresh()}}insertColumns(e,t){var o,i,l,n,s,r,a=wjcCore.isNumber(e)&&e>=0?e:this.selection&&this.selection.leftCol>-1?this.selection.leftCol:0,h=wjcCore.isNumber(t)?t:1;if(this.selectedSheet){for(this.columns.length>0?a>=this.columns.length&&(a=this.columns.length-1):a=0,this._clearCalcEngine(),this.finishEditing(),this.onPrepareChangingColumn(new RowColumnChangedEventArgs(a,h,!0)),this.undoStack.stackSize>0&&(o=new _ColumnsChangedAction(this,a,h,!0)),this._updateCellsForUpdatingColumn(this.columns.length,a,h),s=this._updateAffectedFormula(a,h,!0,!1),r=this._updateAffectedNamedRanges(a,h,!0,!1),o&&(o._affectedFormulas=s,o._affectedDefinedNameVals=r),this.columns.beginUpdate(),l=0;l<h;l++)(i=new wjcGrid.Column).isRequired=!1,this.itemsSource&&(i.binding=this._getUniqueColumnName(),(n=this.allowAddNew&&this.newRowAtTop?this.rows[1]:this.rows[0])&&(n._ubv||(n._ubv={}),n._ubv[i._hash]=i.header)),this.columns.insert(a,i);this.columns.endUpdate(),this.selectedSheet._filterDefinition=this._filter.filterDefinition,this._sortManager._updateSortSortDescription(a,h),this._sortManager.commitSort(!1),this._updateTablesForUpdatingColumn(a,h),this.selection&&-1!==this.selection.row&&-1!==this.selection.col||(this.selection=new wjcGrid.CellRange(0,0)),o&&(o.saveNewState(),this._undoStack._addAction(o)),this.onColumnChanged(new RowColumnChangedEventArgs(a,h,!0))}}deleteColumns(e,t){var o,i,l,n,s,r=wjcCore.isNumber(t)&&t>=0?t:this.selection&&this.selection.leftCol>-1?this.selection.rightCol-this.selection.leftCol+1:1,a=wjcCore.isNumber(e)&&e>=0?e:this.selection&&this.selection.leftCol>-1?this.selection.leftCol:-1,h=wjcCore.isNumber(e)&&e>=0?e+r-1:this.selection&&this.selection.leftCol>-1?this.selection.rightCol:-1;if(this.selectedSheet&&!(a>=this.columns.length)&&(h=Math.min(h,this.columns.length-1),this._clearCalcEngine(),this.finishEditing(),a>-1&&h>-1)){for(this.onPrepareChangingColumn(new RowColumnChangedEventArgs(a,r,!1)),this.undoStack.stackSize>0&&(i=new _ColumnsChangedAction(this,a,r,!1)),this._updateCellsForUpdatingColumn(this.columns.length,a,r,!0),l=this._updateAffectedFormula(h,h-a+1,!1,!1),n=this._updateAffectedNamedRanges(h,h-a+1,!1,!1),s=this._updateTablesForUpdatingColumn(a,r,!0),i&&(i._affectedFormulas=l,i._affectedDefinedNameVals=n,i._deletedTables=s),this.columns.beginUpdate();h>=a;h--)this.columns[h].isVisible&&(this.columns.removeAt(h),this._sortManager.deleteSortLevel(h));this.columns.endUpdate(),this.selectedSheet._filterDefinition=this._filter.filterDefinition,this._sortManager._updateSortSortDescription(a,r,!1),this._sortManager.commitSort(!1),o=this.columns.length,this.selectedSheet.selectionRanges.clear(),0===o?(this.select(new wjcGrid.CellRange),"move"===this.hostElement.style.cursor&&(this.hostElement.style.cursor="default")):h===o-1?this.select(new wjcGrid.CellRange(0,h,this.rows.length-1,h)):this.select(new wjcGrid.CellRange(this.selection.row,this.selection.leftCol,this.selection.row2,this.selection.leftCol)),i&&(i.saveNewState(),this._undoStack._addAction(i)),this.onColumnChanged(new RowColumnChangedEventArgs(a,r,!1))}}mergeRange(e,t=!1){var o,i,l,n,s,r=e||this.selection,a=-1,h=-1;if(this.selectedSheet){if(r){if(1===r.rowSpan&&1===r.columnSpan)return;for(o=r.topRow;o<=r.bottomRow;o++)for(i=r.leftCol;i<=r.rightCol;i++)if(this.selectedSheet.findTable(o,i))return;if(e||t||(this.undoStack.stackSize>0&&(s=new _CellMergeAction(this)),this.hostElement.focus()),!this._resetMergedRange(r)){for(o=r.topRow;o<=r.bottomRow;o++)if((l=this.rows[o])&&l.isVisible){a=o;break}for(i=r.leftCol;i<=r.rightCol;i++)if((n=this.columns[i])&&n.isVisible){h=i;break}a>-1&&h>-1&&this.selectedSheet._mergedRanges.push(new wjcGrid.CellRange(a,h,r.bottomRow,r.rightCol))}s&&(s.saveNewState(),this._undoStack._addAction(s))}e||this.refresh()}}getMergedRange(e,t,o,i=!0){var l,n,s,r,a=this.selectedSheet?this.selectedSheet._getMergedRange(t,o):null;return e===this.cells&&a?!a.isSingleCell&&(this.frozenRows>0||this.frozenColumns>0)&&(a.topRow<this.frozenRows&&a.bottomRow>=this.frozenRows||a.leftCol<this.frozenColumns&&a.rightCol>=this.frozenColumns)?(l=a.topRow,n=a.bottomRow,s=a.leftCol,r=a.rightCol,t>=this.frozenRows&&a.topRow<this.frozenRows&&(l=this.frozenRows),t<this.frozenRows&&a.bottomRow>=this.frozenRows&&(n=this.frozenRows-1),n>=this.rows.length&&(n=this.rows.length-1),o>=this.frozenColumns&&a.leftCol<this.frozenColumns&&(s=this.frozenColumns),o<this.frozenColumns&&a.rightCol>=this.frozenColumns&&(r=this.frozenColumns-1),r>=this.columns.length&&(r=this.columns.length-1),new wjcGrid.CellRange(l,s,n,r)):a.bottomRow>=this.rows.length?new wjcGrid.CellRange(a.topRow,a.leftCol,this.rows.length-1,a.rightCol):a.rightCol>=this.columns.length?new wjcGrid.CellRange(a.topRow,a.leftCol,a.bottomRow,this.columns.length-1):a.clone():o>=0&&this.columns&&this.columns.length>o&&t>=0&&this.rows&&this.rows.length>t?super.getMergedRange(e,t,o,i):null}evaluate(e,t,o,i=!0){let l=this._evaluate(e,t,o);return i&&null!=l&&!wjcCore.isPrimitive(l)?l.value:l}getCellValue(e,t,o=!1,i){var l,n,s=i&&i!==this.selectedSheet?i.grid.columns[t]:this.columns[t],r=this._getCellStyle(e,t,i);return l=r&&r.format?r.format:"",n=i&&i!==this.selectedSheet?i.grid.getCellData(e,t,!1):this.getCellData(e,t,!1),wjcCore.isString(n)&&"="===n[0]&&(n=this._evaluate(n,o?l:"",i,e,t)),o?(l||null==n||wjcCore.isPrimitive(n)||(l=n.format),n=this._formatEvaluatedResult(n,s,l)):null==n||wjcCore.isPrimitive(n)||(n=n.value),null==n?"":n}showFunctionList(e){var t,o,i=this,l=i._cumulativeOffset(e),n=i._cumulativeOffset(i._root);i._enableFormulas&&(i._functionTarget=wjcCore.tryCast(e,HTMLInputElement),i._functionTarget&&i._functionTarget.value&&"="===i._functionTarget.value[0]?(i._functionList._cv.filter=(e=>{var t,o=e.actualvalue.toLowerCase(),l=i._getCurrentFormulaIndex(i._functionTarget.value);return-1===l&&(l=0),(t=i._functionTarget.value.substr(l+1).trim().toLowerCase()).length>0&&0===o.indexOf(t)||"="===i._functionTarget.value}),i._functionList.selectedIndex=0,t=l.y+e.clientHeight+2+(wjcCore.hasClass(e,"wj-grid-editor")?this._ptScrl.y:0),o=l.x+(wjcCore.hasClass(e,"wj-grid-editor")?this._ptScrl.x:0),wjcCore.setCss(i._functionListHost,{height:i._functionList._cv.items.length>5?"218px":"auto",display:i._functionList._cv.items.length>0?"block":"none",top:"",left:""}),i._functionListHost.scrollTop=0,i._functionListHost.offsetHeight+t>n.y+i._root.offsetHeight?t=t-e.clientHeight-i._functionListHost.offsetHeight-5:t+=5,i._functionListHost.offsetWidth+o>n.x+i._root.offsetWidth&&(o=n.x+i._root.offsetWidth-i._functionListHost.offsetWidth),wjcCore.setCss(i._functionListHost,{top:t,left:o})):i.hideFunctionList())}hideFunctionList(){this._functionListHost.style.display="none"}selectPreviousFunction(){this._functionList.selectedIndex>0&&this._functionList.selectedIndex--}selectNextFunction(){this._functionList.selectedIndex<this._functionList.itemsSource.length&&this._functionList.selectedIndex++}applyFunctionToCell(){var e,t=this;t._functionTarget&&(-1===(e=t._getCurrentFormulaIndex(t._functionTarget.value))?e=t._functionTarget.value.indexOf("="):e+=1,t._functionTarget.value=t._functionTarget.value.substring(0,e)+t._functionList.selectedValue+"(","="!==t._functionTarget.value[0]&&(t._functionTarget.value="="+t._functionTarget.value),t._functionTarget.focus(),t.hideFunctionList())}save(e,t){var o=this._saveToWorkbook(t);return e&&o.save(e),o}saveAsync(e,t,o,i){var l=this._saveToWorkbook(i);return l.saveAsync(e,t,o),l}saveToWorkbookOM(e){return this._saveToWorkbook(e)._serialize()}load(e){var t,o,i=this;if(e instanceof Blob)(o=new FileReader).onload=(()=>{var e=o.result;e=wjcXlsx.Workbook._base64EncArr(new Uint8Array(e)),(t=new wjcXlsx.Workbook).load(e),i._loadFromWorkbook(t)}),o.readAsArrayBuffer(e);else if(e instanceof wjcXlsx.Workbook)i._loadFromWorkbook(e);else{if(e instanceof ArrayBuffer)e=wjcXlsx.Workbook._base64EncArr(new Uint8Array(e));else if(!wjcCore.isString(e))throw"Invalid workbook.";(t=new wjcXlsx.Workbook).load(e),i._loadFromWorkbook(t)}}loadAsync(e,t,o){var i,l,n=this;if(e instanceof Blob)(l=new FileReader).onload=(()=>{var e=l.result;e=wjcXlsx.Workbook._base64EncArr(new Uint8Array(e)),(i=new wjcXlsx.Workbook).loadAsync(e,e=>{n._loadFromWorkbook(e),t&&t(e)},o)}),l.readAsArrayBuffer(e);else if(e instanceof wjcXlsx.Workbook)n._loadFromWorkbook(e),t&&t(e);else{if(e instanceof ArrayBuffer)e=wjcXlsx.Workbook._base64EncArr(new Uint8Array(e));else if(!wjcCore.isString(e))throw"Invalid workbook.";(i=new wjcXlsx.Workbook).loadAsync(e,e=>{n._loadFromWorkbook(e),t&&t(e)},o)}}loadFromWorkbookOM(e){var t;e instanceof wjcXlsx.Workbook?t=e:(t=new wjcXlsx.Workbook)._deserialize(e),this._loadFromWorkbook(t)}undo(){var e=this;setTimeout(()=>{e._undoStack.undo()},100)}redo(){var e=this;setTimeout(()=>{e._undoStack.redo()},100)}select(e,t=!0){var o,i,l;if(wjcCore.isNumber(e)&&wjcCore.isNumber(t)&&(e=new wjcGrid.CellRange(e,t),t=!0),e.rowSpan!==this.rows.length&&e.columnSpan!==this.columns.length)for(i=e.topRow;i<=e.bottomRow;i++)for(l=e.leftCol;l<=e.rightCol;l++)(o=this.getMergedRange(this.cells,i,l))&&!e.equals(o)&&(e.row<=e.row2?(e.row=Math.min(e.topRow,o.topRow),e.row2=Math.max(e.bottomRow,o.bottomRow)):(e.row=Math.max(e.bottomRow,o.bottomRow),e.row2=Math.min(e.topRow,o.topRow)),e.col<=e.col2?(e.col=Math.min(e.leftCol,o.leftCol),e.col2=Math.max(e.rightCol,o.rightCol)):(e.col=Math.max(e.rightCol,o.rightCol),e.col2=Math.min(e.leftCol,o.leftCol)));this._isPasting&&this.collectionView&&(this.collectionView._pendingRefresh=!1),super.select(e,t)}addCustomFunction(e,t,o,i,l){wjcCore._deprecated("addCustomFunction","addFunction"),this._calcEngine.addCustomFunction(e,t,i,l),this._addCustomFunctionDescription(e,o)}addFunction(e,t,o,i,l){this._calcEngine.addFunction(e,t,i,l),this._addCustomFunctionDescription(e,o)}dispose(){var e=window.navigator.userAgent;this._needCopyToSheet=!1,this.removeEventListener(document.body,"mousemove",this._mouseMoveHdl),this.removeEventListener(document.body,"keydown",this._keydownHdl),this.removeEventListener(document.body,"click",this._clickHdl),(e.match(/iPad/i)||e.match(/iPhone/i))&&(this.removeEventListener(document.body,"touchstart",this._touchStartHdl),this.removeEventListener(document.body,"touchend",this._touchEndHdl)),this.hideFunctionList(),super.dispose()}getClipString(e){var t,o,i,l,n,s,r="",a=!0;if(!this.selectedSheet)return super.getClipString(e);if(this._isCutting=!1,!e)if(this.selectedSheet.selectionRanges.length>1){if(this._isMultipleRowsSelected()){for(r="",0===(t=this.selectedSheet.selectionRanges.slice(0)).length&&(t=[this.selection]),t.sort(this._sortByRow),i=0;i<t.length;i++)r&&(r+="\n"),r+=this.getClipString(t[i]);return r}if(this._isMultipleColumnsSelected()){for(r="",0===(t=this.selectedSheet.selectionRanges.slice(0)).length&&(t=[this.selection]),t.sort(this._sortByColumn),o=(l=t[0]).topRow,a=!0;o<=l.bottomRow;o++)for(a||(r+="\n"),a=!1,i=0,_=!0;i<t.length;i++)n=t[i],_||(r+="\t"),_=!1,r+=this.getClipString(new wjcGrid.CellRange(o,n.col,o,n.col2));return r}wjcCore.assert(!1,"Copy or Cut operation cannot be used on multiple selections.")}else switch(e=this.selection,this.selectionMode){case wjcGrid.SelectionMode.Row:case wjcGrid.SelectionMode.RowRange:e.col=0,e.col2=this.columns.length-1;break;case wjcGrid.SelectionMode.ListBox:e.col=0,e.col2=this.columns.length-1;for(var h=0;h<this.rows.length;h++)this.rows[h].isSelected&&this.rows[h].isVisible&&(e.row=e.row2=h,r&&(r+="\n"),r+=this.getClipString(e));return r}if(!(e=wjcCore.asType(e,wjcGrid.CellRange)).isValid)return"";for(var d=e.topRow,a=!0;d<=e.bottomRow;d++)if(this.rows[d].isVisible){a||(r+="\n"),a=!1;for(var c=e.leftCol,_=!0;c<=e.rightCol;c++)this.columns[c].isVisible&&(_||(r+="\t"),_=!1,(s=(s=this.getCellValue(d,c,!0).toString()).replace(/\t/g," ")).indexOf("\n")>-1&&(s='"'+s.replace(/"/g,'""')+'"'),r+=s)}return r}setClipString(e,t){var o,i,l,n,s,r,a,h,d,c,_,u,g,w,m,f,C,p,S,b,R,y,v,T=null==t,x=!1,k=!1;if(this.selectedSheet){if(t=t?wjcCore.asType(t,wjcGrid.CellRange):this.selection,(e=wjcCore.asString(e).replace(/\r\n/g,"\n").replace(/\r/g,"\n"))&&"\n"==e[e.length-1]&&(e=e.substring(0,e.length-1)),R=e,h=this._edtHdl._parseClipString(wjcCore.asString(e)),T&&!t.isSingleCell&&h.length&&this._edtHdl._expandClipRows(h,t),k=this._containsMultiLineText(h),(!this._copiedRanges||0===this._copiedRanges.length||R.trim()!==this._getRangeString(this._copiedRanges,this._copiedSheet).trim()&&!this._containsRandFormula(this._copiedRanges,this._copiedSheet)||this._cutValue)&&!k)return R!==this._cutValue&&(this._cutValue=null,super.setClipString(e)),this._copiedRanges=null,void(this._copiedSheet=null);if(y=this._getRangeString(this._copiedRanges,this._copiedSheet,!1),(y=wjcCore.asString(y).replace(/\r\n/g,"\n").replace(/\r/g,"\n"))&&"\n"==y[y.length-1]&&(y=y.substring(0,y.length-1)),h=this._edtHdl._parseClipString(wjcCore.asString(y)),T&&!t.isSingleCell&&h.length&&this._edtHdl._expandClipRows(h,t),(n=t.topRow+h.length-1)>=this.rows.length&&(n=this.rows.length-1),(s=t.leftCol+h[0].length-1)>=this.columns.length&&(s=this.columns.length-1),o=new wjcGrid.CellRange(t.topRow,t.leftCol,n,s),!this.onPasting(new wjcGrid.CellRangeEventArgs(this.cells,o)))return this._cutValue=null,this._copiedRanges=null,this._copiedSheet=null,!1;if(this.beginUpdate(),k||!this._copiedRanges||this._copiedRanges.length>1||0===this._copiedRanges.length)for(i=t.topRow,r=(p=this._copiedRanges&&this._copiedRanges.length>1?this._copiedRanges[0]:new wjcGrid.CellRange).topRow,_=0;_<h.length&&i<this.rows.length;_++,i++)if(this.rows[i].isVisible){for(d=h[_],a=p.leftCol,w=(l=t.leftCol)-a,u=0;u<d.length&&l<this.columns.length;u++,l++)this.columns[l].isVisible?(c=d[u],this.columns[l].isReadOnly||this.rows[i].isReadOnly||(x=this._postSetClipStringProcess(c,i,l,r,a),o.row2=Math.max(o.row2,i),o.col2=Math.max(o.col2,l)),a>=0&&a++):u--;r>=0&&r++}else _--;else if(this._copiedRanges&&1===this._copiedRanges.length)for(S=0,(p=this.selectionMode===wjcGrid.SelectionMode.ListBox?this._getSelectionForListBoxMode(this._copiedSheet.grid):this._copiedRanges[0]).rowSpan>t.rowSpan?p.rowSpan:t.rowSpan,p.columnSpan>t.columnSpan?p.columnSpan:t.columnSpan,i=t.topRow,_=0;_<h.length&&i<this.rows.length;_++,i++)if(b=0,this.rows[i].isVisible){for(;this._copiedSheet.grid.rows[p.topRow+S]&&!this._copiedSheet.grid.rows[p.topRow+S].isVisible;)S++;if(S>=p.rowSpan&&(S%=p.rowSpan),!this._copiedSheet.grid.rows[p.topRow+S])break;for(g=i-p.topRow-S,d=h[_],l=t.leftCol,u=0;u<d.length&&l<this.columns.length;u++,l++)if(this.columns[l]&&this.columns[l].isVisible){if(b>=p.columnSpan&&(b%=p.columnSpan),!this._copiedSheet.grid.columns[p.leftCol+b])break;if(w=l-p.leftCol-b,!this.columns[l].isReadOnly&&!this.rows[i].isReadOnly){if(null!=this._copiedSheet.grid.columns[p.leftCol+b].dataMap,c=d[u],v=this._getCellStyle(p.topRow+S,p.leftCol+b,this._copiedSheet),c&&"string"==typeof c&&"="===c[0]&&(0!==g||0!==w))try{m=this._calcEngine._parse(c),f=new wjcGrid.CellRange(p.topRow+S,p.leftCol+b),C=new wjcGrid.CellRange(p.topRow+S+g,p.leftCol+b+w),m._moveCellRangeExp(this.selectedSheetIndex,f,C,!1,!0)&&(c="="+m._getStringExpression())}catch(e){}this._copiedSheet.grid.columns[p.leftCol+b].format&&!this.columns[l].format&&(v?v.format||(v.format=this._copiedSheet.grid.columns[p.leftCol+b].format):v={format:this._copiedSheet.grid.columns[p.leftCol+b].format}),x=this._postSetClipStringProcess(c,i,l,p.topRow+S,p.leftCol+b,v),o.row2=Math.max(o.row2,i),o.col2=Math.max(o.col2,l)}b++}else u--;S++}else _--;this._isCutting&&(this._delCutData(h.length,h[0].length),this._isCutting=!1,this._cutValue=R,this._copiedRanges=null,this._copiedSheet=null),this.endUpdate(),this.collectionView&&x&&this.collectionView.refresh(),this.select(o),this.onPasted(new wjcGrid.CellRangeEventArgs(this.cells,o))}else super.setClipString(e,t)}getBuiltInTableStyle(e){var t;return null==this._builtInTableStylesCache&&(this._builtInTableStylesCache={}),null==(t=this._builtInTableStylesCache[e.toLowerCase()])&&(t=this._createBuiltInTableStyle(e),Object.freeze(t),this._builtInTableStylesCache[e.toLowerCase()]=t),t}_getCvIndex(e){return e>-1&&this.collectionView?this.rows[e]instanceof HeaderRow?e:super._getCvIndex(e):-1}_bindGrid(e){this.itemsSource&&super._bindGrid(e)}_init(){var e=this,t=window.navigator.userAgent,o=t=>{document.removeEventListener("mouseup",o),e._mouseUp(t)};e.hostElement.setAttribute("tabindex","-1"),e._divContainer=e.hostElement.querySelector('[wj-part="container"]'),e._tabHolder=new _TabHolder(e.hostElement.querySelector('[wj-part="tab-holder"]'),e),e._contextMenu=new _ContextMenu(e.hostElement.querySelector('[wj-part="context-menu"]'),e),e._gpCells=new FlexSheetPanel(e,wjcGrid.CellType.Cell,e.rows,e.columns,e._eCt),e._gpCHdr=new FlexSheetPanel(e,wjcGrid.CellType.ColumnHeader,e._hdrRows,e.columns,e._eCHdrCt),e._gpRHdr=new FlexSheetPanel(e,wjcGrid.CellType.RowHeader,e.rows,e._hdrCols,e._eRHdrCt),e._gpTL=new FlexSheetPanel(e,wjcGrid.CellType.TopLeft,e._hdrRows,e._hdrCols,e._eTLCt),e._syncSelection=e._flexSheetSyncSelection.bind(e),e._sortManager=new SortManager(e),e._filter=new FlexSheetFilter(e),e._filter.filterApplied.addHandler(()=>{e.selectedSheet&&(e.selectedSheet._filterDefinition=e._filter.filterDefinition,e.selectedSheet.itemsSource&&(e.selectedSheet._storeRowSettings(),e.selectedSheet._setRowSettings()))}),e._calcEngine=new _CalcEngine(e),e._calcEngine.unknownFunction.addHandler((t,o)=>{e.onUnknownFunction(o)},e),e._initFuncsList(),e._undoStack=new UndoStack(e),e.loadedRows.addHandler(()=>{if(e.collectionView&&!(e.rows[0]instanceof HeaderRow)){var t,o=new HeaderRow;o.isReadOnly=!0;for(var i=0;i<e.columns.length;i++)t=e.columns[i],o._ubv||(o._ubv={}),o._ubv[t._hash]=t.header;e.rows[0]instanceof wjcGrid._NewRowTemplate&&e.newRowAtTop?e.rows.insert(1,o):e.rows.insert(0,o)}e._filter&&e._filter.apply()}),e.itemsSourceChanged.addHandler(()=>{var t;for(t=0;t<e.columns.length;t++)e.columns[t].isRequired=!1;e.collectionView&&e.collectionView.currentChanged.removeHandler(this._cvCurrentChanged,this)}),e.copied.addHandler((t,o)=>{var i;e.selectedSheet&&(e._copiedSheet=e.selectedSheet,e._needCopyToSheet=!0,e.selectedSheet.selectionRanges.length>1?e._isMultipleRowsSelected()?((i=e.selectedSheet.selectionRanges.slice(0)).sort(e._sortByRow),e._copiedRanges=i):e._isMultipleColumnsSelected()?((i=e.selectedSheet.selectionRanges.slice(0)).sort(e._sortByColumn),e._copiedRanges=i):wjcCore.assert(!1,"Copy operation cannot be used on multiple selections."):e._copiedRanges=[o.range])}),e.rows.collectionChanged.addHandler((t,o)=>{e._clearForEmptySheet("rows"),e.itemsSource||!e.selectedSheet||!e._needCopyToSheet||e._isCopying||e._isUndoing||o.item instanceof wjcGrid._NewRowTemplate||e._copyRowsToSelectedSheet()},e),e.columns.collectionChanged.addHandler((t,o)=>{e._clearForEmptySheet("columns"),e.selectedSheet&&e._needCopyToSheet&&!e._isCopying&&!e._isUndoing&&e._copyColumnsToSelectedSheet()},e),e.definedNames.collectionChanged.addHandler((t,o)=>{if(o.action===wjcCore.NotifyCollectionChangedAction.Add||o.action===wjcCore.NotifyCollectionChangedAction.Change){var i=o.action===wjcCore.NotifyCollectionChangedAction.Add?"inserted":"updated";if(!(o.item instanceof DefinedName))throw e.definedNames.remove(o.item),"Invalid defined name item object was "+i+".  The DefinedName instance should be "+i+" in the definedNames array.";if(!o.item||!o.item.name||null==o.item.value)throw e.definedNames.remove(o.item),"Invalid defined name was "+i+".";if(null!=o.item.sheetName&&!e._validateSheetName(o.item.sheetName))throw e.definedNames.remove(o.item),"The sheet name ("+o.item.sheetName+") does not exist in FlexSheet.";if(e._checkExistDefinedName(o.item.name,o.item.sheetName,o.index))throw e.definedNames.remove(o.item),"The "+o.item.name+" already existed in definedNames."}}),e.addEventListener(e.hostElement,"mousedown",t=>{document.addEventListener("mouseup",o),e._isDescendant(e._divContainer,t.target)&&e._mouseDown(t)},!0),e.addEventListener(e.hostElement,"drop",()=>{e._columnHeaderClicked=!1}),e.addEventListener(e.hostElement,"contextmenu",t=>{var o,i,l,n,s,r,a,h,d;if(!t.defaultPrevented&&e.selectedSheet){if(!e.activeEditor&&(e._isContextMenuKeyDown&&e.selection.row>-1&&e.selection.col>-1&&e.rows.length>0&&e.columns.length>0?(l=e.columns[e.selection.col],i=e.rows[e.selection.row],a=e._cumulativeOffset(e.hostElement),h=e._cumulativeScrollOffset(e.hostElement),n=l.pos+e._eCt.offsetLeft+a.x+l.renderSize/2+e._ptScrl.x,s=i.pos+e._eCt.offsetTop+a.y+i.renderSize/2+e._ptScrl.y,r=new wjcCore.Point(n-h.x,s-h.y),o=e.hitTest(n,s)):o=e.hitTest(t),t.preventDefault(),o&&o.cellType!==wjcGrid.CellType.None)){switch(o.cellType){case wjcGrid.CellType.TopLeft:d=new wjcGrid.CellRange(0,0,e.rows.length-1,e.columns.length-1);break;case wjcGrid.CellType.RowHeader:d=new wjcGrid.CellRange(o.row,0,o.row,e.columns.length-1);break;case wjcGrid.CellType.ColumnHeader:d=new wjcGrid.CellRange(e.itemsSource&&e.rows[0]&&!e.rows[0].isVisible?1:0,o.col,e.rows.length-1,o.col);break;case wjcGrid.CellType.Cell:d=new wjcGrid.CellRange(o.row,o.col)}e.selection.contains(d)&&(d=null),d&&(e.selectedSheet&&(e.selectedSheet.selectionRanges.clear(),e.selectedSheet.selectionRanges.push(d)),e.selection=d),e._contextMenu.show(t,r)}e._isContextMenuKeyDown=!1}}),e.prepareCellForEdit.addHandler(e._prepareCellForEditHandler,e),e.cellEditEnded.addHandler((t,o)=>{(!o.data||46!==o.data.keyCode&&8!==o.data.keyCode)&&setTimeout(()=>{e.hideFunctionList()},200)}),e.cellEditEnding.addHandler((t,o)=>{if(o.data&&(46===o.data.keyCode||8===o.data.keyCode))return;let i,l,n;i=e.getCellData(o.row,o.col,!1),l=e.cellFactory.getEditorValue(e),null!=i&&""!==i||null==l||""===l||isNaN(+l)||(n=e._updateFormulaBoundaryForEditingCell(o.row,o.col),e._undoStack._pendingAction&&e._undoStack._pendingAction instanceof _EditAction&&(e._undoStack._pendingAction._affectedFormulas=n)),e._clearCalcEngine()}),e.rowEditEnding.addHandler((t,o)=>{let i=e.collectionView;i&&(e._orgRowVisible=e.rows[o.row].visible,i.sortDescriptions.length>0&&(e.selectedSheet._dataView=i._view.slice(),e.selectedSheet._scrollPosition=e.scrollPosition))}),e.rowEditEnded.addHandler((t,o)=>{let i=e.collectionView;i&&(i.sortDescriptions.length>0&&(i._view=e.selectedSheet._dataView,i._pgView=i._getPageView(),e.itemsSource instanceof wjcCore.CollectionView||(e.selectedSheet.grid.collectionView._view=e.selectedSheet._dataView,e.selectedSheet.grid.collectionView._pgView=e.selectedSheet.grid.collectionView._getPageView()),e._bindGrid(!1),e.selectedSheet.grid._bindGrid(!1),e.scrollPosition=e.selectedSheet._scrollPosition),e.rows[o.row].visible=e._orgRowVisible)}),e.pasting.addHandler(()=>{e._needCopyToSheet=!1,e._isPasting=!0}),e.pasted.addHandler(()=>{e.selection;e._needCopyToSheet=!0,e._isPasting=!1,e._clearCalcEngine()}),e.resizingColumn.addHandler(()=>{e._resizing=!0}),e.resizingRow.addHandler(()=>{e._resizing=!0}),e.resizedColumn.addHandler(()=>{e._resizing=!1}),e.resizedRow.addHandler(()=>{e._resizing=!1}),e.selectionChanged.addHandler(()=>{let t=e.selection;e._isCopying||!t.isValid||e.containsFocus()||e.hostElement.focus(),t.rightCol>=e.columns.length&&(e.selection=new wjcGrid.CellRange(t.row,Math.min(t.col,e.columns.length-1),t.row2,Math.min(e.selection.col2,e.columns.length-1))),e._enableMulSel||e._isCopying||!e.selectedSheet||e.selectedSheet.selectionRanges.clear()}),e.addEventListener(e.hostElement,"keydown",t=>{var o,i,l=!1,n=!1;if(t.ctrlKey){if(89===t.keyCode&&(e.finishEditing(),e.redo(),t.preventDefault()),90===t.keyCode&&(e.finishEditing(),e.undo(),t.preventDefault()),e.selectedSheet&&65===t.keyCode&&(e.selectedSheet.selectionRanges.clear(),e.selectedSheet.selectionRanges.push(e.selection)),67!==t.keyCode&&45!=t.keyCode||(e.activeEditor&&(e._copiedRanges=null,e._copiedSheet=null),e._cutValue=null),88===t.keyCode&&!e.activeEditor){if(t.stopPropagation(),e.selectionMode===wjcGrid.SelectionMode.ListBox)for(var s=0;s<e.rows.length;s++)if(e.rows[s].isSelected)if(l){if(n)continue;wjcCore.assert(!1,"Cut operation cannot be used on multiple selections.")}else l=!0,n=!0;else n&&(n=!1);e.selectedSheet.selectionRanges.length>1?wjcCore.assert(!1,"Cut operation cannot be used on multiple selections."):(e.finishEditing(),o=new wjcGrid.CellRangeEventArgs(e.cells,e.selection),e.onCopying(o)&&(e._cutValue=null,i=e.getClipString(),e._isCutting=!0,wjcCore.Clipboard.copy(i),e.onCopied(o)))}t.keyCode===wjcCore.Key.Space&&e.selection.isValid&&e.selectionMode===wjcGrid.SelectionMode.CellRange&&e.select(new wjcGrid.CellRange(0,e.selection.col,e.rows.length-1,e.selection.col))}t.keyCode===wjcCore.Key.Escape&&e._contextMenu.hide(),(93===t.keyCode||t.shiftKey&&121===t.keyCode)&&(e._contextMenu.visible&&!wjcCore.isFirefox()?e._isContextMenuKeyDown=!1:e._isContextMenuKeyDown=!0)}),e.addEventListener(document.body,"keydown",e._keydownHdl,!0),e.addEventListener(document.body,"click",e._clickHdl),e.addEventListener(document.body,"mousemove",e._mouseMoveHdl),(t.match(/iPad/i)||t.match(/iPhone/i))&&(e.addEventListener(document.body,"touchstart",e._touchStartHdl),e.addEventListener(document.body,"touchend",e._touchEndHdl)),e.addEventListener(e.hostElement,"drop",()=>{e._htDown=null})}_flexSheetSyncSelection(e){if(this.collectionView&&this.selectionMode!=wjcGrid.SelectionMode.None){let t=this.selection,o=t.row>-1&&t.row<this.rows.length?this.rows[t.row]:null,i=o?o.dataItem:null;if((o instanceof HeaderRow||this.newRowAtTop&&o instanceof wjcGrid._NewRowTemplate||i instanceof wjcCore.CollectionViewGroup)&&(i=null),(i!=this.collectionView.currentItem||e)&&(!this.editableCollectionView||!this.editableCollectionView.currentAddItem)){let e=this._getRowIndex(this.collectionView.currentPosition);e!=t.row&&(t.row=t.row2=e,this.select(t,!1),this.selectionMode&&this.scrollIntoView(t.row,-1))}}}_initFuncsList(){var e=this;e._functionListHost=document.createElement("div"),wjcCore.addClass(e._functionListHost,"wj-flexsheet-formula-list"),document.querySelector("body").appendChild(e._functionListHost),e._functionListHost.style.display="none",e._functionListHost.style.position="absolute",e._functionList=new wjcInput.ListBox(e._functionListHost),e._functionList.isContentHtml=!0,e._functionList.itemsSource=e._getFunctions(),e._functionList.displayMemberPath="displayValue",e._functionList.selectedValuePath="actualvalue",e.addEventListener(e._functionListHost,"click",e.applyFunctionToCell.bind(e)),e.addEventListener(e._functionListHost,"keydown",t=>{t.keyCode===wjcCore.Key.Escape&&(e.hideFunctionList(),e.hostElement.focus(),t.preventDefault()),t.keyCode===wjcCore.Key.Enter&&(e.applyFunctionToCell(),e.hostElement.focus(),t.preventDefault(),t.stopPropagation())})}_getFunctions(){for(var e,t=[],o=0;o<FlexSheetFunctions.length;o++)e=FlexSheetFunctions[o],t.push({displayValue:'<div class="wj-flexsheet-formula-name">'+e.name+'</div><div class="wj-flexsheet-formula-description">'+e.description+"</div>",actualvalue:e.name});return t}_addCustomFunctionDescription(e,t){for(var o={displayValue:'<div class="wj-flexsheet-formula-name">'+e+"</div>"+(t?'<div class="wj-flexsheet-formula-description">'+t+"</div>":""),actualvalue:e},i=this._functionList.itemsSource,l=-1,n=0;n<i.length;n++)if(i[n].actualvalue===e){l=n;break}l>-1?i.splice(l,1,o):i.push(o)}_getCurrentFormulaIndex(e){var t=-1;return["+","-","*","/","^","(","&"].forEach(o=>{var i=e.lastIndexOf(o);i>t&&(t=i)}),t}_prepareCellForEditHandler(){var e=this,t=e._edtHdl._edt;t&&(e.addEventListener(t,"keydown",t=>{if(e.isFunctionListOpen)switch(t.keyCode){case wjcCore.Key.Up:e.selectPreviousFunction(),t.preventDefault(),t.stopPropagation();break;case wjcCore.Key.Down:e.selectNextFunction(),t.preventDefault(),t.stopPropagation();break;case wjcCore.Key.Tab:case wjcCore.Key.Enter:e.applyFunctionToCell(),t.preventDefault(),t.stopPropagation();break;case wjcCore.Key.Escape:e.hideFunctionList(),t.preventDefault(),t.stopPropagation()}}),e.addEventListener(t,"keyup",o=>{(o.keyCode>40||o.keyCode<32)&&o.keyCode!==wjcCore.Key.Tab&&o.keyCode!==wjcCore.Key.Escape&&setTimeout(()=>{e.showFunctionList(t)},0)}))}_addSheet(e,t,o,i,l){var n=this,s=new Sheet(n,l,e,t,o);return n.sheets.isValidSheetName(s)||s._setValidName(n.sheets.getValidSheetName(s)),s.nameChanged.addHandler((e,t)=>{n._updateDefinedNameWithSheetRefUpdating(t.oldValue,t.newValue)}),"number"==typeof i?(i<0&&(i=0),i>=n.sheets.length&&(i=n.sheets.length)):i=n.sheets.length,n.sheets.insert(i,s),s}_showSheet(e){!this.sheets||!this.sheets.length||e>=this.sheets.length||e<0||e===this.selectedSheetIndex||this.sheets[e]&&!this.sheets[e].visible||(this.finishEditing(),this._clearCalcEngine(),this._isCopying=!0,this.selectedSheetIndex>-1&&this.selectedSheetIndex<this.sheets.length&&this._copyTo(this.sheets[this.selectedSheetIndex]),this.sheets[e]&&(this._selectedSheetIndex=e,this._copyFrom(this.sheets[e])),this._isCopying=!1,this._filter.closeEditor())}_selectedSheetChange(e,t){this._showSheet(t.newValue),this.invalidate(!0),this.onSelectedSheetChanged(t)}_sourceChange(e,t){if(t.action===wjcCore.NotifyCollectionChangedAction.Add||t.action===wjcCore.NotifyCollectionChangedAction.Change)t.item._attachOwner(this),t.action===wjcCore.NotifyCollectionChangedAction.Add?(this._addingSheet=!0,t.index<=this.selectedSheetIndex&&(this._selectedSheetIndex+=1)):t.index===this.selectedSheetIndex&&this._copyFrom(t.item,!0),this.selectedSheetIndex=t.index;else if(t.action===wjcCore.NotifyCollectionChangedAction.Reset){for(var o=0;o<this.sheets.length;o++)this.sheets[o]._attachOwner(this);this.sheets.length>0?(0===this.selectedSheetIndex&&this._copyFrom(this.selectedSheet,!0),this.selectedSheetIndex=0):(this.rows.clear(),this.columns.clear(),this._selectedSheetIndex=-1)}else this.sheets.length>0?this.selectedSheetIndex>=this.sheets.length?this.selectedSheetIndex=0:this.selectedSheetIndex>t.index&&(this._selectedSheetIndex-=1):(this.rows.clear(),this.columns.clear(),this._selectedSheetIndex=-1);this.invalidate(!0)}_sheetVisibleChange(e,t){t.item.visible||t.index===this.selectedSheetIndex&&(this.selectedSheetIndex===this.sheets.length-1?this.selectedSheetIndex=t.index-1:this.selectedSheetIndex=t.index+1)}_applyStyleForCell(e,t,o,i=!1){var l,n,s,r=this,a=r.rows[e];null==a||a instanceof HeaderRow||!a.isVisible&&!i||(s=e*r.columns.length+t,(n=r.selectedSheet._getMergedRange(e,t))&&(s=n.topRow*r.columns.length+n.leftCol),(l=r.selectedSheet._styledCells[s])?(l.className="normal"===o.className?"":o.className||l.className,l.textAlign=o.textAlign||l.textAlign,l.verticalAlign=o.verticalAlign||l.verticalAlign,l.fontFamily=o.fontFamily||l.fontFamily,l.fontSize=o.fontSize||l.fontSize,l.backgroundColor=o.backgroundColor||l.backgroundColor,l.color=o.color||l.color,l.fontStyle="none"===o.fontStyle?"":o.fontStyle||l.fontStyle,l.fontWeight="none"===o.fontWeight?"":o.fontWeight||l.fontWeight,l.textDecoration="none"===o.textDecoration?"":o.textDecoration||l.textDecoration,l.format=o.format||l.format,l.whiteSpace=o.whiteSpace||l.whiteSpace,l.borderTopColor=o.borderTopColor||l.borderTopColor,l.borderTopStyle=o.borderTopStyle||l.borderTopStyle,l.borderTopWidth=o.borderTopWidth||l.borderTopWidth,l.borderBottomColor=o.borderBottomColor||l.borderBottomColor,l.borderBottomStyle=o.borderBottomStyle||l.borderBottomStyle,l.borderBottomWidth=o.borderBottomWidth||l.borderBottomWidth,l.borderLeftColor=o.borderLeftColor||l.borderLeftColor,l.borderLeftStyle=o.borderLeftStyle||l.borderLeftStyle,l.borderLeftWidth=o.borderLeftWidth||l.borderLeftWidth,l.borderRightColor=o.borderRightColor||l.borderRightColor,l.borderRightStyle=o.borderRightStyle||l.borderRightStyle,l.borderRightWidth=o.borderRightWidth||l.borderRightWidth):r.selectedSheet._styledCells[s]={className:o.className,textAlign:o.textAlign,verticalAlign:o.verticalAlign,fontStyle:o.fontStyle,fontWeight:o.fontWeight,fontFamily:o.fontFamily,fontSize:o.fontSize,textDecoration:o.textDecoration,backgroundColor:o.backgroundColor,color:o.color,format:o.format,whiteSpace:o.whiteSpace,borderTopColor:o.borderTopColor,borderTopStyle:o.borderTopStyle,borderTopWidth:o.borderTopWidth,borderBottomColor:o.borderBottomColor,borderBottomStyle:o.borderBottomStyle,borderBottomWidth:o.borderBottomWidth,borderLeftColor:o.borderLeftColor,borderLeftStyle:o.borderLeftStyle,borderLeftWidth:o.borderLeftWidth,borderRightColor:o.borderRightColor,borderRightStyle:o.borderRightStyle,borderRightWidth:o.borderRightWidth})}_checkCellFormat(e,t,o){var i,l,n=e*this.columns.length+t;this.selectedSheet&&((i=this.selectedSheet._getMergedRange(e,t))&&(o.isMergedCell=!0,n=i.topRow*this.columns.length+i.leftCol),(l=this.selectedSheet._styledCells[n])&&(o.isBold=o.isBold||"bold"===l.fontWeight,o.isItalic=o.isItalic||"italic"===l.fontStyle,o.isUnderline=o.isUnderline||"underline"===l.textDecoration),e===this.selection.row&&t===this.selection.col&&(l&&l.textAlign?o.textAlign=l.textAlign:t>-1&&(o.textAlign=this.columns[t].getAlignment()||o.textAlign)))}_resetMergedRange(e){var t,o,i,l,n=!1;for(t=e.topRow;t<=e.bottomRow;t++)for(o=e.leftCol;o<=e.rightCol;o++)(l=this.selectedSheet._getMergedRange(t,o))&&(n=!0,i=this.selectedSheet._mergedRanges.indexOf(l),this.selectedSheet._mergedRanges.splice(i,1));return n}_updateCellsForUpdatingRow(e,t,o,i){var l,n,s,r,a,h,d,c=e*this.columns.length;if(i)for(n=l=t*this.columns.length;n<c;n++)s=n-o*this.columns.length,(r=this.selectedSheet._styledCells[n])&&(n>=(t+o)*this.columns.length&&(this.selectedSheet._styledCells[s]=r),delete this.selectedSheet._styledCells[n]);else for(l=t*this.columns.length-1,n=c-1;n>l;n--)s=n+this.columns.length*o,(r=this.selectedSheet._styledCells[n])&&(this.selectedSheet._styledCells[s]=r,delete this.selectedSheet._styledCells[n]);if(this.selectedSheet._mergedRanges.length>0)for(h=this.selectedSheet._mergedRanges.length-1;h>=0;h--)a=this.selectedSheet._mergedRanges[h],i?(d=t+o-1)<a.topRow?(a.row-=o,a.row2-=o):d>=a.topRow&&d<=a.bottomRow?t<=a.topRow&&d>=a.bottomRow?this.selectedSheet._mergedRanges.splice(h,1):t<a.topRow?a.row<=a.row2?(a.row+=t-a.topRow,a.row2-=o):(a.row2+=t-a.topRow,a.row-=o):t===a.topRow&&o===a.rowSpan?this.selectedSheet._mergedRanges.splice(h,1):a.row<=a.row2?a.row2-=o:a.row-=o:t<=a.topRow?this.selectedSheet._mergedRanges.splice(h,1):t<=a.bottomRow&&(a.row<=a.row2?a.row2+=t-a.bottomRow-1:a.row+=t-a.bottomRow-1):t<=a.topRow?(a.row+=o,a.row2+=o):t>a.topRow&&t<=a.bottomRow&&(a.row<=a.row2?a.row2+=o:a.row+=o)}_updateCellsForUpdatingColumn(e,t,o,i){var l,n,s,r,a,h,d,c=this.rows.length*e;if(i)for(l=t;l<c;l++)n=l-o*(Math.floor(l/e)+((r=l%e)>=t?1:0)),(s=this.selectedSheet._styledCells[l])&&((r<t||r>=t+o)&&(this.selectedSheet._styledCells[n]=s),delete this.selectedSheet._styledCells[l]);else for(l=c-1;l>=t;l--)n=l+Math.floor(l/e)*o+((r=l%e)>=t?1:0),(s=this.selectedSheet._styledCells[l])&&(this.selectedSheet._styledCells[n]=s,delete this.selectedSheet._styledCells[l]);if(this.selectedSheet._mergedRanges.length>0)for(h=this.selectedSheet._mergedRanges.length-1;h>=0;h--)a=this.selectedSheet._mergedRanges[h],i?(d=t+o-1)<a.leftCol?(a.col-=o,a.col2-=o):d>=a.leftCol&&d<=a.rightCol?t<=a.leftCol&&d>=a.rightCol?this.selectedSheet._mergedRanges.splice(h,1):t<a.leftCol?a.col<=a.col2?(a.col+=t-a.leftCol,a.col2-=o):(a.col2+=t-a.leftCol,a.col-=o):t===a.leftCol&&o===a.columnSpan?this.selectedSheet._mergedRanges.splice(h,1):a.col<=a.col2?a.col2-=o:a.col-=o:t<=a.leftCol?this.selectedSheet._mergedRanges.splice(h,1):t<=a.rightCol&&(a.col<=a.col2?a.col2-=a.rightCol-t+1:a.col-=a.rightCol-t+1):t<=a.leftCol?(a.col+=o,a.col2+=o):t>a.leftCol&&t<=a.rightCol&&(a.col<=a.col2?a.col2+=o:a.col+=o)}_cloneObject(e){var t;if(null==e||!wjcCore.isObject(e))return e;t={};for(var o in e)e.hasOwnProperty(o)&&null!=e[o]&&(e[o].clone?t[o]=e[o].clone():t[o]=this._cloneObject(e[o]));return t}_evaluate(e,t,o,i,l){return e&&e.length>1&&this._enableFormulas?(e="="===e[0]?e:"="+e,this._calcEngine.evaluate(e,t,o,i,l)):e}_copyTo(e){var t,o,i,l=this,n=e.grid.autoGenerateColumns;if(e._storeRowSettings(),i=this.selection.clone(),e.grid.selection=new wjcGrid.CellRange,e.grid.rows.clear(),e.grid.columns.clear(),e.grid.columnHeaders.columns.clear(),e.grid.rowHeaders.rows.clear(),l.itemsSource)e.grid.autoGenerateColumns=!1,e.itemsSource=l.itemsSource,l.collectionView.sortDescriptions.length>0&&(e._dataView=l.collectionView._view.slice()),e.grid.collectionView.beginUpdate();else for(e.itemsSource=null,o=0;o<l.rows.length;o++)e.grid.rows.push(l.rows[o]);for(e._sortList=l.sortManager._committedList.slice(),e._getFilterSetting(),t=0;t<l.columns.length;t++)e.grid.columns.push(l.columns[t]);e.grid.collectionView&&(l._resetMappedColumns(e.grid),e.grid.collectionView.endUpdate()),e.grid.autoGenerateColumns=n,e.grid.frozenRows=l.frozenRows,e.grid.frozenColumns=l.frozenColumns,e.grid.allowAddNew=l.allowAddNew,null!=l.newRowAtTop&&(e.grid.newRowAtTop=l.newRowAtTop),e.grid.selection=i,e._scrollPosition=l.scrollPosition,setTimeout(()=>{l._setFlexSheetToDirty(),l.refresh(!0)},10)}_copyFrom(e,t=!0){var o,i,l,n,s,r,a,h=this,d=h.autoGenerateColumns;if(h._isCopying=!0,h._dragable=!1,h.itemsSource=null,h.rows.clear(),h.columns.clear(),h.columnHeaders.columns.clear(),h.rowHeaders.rows.clear(),r=e.grid.selection.clone(),h.selection=new wjcGrid.CellRange,e.selectionRanges.length>1&&h.selectionMode===wjcGrid.SelectionMode.CellRange&&(h._enableMulSel=!0),e.itemsSource)h.autoGenerateColumns=!1,h.itemsSource=e.itemsSource,h.collectionView.beginUpdate();else for(i=0;i<e.grid.rows.length;i++)h.rows.push(e.grid.rows[i]);for(h.sortManager.sortDescriptions.sourceCollection=e._sortList.slice(),h.sortManager._committedList=e._sortList.slice(),o=0;o<e.grid.columns.length;o++)(n=e.grid.columns[o]).isRequired=!1,h.columns.push(n);for(h.collectionView&&(h.collectionView.moveCurrentToPosition(h._getCvIndex(r.row)),h._resetMappedColumns(h),h.collectionView.endUpdate(),e._dataView&&(h.collectionView._view=e._dataView,h.collectionView._pgView=h.collectionView._getPageView(),h.itemsSource instanceof wjcCore.CollectionView||(e.grid.collectionView._view=e._dataView,e.grid.collectionView._pgView=e.grid.collectionView._getPageView()),h._bindGrid(!1),e.grid._bindGrid(!1)),h.collectionView.collectionChanged.addHandler((e,t)=>{t.action===wjcCore.NotifyCollectionChangedAction.Reset&&setTimeout(()=>{h.invalidate()},10)},h)),h.rows.length&&h.columns.length&&(h.selection=r),e._applyFilterSetting(),i=0;i<h.rows.length;i++)(l=e._rowSettings[i])&&(a=(s=h.rows[i])instanceof HeaderRow,s.height=l.height,s.allowMerging=l.allowMerging,s.visible=l.visible,s instanceof wjcGrid.GroupRow&&(s.isCollapsed=!!l.isCollapsed),s.isSelected=!!l.isSelected,s.isReadOnly=a||!!l.readOnly);h.autoGenerateColumns=d,h.frozenRows=e.grid.frozenRows,h.frozenColumns=e.grid.frozenColumns,h._isCopying=!1,h._addingSheet?(h._toRefresh&&(clearTimeout(h._toRefresh),h._toRefresh=null),h._toRefresh=setTimeout(()=>{h._setFlexSheetToDirty(),h.invalidate()},10),h._addingSheet=!1):t&&h.refresh(),h.scrollPosition=e._scrollPosition,h._ptScrl=e._scrollPosition}_resetMappedColumns(e){var t,o,i=0;if(e._mappedColumns=null,e.collectionView)for(o=e.collectionView.sortDescriptions;i<o.length;i++)(t=e.columns.getColumn(o[i].property))&&t.dataMap&&(e._mappedColumns||(e._mappedColumns={}),e._mappedColumns[t.binding]=t.dataMap)}_loadFromWorkbook(e){var t,o,i,l,n=0,s=this;if(null!=e.sheets&&0!==e.sheets.length){if(s.beginUpdate(),s.clear(),s._reservedContent=e.reservedContent,t=e.sheets.length,e.colorThemes&&e.colorThemes.length>0)for(l=0;l<this._colorThemes.length;l++)this._colorThemes[l]=e.colorThemes[l];for(;n<t;n++){if(n>0&&s.addUnboundSheet(),s.selectedSheet.grid.wj_sheetInfo={},wjcGridXlsx.FlexGridXlsxConverter.load(s.selectedSheet.grid,e,{sheetIndex:n,includeColumnHeaders:!1}),s.selectedSheet.name=s.selectedSheet.grid.wj_sheetInfo.name,s.selectedSheet.visible=s.selectedSheet.grid.wj_sheetInfo.visible,s.selectedSheet._styledCells=s.selectedSheet.grid.wj_sheetInfo.styledCells,s.selectedSheet.grid.wj_sheetInfo.mergedRanges)for(i=0;i<s.selectedSheet.grid.wj_sheetInfo.mergedRanges.length;i++)s.selectedSheet._mergedRanges[i]=s.selectedSheet.grid.wj_sheetInfo.mergedRanges[i];if(s._copyFrom(s.selectedSheet,!1),null!=s.selectedSheet.grid.wj_sheetInfo.tables&&s.selectedSheet.grid.wj_sheetInfo.tables.length>0)for(l=0;l<s.selectedSheet.grid.wj_sheetInfo.tables.length;l++)this._parseFromWorkbookTable(s.selectedSheet.grid.wj_sheetInfo.tables[l],s.selectedSheet)}if(null!=e.activeWorksheet&&e.activeWorksheet>-1&&e.activeWorksheet<s.sheets.length?s.selectedSheetIndex=e.activeWorksheet:s.selectedSheetIndex=0,e.definedNames&&e.definedNames.length>0)for(l=0;l<e.definedNames.length;l++)o=e.definedNames[l],s.definedNames.push(new DefinedName(s,o.name,o.value,o.sheetName));s.endUpdate(),s.onLoaded()}}_saveToWorkbook(e){var t,o,i,l,n,s,r=this,a=!(!e||!e.includeFormulaValues),h=e=>r.evaluate(e,null,l);if(0===r.sheets.length)throw"The flexsheet is empty.";if(l=r.sheets[0],a&&(l.grid.wj_sheetInfo.evaluateFormula=h),0===r.selectedSheetIndex&&(l._storeRowSettings(),l.itemsSource instanceof wjcCore.CollectionView||r._copyRowsToSelectedSheet()),l._setRowSettings(),l.tables.length>0)for(l.grid.wj_sheetInfo.tables=[],s=0;s<l.tables.length;s++)l.grid.wj_sheetInfo.tables.push(r._parseToWorkbookTable(l.tables[s]));for(t=wjcGridXlsx.FlexGridXlsxConverter.save(l.grid,{sheetName:l.name,sheetVisible:l.visible,includeColumnHeaders:!1}),r._checkTableHeaderRow(l.tables,t),l.grid.wj_sheetInfo.evaluateFormula&&(l.grid.wj_sheetInfo.evaluateFormula=null),t.reservedContent=r._reservedContent,n=1;n<r.sheets.length;n++){if(l=r.sheets[n],a&&(l.grid.wj_sheetInfo.evaluateFormula=h),r.selectedSheetIndex===n&&(l._storeRowSettings(),l.itemsSource instanceof wjcCore.CollectionView||r._copyRowsToSelectedSheet()),l._setRowSettings(),l.tables.length>0)for(l.grid.wj_sheetInfo.tables=[],s=0;s<l.tables.length;s++)l.grid.wj_sheetInfo.tables.push(r._parseToWorkbookTable(l.tables[s]));o=wjcGridXlsx.FlexGridXlsxConverter.save(l.grid,{sheetName:l.name,sheetVisible:l.visible,includeColumnHeaders:!1}),r._checkTableHeaderRow(l.tables,o),l.grid.wj_sheetInfo.evaluateFormula&&(l.grid.wj_sheetInfo.evaluateFormula=null),t._addWorkSheet(o.sheets[0],n)}for(t.activeWorksheet=r.selectedSheetIndex,s=0;s<r.definedNames.length;s++){var d=r.definedNames[s];(i=new wjcXlsx.DefinedName).name=d.name,i.value=d.value,i.sheetName=d.sheetName,t.definedNames.push(i)}if(r._colorThemes&&r._colorThemes.length>0)for(s=0;s<r._colorThemes.length;s++)t.colorThemes[s]=r._colorThemes[s];return t}_mouseDown(e){var t,o,i=window.navigator.userAgent,l=this.hitTest(e);this.columns;if(this.selectedSheet&&(this.selectedSheet._scrollPosition=this.scrollPosition),l.cellType!==wjcGrid.CellType.None&&(this._isClicking=!0),this._dragable)return this._isDragging=!0,this._draggingMarker=document.createElement("div"),wjcCore.setCss(this._draggingMarker,{position:"absolute",display:"none",borderStyle:"dotted",cursor:"move"}),document.body.appendChild(this._draggingMarker),this._draggingTooltip=new wjcCore.Tooltip,this._draggingCells=this.selection,this.selectedSheet&&this.selectedSheet.selectionRanges.clear(),this.onDraggingRowColumn(new DraggingRowColumnEventArgs(this._draggingRow,e.shiftKey)),void e.preventDefault();if("crosshair"===this.hostElement.style.cursor&&null==this._fillingMarker)return this.finishEditing(),this._fillingData=!0,this._fillingPoint=new wjcCore.Point(e.clientX-this.scrollPosition.x,e.clientY-this.scrollPosition.y),this._fillingSource=this.selection.clone(),this._fillingMarker=document.createElement("div"),wjcCore.setCss(this._fillingMarker,{position:"absolute",display:"none",border:"2px dashed"}),this._root.appendChild(this._fillingMarker),this._fillingTooltip=new wjcCore.Tooltip,void e.preventDefault();if(this.selectionMode===wjcGrid.SelectionMode.CellRange?e.ctrlKey?this._enableMulSel||(this._enableMulSel=!0,0===this.selectedSheet.selectionRanges.length&&this.selectedSheet.selectionRanges.push(this.selection)):l.cellType!==wjcGrid.CellType.None&&(this.selectedSheet&&this.selectedSheet.selectionRanges.clear(),this._enableMulSel&&this.refresh(!1),this._enableMulSel=!1):(this._enableMulSel=!1,this.selectedSheet&&this.selectedSheet.selectionRanges.clear()),this._htDown=l,0!==this.rows.length&&0!==this.columns.length&&(i.match(/iPad/i)||i.match(/iPhone/i)||this._contextMenu.hide(),3!==e.which&&this.selectionMode===wjcGrid.SelectionMode.CellRange&&(l.cellType===wjcGrid.CellType.ColumnHeader||l.cellType===wjcGrid.CellType.None)&&!(l.col>-1&&this.columns[l.col].isSelected)&&wjcCore.hasClass(e.target,"wj-cell")&&!l.edgeRight)){if(this._columnHeaderClicked=!0,o=this.itemsSource&&this.rows[0]&&!this.rows[0].isVisible?1:0,e.shiftKey)this._multiSelectColumns(l);else{if(t=new wjcGrid.CellRange(o,l.col,this.rows.length-1,l.col),3===e.which&&this.selection.contains(t))return;this.select(t)}this._eCt.children[o]&&this._eCt.children[o].children[l.col]&&this._eCt.children[o].children[l.col].focus(),e.preventDefault()}}_mouseMove(e){var t,o=this.hitTest(e),i=this.selection.clone(),l=this.rows.length,n=this.columns.length,s=this.hostElement.style.cursor;if(0===this.rows.length||0===this.columns.length)return this._dragable=!1,void(o.cellType===wjcGrid.CellType.Cell&&(this.hostElement.style.cursor="default"));if(this._isDragging)return this.hostElement.style.cursor="move",void this._showDraggingMarker(e);if(!this._isClicking&&o.edgeBottom&&o.edgeRight&&o.row===i.bottomRow&&o.col===i.rightCol)this.hostElement.style.cursor="crosshair";else{if(this._fillingData)return this.hostElement.style.cursor="crosshair",void this._showFillMarker(e);t=this.itemsSource?0===i.topRow||1===i.topRow:0===i.topRow,this._isClicking||!i||o.cellType===wjcGrid.CellType.None||this.itemsSource||this.isReadOnly||!this._enableDragDrop||(this._draggingColumn=t&&i.bottomRow===l-1,this._draggingRow=0===i.leftCol&&i.rightCol===n-1,o.cellType===wjcGrid.CellType.Cell?(this._draggingColumn&&((o.col===i.leftCol-1||o.col===i.rightCol)&&o.edgeRight||o.row===l-1&&o.edgeBottom)&&(s="move"),this._draggingRow&&!this._containsGroupRows(i)&&((o.row===i.topRow-1||o.row===i.bottomRow)&&o.edgeBottom||o.col===n-1&&o.edgeRight)&&(s="move")):o.cellType===wjcGrid.CellType.ColumnHeader?o.edgeBottom&&(this._draggingColumn&&o.col>=i.leftCol&&o.col<=i.rightCol?s="move":this._draggingRow&&0===i.topRow&&(s="move")):o.cellType===wjcGrid.CellType.RowHeader&&o.edgeRight&&(this._draggingColumn&&0===i.leftCol?s="move":this._draggingRow&&o.row>=i.topRow&&o.row<=i.bottomRow&&!this._containsGroupRows(i)&&(s="move")),this._dragable="move"===s,this.hostElement.style.cursor=s),this._htDown&&this._htDown.panel&&(o=new wjcGrid.HitTestInfo(this._htDown.panel,e),this._multiSelectColumns(o),o.cellType===wjcGrid.CellType.Cell&&this.scrollIntoView(o.row,o.col))}}_mouseUp(e){try{if(this._isDragging)this._draggingCells.equals(this._dropRange)||(this._handleDropping(e),this.onDroppingRowColumn());else if(this._fillingData){let e,t,o=_FillDataOperation.CopyContent,i=this._fillingRange,l=this._fillingSource;this._orgCellSettings=null,this._fillingRange&&this._fillingRange.isValid&&(wjcCore.assert(this._canDoFillOperation(),"To do this, all the merged cells need be the same size."),(e=l.leftCol===i.leftCol&&l.rightCol===i.rightCol)?l.row!==l.row2&&(o=_FillDataOperation.FillSeries):l.col!==l.col2&&(o=_FillDataOperation.FillSeries),this._orgCellSettings=this._getCellSettingsForFill(),t=new _FillAction(this,this._fillingSource),this._undoStack._addAction(t),o=_FillDataOperation.CopyFormat|o,this._fillData(o),this._showFillMenuSmartTag(o))}}finally{this._isDragging&&(this._draggingCells=null,this._dropRange=null,document.body.removeChild(this._draggingMarker),this._draggingMarker=null,this._draggingTooltip.hide(),this._draggingTooltip=null,this._isDragging=!1,this._draggingColumn=!1,this._draggingRow=!1),this._htDown&&this._htDown.cellType!==wjcGrid.CellType.None&&this.selectedSheet&&(this._htDown.cellType===wjcGrid.CellType.TopLeft&&this.selectionMode===wjcGrid.SelectionMode.CellRange&&(this.selection=new wjcGrid.CellRange(0,0,this.rows.length-1,this.columns.length-1)),this.selection.isValid&&this.selectedSheet._addSelection(this.selection),this._enableMulSel=!1),this._fillingData&&(this._fillingData=!1,this._fillingPoint=null,this._fillingRange=null,this._root.removeChild(this._fillingMarker),this._fillingMarker=null,this._fillingTooltip.hide(),this._fillingTooltip=null,this.hostElement.style.cursor="default"),this._isClicking=!1,this._columnHeaderClicked=!1,this._htDown=null}}_click(){var e=this,t=window.navigator.userAgent;t.match(/iPad/i)||t.match(/iPhone/i)||e._contextMenu.hide(),setTimeout(()=>{e.hideFunctionList()},200)}_touchStart(e){var t=this;wjcCore.hasClass(e.target,"wj-context-menu-item")||t._contextMenu.hide(),t._longClickTimer=setTimeout(()=>{var o;t._isDescendant(t._divContainer,e.target)&&(o=t.hitTest(e))&&o.cellType!==wjcGrid.CellType.None&&!t._resizing&&(o.cellType===wjcGrid.CellType.TopLeft&&(t.selection=new wjcGrid.CellRange(0,0,t.rows.length-1,t.columns.length-1),t.selectedSheet&&(t.selectedSheet.selectionRanges.clear(),t.selectedSheet.selectionRanges.push(t.selection))),t._contextMenu.show(null,new wjcCore.Point(e.pageX+10,e.pageY+10)))},500)}_touchEnd(){clearTimeout(this._longClickTimer)}_keydown(e){this._endDragFillOperation(e),!this._isDescendant(this.hostElement,e.target)&&this.hostElement!==e.target||this._edtHdl.activeEditor||!this.selectedSheet||e.keyCode!==wjcCore.Key.Delete&&e.keyCode!==wjcCore.Key.Back||(this._delSeletionContent(e),e.preventDefault()),this._contextMenu.visible&&(e.keyCode===wjcCore.Key.Down&&this._contextMenu.moveToNext(),e.keyCode===wjcCore.Key.Up&&this._contextMenu.moveToPrev(),e.keyCode===wjcCore.Key.Home&&this._contextMenu.moveToFirst(),e.keyCode===wjcCore.Key.End&&this._contextMenu.moveToLast(),e.keyCode===wjcCore.Key.Enter&&this._contextMenu.handleContextMenu(),e.preventDefault())}_showDraggingMarker(e){var t,o,i,l,n,s,r,a,h,d=new wjcGrid.HitTestInfo(this.cells,e),c=this.selection,_=this.columns.length,u=this.rows.length,g=this._cumulativeScrollOffset(this.hostElement),w=this._root.getBoundingClientRect(),m=w.left+g.x,f=w.top+g.y;if(this.scrollIntoView(d.row,d.col),this._draggingColumn){for(o=c.rightCol-c.leftCol+1,n=0,((i=d.col)<0||i+o>_)&&(i=_-o),t=this.cells.getCellBoundingRect(0,i),s=this._root.offsetHeight-this._eCHdr.offsetHeight,l=(l=this.cells.height)>s?s:l,r=0;r<o;r++)n+=this.columns[i+r].renderSize;a=FlexSheet.convertNumberToAlpha(i)+" : "+FlexSheet.convertNumberToAlpha(i+o-1),this._dropRange?(this._dropRange.col=i,this._dropRange.col2=i+o-1):this._dropRange=new wjcGrid.CellRange(0,i,this.rows.length-1,i+o-1)}else if(this._draggingRow){for(o=c.bottomRow-c.topRow+1,l=0,((i=d.row)<0||i+o>u)&&(i=u-o),t=this.cells.getCellBoundingRect(i,0),s=this._root.offsetWidth-this._eRHdr.offsetWidth,r=0;r<o;r++)l+=this.rows[i+r].renderSize;n=(n=this.cells.width)>s?s:n,a=i+1+" : "+(i+o),this._dropRange?(this._dropRange.row=i,this._dropRange.row2=i+o-1):this._dropRange=new wjcGrid.CellRange(i,0,i+o-1,this.columns.length-1)}if(t){if(h={display:"inline",zIndex:"9999",opacity:.5,top:t.top-(this._draggingColumn?this._ptScrl.y:0)+g.y,left:t.left-(this._draggingRow?this._ptScrl.x:0)+g.x,height:l,width:n},t.top=t.top-(this._draggingColumn?this._ptScrl.y:0),t.left=t.left-(this._draggingRow?this._ptScrl.x:0),this.rightToLeft&&this._draggingRow&&(h.left=h.left-n+t.width+2*this._ptScrl.x,t.left=t.left+2*this._ptScrl.x),this._draggingRow){if(m+this._eRHdr.offsetWidth!==h.left||f+this._root.offsetHeight+1<h.top+h.height)return}else if(f+this._eCHdr.offsetHeight!==h.top||m+this._root.offsetWidth+1<h.left+h.width)return;wjcCore.setCss(this._draggingMarker,h),this._draggingTooltip.show(this.hostElement,a,t)}}_showFillMarker(e){let t,o,i,l,n,s,r,a,h=new wjcGrid.HitTestInfo(this.cells,e);h.row>-1&&h.col>-1&&(t=e.clientX-this.scrollPosition.x-this._fillingPoint.x,o=e.clientY-this.scrollPosition.y-this._fillingPoint.y,Math.abs(t)>=Math.abs(o)?(i=this._fillingSource.topRow,n=this._fillingSource.bottomRow,l=t>=0?this._fillingSource.leftCol:h.col,s=t>=0?h.col:this._fillingSource.rightCol):(i=o>=0?this._fillingSource.topRow:h.row,n=o>=0?h.row:this._fillingSource.bottomRow,l=this._fillingSource.leftCol,s=this._fillingSource.rightCol),r=this.cells.getCellBoundingRect(i,l,!0),a=this.cells.getCellBoundingRect(n,s,!0),wjcCore.setCss(this._fillingMarker,{left:r.left+this.cells.hostElement.offsetLeft-2,top:r.top+this.cells.hostElement.offsetTop-2,width:a.right-r.left+4,height:a.bottom-r.top+4,display:"",zIndex:"9999"}),this._fillingRange=new wjcGrid.CellRange(i,l,n,s),this.scrollIntoView(h.row,h.col),this._showFillTooltip())}_showFillTooltip(){let e,t,o,i,l,n,s,r,a,h,d,c,_=this._fillingSource,u=this._fillingRange;this._fillingTooltip.hide(),u.equals(_)||_.contains(u)||((t=_.leftCol===u.leftCol&&_.rightCol===u.rightCol)?(u.bottomRow>_.bottomRow?((e=this.cells.getCellBoundingRect(u.bottomRow,u.rightCol)).top=e.bottom+10,o=u.bottomRow-_.topRow):((e=this.cells.getCellBoundingRect(u.topRow,u.rightCol)).top+=10,o=u.topRow-_.topRow),e.left=e.right,(i=o%_.rowSpan)<0&&(i+=_.rowSpan),_.row===_.row2&&(l=!0),a=this.selectedSheet.getCellStyle(_.topRow+i,_.leftCol),h=this.getMergedRange(this.cells,_.topRow+i,_.leftCol),d=this.columns[_.leftCol],c=a&&a.format?a.format:d.format,l?(r=this.getCellData(h?h.topRow:_.topRow+i,_.leftCol,!1),r=wjcCore.isString(r)&&"="===r[0]?"":wjcCore.Globalize.format(r,c)):(n=this.getCellData(_.topRow+i,_.leftCol,!1),wjcCore.isNumber(n)||wjcCore.isDate(n)?(s=this._getFillSeries(t,0,i))?(r=this._getFillData(i,o,_,t,s,!0),r=wjcCore.Globalize.format(r,c)):r="":(r=n,wjcCore.isString(r)&&"="===r[0]&&(r="")))):(u.rightCol>_.rightCol?(e=this.cells.getCellBoundingRect(u.bottomRow,u.rightCol),o=u.rightCol-_.leftCol):(e=this.cells.getCellBoundingRect(u.bottomRow,u.leftCol),o=u.leftCol-_.leftCol),e.top=e.bottom+10,(i=o%_.columnSpan)<0&&(i+=_.columnSpan),_.col===_.col2&&(l=!0),a=this.selectedSheet.getCellStyle(_.topRow,_.leftCol+i),h=this.getMergedRange(this.cells,_.topRow,_.leftCol+i),d=this.columns[_.leftCol+i],c=a&&a.format?a.format:d.format,l?(r=this.getCellData(_.topRow,h?h.leftCol:_.leftCol+i,!1),r=wjcCore.isString(r)&&"="===r[0]?"":wjcCore.Globalize.format(r,c)):(n=this.getCellData(_.topRow,_.leftCol+i,!1),wjcCore.isNumber(n)||wjcCore.isDate(n)?(s=this._getFillSeries(t,0,i))?(r=this._getFillData(i,o,_,t,s,!0),r=wjcCore.Globalize.format(r,c)):r="":(r=n,wjcCore.isString(r)&&"="===r[0]&&(r="")))),e.top+=this.cells.hostElement.offsetTop,this._fillingTooltip.show(this.hostElement,r,e))}_showFillMenuSmartTag(e){let t=this,o=document.createElement("img"),i=document.createElement("img"),l=t.selection,n=t.cells.getCellBoundingRect(l.bottomRow,l.rightCol,!0),s=n.right+t.cells.hostElement.offsetLeft,r=n.bottom+t.cells.hostElement.offsetTop;t.addEventListener(document.body,"mousedown",t._endDragFillOperationHdl,!0),t._fillSmartTagHost=document.createElement("div"),wjcCore.addClass(t._fillSmartTagHost,"wj-flexsheet-smart-tag"),s+t._ptScrl.x+32+(t.cells.hostElement.offsetHeight>t._root.offsetHeight?17:0)>t._root.offsetWidth&&(s-=32),r+t._ptScrl.y+18+(t.cells.hostElement.offsetWidth>t._root.offsetWidth?17:0)>t._root.offsetHeight&&(r-=18),wjcCore.setCss(t._fillSmartTagHost,{left:s,top:r}),o.setAttribute("src","data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAAFJJREFUeNrclEEKACAIBOfp/Xy7i4WSRnRYBIVRVhFJVIhyEAxllQa5E/wBSnsU6Rza2nugqNmASi57C/KKNg/Iqn+iVWzx6M4bOdUEAAD//wMAAYRMfiNaiqEAAAAASUVORK5CYII="),wjcCore.setCss(o,{float:"left",height:18,margin:0}),i.setAttribute("src","data:image/png;base64,  "),wjcCore.setCss(i,{float:"left",margin:0,height:18,display:"none"}),t._fillSmartTagHost.appendChild(o),t._fillSmartTagHost.appendChild(i),t._root.appendChild(t._fillSmartTagHost),t.addEventListener(t._fillSmartTagHost,"mouseover",()=>{t._fillSmartTagHost.style.width="32px",i.style.display=""}),t.addEventListener(t._fillSmartTagHost,"mouseleave",()=>{t._fillMenuHost||(t._fillSmartTagHost.style.width="18px",i.style.display="none")}),t.addEventListener(t._fillSmartTagHost,"mousedown",o=>{wjcCore.hasClass(t._fillSmartTagHost,"wj-flexsheet-smart-tag-active")?(wjcCore.removeClass(t._fillSmartTagHost,"wj-flexsheet-smart-tag-active"),t._fillMenuHost.style.display="none"):(wjcCore.addClass(t._fillSmartTagHost,"wj-flexsheet-smart-tag-active"),t._showFillMenu(e),e=null),o.preventDefault()},!0)}_showFillMenu(e){let t,o,i=wjcCore.culture.FlexSheet,l=this,n=l._fillSmartTagHost.offsetLeft,s=l._fillSmartTagHost.offsetTop+18;if(!l._fillMenuHost){l._fillMenuHost=document.createElement("div"),wjcCore.setCss(l._fillMenuHost,{display:"none",zIndex:100}),l._fillMenuHost.innerHTML='<div class="wj-flexsheet-fill-menu-item">'+i.copyCells+'</div><div class="wj-flexsheet-fill-menu-item">'+i.fillSeries+'</div><div class="wj-flexsheet-fill-menu-item">'+i.fillFormat+'</div><div class="wj-flexsheet-fill-menu-item">'+i.fillWithoutFormat+"</div>",wjcCore.addClass(l._fillMenuHost,"wj-flexsheet-fill-menu"),l._root.appendChild(l._fillMenuHost);for(let e=0;e<l._fillMenuHost.childElementCount;e++)t=l._fillMenuHost.childNodes[e],l.addEventListener(t,"mousedown",t=>{let o;switch(l._removeActiveStyleForFillMenuItem(),wjcCore.addClass(t.target,"wj-flexsheet-fill-menu-item-active"),e){case 0:o=_FillDataOperation.CopyFormat|_FillDataOperation.CopyContent;break;case 1:o=_FillDataOperation.CopyFormat|_FillDataOperation.FillSeries;break;case 2:o=_FillDataOperation.CopyFormat;break;case 3:o=_FillDataOperation.FillSeries}l._fillData(o),l._fillMenuHost.style.display="none",wjcCore.removeClass(l._fillSmartTagHost,"wj-flexsheet-smart-tag-active"),t.preventDefault()},!0)}if(e){switch(l._removeActiveStyleForFillMenuItem(),e){case _FillDataOperation.CopyFormat|_FillDataOperation.CopyContent:o=0;break;case _FillDataOperation.CopyFormat|_FillDataOperation.FillSeries:o=1;break;case _FillDataOperation.CopyFormat:o=2;break;case _FillDataOperation.FillSeries:o=3}wjcCore.addClass(l._fillMenuHost.childNodes[o],"wj-flexsheet-fill-menu-item-active")}wjcCore.setCss(l._fillMenuHost,{display:""}),n+l._ptScrl.x+l._fillMenuHost.offsetWidth+(l.cells.hostElement.offsetHeight>l._root.offsetHeight?17:0)>l._root.offsetWidth&&(n=n-l._fillMenuHost.offsetWidth+l._fillSmartTagHost.offsetWidth),s+l._ptScrl.y+l._fillMenuHost.offsetHeight+ +(l.cells.hostElement.offsetWidth>l._root.offsetWidth?17:0)>l._root.offsetHeight&&(s=l._fillSmartTagHost.offsetTop-l._fillMenuHost.offsetHeight),l._fillMenuHost.style.left=n+"px",l._fillMenuHost.style.top=s+"px"}_endDragFillOperation(e){this._fillSmartTagHost&&(e instanceof MouseEvent&&(e.target===this._fillSmartTagHost||this._isDescendant(this._fillSmartTagHost,e.target)||e.target===this._fillMenuHost||this._isDescendant(this._fillMenuHost,e.target))||(this.removeEventListener(document.body,"mousedown",this._endDragFillOperationHdl),this._disposeFillSmartTag(),this._fillMenuHost&&this._disposeFillMenu(),this._undoStack._updateCurrentAction(_FillAction)))}_removeActiveStyleForFillMenuItem(){let e;for(let t=0;t<this._fillMenuHost.childElementCount;t++)e=this._fillMenuHost.childNodes[t],wjcCore.removeClass(e,"wj-flexsheet-fill-menu-item-active")}_disposeFillSmartTag(){this.removeEventListener(this._fillSmartTagHost),this._root.removeChild(this._fillSmartTagHost),this._fillSmartTagHost=null,this._orgCellSettings=null}_disposeFillMenu(){let e;for(let t=0;t<this._fillMenuHost.childElementCount;t++)e=this._fillMenuHost.childNodes[t],this.removeEventListener(e);this._root.removeChild(this._fillMenuHost),this._fillMenuHost=null}_handleDropping(e){var t,o,i,l,n,s,r,a=this;if(a.selectedSheet&&a._draggingCells&&a._dropRange&&!a._containsMergedCells(a._draggingCells)&&!a._containsMergedCells(a._dropRange)){if(a._clearCalcEngine(),a._draggingColumn&&a._draggingCells.leftCol>a._dropRange.leftCol||a._draggingRow&&a._draggingCells.topRow>a._dropRange.topRow)if(e.shiftKey){if(!a._allowExchangeCells(a._draggingRow,!0))return void console.warn("Can not complete operation: You are attempting to change a position of table row or column in a way that is not allowed.");if(a._draggingColumn){for(l=a._dropRange.leftCol,o=a._draggingCells.leftCol;o<=a._draggingCells.rightCol;o++)a.columns.moveElement(o,l),l++;a._exchangeTableColumns(!0)}else if(a._draggingRow)for(i=a._dropRange.topRow,t=a._draggingCells.topRow;t<=a._draggingCells.bottomRow;t++)a.rows.moveElement(t,i),i++;a._exchangeCellStyle(!0)}else{for(this.undoStack.stackSize>0&&(n=new _MoveCellsAction(a,a._draggingCells,a._dropRange,e.ctrlKey)),i=a._dropRange.topRow,t=a._draggingCells.topRow;t<=a._draggingCells.bottomRow;t++){for(l=a._dropRange.leftCol,o=a._draggingCells.leftCol;o<=a._draggingCells.rightCol;o++)a._moveCellContent(t,o,i,l,e.ctrlKey),a._draggingColumn&&i===a._dropRange.topRow&&(a.columns[l].dataType=a.columns[o].dataType?a.columns[o].dataType:wjcCore.DataType.Object,a.columns[l].align=a.columns[o].align,a.columns[l].format=a.columns[o].format,e.ctrlKey||(a.columns[o].dataType=wjcCore.DataType.Object,a.columns[o].align=null,a.columns[o].format=null)),l++;i++}if(a._draggingColumn&&!e.ctrlKey)for(l=a._dropRange.leftCol,o=a._draggingCells.leftCol;o<=a._draggingCells.rightCol;o++)a._updateColumnFiler(o,l),l++}else if(a._draggingColumn&&a._draggingCells.leftCol<a._dropRange.leftCol||a._draggingRow&&a._draggingCells.topRow<a._dropRange.topRow)if(e.shiftKey){if(!a._allowExchangeCells(a._draggingRow,!1))return void console.warn("Can not complete operation: You are attempting to change a position of table row or column in a way that is not allowed.");if(a._draggingColumn){for(l=a._dropRange.rightCol,o=a._draggingCells.rightCol;o>=a._draggingCells.leftCol;o--)a.columns.moveElement(o,l),l--;a._exchangeTableColumns(!1)}else if(a._draggingRow)for(i=a._dropRange.bottomRow,t=a._draggingCells.bottomRow;t>=a._draggingCells.topRow;t--)a.rows.moveElement(t,i),i--;a._exchangeCellStyle(!1)}else{for(this.undoStack.stackSize>0&&(n=new _MoveCellsAction(a,a._draggingCells,a._dropRange,e.ctrlKey)),i=a._dropRange.bottomRow,t=a._draggingCells.bottomRow;t>=a._draggingCells.topRow;t--){for(l=a._dropRange.rightCol,o=a._draggingCells.rightCol;o>=a._draggingCells.leftCol;o--)a._moveCellContent(t,o,i,l,e.ctrlKey),a._draggingColumn&&i===a._dropRange.bottomRow&&(a.columns[l].dataType=a.columns[o].dataType?a.columns[o].dataType:wjcCore.DataType.Object,a.columns[l].align=a.columns[o].align,a.columns[l].format=a.columns[o].format,e.ctrlKey||(a.columns[o].dataType=wjcCore.DataType.Object,a.columns[o].align=null,a.columns[o].format=null)),l--;i--}if(a._draggingColumn&&!e.ctrlKey)for(l=a._dropRange.rightCol,o=a._draggingCells.rightCol;o>=a._draggingCells.leftCol;o--)a._updateColumnFiler(o,l),l--}e.ctrlKey||(s=a._updateFormulaForDropping(e.shiftKey),r=a._updateNamedRangesForDropping(e.shiftKey)),n&&n.saveNewState()&&(n._affectedFormulas=s,n._affectedDefinedNameVals=r,a._undoStack._addAction(n)),a._undoStack._pendingAction&&(a._undoStack._pendingAction._affectedFormulas=s,a._undoStack._pendingAction._affectedDefinedNameVals=r),a.select(a._dropRange),a.selectedSheet._addSelection(a.selection),a.hostElement.focus()}}_moveCellContent(e,t,o,i,l){var n,s,r,a,h,d,c,_,u,g=this.getCellData(e,t,!1),w=e*this.columns.length+t,m=o*this.columns.length+i,f=this.selectedSheet._styledCells[w],C=!0;if((s=this.selectedSheet.findTable(o,i))&&(c=s.getRange(),_=s.getColumns(),s.showHeaderRow&&o===c.topRow&&(h=_[a=i-c.leftCol].name,null==g||""===g?C=!1:_[a].name=g)),C){if(l&&g&&"string"==typeof g&&"="===g[0]&&m-w!=0)try{(u=this._calcEngine._parse(g))._moveCellRangeExp(this.selectedSheetIndex,new wjcGrid.CellRange(e,t),new wjcGrid.CellRange(o,i),!1,!0)&&(g="="+u._getStringExpression())}catch(e){}this.setCellData(o,i,g)}else C=!0;if(f?this.selectedSheet._styledCells[m]=this._cloneObject(f):delete this.selectedSheet._styledCells[m],l)(n=this.selectedSheet.findTable(e,t))&&(d=n.getRange(),n===s&&e===o&&n.showHeaderRow&&e===d.topRow&&(r=t-d.leftCol,n._updateColumnName(r,g)));else{if(delete this.selectedSheet._styledCells[w],n=this.selectedSheet.findTable(e,t)){if(d=n.getRange(),n===s&&e===o&&n.showHeaderRow&&e===d.topRow)return r=t-d.leftCol,void n._updateColumnName(r,h);if(n.showHeaderRow&&e===d.topRow)return}this.setCellData(e,t,null)}}_allowExchangeCells(e,t){let o,i,l,n,s,r,a=this.selectedSheet.tables;for(o=0;o<a.length;o++)if(i=a[o],e?(l=i.getRange(TableSection.Data),r=this._draggingCells.rowSpan,n=new wjcGrid.CellRange(this._draggingCells.topRow,l.leftCol,this._draggingCells.bottomRow,l.rightCol),s=new wjcGrid.CellRange(this._dropRange.topRow,l.leftCol,this._dropRange.bottomRow,l.rightCol)):(l=i.getRange(),r=this._draggingCells.columnSpan,n=new wjcGrid.CellRange(l.topRow,this._draggingCells.leftCol,l.bottomRow,this._draggingCells.rightCol),s=new wjcGrid.CellRange(l.topRow,this._dropRange.leftCol,l.bottomRow,this._dropRange.rightCol)),l.intersects(n)&&!l.contains(n)||l.intersects(s)&&!l.contains(s)||l.contains(n)&&!l.contains(s)||!l.contains(n)&&l.contains(s))return!1;return!0}_exchangeTableColumns(e){let t,o,i,l,n,s,r=this.selectedSheet.tables;for(t=0;t<r.length;t++)if(o=r[t],(i=o.getRange()).leftCol<=this._draggingCells.leftCol&&i.rightCol>=this._draggingCells.rightCol)for(l=(e?this._draggingCells.leftCol:this._draggingCells.rightCol)-i.leftCol,n=(e?this._dropRange.leftCol:this._dropRange.rightCol)-i.leftCol,s=0;s<this._draggingCells.columnSpan;s++)o._moveColumns(l,n),e?(l++,n++):(l--,n--)}_exchangeCellStyle(e){var t,o,i,l,n,s=0,r=[];for(t=this._draggingCells.topRow;t<=this._draggingCells.bottomRow;t++)for(o=this._draggingCells.leftCol;o<=this._draggingCells.rightCol;o++)i=t*this.columns.length+o,this.selectedSheet._styledCells[i]?(r.push(this._cloneObject(this.selectedSheet._styledCells[i])),delete this.selectedSheet._styledCells[i]):r.push(void 0);if(e){if(this._draggingColumn)for(n=this._draggingCells.rightCol-this._draggingCells.leftCol+1,o=this._draggingCells.leftCol-1;o>=this._dropRange.leftCol;o--)for(t=0;t<this.rows.length;t++)i=t*this.columns.length+o,l=t*this.columns.length+o+n,this.selectedSheet._styledCells[i]?(this.selectedSheet._styledCells[l]=this._cloneObject(this.selectedSheet._styledCells[i]),delete this.selectedSheet._styledCells[i]):delete this.selectedSheet._styledCells[l];else if(this._draggingRow)for(n=this._draggingCells.bottomRow-this._draggingCells.topRow+1,t=this._draggingCells.topRow-1;t>=this._dropRange.topRow;t--)for(o=0;o<this.columns.length;o++)i=t*this.columns.length+o,l=(t+n)*this.columns.length+o,this.selectedSheet._styledCells[i]?(this.selectedSheet._styledCells[l]=this._cloneObject(this.selectedSheet._styledCells[i]),delete this.selectedSheet._styledCells[i]):delete this.selectedSheet._styledCells[l]}else if(this._draggingColumn)for(n=this._draggingCells.rightCol-this._draggingCells.leftCol+1,o=this._draggingCells.rightCol+1;o<=this._dropRange.rightCol;o++)for(t=0;t<this.rows.length;t++)i=t*this.columns.length+o,l=t*this.columns.length+o-n,this.selectedSheet._styledCells[i]?(this.selectedSheet._styledCells[l]=this._cloneObject(this.selectedSheet._styledCells[i]),delete this.selectedSheet._styledCells[i]):delete this.selectedSheet._styledCells[l];else if(this._draggingRow)for(n=this._draggingCells.bottomRow-this._draggingCells.topRow+1,t=this._draggingCells.bottomRow+1;t<=this._dropRange.bottomRow;t++)for(o=0;o<this.columns.length;o++)i=t*this.columns.length+o,l=(t-n)*this.columns.length+o,this.selectedSheet._styledCells[i]?(this.selectedSheet._styledCells[l]=this._cloneObject(this.selectedSheet._styledCells[i]),delete this.selectedSheet._styledCells[i]):delete this.selectedSheet._styledCells[l];for(t=this._dropRange.topRow;t<=this._dropRange.bottomRow;t++)for(o=this._dropRange.leftCol;o<=this._dropRange.rightCol;o++)i=t*this.columns.length+o,r[s]?this.selectedSheet._styledCells[i]=r[s]:delete this.selectedSheet._styledCells[i],s++}_containsMergedCells(e,t){var o,i;if(!(t=t||this.selectedSheet))return!1;for(o=0;o<t._mergedRanges.length;o++)if(i=t._mergedRanges[o],e.intersects(i))return!0;return!1}_multiSelectColumns(e){var t;e&&this._columnHeaderClicked&&((t=new wjcGrid.CellRange(e.row,e.col)).row=this.itemsSource&&this.rows[0]&&!this.rows[0].isVisible?1:0,t.row2=this.rows.length-1,t.col2=this.selection.col2,this.select(t))}_cumulativeOffset(e){var t=0,o=0;do{t+=e.offsetTop||0,o+=e.offsetLeft||0,e=e.offsetParent}while(e);return new wjcCore.Point(o,t)}_cumulativeScrollOffset(e){var t=0,o=0;do{t+=e.scrollTop||0,o+=e.scrollLeft||0,e=e.offsetParent}while(e&&!(e instanceof HTMLBodyElement));return t+=document.body.scrollTop||document.documentElement.scrollTop,o+=document.body.scrollLeft||document.documentElement.scrollLeft,new wjcCore.Point(o,t)}_checkHitWithinSelection(e){var t;if(null!=e&&e.cellType===wjcGrid.CellType.Cell){if((t=this.getMergedRange(this.cells,e.row,e.col))&&t.contains(this.selection))return!0;if(this.selection.row===e.row&&this.selection.col===e.col)return!0}return!1}_clearForEmptySheet(e){this.selectedSheet&&0===this[e].length&&!0!==this._isCopying&&!0!==this._isUndoing&&!0!==this._isSorting&&(this.selectedSheet._mergedRanges.length=0,this.selectedSheet._styledCells=null,this.select(new wjcGrid.CellRange))}_containsGroupRows(e){var t;for(t=e.topRow;t<=e.bottomRow;t++)if(this.rows[t]instanceof wjcGrid.GroupRow)return!0;return!1}_delSeletionContent(e){var t,o,i,l,n,s,r,a,h,d,c,_=this.selectedSheet.selectionRanges.slice(),u=!1,g=new _EditAction(this),w=this.editableCollectionView,m=!1,f=this.scrollPosition;if(!this.isReadOnly)if(this.allowDelete&&this.selection.isValid&&0===this.selection.leftCol&&this.selection.rightCol===this.columns.length-1)this.deleteRows(this.selection.topRow,this.selection.rowSpan);else{for(this.beginUpdate(),this.undoStack.stackSize>0&&(g=new _EditAction(this)),null!=_&&0!==_.length||(_=[this.selection]),i=0;i<_.length;i++){if(t=_[i],o=new wjcGrid.CellRange,d=new wjcGrid.CellEditEndingEventArgs(this.cells,o,e),(a=this.selectedSheet.tables.length)>0)for(s=a-1;s>=0;s--)r=this.selectedSheet.tables[s],t.contains(r.getRange())&&(g&&g._storeDeletedTables(r),this.selectedSheet.tables.remove(r));for(n=t.topRow;n<=t.bottomRow;n++)if((c=this.rows[n])&&!c.isReadOnly&&(c.visible||this.selectedSheet._freezeHiddenRows&&this.selectedSheet._freezeHiddenRows[n]))for(l=t.leftCol;l<=t.rightCol;l++)(h=this._getBindingColumn(this.cells,n,this.columns[l])).isReadOnly||!1!==h.isRequired&&(null!=h.isRequired||h.dataType!=wjcCore.DataType.String)||!h.visible&&!this.selectedSheet._freezeHiddenCols[l]||this.getCellData(n,l,!0)&&(o.setRange(n,l),d.cancel=!1,this.onBeginningEdit(d)&&(w&&(m||(m=!0,w.beginUpdate()),w.editItem(c.dataItem),this._edtHdl._edItem=w.currentEditItem),this.setCellData(n,l,"",!0),u=!0,this.onCellEditEnding(d),this.onCellEditEnded(d)));m&&(w.endUpdate(),w._pendingRefresh=!1,t.rowSpan>1&&w.commitEdit())}u&&g&&(g.saveNewState(),this._undoStack._addAction(g)),this.selection=t,this.scrollPosition=f,this.endUpdate()}}_updateAffectedFormula(e,t,o,i,l){var n,s,r,a,h,d,c,_,u,g=[],w=[],m=this.selection.clone();for(this.selectedSheet._storeRowSettings(),this.beginUpdate(),n=0;n<this.sheets.length;n++)for(r=(s=this.sheets[n]).grid,a=0;a<r.rows.length;a++)for(h=0;h<r.columns.length;h++)if((_=r.getCellData(a,h,!1))&&wjcCore.isString(_)&&"="===_[0]&&(u=this._updateCellRef(_,n,e,t,o,i,l))){if(g.push({sheet:s,point:new wjcCore.Point(a,h),formula:_}),d=a,c=h,n===this.selectedSheetIndex&&(i?a>=e&&(o?d+=t:d-=t):h>=e&&(o?c+=t:c-=t),!o&&(i&&a<=e&&a>=e-t+1||!i&&h<=e&&h>=e-t+1)))continue;r.setCellData(a,h,u,!1),w.push({sheet:s,point:new wjcCore.Point(d,c),formula:u})}return this.selection=m,this.endUpdate(),{oldFormulas:g,newFormulas:w}}_updateAffectedNamedRanges(e,t,o,i){var l,n,s,r,a=[],h=[];for(l=0;l<this.definedNames.length;l++)(s=(n=this.definedNames[l]).value)&&wjcCore.isString(s)&&(r=this._updateCellRef(s,this.selectedSheetIndex,e,t,o,i))&&(a.push({name:n.name,value:s}),n.value=r,h.push({name:n.name,value:r}));return{oldDefinedNameVals:a,newDefinedNameVals:h}}_updateFormulaBoundaryForEditingCell(e,t){let o,i,l,n,s=[],r=[];for(this.beginUpdate(),o=e;o<this.rows.length;o++)(l=this.getCellData(o,t,!1))&&wjcCore.isString(l)&&"="===l[0]&&(n=this._updateCellBoundary(l,e,t))&&(s.push({point:new wjcCore.Point(o,t),formula:l}),this.setCellData(o,t,n,!1),r.push({point:new wjcCore.Point(o,t),formula:n}));for(i=t;i<this.columns.length;i++)(l=this.getCellData(e,i,!1))&&wjcCore.isString(l)&&"="===l[0]&&(n=this._updateCellBoundary(l,e,t))&&(s.push({point:new wjcCore.Point(e,i),formula:l}),this.setCellData(e,i,n,!1),r.push({point:new wjcCore.Point(e,i),formula:n}));return this.endUpdate(),{oldFormulas:s,newFormulas:r}}_updateColumnFiler(e,t){for(var o=JSON.parse(this._filter.filterDefinition),i=0;i<o.filters.length;i++){var l=o.filters[i];if(l.columnIndex===e){l.columnIndex=t;break}}this._filter.filterDefinition=JSON.stringify(o)}_isDescendant(e,t){for(var o=t.parentNode;null!=o;){if(o===e)return!0;o=o.parentNode}return!1}_clearCalcEngine(){this._calcEngine._clearExpressionCache()}_getRangeString(e,t,o=!0){var i,l,n,s,r,a="",h=!0,d=t.grid;if(wjcCore.isArray(e))if(e.length>1){if(this._isMultipleRowsSelected(e,t)){for(a="",l=0;l<e.length;l++)a&&(a+="\n"),a+=this._getRangeString(e[l],t);return a}if(!this._isMultipleColumnsSelected(e,t))return"";for(a="",i=0,h=!0;i<d.rows.length;i++){for(h||(a+="\n"),h=!1,l=0,g=!0;l<e.length;l++)(n=e[l].clone()).row=n.row2=i,g||(a+="\t"),g=!1,a+=this._getRangeString(e[l],t);return a}}else switch(r=e[0],this.selectionMode){case wjcGrid.SelectionMode.Row:case wjcGrid.SelectionMode.RowRange:r.col=0,r.col2=t.grid.columns.length-1;break;case wjcGrid.SelectionMode.ListBox:r.col=0,r.col2=t.grid.columns.length-1;for(var c=0;c<t.grid.rows.length;c++)t.grid.rows[c].isSelected&&t.grid.rows[c].isVisible&&(r.row=r.row2=c,a&&(a+="\n"),a+=this._getRangeString(r,t));return a}for(var _=(r=wjcCore.asType(wjcCore.isArray(e)?e[0]:e,wjcGrid.CellRange)).topRow;_<=r.bottomRow;_++)if(d.rows[_]&&d.rows[_].isVisible){h||(a+="\n"),h=!1;for(var u=r.leftCol,g=!0;u<=r.rightCol;u++)if(d.columns[u]&&d.columns[u].isVisible){g||(a+="\t"),g=!1;var w=this._getCellStyle(_,u,t),m=w?w.format:"",f=d.columns[u];o?(s=d.getCellData(_,u,!1),wjcCore.isString(s)&&"="===s[0]&&(s=this._evaluate(s,m,t,_,u)),s=this._formatEvaluatedResult(s,f,m)):(s=d.getCellData(_,u,!1),wjcCore.isDate(s)&&(s=wjcCore.Globalize.format(s,f.format)),f.dataMap&&(s=f.dataMap.getDisplayValue(s))),(s=(s=null==s?"":s.toString()).replace(/\t/g," ")).indexOf("\n")>-1&&(s='"'+s.replace(/"/g,'""')+'"'),a+=s}}return a}_getSelectionForListBoxMode(e){let t,o=0;for(;o<e.rows.length;o++)e.rows[o].isSelected&&(t?t.row2=o:t=new wjcGrid.CellRange(o,0,o,e.columns.length-1));return t}_containsRandFormula(e,t){for(var o=0;o<e.length;o++)for(var i=e[o],l=i.topRow;l<=i.bottomRow&&l<t.grid.rows.length;l++)for(var n=i.leftCol;n<=i.rightCol&&n<t.grid.columns.length;n++){var s=t.grid.getCellData(l,n,!1);if(wjcCore.isString(s)&&"="===s[0]&&-1!==s.search(/rand/i))return!0}return!1}_isMultipleRowsSelected(e,t){var o,i,l;e&&e.length>1?l=e:this.selectedSheet.selectionRanges.length>1&&(l=this.selectedSheet.selectionRanges),o=l[0];for(var n=1;n<l.length;n++)if((i=l[n]).leftCol!==o.leftCol||i.rightCol!==o.rightCol)return!1;return!0}_isMultipleColumnsSelected(e,t){var o,i,l;e&&e.length>1?l=e:this.selectedSheet.selectionRanges.length>1&&(l=this.selectedSheet.selectionRanges),o=l[0];for(var n=0;n<l.length;n++)if((i=l[n]).topRow!==o.topRow||i.bottomRow!==o.bottomRow)return!1;return!0}_postSetClipStringProcess(e,t,o,i,l,n){var s,r,a,h,d,c,_,u=!1;return h=new wjcGrid.CellRangeEventArgs(this.cells,new wjcGrid.CellRange(t,o),e),this.onPastingCell(h)&&(i>=0&&l>=0&&this._copiedSheet&&(s=this._copiedSheet._getMergedRange(i,l))&&s.topRow===i&&s.leftCol===l&&(r=(r=t+s.rowSpan-1)<this.rows.length?r:this.rows.length-1,a=(a=o+s.columnSpan-1)<this.columns.length?a:this.columns.length-1,this.mergeRange(new wjcGrid.CellRange(t,o,r,a),!0)),this.cells.setCellData(t,o,h.data)&&(wjcCore.isString(h.data)&&(d=h.data.match(/\n/g))&&d.length>0&&(n?n.whiteSpace="pre":n={whiteSpace:"pre"},this.rows[t].height=this.rows.defaultSize*(d.length+1)),c=t*this.columns.length+o,(s=this.selectedSheet._getMergedRange(t,o))&&(c=s.topRow*this.columns.length+s.leftCol),n&&(_=this._cloneObject(n)),this.selectedSheet._styledCells[c]=_,this.onPastedCell(h),u=!0)),u}_delCutData(e,t){var o,i,l,n,s=this._copiedSheet===this.selectedSheet?this:this._copiedSheet.grid;for(o=(n=this.selectionMode===wjcGrid.SelectionMode.ListBox?this._getSelectionForListBoxMode(s):this._copiedRanges[0]).topRow;o<=n.bottomRow;o++)if(null!=s.rows[o])for(i=n.leftCol;i<=n.rightCol;i++)(this._copiedSheet!==this.selectedSheet||o<this.selection.topRow||o>this.selection.topRow+e-1||i<this.selection.leftCol||i>this.selection.leftCol+t-1)&&(0==(l=s._getBindingColumn(s.cells,o,s.columns[i])).isRequired||null==l.isRequired&&l.dataType==wjcCore.DataType.String)&&s.getCellData(o,i,!0)&&s.setCellData(o,i,"",!0)}_containsMultiLineText(e){for(var t=0;t<e.length;t++)for(var o=e[t],i=0;i<o.length;i++)if(o[i].indexOf("\n")>=0)return!0;return!1}_sortByRow(e,t){return e.topRow>t.topRow?1:e.topRow<t.topRow?-1:0}_sortByColumn(e,t){return e.leftCol>t.leftCol?1:e.leftCol<t.leftCol?-1:0}_setFlexSheetToDirty(){this.columns._dirty=!0,this.rows._dirty=!0,this.rowHeaders.columns._dirty=!0,this.rowHeaders.rows._dirty=!0,this.columnHeaders.columns._dirty=!0,this.columnHeaders.rows._dirty=!0}static convertNumberToAlpha(e){var t,o,i="";if(e>=0)do{t=Math.floor(e/26),o=e%26,i=String.fromCharCode(o+65)+i,e=t-1}while(t);return i}_updateFormulaForReorderingRows(e,t,o=!1){var i,l,n=o?e-t:t-e;this.beginUpdate();for(var s=0;s<this.columns.length;s++)if((i=this.getCellData(t,s,!1))&&"string"==typeof i&&"="===i[0]&&0!==n){try{l=this._calcEngine._parse(i)}catch(e){continue}l._updateCellRangeExpForReorderingRows(n)&&this.setCellData(t,s,"="+l._getStringExpression())}this.endUpdate()}_updateFormulaForDropping(e){var t,o,i,l,n,s,r,a,h,d=[],c=[];for(this.beginUpdate(),i=0;i<this.sheets.length;i++)for(o=(t=this.sheets[i]).grid,l=0;l<o.rows.length;l++)for(s=0;s<o.columns.length;s++)(a=o.getCellData(l,s,!1))&&"string"==typeof a&&"="===a[0]&&(h=this._updateCellRefForDropping(a,i,e))&&(o.setCellData(l,s,h,!1),e&&i===this.selectedSheetIndex?(n=o.rows[l],r=o.columns[s],d.push({sheet:t,row:n,column:r,formula:a}),c.push({sheet:t,row:n,column:r,formula:h})):(d.push({sheet:t,point:new wjcCore.Point(l,s),formula:a}),c.push({sheet:t,point:new wjcCore.Point(l,s),formula:h})));return this.endUpdate(),{oldFormulas:d,newFormulas:c}}_updateNamedRangesForDropping(e){var t,o,i,l,n=[],s=[];for(t=0;t<this.definedNames.length;t++)(i=(o=this.definedNames[t]).value)&&wjcCore.isString(i)&&(l=this._updateCellRefForDropping(i,this.selectedSheetIndex,e))&&(n.push({name:o.name,value:i}),o.value=l,s.push({name:o.name,value:l}));return{oldDefinedNameVals:n,newDefinedNameVals:s}}_updateCellRefForDropping(e,t,o=!1){let i;try{i=this._calcEngine._parse(e)}catch(e){return null}return i._moveCellRangeExp(t,this._draggingCells,this._dropRange,o)?"="+i._getStringExpression():null}_updateCellStyleForReorderingRows(e,t,o){let i,l,n,s=this.columns.length;for(i=0;i<s;i++)(n=this._getCellStyle(e,i))&&(o[l=t*s+i]=n)}_scanFormulas(){for(var e=[],t=0;t<this.rows.length;t++)for(var o=0;o<this.columns.length;o++){var i=this.getCellData(t,o,!1);i&&wjcCore.isString(i)&&"="===i[0]&&e.push({row:t,column:o,formula:i})}return e}_resetFormulas(e){var t=this;e&&t.deferUpdate(()=>{for(var o=0;o<e.length;o++){var i=e[o];t.setCellData(i.row,i.column,i.formula)}})}_getCellStyle(e,t,o){return(o=o||this.selectedSheet)?o.getCellStyle(e,t):null}_validateSheetName(e){for(let t=0;t<this.sheets.length;t++)if(this.sheets[t].name===e)return!0;return!1}_checkExistDefinedName(e,t,o=-1){for(let i=0;i<this.definedNames.length;i++)if(this.definedNames[i].name===e&&this.definedNames[i].sheetName===t&&i!==o)return!0;return!1}_updateDefinedNameWithSheetRefUpdating(e,t){for(var o,i,l,n=0;n<this.definedNames.length;n++)if((o=this.definedNames[n]).sheetName===e&&null!=o.sheetName&&(o._sheetName=t),(i=o.value.match(/(\w+)\!\$?[A-Za-z]+\$?\d+/g))&&i.length>0)for(var s=0;s<i.length;s++)(l=i[s]).substring(0,l.indexOf("!"))===e&&(o.value=o.value.replace(l,l.replace(e,t)))}_updateFormulasWithNameUpdating(e,t,o=!1){let i,l,n,s,r,a,h,d,c,_,u,g=this.selection.clone(),w=!1;for(u=o?/\[/:/\w/,this.selectedSheet._storeRowSettings(),this.beginUpdate(),i=0;i<this.sheets.length;i++)for(r=(s=this.sheets[i]).grid,l=0;l<r.rows.length;l++)for(n=0;n<r.columns.length;n++)if((a=r.getCellData(l,n,!1))&&"string"==typeof a&&"="===a[0]){for(w=!1,h=a.indexOf(e),_=new RegExp(e,"g");h>-1;)d="",c="",h>0&&(d=a[h-1]),h+e.length<a.length&&(c=a[h+e.length]),!/\w/.test(d)&&(o&&u.test(c)||!o&&!u.test(c))&&(a=a.replace(_,(o,i)=>i===h?t:e),w=!0),h=a.indexOf(e,h+e.length);w&&r.setCellData(l,n,a,!1)}this.selection=g,this.endUpdate()}_getDefinedNameIndexByName(e){for(var t=0;t<this.definedNames.length;t++)if(this.definedNames[t].name===e)return t;return-1}_updateTablesForUpdatingRow(e,t,o){var i,l,n,s,r;if(this.selectedSheet.tables.length>0)for(i=this.selectedSheet.tables.length-1;i>=0;i--)if(l=this.selectedSheet.tables[i],n=l.getRange(),o)if((s=e+t-1)<n.topRow)l._updateTableRange(-t,-t,0,0);else if(s>=n.topRow&&s<=n.bottomRow){if(e<=n.topRow&&s===n.bottomRow){null==r&&(r=[]),r.push(l),this.selectedSheet.tables.remove(l);continue}e<n.topRow?(l.showHeaderRow&&(l._showHeaderRow=!1),l._updateTableRange(e-n.topRow,-t,0,0)):(e===n.topRow&&l.showHeaderRow&&(l._showHeaderRow=!1),s===n.bottomRow&&l.showTotalRow&&(l._showTotalRow=!1),l._updateTableRange(0,-t,0,0))}else e<=n.topRow?(null==r&&(r=[]),r.push(l),this.selectedSheet.tables.remove(l)):e<=n.bottomRow&&(l.showTotalRow&&(l._showTotalRow=!1),l._updateTableRange(0,e-n.bottomRow-1,0,0));else e<=n.topRow?l._updateTableRange(t,t,0,0):e>n.topRow&&e<=n.bottomRow&&l._updateTableRange(0,t,0,0);return r}_updateTablesForUpdatingColumn(e,t,o){var i,l,n,s,r,a,h,d;if(this.selectedSheet.tables.length>0)for(i=this.selectedSheet.tables.length-1;i>=0;i--)if(l=this.selectedSheet.tables[i],n=l.getRange(),o)if((s=e+t-1)<n.leftCol)l._updateTableRange(0,0,-t,-t);else if(s>=n.leftCol&&s<=n.rightCol){if(e<=n.leftCol&&s===n.rightCol){null==d&&(d=[]),d.push(l),this.selectedSheet.tables.remove(l);continue}e<n.leftCol?(r=t-n.leftCol+e,a=n.leftCol,l._updateTableRange(0,0,e-n.leftCol,-t)):(r=t,a=e,l._updateTableRange(0,0,0,-r)),l._columns.splice(a-n.leftCol,r)}else e<=n.leftCol?(null==d&&(d=[]),d.push(l),this.selectedSheet.tables.remove(l)):e<=n.rightCol&&(r=n.rightCol-e+1,l._updateTableRange(0,0,0,-r),l._columns.splice(e,r));else if(e<=n.leftCol)l._updateTableRange(0,0,t,t);else if(e>n.leftCol&&e<=n.rightCol)for(l._updateTableRange(0,0,0,t),a=e-n.leftCol,h=0;h<t;h++)l._addColumn(a+h);return d}_isDisableDeleteRow(e,t){var o,i,l;if(this.selectedSheet.tables.length>0)for(o=0;o<this.selectedSheet.tables.length;o++)if(i=this.selectedSheet.tables[o],l=i.getRange(),i.showHeaderRow&&l.topRow>=e&&l.topRow<=t)return!0;return!1}_copy(e,t){var o,i;if("columns"==e){if(super._copy(e,t),this.itemsSource&&(o=this.rows[0])instanceof HeaderRow){o._ubv=null,o._ubv={};for(var l=0;l<this.columns.length;l++)i=this.columns[l],o._ubv[i._hash]=i.header}return!0}return!1}_getTableSheetIndex(e,t){this.sheets;for(let o=0;o<e.length;o++)if(e[o].indexOf(t)>-1)return o;return-1}_sheetSortConverter(e,t,o,i){return o=super._sortConverter(e,t,o,i),wjcCore.isString(o)&&o.length>0&&"="===o[0]&&(o=this.evaluate(o)),o}_formatEvaluatedResult(e,t,o){return wjcCore.isPrimitive(e)?(t.dataMap&&(e=t.dataMap.getDisplayValue(e)),!wjcCore.isInt(e)||t.format||t.dataMap||o?((o&&"@"!==o||t.format&&"@"!==t.format)&&wjcCore.isString(e)&&(+e).toString()===e&&(e=+e),e=null!=e?wjcCore.Globalize.format(e,o||t.format):""):e=e.toString()):e&&(!wjcCore.isInt(e.value)||t.format||t.dataMap||o||e.format?(wjcCore.isString(e.value)&&(+e.value).toString()===e.value&&(e.value=+e.value),e=null!=e.value?wjcCore.Globalize.format(e.value,o||e.format||t.format):""):e=e.value.toString()),e}_updateCellRef(e,t,o,i,l,n,s){let r;try{r=this._calcEngine._parse(e)}catch(e){return null}return r._updateCellRangeExp(t,o,i,l,n,s)?"="+r._getStringExpression():null}_updateCellBoundary(e,t,o){let i;try{i=this._calcEngine._parse(e)}catch(e){return null}return i instanceof _FunctionExpression&&i._updateCellBoundary(t,o)?"="+i._getStringExpression():null}_fillData(e){let t,o,i,l,n,s,r,a,h,d,c,_,u,g,w,m,f,C,p,S=this._fillingRange||this.selection,b=this._fillingSource,R=!e||0!=(e&_FillDataOperation.CopyFormat),y=!!e&&0!=(e&_FillDataOperation.CopyContent),v=!e||0!=(e&_FillDataOperation.FillSeries),T=b.leftCol===S.leftCol&&b.rightCol===S.rightCol,x=[];for(this.beginUpdate(),this._resetCellsForFillRange(e),t=0;t<S.rowSpan;t++)for((i=(a=(n=S.topRow+t)-b.topRow)%b.rowSpan)<0&&(i+=b.rowSpan),o=0;o<S.columnSpan;o++)h=(s=S.leftCol+o)-b.leftCol,a>=0&&a<b.rowSpan&&h>=0&&h<b.columnSpan||((l=h%b.columnSpan)<0&&(l+=b.columnSpan),w=!1,(u=this.getMergedRange(this.cells,b.topRow+i,b.leftCol+l))&&(w=u.topRow===b.topRow+i&&u.leftCol===b.leftCol+l)&&((g=this.getMergedRange(this.cells,n,s))||this.mergeRange(new wjcGrid.CellRange(n,s,n+u.rowSpan-1,s+u.columnSpan-1))),R&&(_=null,(c=this.selectedSheet.getCellStyle(b.topRow+i,b.leftCol+l))&&(_=this._cloneObject(c)),r=n*this.columns.length+s,this.selectedSheet._styledCells[r]=_),u&&!w||(y?(d=this.getCellData(b.topRow+i,b.leftCol+l,!1))&&wjcCore.isString(d)&&"="===d[0]?this._fillFormula(d,b.topRow+i,b.leftCol+l,n,s):this.setCellData(n,s,d):v&&(T?(m=o,f=i):(m=t,f=l),null==(d=this.getCellData(b.topRow+i,b.leftCol+l,!1))||wjcCore.isString(d)?(d&&wjcCore.isString(d)&&"="===d[0]?this._fillFormula(d,b.topRow+i,b.leftCol+l,n,s):this.setCellData(n,s,d),x[m]=null):(x[m]||(x[m]=this._getFillSeries(T,m,f)),(C=x[m])&&(p=C.items,T?(d=this._getFillData(i,a,b,T,C,null!=e||0===m),C.endIndex===b.topRow+i&&(x[m]=null)):(d=this._getFillData(l,h,b,T,C,null!=e||0===m),C.endIndex===b.leftCol+l&&(x[m]=null)),this.setCellData(n,s,d))))));this._fillingRange&&this.select(this._fillingRange,!1),this.endUpdate()}_getFillData(e,t,o,i,l,n){let s,r,a=l.items;return 1!==a.length||n?(s=i?Math.floor(t/o.rowSpan)*l.itemIndexes[l.itemIndexes.length-1]+o.topRow+e-l.startIndex+1:Math.floor(t/o.columnSpan)*l.itemIndexes[l.itemIndexes.length-1]+o.leftCol+e-l.startIndex+1,r=this._getLinearBestFitTrendData(a,l.itemIndexes,s),"date"===l.type&&(r=FlexSheet._fromOADate(r)),r):a[0]}_fillFormula(e,t,o,i,l){let n,s,r;try{n=this._calcEngine._parse(e),s=new wjcGrid.CellRange(t,o),r=new wjcGrid.CellRange(i,l),n._moveCellRangeExp(this.selectedSheetIndex,s,r,!1,!0)&&(e="="+n._getStringExpression())}catch(e){}finally{this.setCellData(i,l,e)}}_getFillSeries(e,t,o){let i,l,n,s,r,a,h,d,c=this._fillingSource,_=[],u=[];if(e)for(o=c.topRow+o,s=0,r=c.topRow;r<=c.bottomRow;r++){if(a=this.getMergedRange(this.cells,r,c.leftCol+t))if(h&&!a.equals(h)){if(s+=h.rowSpan,h=a,a.leftCol!==c.leftCol+t)continue}else{if(a.topRow!==r||a.leftCol!==c.leftCol+t)continue;s+=1,h=a}else h?(s+=h.rowSpan,h=null):s+=1;if(null!=(d=this.getCellData(r,c.leftCol+t,!1))&&""!==d)if(wjcCore.isNumber(d)||wjcCore.isDate(d))if(i=wjcCore.isNumber(d)?"number":"date",wjcCore.isDate(d)&&(d=FlexSheet._toOADate(d)),0===_.length)n=r,l=i,_.push(d),u.push(s);else if(i===l)_.push(d),u.push(s);else{if(o>=n&&o<=r)return{type:l,startIndex:n,endIndex:r-1,items:_,itemIndexes:u};_.splice(0,_.length),u.splice(0,u.length)}else if(_.length>0){if(o>=n&&o<=r)return{type:l,startIndex:n,endIndex:r-1,items:_,itemIndexes:u};_.splice(0,_.length),u.splice(0,u.length)}}else for(o=c.leftCol+o,s=0,r=c.leftCol;r<=c.rightCol;r++){if(a=this.getMergedRange(this.cells,c.topRow+t,r))if(h&&!a.equals(h)){if(s+=h.columnSpan,h=a,a.topRow!==c.topRow+t)continue}else{if(a.leftCol!==r||a.topRow!==c.topRow+t)continue;s+=1,h=a}else h?(s+=h.columnSpan,h=null):s+=1;if(null!=(d=this.getCellData(c.topRow+t,r,!1))&&""!==d)if(wjcCore.isNumber(d)||wjcCore.isDate(d))if(i=wjcCore.isNumber(d)?"number":"date",wjcCore.isDate(d)&&(d=FlexSheet._toOADate(d)),0===_.length)n=r,l=i,_.push(d),u.push(s);else if(i===l)_.push(d),u.push(s);else{if(o>=n&&o<=r)return{type:l,startIndex:n,endIndex:r-1,items:_,itemIndexes:u};_.splice(0,_.length),u.splice(0,u.length)}else if(_.length>0){if(o>=n&&o<=r)return{type:l,startIndex:n,endIndex:r-1,items:_,itemIndexes:u};_.splice(0,_.length),u.splice(0,u.length)}}return _.length>0?{type:l,startIndex:n,endIndex:r-1,items:_,itemIndexes:u}:null}_getLinearBestFitTrendData(e,t,o){let i,l,n,s,r,a,h=0,d=0,c=0,_=0;if(1===(s=e.length))return e[0]+o-1;for(i=0;i<t.length;i++)h+=l=t[i],c+=l*l,d+=n=e[i],_+=l*n;return r=(s*_-h*d)/(s*c-h*h),a=(d*c-h*_)/(s*c-h*h),o*r+a}_getCellSettingsForFill(e,t){let o,i,l,n,s,r;for(e||(e=this._fillingSource),t||(t=this._fillingRange),s=[],o=t.topRow;o<=t.bottomRow;o++)for(i=t.leftCol;i<=t.rightCol;i++)o>=e.topRow&&o<=e.bottomRow&&i>=e.leftCol&&i<=e.rightCol||(l=this.getCellData(o,i,!1),n=this._cloneObject(this.selectedSheet.getCellStyle(o,i)),(r=this.getMergedRange(this.cells,o,i))&&r.topRow===o&&r.leftCol===i||(r=null),s.push({row:o,col:i,value:l,style:n,mergedCell:r?r.clone():null}));return s}_resetCellsForFillRange(e){let t,o,i,l,n,s=!e||0!=(e&_FillDataOperation.CopyFormat),r=!!e&&0!=(e&_FillDataOperation.CopyContent),a=!e||0!=(e&_FillDataOperation.FillSeries);if(this._orgCellSettings&&this._orgCellSettings.length>0)for(t=0;t<this._orgCellSettings.length;t++)i=(o=this._orgCellSettings[t]).row,l=o.col,s||(n=i*this.columns.length+l,this.selectedSheet._styledCells[n]=o.style),r||a||this.setCellData(i,l,o.value)}_canDoFillOperation(){let e,t,o,i,l,n,s,r,a,h,d,c,_,u,g,w=this._fillingSource,m=this._fillingRange,f=!1;for(e=w.topRow;e<=w.bottomRow;e++)for(t=w.leftCol;t<=w.rightCol;t++)if(h=this.getMergedRange(this.cells,e,t),d){if(!h||!d.equals(h)){f=!0;break}}else d=h;for(o=m.topRow;o<=m.bottomRow;o++)for((i=(l=o-w.topRow)%w.rowSpan)<0&&(i+=w.rowSpan),i+=w.topRow,n=m.leftCol;n<=m.rightCol;n++)if(r=n-w.leftCol,!(l>=0&&l<w.rowSpan&&r>=0&&r<w.columnSpan)&&((s=r%w.columnSpan)<0&&(s+=w.columnSpan),s+=w.leftCol,h=this.getMergedRange(this.cells,i,s),a=this.getMergedRange(this.cells,o,n))){if(f||!h)return!1;if(c=a?o-a.topRow:NaN,_=a?n-a.leftCol:NaN,u=h?i-h.topRow:NaN,g=h?s-h.leftCol:NaN,c!==u||_!==g)return!1}return!0}_updateItemIndexForInsertingRow(e,t,o){let i,l;for(i=0;i<e.length;i++)(l=e[i])&&null!=l._itemIdx&&l._itemIdx>=t&&(l._itemIdx+=o)}_updateItemIndexForRemovingRow(e,t){let o,i;for(o=0;o<e.length;o++)(i=e[o])&&null!=i._itemIdx&&i._itemIdx>=t&&(i._itemIdx-=1)}_copyRowsToSelectedSheet(){var e,t=this;if(t.selectedSheet){for(t.selectedSheet.grid.rows.clear(),e=0;e<t.rows.length;e++)t.selectedSheet.grid.rows.push(t.rows[e]);setTimeout(()=>{t._setFlexSheetToDirty(),t.invalidate()},10)}}_copyColumnsToSelectedSheet(){var e,t=this;if(t.selectedSheet){for(t.selectedSheet.grid.columns.clear(),e=0;e<t.columns.length;e++)t.selectedSheet.grid.columns.push(t.columns[e]);setTimeout(()=>{t._setFlexSheetToDirty(),t.invalidate()},10)}}_getUniqueColumnName(){let e=1;for(;null!=this.columns.getColumn("col"+e);)e++;return"col"+e}_parseFromWorkbookTable(e,t){var o,i,l,n,s,r,a,h,d,c,_,u=t===this.selectedSheet?this:t.grid;if(i=e.range.split(":"),l=i[0],n=i[1],s=wjcXlsx.Workbook.tableAddress(l),o=new wjcGrid.CellRange(s.row,s.col),r=wjcXlsx.Workbook.tableAddress(n),o.row2=r.row,o.col2=r.col,o.bottomRow>=t.rowCount)for(_=o.bottomRow-t.rowCount+1,g=0;g<_;g++)u.rows.push(new wjcGrid.Row);if(o.rightCol>=t.columnCount)for(_=o.rightCol-t.columnCount+1,g=0;g<_;g++)u.columns.push(new wjcGrid.Column);if(e.columns&&e.columns.length>0){a=[];for(var g=0;g<e.columns.length;g++)h=e.columns[g],a[g]=new TableColumn(h.name,h.totalRowLabel,h.totalRowFunction,h.showFilterButton)}return null!=e.style&&(d=this._isBuiltInStyleName(e.style.name)?this.getBuiltInTableStyle(e.style.name):this._parseFromWorkbookTableStyle(e.style)),c=new Table(e.name,o,d,a,{showHeaderRow:e.showHeaderRow,showTotalRow:e.showTotalRow,showBandedColumns:e.showBandedColumns,showBandedRows:e.showBandedRows,alterFirstColumn:e.alterFirstColumn,alterLastColumn:e.alterLastColumn}),t.tables.push(c),c}_parseFromWorkbookTableStyle(e){var t=new TableStyle(e.name);return null!=e.firstBandedColumnStyle&&(t.firstBandedColumnStyle=this._parseFromWorkbookTableStyleElement(e.firstBandedColumnStyle)),null!=e.firstBandedRowStyle&&(t.firstBandedRowStyle=this._parseFromWorkbookTableStyleElement(e.firstBandedRowStyle)),null!=e.firstColumnStyle&&(t.firstColumnStyle=this._parseFromWorkbookTableStyleElement(e.firstColumnStyle)),null!=e.firstHeaderCellStyle&&(t.firstHeaderCellStyle=this._parseFromWorkbookTableStyleElement(e.firstHeaderCellStyle)),null!=e.firstTotalCellStyle&&(t.firstTotalCellStyle=this._parseFromWorkbookTableStyleElement(e.firstTotalCellStyle)),null!=e.headerRowStyle&&(t.headerRowStyle=this._parseFromWorkbookTableStyleElement(e.headerRowStyle)),null!=e.lastColumnStyle&&(t.lastColumnStyle=this._parseFromWorkbookTableStyleElement(e.lastColumnStyle)),null!=e.lastHeaderCellStyle&&(t.lastHeaderCellStyle=this._parseFromWorkbookTableStyleElement(e.lastHeaderCellStyle)),null!=e.lastTotalCellStyle&&(t.lastTotalCellStyle=this._parseFromWorkbookTableStyleElement(e.lastTotalCellStyle)),null!=e.secondBandedColumnStyle&&(t.secondBandedColumnStyle=this._parseFromWorkbookTableStyleElement(e.secondBandedColumnStyle)),null!=e.secondBandedRowStyle&&(t.secondBandedRowStyle=this._parseFromWorkbookTableStyleElement(e.secondBandedRowStyle)),null!=e.totalRowStyle&&(t.totalRowStyle=this._parseFromWorkbookTableStyleElement(e.totalRowStyle)),null!=e.wholeTableStyle&&(t.wholeTableStyle=this._parseFromWorkbookTableStyleElement(e.wholeTableStyle)),t}_parseFromWorkbookTableStyleElement(e){var t;return t={fontWeight:e.font&&e.font.bold?"bold":"none",fontStyle:e.font&&e.font.italic?"italic":"none",textDecoration:e.font&&e.font.underline?"underline":"none",fontFamily:e.font&&e.font.family?e.font.family:"",fontSize:e.font&&e.font.size?e.font.size+"px":"",color:e.font&&e.font.color?e.font.color:"",backgroundColor:e.fill&&e.fill.color?e.fill.color:""},e.borders&&(e.borders.left&&(wjcGridXlsx.FlexGridXlsxConverter._parseBorderStyle(e.borders.left.style,"Left",t),t.borderLeftColor=e.borders.left.color),e.borders.right&&(wjcGridXlsx.FlexGridXlsxConverter._parseBorderStyle(e.borders.right.style,"Right",t),t.borderRightColor=e.borders.right.color),e.borders.top&&(wjcGridXlsx.FlexGridXlsxConverter._parseBorderStyle(e.borders.top.style,"Top",t),t.borderTopColor=e.borders.top.color),e.borders.bottom&&(wjcGridXlsx.FlexGridXlsxConverter._parseBorderStyle(e.borders.bottom.style,"Bottom",t),t.borderBottomColor=e.borders.bottom.color),e.borders.vertical&&(wjcGridXlsx.FlexGridXlsxConverter._parseBorderStyle(e.borders.vertical.style,"Vertical",t),t.borderVerticalColor=e.borders.vertical.color),e.borders.horizontal&&(wjcGridXlsx.FlexGridXlsxConverter._parseBorderStyle(e.borders.horizontal.style,"Horizontal",t),t.borderHorizontalColor=e.borders.horizontal.color)),null!=e.size&&(t.size=e.size),t}_parseToWorkbookTable(e){var t,o,i=new wjcXlsx.WorkbookTable,l=e.getRange(),n=e.getColumns();i.name=e.name,t=wjcXlsx.Workbook.xlsxAddress(l.topRow,l.leftCol),o=wjcXlsx.Workbook.xlsxAddress(l.bottomRow,l.rightCol),i.range=t+":"+o,null!=e.style&&(e.style.isBuiltIn?(i.style=new wjcXlsx.WorkbookTableStyle,i.style.name=e.style.name):i.style=this._parseToWorkbookTableStyle(e.style)),i.showBandedColumns=e.showBandedColumns,i.showBandedRows=e.showBandedRows,i.showHeaderRow=e.showHeaderRow,i.showTotalRow=e.showTotalRow,i.alterFirstColumn=e.alterFirstColumn,i.alterLastColumn=e.alterLastColumn;for(var s=0;s<n.length;s++){var r=n[s],a=new wjcXlsx.WorkbookTableColumn;a.name=r.name,a.totalRowLabel=r.totalRowLabel,a.totalRowFunction=r.totalRowFunction,a.showFilterButton=r.showFilterButton,i.columns.push(a)}return i}_parseToWorkbookTableStyle(e){var t=new wjcXlsx.WorkbookTableStyle;return t.name=e.name,null!=e.firstBandedColumnStyle&&(t.firstBandedColumnStyle=this._parseToWorkbookTableStyleElement(e.firstBandedColumnStyle,!0)),null!=e.firstBandedRowStyle&&(t.firstBandedRowStyle=this._parseToWorkbookTableStyleElement(e.firstBandedRowStyle,!0)),null!=e.firstColumnStyle&&(t.firstColumnStyle=this._parseToWorkbookTableStyleElement(e.firstColumnStyle)),null!=e.firstHeaderCellStyle&&(t.firstHeaderCellStyle=this._parseToWorkbookTableStyleElement(e.firstHeaderCellStyle)),null!=e.firstTotalCellStyle&&(t.firstTotalCellStyle=this._parseToWorkbookTableStyleElement(e.firstTotalCellStyle)),null!=e.headerRowStyle&&(t.headerRowStyle=this._parseToWorkbookTableStyleElement(e.headerRowStyle)),null!=e.lastColumnStyle&&(t.lastColumnStyle=this._parseToWorkbookTableStyleElement(e.lastColumnStyle)),null!=e.lastHeaderCellStyle&&(t.lastHeaderCellStyle=this._parseToWorkbookTableStyleElement(e.lastHeaderCellStyle)),null!=e.lastTotalCellStyle&&(t.lastTotalCellStyle=this._parseToWorkbookTableStyleElement(e.lastTotalCellStyle)),null!=e.secondBandedColumnStyle&&(t.secondBandedColumnStyle=this._parseToWorkbookTableStyleElement(e.secondBandedColumnStyle,!0)),null!=e.secondBandedRowStyle&&(t.secondBandedRowStyle=this._parseToWorkbookTableStyleElement(e.secondBandedRowStyle,!0)),null!=e.totalRowStyle&&(t.totalRowStyle=this._parseToWorkbookTableStyleElement(e.totalRowStyle)),null!=e.wholeTableStyle&&(t.wholeTableStyle=this._parseToWorkbookTableStyleElement(e.wholeTableStyle)),t}_parseToWorkbookTableStyleElement(e,t=!1){var o,i=wjcGridXlsx.FlexGridXlsxConverter._parseCellStyle(e,!0);return t?(o=new wjcXlsx.WorkbookTableBandedStyle).size=e.size:o=new wjcXlsx.WorkbookTableCommonStyle,o._deserialize(i),o}_isBuiltInStyleName(e){var t;if(0===e.search(/TableStyleLight/i)){if(t=+e.substring(15),!isNaN(t)&&t>=1&&t<=21)return!0}else if(0===e.search(/TableStyleMedium/i)){if(t=+e.substring(16),!isNaN(t)&&t>=1&&t<=28)return!0}else if(0===e.search(/TableStyleDark/i)&&(t=+e.substring(14),!isNaN(t)&&t>=1&&t<=11))return!0;return!1}_getTable(e){for(var t,o,i,l=0;l<this.sheets.length;l++)for(o=this.sheets[l].tables,i=0;i<o.length;i++)if((t=o[i]).name.toLowerCase()===e.toLowerCase())return t;return null}_checkTableHeaderRow(e,t){let o,i,l,n,s;for(i=0;i<e.length;i++)if((o=e[i]).showHeaderRow)for(l=(s=o.getRange(TableSection.Header)).row,n=s.leftCol;n<=s.rightCol;n++)t.sheets[0].rows[l].cells[n].isDate=!1}_isTableColumnRef(e,t){return new RegExp("\\[(\\s*@)?"+t+"\\]","i").test(e)}_getThemeColor(e,t){var o,i,l=this._colorThemes[e];return null!=t?(o=new wjcCore.Color("#"+l),i=o.getHsl(),i[2]=t<0?i[2]*(1+t):i[2]*(1-t)+(1-1*(1-t)),(o=wjcCore.Color.fromHsl(i[0],i[1],i[2])).toString()):"#"+l}_createBuiltInTableStyle(e){var t;if(0===e.search(/TableStyleLight/i)){if(t=+e.substring(15),!isNaN(t)&&t>=1&&t<=21)return t<=7?this._generateTableLightStyle1(t-1,e,!0):t<=14?this._generateTableLightStyle2(t-8,e):this._generateTableLightStyle1(t-15,e,!1)}else if(0===e.search(/TableStyleMedium/i)){if(t=+e.substring(16),!isNaN(t)&&t>=1&&t<=28)return t<=7?this._generateTableMediumStyle1(t-1,e):t<=14?this._generateTableMediumStyle2(t-8,e):t<=21?this._generateTableMediumStyle3(t-15,e):this._generateTableMediumStyle4(t-22,e)}else if(0===e.search(/TableStyleDark/i)&&(t=+e.substring(14),!isNaN(t)&&t>=1&&t<=11))return t<=7?this._generateTableDarkStyle1(t-1,e):this._generateTableDarkStyle2(t-8,e);return null}_generateTableLightStyle1(e,t,o){var i=new TableStyle(t,!0),l=0===e?1:e+3,n=o?"1px":"2px",s=o?"solid":"double",r=o?"1px":"3px";return i.wholeTableStyle={borderTopColor:this._getThemeColor(l),borderTopStyle:"solid",borderTopWidth:"1px",borderBottomColor:this._getThemeColor(l),borderBottomStyle:"solid",borderBottomWidth:"1px"},i.firstColumnStyle={fontWeight:"bold"},i.lastColumnStyle={fontWeight:"bold"},i.headerRowStyle={borderBottomColor:this._getThemeColor(l),borderBottomStyle:"solid",borderBottomWidth:n,fontWeight:"bold"},i.totalRowStyle={borderTopColor:this._getThemeColor(l),borderTopStyle:s,borderTopWidth:r,fontWeight:"bold"},0===e?(i.wholeTableStyle.color=this._getThemeColor(l),i.firstColumnStyle.color=this._getThemeColor(l),i.lastColumnStyle.color=this._getThemeColor(l),i.headerRowStyle.color=this._getThemeColor(l),i.totalRowStyle.color=this._getThemeColor(l),i.firstBandedRowStyle={backgroundColor:this._getThemeColor(0,-.15)},i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(0,-.15)}):(o?(i.wholeTableStyle.color=this._getThemeColor(l,-.25),i.firstColumnStyle.color=this._getThemeColor(l,-.25),i.lastColumnStyle.color=this._getThemeColor(l,-.25),i.headerRowStyle.color=this._getThemeColor(l,-.25),i.totalRowStyle.color=this._getThemeColor(l,-.25)):(i.wholeTableStyle.color=this._getThemeColor(1),i.firstColumnStyle.color=this._getThemeColor(1),i.lastColumnStyle.color=this._getThemeColor(1),i.headerRowStyle.color=this._getThemeColor(1),i.totalRowStyle.color=this._getThemeColor(1)),i.firstBandedRowStyle={backgroundColor:this._getThemeColor(l,.8)},i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(l,.8)}),o||(i.wholeTableStyle.borderLeftColor=this._getThemeColor(l),i.wholeTableStyle.borderLeftStyle="solid",i.wholeTableStyle.borderLeftWidth="1px",i.wholeTableStyle.borderRightColor=this._getThemeColor(l),i.wholeTableStyle.borderRightStyle="solid",i.wholeTableStyle.borderRightWidth="1px",i.wholeTableStyle.borderHorizontalColor=this._getThemeColor(l),i.wholeTableStyle.borderHorizontalStyle="solid",i.wholeTableStyle.borderHorizontalWidth="1px",i.wholeTableStyle.borderVerticalColor=this._getThemeColor(l),i.wholeTableStyle.borderVerticalStyle="solid",i.wholeTableStyle.borderVerticalWidth="1px"),i}_generateTableLightStyle2(e,t){var o=new TableStyle(t,!0),i=0===e?1:e+3;return o.wholeTableStyle={borderTopColor:this._getThemeColor(i),borderTopStyle:"solid",borderTopWidth:"1px",borderBottomColor:this._getThemeColor(i),borderBottomStyle:"solid",borderBottomWidth:"1px",borderLeftColor:this._getThemeColor(i),borderLeftStyle:"solid",borderLeftWidth:"1px",borderRightColor:this._getThemeColor(i),borderRightStyle:"solid",borderRightWidth:"1px",color:this._getThemeColor(1)},o.firstBandedRowStyle={borderTopColor:this._getThemeColor(i),borderTopStyle:"solid",borderTopWidth:"1px"},o.secondBandedRowStyle={borderTopColor:this._getThemeColor(i),borderTopStyle:"solid",borderTopWidth:"1px"},o.firstBandedColumnStyle={borderLeftColor:this._getThemeColor(i),borderLeftStyle:"solid",borderLeftWidth:"1px"},o.secondBandedColumnStyle={borderLeftColor:this._getThemeColor(i),borderLeftStyle:"solid",borderLeftWidth:"1px"},o.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)},o.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)},o.headerRowStyle={backgroundColor:this._getThemeColor(i),fontWeight:"bold",color:this._getThemeColor(0)},o.totalRowStyle={borderTopColor:this._getThemeColor(i),borderTopStyle:"double",borderTopWidth:"3px",fontWeight:"bold",color:this._getThemeColor(1)},o}_generateTableMediumStyle1(e,t){var o=new TableStyle(t,!0),i=0===e?1:e+3;return o.wholeTableStyle={borderTopStyle:"solid",borderTopWidth:"1px",borderBottomStyle:"solid",borderBottomWidth:"1px",borderLeftStyle:"solid",borderLeftWidth:"1px",borderRightStyle:"solid",borderRightWidth:"1px",borderHorizontalStyle:"solid",borderHorizontalWidth:"1px",color:this._getThemeColor(1)},0===e?(o.wholeTableStyle.borderTopColor=this._getThemeColor(i),o.wholeTableStyle.borderBottomColor=this._getThemeColor(i),o.wholeTableStyle.borderLeftColor=this._getThemeColor(i),o.wholeTableStyle.borderRightColor=this._getThemeColor(i),o.wholeTableStyle.borderHorizontalColor=this._getThemeColor(i),o.firstBandedRowStyle={backgroundColor:this._getThemeColor(0,-.15)},o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(0,-.15)}):(o.wholeTableStyle.borderTopColor=this._getThemeColor(i,.4),o.wholeTableStyle.borderBottomColor=this._getThemeColor(i,.4),o.wholeTableStyle.borderLeftColor=this._getThemeColor(i,.4),o.wholeTableStyle.borderRightColor=this._getThemeColor(i,.4),o.wholeTableStyle.borderHorizontalColor=this._getThemeColor(i,.4),o.firstBandedRowStyle={backgroundColor:this._getThemeColor(i,.8)},o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(i,.8)}),o.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)},o.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)},o.headerRowStyle={backgroundColor:this._getThemeColor(i),fontWeight:"bold",color:this._getThemeColor(0)},o.totalRowStyle={borderTopColor:this._getThemeColor(i),borderTopStyle:"double",borderTopWidth:"3px",fontWeight:"bold",color:this._getThemeColor(1)},o}_generateTableMediumStyle2(e,t){var o=new TableStyle(t,!0),i=0===e?1:e+3;return o.wholeTableStyle={borderVerticalStyle:"solid",borderVerticalWidth:"1px",borderVerticalColor:this._getThemeColor(0),borderHorizontalStyle:"solid",borderHorizontalWidth:"1px",borderHorizontalColor:this._getThemeColor(0),color:this._getThemeColor(1)},0===e?(o.wholeTableStyle.backgroundColor=this._getThemeColor(0,-.15),o.firstBandedRowStyle={backgroundColor:this._getThemeColor(0,-.35)},o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(0,-.35)}):(o.wholeTableStyle.backgroundColor=this._getThemeColor(i,.8),o.firstBandedRowStyle={backgroundColor:this._getThemeColor(i,.6)},o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(i,.6)}),o.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(i)},o.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(i)},o.headerRowStyle={borderBottomColor:this._getThemeColor(0),borderBottomStyle:"solid",borderBottomWidth:"3px",backgroundColor:this._getThemeColor(i),fontWeight:"bold",color:this._getThemeColor(0)},o.totalRowStyle={borderTopColor:this._getThemeColor(0),borderTopStyle:"solid",borderTopWidth:"3px",backgroundColor:this._getThemeColor(i),fontWeight:"bold",color:this._getThemeColor(0)},o}_generateTableMediumStyle3(e,t){var o=new TableStyle(t,!0),i=0===e?1:e+3;return o.wholeTableStyle={borderTopStyle:"solid",borderTopWidth:"2px",borderTopColor:this._getThemeColor(1),borderBottomStyle:"solid",borderBottomWidth:"2px",borderBottomColor:this._getThemeColor(1),color:this._getThemeColor(1)},0===e&&(o.wholeTableStyle.borderLeftColor=this._getThemeColor(1),o.wholeTableStyle.borderLeftStyle="solid",o.wholeTableStyle.borderLeftWidth="1px",o.wholeTableStyle.borderRightColor=this._getThemeColor(1),o.wholeTableStyle.borderRightStyle="solid",o.wholeTableStyle.borderRightWidth="1px",o.wholeTableStyle.borderVerticalColor=this._getThemeColor(1),o.wholeTableStyle.borderVerticalStyle="solid",o.wholeTableStyle.borderVerticalWidth="1px",o.wholeTableStyle.borderHorizontalColor=this._getThemeColor(1),o.wholeTableStyle.borderHorizontalStyle="solid",o.wholeTableStyle.borderHorizontalWidth="1px"),o.firstBandedRowStyle={backgroundColor:this._getThemeColor(0,-.35)},o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(0,-.35)},o.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(i)},o.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(i)},o.headerRowStyle={borderBottomColor:this._getThemeColor(1),borderBottomStyle:"solid",borderBottomWidth:"2px",backgroundColor:this._getThemeColor(i),fontWeight:"bold",color:this._getThemeColor(0)},o.totalRowStyle={borderTopColor:this._getThemeColor(1),borderTopStyle:"double",borderTopWidth:"3px"},o}_generateTableMediumStyle4(e,t){var o=new TableStyle(t,!0),i=0===e?1:e+3;return o.wholeTableStyle={borderTopStyle:"solid",borderTopWidth:"1px",borderBottomStyle:"solid",borderBottomWidth:"1px",borderLeftStyle:"solid",borderLeftWidth:"1px",borderRightStyle:"solid",borderRightWidth:"1px",borderVerticalStyle:"solid",borderVerticalWidth:"1px",borderHorizontalStyle:"solid",borderHorizontalWidth:"1px",color:this._getThemeColor(1)},0===e?(o.wholeTableStyle.borderTopColor=this._getThemeColor(i),o.wholeTableStyle.borderBottomColor=this._getThemeColor(i),o.wholeTableStyle.borderLeftColor=this._getThemeColor(i),o.wholeTableStyle.borderRightColor=this._getThemeColor(i),o.wholeTableStyle.borderVerticalColor=this._getThemeColor(i),o.wholeTableStyle.borderHorizontalColor=this._getThemeColor(i),o.wholeTableStyle.backgroundColor=this._getThemeColor(0,-.15),o.firstBandedRowStyle={backgroundColor:this._getThemeColor(0,-.35)},o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(0,-.35)}):(o.wholeTableStyle.borderTopColor=this._getThemeColor(i,.4),o.wholeTableStyle.borderBottomColor=this._getThemeColor(i,.4),o.wholeTableStyle.borderLeftColor=this._getThemeColor(i,.4),o.wholeTableStyle.borderRightColor=this._getThemeColor(i,.4),o.wholeTableStyle.borderVerticalColor=this._getThemeColor(i,.4),o.wholeTableStyle.borderHorizontalColor=this._getThemeColor(i,.4),o.wholeTableStyle.backgroundColor=this._getThemeColor(i,.8),o.firstBandedRowStyle={backgroundColor:this._getThemeColor(i,.6)},o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(i,.6)}),o.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)},o.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)},o.headerRowStyle={fontWeight:"bold",color:this._getThemeColor(1)},o.totalRowStyle={borderTopColor:this._getThemeColor(i),borderTopStyle:"solid",borderTopWidth:"2px",fontWeight:"bold",color:this._getThemeColor(1)},o}_generateTableDarkStyle1(e,t){var o=new TableStyle(t,!0),i=0===e?1:e+3,l=0===e?.25:-.25;return o.wholeTableStyle={color:this._getThemeColor(0)},o.firstBandedRowStyle={backgroundColor:this._getThemeColor(i,l)},o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(i,l)},o.firstColumnStyle={borderRightColor:this._getThemeColor(0),borderRightStyle:"solid",borderRightWidth:"2px",fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(i,l)},o.lastColumnStyle={borderLeftColor:this._getThemeColor(0),borderLeftStyle:"solid",borderLeftWidth:"2px",fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(i,l)},o.headerRowStyle={borderBottomColor:this._getThemeColor(0),borderBottomStyle:"solid",borderBottomWidth:"2px",fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(1)},o.totalRowStyle={borderTopColor:this._getThemeColor(0),borderTopStyle:"solid",borderTopWidth:"2px",fontWeight:"bold",color:this._getThemeColor(0)},0===e?(o.wholeTableStyle.backgroundColor=this._getThemeColor(i,.5),o.totalRowStyle.backgroundColor=this._getThemeColor(i,.15)):(o.wholeTableStyle.backgroundColor=this._getThemeColor(i),o.totalRowStyle.backgroundColor=this._getThemeColor(i,-.5)),o}_generateTableDarkStyle2(e,t){var o=new TableStyle(t,!0),i=0===e?0:2*e+2,l=0===e?1:2*e+3,n=0===e?-.15:.8;return o.wholeTableStyle={backgroundColor:this._getThemeColor(i,n)},o.firstBandedRowStyle={backgroundColor:this._getThemeColor(i,n-.2)},o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(i,n-.2)},o.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)},o.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)},o.headerRowStyle={color:this._getThemeColor(0),backgroundColor:this._getThemeColor(l)},o.totalRowStyle={borderTopColor:this._getThemeColor(1),borderTopStyle:"double",borderTopWidth:"3px",fontWeight:"bold",color:this._getThemeColor(1)},o}static _toOADate(e){let t,o=new Date(1900,0,0),i=Date.UTC(1900,0,0),l=o.getTime()-i-6e4*o.getTimezoneOffset(),n=6e4*(e.getTimezoneOffset()-o.getTimezoneOffset());return t=(e.getTime()-o.getTime()-(0!==n?n-l:0))/864e5,t+=t>59?1:0}static _fromOADate(e){let t,o,i,l=new Date(1900,0,0),n=Date.UTC(1900,0,0),s=l.getTime()-n-6e4*l.getTimezoneOffset();return o=e>59?1:0,i=new Date(l.getTime()+864e5*(e-o)),0!==(t=6e4*(i.getTimezoneOffset()-l.getTimezoneOffset()))?new Date(l.getTime()+t-s+864e5*(e-o)):i}};FlexSheet.controlTemplate='<div style="width:100%;height:100%"><div wj-part="container" style="width:100%">'+wjcGrid.FlexGrid.controlTemplate+'</div><div wj-part="tab-holder" class="wj-tabholder" style="width:100%; min-width:100px"></div><div wj-part="context-menu" style="display:none;z-index:100"></div></div>';export class DraggingRowColumnEventArgs extends wjcCore.EventArgs{constructor(e,t){super(),this._isDraggingRows=e,this._isShiftKey=t}get isDraggingRows(){return this._isDraggingRows}get isShiftKey(){return this._isShiftKey}};export class UnknownFunctionEventArgs extends wjcCore.EventArgs{constructor(e,t){super(),this._funcName=e,this._params=t}get funcName(){return this._funcName}get params(){return this._params}};export class RowColumnChangedEventArgs extends wjcCore.EventArgs{constructor(e,t,o){super(),this._index=e,this._count=t,this._added=o}get index(){return this._index}get count(){return this._count}get added(){return this._added}get isAdd(){return wjcCore._deprecated("RowColumnChangedEventArgs.isAdd","RowColumnChangedEventArgs.added"),this._added}};export class FlexSheetPanel extends wjcGrid.GridPanel{constructor(e,t,o,i,l){super(e,t,o,i,l)}getSelectedState(e,t,o){var i,l,n,s,r,a;if(this.grid){if(a=this.grid.getMergedRange(this,e,t),i=this.grid.selectedSheet?this.grid.selectedSheet.selectionRanges:null,r=super.getSelectedState(e,t,o),l=i?i.length:0,r===wjcGrid.SelectedState.None&&l>0)for(n=0;n<i.length;n++)if((s=i[n])&&s instanceof wjcGrid.CellRange){if(this.cellType===wjcGrid.CellType.Cell){if(a){if(a.contains(s.row,s.col))return n!==l-1||this.grid._isClicking?wjcGrid.SelectedState.Selected:this.grid.showMarquee?wjcGrid.SelectedState.None:wjcGrid.SelectedState.Cursor;if(a.intersects(s))return wjcGrid.SelectedState.Selected}if(s.row===e&&s.col===t)return n!==l-1||this.grid._isClicking?wjcGrid.SelectedState.Selected:this.grid.showMarquee?wjcGrid.SelectedState.None:wjcGrid.SelectedState.Cursor;if(s.contains(e,t))return wjcGrid.SelectedState.Selected}if(this.grid.showSelectedHeaders&wjcGrid.HeadersVisibility.Row&&this.cellType===wjcGrid.CellType.RowHeader&&s.containsRow(e))return wjcGrid.SelectedState.Selected;if(this.grid.showSelectedHeaders&wjcGrid.HeadersVisibility.Column&&this.cellType===wjcGrid.CellType.ColumnHeader&&s.containsColumn(t))return wjcGrid.SelectedState.Selected}return r}}getCellData(e,t,o){var i,l,n,s,r,a;if(wjcCore.isString(t)&&(t=this.columns.indexOf(t))<0)throw"Invalid column name or binding.";return e>=this.rows.length||wjcCore.asNumber(t,!1,!0)>=this.columns.length?null:(i=super.getCellData(e,t,o),l=this.columns[wjcCore.asNumber(t,!1,!0)],n=this.grid?this.grid._getBindingColumn(this,e,l):l,o&&(r=super.getCellData(e,t,!1),s=this.grid?this.grid._getCellStyle(e,t):null,wjcCore.isNumber(r)&&0!==r&&(n&&n.dataMap||(""===(a=s?s.format:"")&&(a=n?n.format:""),i=wjcCore.Globalize.format(r,a)))),i)}setCellData(e,t,o,i=!0,l=!0){if(e>=this.rows.length||t>=this.columns.length)return!1;var n,s,r,a,h,d=this.getCellData(e,t,!1),c=this.grid._isPasting,_=this.columns[t],u=this.grid?this.grid._getBindingColumn(this,e,_):_,g=this.rows[e],w=this.grid?this.grid._getCellStyle(e,t):null,m=wjcCore.getType(d),f=wjcCore.culture.Globalize.numberFormat.currency.symbol;if(this.grid&&(r=this.grid.selectedSheet.findTable(e,t))&&r.showHeaderRow&&(a=r.getRange(TableSection.Header),e===a.row&&t>=a.leftCol&&t<=a.rightCol))return null==o||wjcCore.isString(o)&&wjcCore.isNullOrWhiteSpace(o)?void 0:super.setCellData(e,t,o.toString(),!1,l);if(i&&o&&wjcCore.isString(o)&&"'"!==o[0]&&"="!==o[0]){if(this.getCellData(e,t,!0)===o)return;let l=w?w.format:"";/[hsmt\:]/.test(l)||(l=""),(n=wjcCore.Globalize.parseDate(o,l))?o=n:(h=new RegExp("[^\\d,\\.\\"+f+"]","g"),u.dataType===wjcCore.DataType.String||wjcCore.isNullOrWhiteSpace(o)||null!=d&&m!==wjcCore.DataType.Number||h.test(o)&&"%"!==o[o.length-1]?u.dataType===wjcCore.DataType.Boolean&&(o=wjcCore.changeType(o,wjcCore.DataType.Boolean,null)):(s=wjcCore.changeType(o,wjcCore.DataType.Number,""),wjcCore.isNumber(s)?o=s:i=!1))}if((o&&wjcCore.isString(o)&&("="===o[0]||"'"===o[0])||!u.dataType)&&(i=!1),!(g instanceof HeaderRow))return super.setCellData(e,t,o,i&&!c,l);g._ubv[u._hash]=o}_renderCell(e,t,o,i,l,n){var s,r,a,h,d=t*this.grid.columns.length+o,c=this.grid.getMergedRange(this,t,o);return h=super._renderCell(e,t,o,i,l,n),this.cellType!==wjcGrid.CellType.Cell?h:c&&d>c.topRow*this.grid.columns.length+c.leftCol?h:((s=e.childNodes[n])&&(null!=this.grid.editRange&&this.grid.editRange.contains(t,o)||this.grid.selectedSheet&&(a=this.grid.selectedSheet.findTable(t,o))&&a._updateCell(t,o,s),wjcCore.hasClass(s,"wj-state-selected")||wjcCore.hasClass(s,"wj-state-multi-selected")?(s.style.backgroundColor="",s.style.color=""):this.grid.selectedSheet&&(r=this.grid.selectedSheet._styledCells[d])&&(""!==r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),""!==r.color&&(s.style.color=r.color))),h)}};export class HeaderRow extends wjcGrid.Row{constructor(){super(),this.isReadOnly=!0}};export class DefinedName{constructor(e,t,o,i){if(this._owner=e,this._name=t,this._value=o,null!=i){if(!e._validateSheetName(i))throw"The sheet name:("+i+") does not exist in FlexSheet.";this._sheetName=i}}get name(){return this._name}set name(e){var t;if(this._name!==e){if(this._owner._checkExistDefinedName(name,this._sheetName))throw"The "+name+" already existed in definedNames.";t=this._name,this._name=e,this._owner._updateFormulasWithNameUpdating(t,this._name)}}get value(){return this._value}set value(e){this._value!==e&&(this._value=e)}get sheetName(){return this._sheetName}};var _FillDataOperation;!function(e){e[e.CopyFormat=1]="CopyFormat",e[e.CopyContent=2]="CopyContent",e[e.FillSeries=4]="FillSeries"}(_FillDataOperation||(_FillDataOperation={}));export class Sheet{constructor(e,t,o,i,l){this._visible=!0,this._unboundSortDesc=new wjcCore.ObservableArray,this._currentStyledCells={},this._currentMergedRanges=[],this._isEmptyGrid=!1,this._rowSettings=[],this._scrollPosition=new wjcCore.Point,this._showDefaultHeader=!1,this.nameChanged=new wjcCore.Event,this.visibleChanged=new wjcCore.Event;var n=this;n._owner=e,n._name=o,n._sortList=[new ColumnSortDescription(-1,!0)],wjcCore.isNumber(i)&&!isNaN(i)&&i>=0?n._rowCount=i:n._rowCount=200,wjcCore.isNumber(l)&&!isNaN(l)&&l>=0?n._columnCount=l:n._columnCount=20,t?(n._showDefaultHeader=!0,n._grid=t):n._grid=this._createGrid(),n._grid.loadedRows.addHandler(()=>{n._addHeaderRow(),n._setRowSettings()}),n._grid.itemsSourceChanged.addHandler(this._gridItemsSourceChanged,this),n._addHeaderRow(),n._unboundSortDesc.collectionChanged.addHandler(()=>{var e,t,o=n._unboundSortDesc,i={};for(e=0;e<o.length;e++)if(!wjcCore.tryCast(o[e],_UnboundSortDescription))throw"sortDescriptions array must contain SortDescription objects.";if(n._owner){if(n._owner.rows.beginUpdate(),n._owner.rows.sort(n._compareRows()),!n._owner._isUndoing){for(e=0;e<n._owner.rows.length;e++)e!==(t=n._owner.rows[e])._idx&&n._owner._updateFormulaForReorderingRows(t._idx,e),n._owner._updateCellStyleForReorderingRows(t._idx,e,i);n._currentStyledCells=i}n._owner.rows.endUpdate(),n._owner.rows._dirty=!0,n._owner.rows._update(),n._owner.selectedSheet&&(n._owner._copyTo(n._owner.selectedSheet),n._owner._copyFrom(n._owner.selectedSheet))}}),n.tables.collectionChanged.addHandler((e,t)=>{if(null!=t.item&&!(t.item instanceof Table))throw"The tables only allows to handle Table instance.";if(t.action===wjcCore.NotifyCollectionChangedAction.Add||t.action===wjcCore.NotifyCollectionChangedAction.Change){if(t.item){let e,o,i,l=t.item,s=l.getRange(),r=n===n._owner.selectedSheet?n._owner:n.grid;try{if(s.topRow>=r.rows.length||s.leftCol>=r.columns.length)throw"";if(s.leftCol+s.columnSpan>r.columns.length)throw"";if(s.topRow+s.rowSpan>r.rows.length)throw"";for(e=s.topRow;e<=s.bottomRow;e++)for(o=s.leftCol;o<=s.rightCol;o++)if((i=n.findTable(e,o))!==l)throw"";l._attachSheet(n)}catch(e){n.tables.removeAt(t.index)}}}else t.action===wjcCore.NotifyCollectionChangedAction.Remove&&t.item&&t.item._detachSheet()})}get grid(){return null==this._grid.wj_sheetInfo&&(this._grid.wj_sheetInfo={}),this._grid}get name(){return this._name}set name(e){if(!wjcCore.isNullOrWhiteSpace(e)&&(this._name&&this._name.toLowerCase()!==e.toLowerCase()||!this._name)){var t=new wjcCore.PropertyChangedEventArgs("sheetName",this._name,e);this._name=e,this.grid.wj_sheetInfo.name=e,this.onNameChanged(t)}}get visible(){return this._visible}set visible(e){this._visible!==e&&(this._visible=e,this.grid.wj_sheetInfo.visible=e,this.onVisibleChanged(new wjcCore.EventArgs))}get rowCount(){return null!=this._grid?this._grid.rows.length:0}set rowCount(e){var t;if(!this.itemsSource&&wjcCore.isNumber(e)&&!isNaN(e)&&e>=0&&this._rowCount!==e){if(this._rowCount<e)for(t=0;t<e-this._rowCount;t++)this.grid.rows.push(new wjcGrid.Row);else this.grid.rows.splice(e,this._rowCount-e);this._rowCount=e,this._owner&&this._owner.selectedSheet&&this._name===this._owner.selectedSheet.name&&this._owner._copyFrom(this,!0)}}get columnCount(){return null!=this._grid?this._grid.columns.length:0}set columnCount(e){var t;if(!this.itemsSource&&wjcCore.isNumber(e)&&!isNaN(e)&&e>=0&&this._columnCount!==e){if(this._columnCount<e)for(t=0;t<e-this._columnCount;t++)this._grid.columns.push(new wjcGrid.Column);else this._grid.columns.splice(e,this._columnCount-e);this._columnCount=e,this._owner&&this._owner.selectedSheet&&this._name===this._owner.selectedSheet.name&&this._owner._copyFrom(this,!0)}}get selectionRanges(){return this._selectionRanges||(this._selectionRanges=new wjcCore.ObservableArray,this._selectionRanges.collectionChanged.addHandler(()=>{var e,t;this._owner&&!this._owner._isClicking&&((e=this._selectionRanges.length)>0&&(t=this._selectionRanges[e-1])&&t instanceof wjcGrid.CellRange&&(this._owner.selection=t),e>1&&(this._owner._enableMulSel=!0,this._owner.refresh(!1)),this._owner._enableMulSel=!1)},this)),this._selectionRanges}get itemsSource(){return null!=this._grid?this._grid.itemsSource:null}set itemsSource(e){var t=this;null==t._grid&&(t._createGrid(),t._grid.itemsSourceChanged.addHandler(t._gridItemsSourceChanged,t)),t._isEmptyGrid&&t._clearGrid(),t._grid.itemsSource=e}get filterSetting(){return this===this._owner.selectedSheet&&this._getFilterSetting(),this._filterSetting}set filterSetting(e){this._filterSetting=e,this===this._owner.selectedSheet&&this._applyFilterSetting()}get tables(){return null==this._tables&&(this._tables=new wjcCore.ObservableArray),this._tables}get _styledCells(){return this._currentStyledCells||(this._currentStyledCells={}),this._currentStyledCells}set _styledCells(e){this._currentStyledCells=e}get _mergedRanges(){return this._currentMergedRanges||(this._currentMergedRanges=[]),this._currentMergedRanges}onNameChanged(e){this.nameChanged.raise(this,e)}onVisibleChanged(e){this.visibleChanged.raise(this,e)}dispose(){if(this._clearGrid(),this._grid.wj_sheetInfo=null,this._grid.dispose(),this._grid=null,null!=this._tables){for(let e=0;e<this._tables.length;e++)this._tables[e]=null;this._tables=null}}getCellStyle(e,t){var o,i=this._grid.rows.length,l=this._grid.columns.length;return e>=i||t>=l?null:(o=e*l+t,this._styledCells[o])}addTableFromArray(e,t,o,i,l,n,s,r=!0){let a,h,d,c,_,u,g,w,m,f,C,p,S=!1,b=this===this._owner.selectedSheet?this._owner:this.grid;if(null==o||0===o.length)throw"Invalid array to load.";if(!(null!=i&&0!==i.length||null!=(i=Object.keys(o[0]))&&0!==i.length))throw"Invalid array to load.";if(e>=this.rowCount||t>=this.columnCount)return null;let R=null==(s&&s.showHeaderRow)||s.showHeaderRow,y=!(!s||!s.showTotalRow),v=e+(R?1:0),T=v+o.length-1+(y?1:0);for(h=[],f=0;f<i.length;f++)C=i[f],d=new TableColumn(C),0===f?d._totalRowLabel="Total":f===i.length-1&&(d._totalRowFunction="Sum"),h.push(d);if(c=new wjcGrid.CellRange(e,t,T,t+i.length-1),0!==(_=this._needShiftForTable(c))){if(!r)return null;if(!this._canShiftCells(c))return null;if(u=this._needAddRowCountForAddTable(_,c),b.collectionView){for(p=b.itemsSource instanceof wjcCore.CollectionView,b.collectionView.beginUpdate(),w=0;w<u;w++)p?b.itemsSource.sourceCollection.push({}):b.itemsSource.push({});b.collectionView.endUpdate()}else for(w=0;w<u;w++)b.rows.push(new wjcGrid.Row);S=!0}if(t+i.length>=b.columns.length){if(!r)return null;if(g=t+i.length-b.columns.length+1,this.itemsSource&&g>0)return null;for(b.columns.beginUpdate(),w=0;w<g;w++)b.columns.push(new wjcGrid.Column);b.columns.endUpdate()}if(b.beginUpdate(),S&&this._moveDownCells(_,c),R)for(f=0;f<i.length;f++)C=i[f],b.setCellData(e,t+f,C);for(m=0;m<o.length;m++)for(f=0;f<i.length;f++)C=i[f],b.setCellData(v+m,t+f,o[m][C]);return b.endUpdate(),a=this._addTable(c,l,n,h,s)}findTable(e,t){var o,i;if(this._tables&&this._tables.length>0)for(var l=0;l<this._tables.length;l++)if(o=this._tables[l],i=o.getRange(),e>=i.topRow&&e<=i.bottomRow&&t>=i.leftCol&&t<=i.rightCol)return o;return null}_attachOwner(e){this._owner!==e&&(this._owner=e)}_setValidName(e){this._name=e,this.grid.wj_sheetInfo.name=e}_storeRowSettings(){var e,t=0;for(this._rowSettings=[];t<this._grid.rows.length;t++)(e=this._owner.rows[t])&&(this._rowSettings[t]={height:e.height,allowMerging:e.allowMerging,isCollapsed:e instanceof wjcGrid.GroupRow?e.isCollapsed:null,visible:e.visible,isSelected:e.isSelected,readOnly:e.isReadOnly})}_setRowSettings(){for(var e,t,o,i=0;i<this._rowSettings.length;i++)(t=this._rowSettings[i])&&(e=this._grid.rows[i])&&(o=e instanceof HeaderRow,e.height=t.height,e.allowMerging=t.allowMerging,e.visible=t.visible,e instanceof wjcGrid.GroupRow&&(e.isCollapsed=!!t.isCollapsed),e.isSelected=!!t.isSelected,e.isReadOnly=o||!!t.readOnly)}_addTable(e,t,o,i,l){if(!e.isValid)return null;let n;return null!=t&&null==this._owner._getTable(t)||(t=this._getUniqueTableName()),n=new Table(t,e,o,i,l),this.tables.push(n),n}_addSelection(e){let t,o;for(this.selectionRanges.beginUpdate(),o=this.selectionRanges.length-1;o>=0;o--)t=this.selectionRanges[o],e.contains(t)&&this.selectionRanges.removeAt(o);e.isValid&&this.selectionRanges.push(e),this.selectionRanges.endUpdate()}_compareRows(){var e=this,t=this._unboundSortDesc;return function(o,i){for(var l=0;l<t.length;l++){var n=t[l],s=o._ubv&&n.column?o._ubv[n.column._hash]:"",r=i._ubv&&n.column?i._ubv[n.column._hash]:"";if(wjcCore.isString(s)&&"="===s[0]&&(s=e._owner.evaluate(s)),wjcCore.isString(r)&&"="===r[0]&&(r=e._owner.evaluate(r)),s!==s&&(s=null),r!==r&&(r=null),wjcCore.isString(s)&&(s=s.toLowerCase()+s),wjcCore.isString(r)&&(r=r.toLowerCase()+r),""===s||null==s)return 1;if(""===r||null==r)return-1;var a=s<r?-1:s>r?1:0;if(wjcCore.isString(s)&&wjcCore.isNumber(r)&&(a=1),wjcCore.isString(r)&&wjcCore.isNumber(s)&&(a=-1),0!==a)return n.ascending?+a:-a}return 0}}_createGrid(){var e,t,o,i,l=document.createElement("div");for(this._isEmptyGrid=!0,l.style.visibility="hidden",document.body.appendChild(l),e=new wjcGrid.FlexGrid(l),document.body.removeChild(l),i=0;i<this._rowCount;i++)e.rows.push(new wjcGrid.Row);for(o=0;o<this._columnCount;o++)(t=new wjcGrid.Column).isRequired=!1,e.columns.push(t);return e.wj_sheetInfo={name:this.name,visible:this.visible,styledCells:this._styledCells,mergedRanges:this._mergedRanges},e}_clearGrid(){this._grid.rows.clear(),this._grid.columns.clear(),this._grid.columnHeaders.columns.clear(),this._grid.rowHeaders.rows.clear()}_gridItemsSourceChanged(){var e=this;e._owner&&!e._owner._isCopying&&e._owner.selectedSheet&&e._name===e._owner.selectedSheet.name&&(e._owner.filter.clear(),e._owner._copyFrom(e,!1),setTimeout(()=>{e._owner._setFlexSheetToDirty(),e._owner.invalidate()},10))}_addHeaderRow(){var e;if(this._grid.collectionView&&!this._grid.collectionView.isEmpty&&!(this._grid.rows[0]instanceof HeaderRow)){var t;(e=new HeaderRow).isReadOnly=!0;for(var o=0;o<this._grid.columns.length;o++)t=this._grid.columns[o],e._ubv||(e._ubv={}),e._ubv[t._hash]=t.header;this._grid.rows.insert(0,e)}}_getUniqueTableName(){for(var e="Table1",t=2;;){if(null==this._owner._getTable(e))break;e="Table"+t,t+=1}return e}_needShiftForTable(e){let t,o,i,l=0,n=0,s=this===this._owner.selectedSheet?this._owner:this.grid;for(t=e.topRow;t<=e.bottomRow;t++){if(t>=s.rows.length)return l=e.rowSpan-n;for(o=e.leftCol;o<=e.rightCol&&o<s.columns.length;o++)if(null!=(i=s.getCellData(t,o,!1))&&""!==i)return l=e.rowSpan-n;n++}return l}_needAddRowCountForAddTable(e,t){var o,i,l,n,s,r=this===this._owner.selectedSheet?this._owner:this.grid;for(o=1;o<=e;o++)for(i=r.rows.length-o,l=t.leftCol;l<=t.rightCol&&l<r.columns.length;l++)if(n=r.getCellData(i,l,!1),s=this.getCellStyle(i,l),null!=n&&""!==n||null!=s)return e-o+1;return 0}_moveDownTable(e){var t,o,i,l,n=e.getRange(),s=this===this._owner.selectedSheet?this._owner:this.grid;for(t=n.bottomRow;t>=n.topRow;t--)for(o=n.leftCol;o<=n.rightCol;o++)l=null!=s.columns[o].dataMap,i=s.getCellData(t,o,l),s.setCellData(t+1,o,i),s.setCellData(t,o,"");e._updateTableRange(1,1,0,0)}_moveDownCells(e,t){var o,i,l,n,s,r,a,h,d,c,_=this===this._owner.selectedSheet?this._owner:this.grid;for(o=_.rows.length-1-e;o>=t.topRow;o--)for(i=t.leftCol;i<=t.rightCol&&i<_.columns.length;i++)c=null!=_.columns[i].dataMap,l=_.getCellData(o,i,c),_.setCellData(o+e,i,l),_.setCellData(o,i,""),n=this.getCellStyle(o,i),r=(o+e)*_.columns.length+i,s=o*_.columns.length+i,n&&(this._styledCells[r]=n,this._styledCells[s]=null),(a=this._mergedRanges[s])&&(a.row+=e,a.row2+=e,this._mergedRanges[r]=a,this._mergedRanges[s]=null),(h=this.findTable(o,i))&&(d=h.getRange()).topRow===o&&d.leftCol===i&&h._updateTableRange(e,e,0,0)}_moveUpCells(e,t){var o,i,l,n,s,r,a,h,d,c,_=this===this._owner.selectedSheet?this._owner:this.grid;for(o=t.topRow;o<_.rows.length;o++)for(i=t.leftCol;i<=t.rightCol&&i<_.columns.length;i++)c=null!=_.columns[i].dataMap,l=_.getCellData(o,i,c),_.setCellData(o-e,i,l),_.setCellData(o,i,""),n=this.getCellStyle(o,i),r=(o-e)*_.columns.length+i,s=o*_.columns.length+i,n&&(this._styledCells[r]=n,this._styledCells[s]=null),(a=this._mergedRanges[s])&&(a.row-=e,a.row2-=e,this._mergedRanges[r]=a,this._mergedRanges[s]=null),(h=this.findTable(o,i))&&(d=h.getRange()).topRow===o&&d.leftCol===i&&h._updateTableRange(-e,-e,0,0)}_moveDownCellsWithinTable(e,t,o){var i,l,n,s,r=this===this._owner.selectedSheet?this._owner:this.grid;for(i=o.bottomRow;i>o.topRow+e;i--)for(l=o.leftCol;l<=o.rightCol;l++)s=null!=r.columns[l].dataMap,n=r.getCellData(i,l,s),r.setCellData(i+t,l,n),r.setCellData(i,l,""),(i+t)*r.columns.length+l,i*r.columns.length+l}_moveUpCellsWithinTable(e,t,o){var i,l,n,s,r=o.topRow+e,a=this===this._owner.selectedSheet?this._owner:this.grid;for(i=r;i<=o.bottomRow;i++)for(l=o.leftCol;l<=o.rightCol;l++)i>=r+t&&(s=null!=a.columns[l].dataMap,n=a.getCellData(i,l,s),a.setCellData(i-t,l,n)),a.setCellData(i,l,""),(i-t)*a.columns.length+l,i*a.columns.length+l}_canShiftCells(e){var t,o,i,l,n,s,r=this===this._owner.selectedSheet?this._owner:this.grid;for(t=e.topRow;t<r.rows.length;t++)for(o=e.leftCol;o<=e.rightCol&&o<r.columns.length;o++){if((n=this.findTable(t,o))&&((s=n.getRange()).leftCol<e.leftCol||s.rightCol>e.rightCol))return!1;if(i=t*r.columns.length+o,(l=this._mergedRanges[i])&&(l.leftCol<e.leftCol||l.rightCol>e.rightCol))return!1}return!0}_needMoveDownTable(e){var t,o,i=e.getRange(),l=e.getColumns(),n=this===this._owner.selectedSheet?this._owner:this.grid;if(0===i.topRow)return!0;for(t=0;t<l.length;t++)if(null!=(o=n.getCellData(i.topRow-1,i.leftCol+t,!1))&&""!==o)return!0;return!1}_needAddRowCountForInsertTableRows(e,t){var o,i,l,n,s,r=this===this._owner.selectedSheet?this._owner:this.grid;for(o=1;o<=e;o++){if((i=r.rows.length-o)<=t.bottomRow)return e;for(l=t.leftCol;l<=t.rightCol&&l<r.columns.length;l++)if(n=r.getCellData(i,l,!1),s=this.getCellStyle(i,l),null!=n&&""!==n||null!=s)return e-o+1}return 0}_getFilterSetting(){let e,t=0;for(this._filterDefinition=this._owner.filter.filterDefinition,this._filterSetting={},this._filterSetting.filterColumns=this._owner.filter.filterColumns,this._filterSetting.columnFilterSettings||(this._filterSetting.columnFilterSettings=[]);t<this._owner.filter._filters.length;t++)(e=this._owner.filter._filters[t])&&this._filterSetting.columnFilterSettings.push({column:e.column,filterType:e.filterType,dataMap:e.dataMap,valueFilterSetting:{maxValues:e.valueFilter.maxValues,uniqueValues:e.valueFilter.uniqueValues,sortValues:e.valueFilter.sortValues,dataMap:e.valueFilter.dataMap},conditionFilterSetting:{dataMap:e.conditionFilter.dataMap}})}_applyFilterSetting(){let e,t,o,i,l,n,s,r,a,h,d=0;if(null==this._filterSetting)this._clearFilterSetting();else if(this._owner.filter.filterColumns=this._filterSetting.filterColumns,this._filterDefinition&&(this._owner.filter.filterDefinition=this._filterDefinition),null!=(e=this._filterSetting.columnFilterSettings)&&e.length>0)for(;d<e.length;d++)(t=e[d])&&null!=t.column&&(l=this._owner.filter.getColumnFilter(t.column))&&(n=l.valueFilter.showValues,s=l.valueFilter.filterText,r={operator:l.conditionFilter.condition1.operator,value:l.conditionFilter.condition1.value},a={operator:l.conditionFilter.condition2.operator,value:l.conditionFilter.condition2.value},h=l.conditionFilter.and,null!=t.dataMap&&(l.dataMap=t.dataMap),null!=t.filterType&&(l.filterType=t.filterType),(o=t.valueFilterSetting)&&(o.dataMap&&(l.valueFilter.dataMap=o.dataMap),null!=o.maxValues&&(l.valueFilter.maxValues=o.maxValues),null!=o.sortValues&&(l.valueFilter.sortValues=o.sortValues),o.uniqueValues&&(l.valueFilter.uniqueValues=o.uniqueValues)),(i=t.conditionFilterSetting)&&i.dataMap&&(l.conditionFilter.dataMap=i.dataMap),l.valueFilter.showValues=n,l.valueFilter.filterText=s,l.conditionFilter.condition1.operator=r.operator,l.conditionFilter.condition1.value=r.value,l.conditionFilter.condition2.operator=a.operator,l.conditionFilter.condition2.value=a.value,l.conditionFilter.and=h)}_clearFilterSetting(){this._owner.filter._filters=[],this._owner.filter.filterColumns=null,this._filterDefinition&&(this._owner.filter.filterDefinition=this._filterDefinition)}_cloneMergedCells(){let e,t=0,o=[];for(;t<this._mergedRanges.length;t++)e=this._mergedRanges[t],o.push(e.clone());return o}_getMergedRange(e,t){let o,i;for(o=0;o<this._mergedRanges.length;o++)if(i=this._mergedRanges[o],e>=i.topRow&&e<=i.bottomRow&&t>=i.leftCol&&t<=i.rightCol)return i;return null}};export class SheetCollection extends wjcCore.ObservableArray{constructor(){super(...arguments),this._current=-1,this.sheetCleared=new wjcCore.Event,this.selectedSheetChanged=new wjcCore.Event,this.sheetNameChanged=new wjcCore.Event,this.sheetVisibleChanged=new wjcCore.Event}onSheetCleared(){this.sheetCleared.raise(this,new wjcCore.EventArgs)}get selectedIndex(){return this._current}set selectedIndex(e){this._moveCurrentTo(+e)}onSelectedSheetChanged(e){this.selectedSheetChanged.raise(this,e)}insert(e,t){var o;(o=t.name?this.getValidSheetName(t):this._getUniqueName())!==t.name&&(t.name=o),super.insert(e,t),this._postprocessSheet(t)}push(...e){this.length;for(var t,o=0;o<e.length;o++)(t=e[o].name?this.getValidSheetName(e[o]):this._getUniqueName())!==e[o].name&&(e[o].name=t),super.push(e[o]),this._postprocessSheet(e[o]);return this.length}splice(e,t,o){var i;return o?((i=o.name?this.getValidSheetName(o):this._getUniqueName())!==o.name&&(o.name=i),this._postprocessSheet(o),super.splice(e,t,o)):super.splice(e,t,o)}removeAt(e){this.hide(e)&&(super.removeAt(e),e<this.selectedIndex&&(this._current-=1))}onSheetNameChanged(e){this.sheetNameChanged.raise(this,e)}onSheetVisibleChanged(e){this.sheetVisibleChanged.raise(this,e)}selectFirst(){return this._moveCurrentTo(0)}selectLast(){return this._moveCurrentTo(this.length-1)}selectPrevious(){return this._moveCurrentTo(this._current-1)}selectNext(){return this._moveCurrentTo(this._current+1)}hide(e){return!(e<0&&e>=this.length)&&(!!this[e].visible&&(this[e].visible=!1,!0))}show(e){return!(e<0&&e>=this.length)&&(this[e].visible=!0,this._moveCurrentTo(e),!0)}clear(){let e;for(let t=0;t<this.length;t++)(e=this[t]).dispose(),e=null;super.clear(),this._current=-1,this.onSheetCleared()}isValidSheetName(e){var t=this._getSheetIndexFrom(e.name),o=this.indexOf(e);return-1===t||t===o}getValidSheetName(e){for(var t,o=e.name,i=1,l=this.indexOf(e);;){if(-1===(t=this._getSheetIndexFrom(o))||t===l)break;o=e.name.concat((i+1).toString()),i+=1}return o}_moveCurrentTo(e){var t,o=e;if(e<0||e>=this.length)return!1;if(this._current<o||0===o)for(;o<this.length&&!this[o].visible;)o++;else if(this._current>o)for(;o>=0&&!this[o].visible;)o--;if(o===this.length)for(o=e;o>=0&&!this[o].visible;)o--;return!(o<0)&&(o!==this._current&&(t=new wjcCore.PropertyChangedEventArgs("sheetIndex",this._current,o),this._current=o,this.onSelectedSheetChanged(t)),!0)}_getSheetIndexFrom(e){var t;if(!e)return-1;e=e.toLowerCase();for(var o=0;o<this.length;o++)if(t=this[o],(t.name?t.name.toLowerCase():"")===e)return o;return-1}_postprocessSheet(e){var t=this;e.nameChanged.addHandler(()=>{var o,i=t._getSheetIndexFrom(e.name);t.isValidSheetName(e)||e._setValidName(t.getValidSheetName(e)),o=new wjcCore.NotifyCollectionChangedEventArgs(wjcCore.NotifyCollectionChangedAction.Change,e,wjcCore.isNumber(i)?i:t.length-1),t.onSheetNameChanged(o)}),e.visibleChanged.addHandler(()=>{var o=t._getSheetIndexFrom(e.name),i=new wjcCore.NotifyCollectionChangedEventArgs(wjcCore.NotifyCollectionChangedAction.Change,e,wjcCore.isNumber(o)?o:t.length-1);t.onSheetVisibleChanged(i)})}_getUniqueName(){for(var e="Sheet1",t=2;;){if(-1===this._getSheetIndexFrom(e))break;e="Sheet"+t,t+=1}return e}};export class _SheetTabs extends wjcCore.Control{constructor(e,t,o){super(e,o),this._rtl=!1,this._sheetTabClicked=!1;var i=this;i._owner=t,i._sheets=t.sheets,i._rtl="rtl"==getComputedStyle(i._owner.hostElement).direction,i._initControl(),i.deferUpdate(()=>{o&&i.initialize(o)})}refresh(e){this._tabContainer.innerHTML="",this._tabContainer.innerHTML=this._getSheetTabs(),this._rtl&&this._adjustSheetsPosition(),this._adjustSize()}_sourceChanged(e,t=wjcCore.NotifyCollectionChangedEventArgs.reset){var o=t;switch(o.action){case wjcCore.NotifyCollectionChangedAction.Add:o.index-1<0&&0,this._tabContainer.innerHTML="",this._tabContainer.innerHTML=this._getSheetTabs(),this._rtl&&this._adjustSheetsPosition(),this._adjustSize();break;case wjcCore.NotifyCollectionChangedAction.Remove:this._tabContainer.removeChild(this._tabContainer.children[o.index]),this._tabContainer.hasChildNodes()&&this._updateTabActive(o.index,!0),this._adjustSize();break;default:this.invalidate()}}_selectedSheetChanged(e,t){this._updateTabActive(t.oldValue,!1),this._updateTabActive(t.newValue,!0),this._sheetTabClicked?this._sheetTabClicked=!1:this._scrollToActiveSheet(t.newValue,t.oldValue),this._adjustSize()}_initControl(){var e=this;e.applyTemplate("",e.getTemplate(),{_sheetContainer:"sheet-container",_tabContainer:"container",_sheetPage:"sheet-page",_newSheet:"new-sheet"}),e._rtl&&(e._sheetPage.style.right="0px",e._tabContainer.parentElement.style.right=e._sheetPage.clientWidth+"px",e._tabContainer.style.right="0px",e._tabContainer.style.cssFloat="right",e._newSheet.style.right=e._sheetPage.clientWidth+e._tabContainer.parentElement.clientWidth+"px"),e._adjustNavigationButtons(e._rtl),e.addEventListener(e.hostElement,"mousedown",()=>{e._owner._mouseHdl._htDown=null}),e.addEventListener(e._newSheet,"click",t=>{var o=e._owner.selectedSheetIndex;e._owner.addUnboundSheet(),e._scrollToActiveSheet(e._owner.selectedSheetIndex,o)}),e._sheets.collectionChanged.addHandler(e._sourceChanged,e),e._sheets.selectedSheetChanged.addHandler(e._selectedSheetChanged,e),e._sheets.sheetNameChanged.addHandler(e._updateSheetName,e),e._sheets.sheetVisibleChanged.addHandler(e._updateTabShown,e),e._initSheetPage(),e._initSheetTab()}_initSheetTab(){var e=this;e.addEventListener(e._tabContainer,"mousedown",t=>{var o,i=t.target;i instanceof HTMLLIElement&&(e._sheetTabClicked=!0,o=e._getItemIndex(e._tabContainer,i),e._scrollSheetTabContainer(i),o>-1&&(e._sheets.selectedIndex=o))})}_initSheetPage(){var e=this;e.hostElement.querySelector("div.wj-sheet-page").addEventListener("click",t=>{var o="[object HTMLButtonElement]"===t.target.toString()?t.target:t.target.parentElement,i=e._getItemIndex(e._sheetPage,o);if(0!==e._sheets.length)switch(i){case 0:e._sheets.selectFirst();break;case 1:e._sheets.selectPrevious();break;case 2:e._sheets.selectNext();break;case 3:e._sheets.selectLast()}})}_getSheetTabs(){var e,t="";for(e=0;e<this._sheets.length;e++)t+=this._getSheetElement(this._sheets[e],this._sheets.selectedIndex===e);return t}_getSheetElement(e,t=!1){var o="<li";return e.visible?t&&(o+=' class="active"'):o+=' class="hidden"',o+=">"+e.name+"</li>"}_updateTabActive(e,t){e<0||e>=this._tabContainer.children.length||(t?wjcCore.addClass(this._tabContainer.children[e],"active"):wjcCore.removeClass(this._tabContainer.children[e],"active"))}_updateTabShown(e,t){t.index<0||t.index>=this._tabContainer.children.length||(t.item.visible?wjcCore.removeClass(this._tabContainer.children[t.index],"hidden"):wjcCore.addClass(this._tabContainer.children[t.index],"hidden"),this._adjustSize())}_adjustSize(){var e,t,o=this._tabContainer.childElementCount,i=0,l=0;if("none"!==this.hostElement.style.display){for(l=this._tabContainer.parentElement.scrollLeft,this._tabContainer.parentElement.style.width="",this._tabContainer.style.width="",this._sheetPage.parentElement.style.width="",e=0;e<o;e++)i+=this._tabContainer.children[e].offsetWidth+1;t=this.hostElement.offsetWidth-this._sheetPage.offsetWidth-this._newSheet.offsetWidth-2,this._tabContainer.parentElement.style.width=(i>t?t:i)+"px",this._tabContainer.style.width=i+"px",this._sheetPage.parentElement.style.width=this._sheetPage.offsetWidth+this._newSheet.offsetWidth+this._tabContainer.parentElement.offsetWidth+3+"px",this._tabContainer.parentElement.scrollLeft=l}}_getItemIndex(e,t){for(var o=0;o<e.children.length;o++)if(e.children[o]===t)return o;return-1}_updateSheetName(e,t){this._tabContainer.querySelectorAll("li")[t.index].textContent=t.item.name,this._adjustSize()}_scrollSheetTabContainer(e){var t,o=this._tabContainer.parentElement.scrollLeft,i=this._sheetPage.offsetWidth,l=this._newSheet.offsetWidth,n=this._tabContainer.parentElement.offsetWidth;if(this._rtl)switch(wjcGrid.FlexGrid._getRtlMode()){case"rev":(t=-this._tabContainer.offsetLeft)+e.offsetLeft+e.offsetWidth>n+o?this._tabContainer.parentElement.scrollLeft+=e.offsetWidth:t+e.offsetLeft<o&&(this._tabContainer.parentElement.scrollLeft-=e.offsetWidth);break;case"neg":e.offsetLeft<o?this._tabContainer.parentElement.scrollLeft-=e.offsetWidth:e.offsetLeft+e.offsetWidth>n+o&&(this._tabContainer.parentElement.scrollLeft+=e.offsetWidth);break;default:e.offsetLeft-l+o<0?this._tabContainer.parentElement.scrollLeft+=e.offsetWidth:e.offsetLeft+e.offsetWidth-l+o>n&&(this._tabContainer.parentElement.scrollLeft-=e.offsetWidth)}else e.offsetLeft+e.offsetWidth-i>n+o?this._tabContainer.parentElement.scrollLeft+=e.offsetWidth:e.offsetLeft-i<o&&(this._tabContainer.parentElement.scrollLeft-=e.offsetWidth)}_adjustSheetsPosition(){var e,t,o=this._tabContainer.querySelectorAll("li"),i=0;for(t=0;t<o.length;t++)(e=o[t]).style.cssFloat="right",e.style.right=i+"px",i+=o[t].clientWidth}_scrollToActiveSheet(e,t){var o,i,l,n=this._tabContainer.querySelectorAll("li");if(i=this._tabContainer.clientWidth>this._tabContainer.parentElement.clientWidth?this._tabContainer.clientWidth-this._tabContainer.parentElement.clientWidth:0,n.length>0&&e<n.length&&t<n.length){if(0===e&&!this._rtl||e===n.length-1&&this._rtl){if(this._rtl)switch(wjcGrid.FlexGrid._getRtlMode()){case"rev":this._tabContainer.parentElement.scrollLeft=0;break;case"neg":this._tabContainer.parentElement.scrollLeft=-i;break;default:this._tabContainer.parentElement.scrollLeft=i}else this._tabContainer.parentElement.scrollLeft=0;return}if(0===e&&this._rtl||e===n.length-1&&!this._rtl){if(this._rtl)switch(wjcGrid.FlexGrid._getRtlMode()){case"rev":this._tabContainer.parentElement.scrollLeft=i;break;case"neg":default:this._tabContainer.parentElement.scrollLeft=0}else this._tabContainer.parentElement.scrollLeft=i;return}if(e>=t)for(l=t+1;l<=e;l++)o=n[l],this._scrollSheetTabContainer(o);else for(l=t-1;l>=e;l--)o=n[l],this._scrollSheetTabContainer(o)}}_adjustNavigationButtons(e){var t,o=this.hostElement.querySelectorAll(".wj-sheet-page button");o&&4===o.length&&(e?(t=o[0].querySelector("span"),wjcCore.removeClass(t,"wj-glyph-step-backward"),wjcCore.addClass(t,"wj-glyph-step-forward"),t=o[1].querySelector("span"),wjcCore.removeClass(t,"wj-glyph-left"),wjcCore.addClass(t,"wj-glyph-right"),t=o[2].querySelector("span"),wjcCore.removeClass(t,"wj-glyph-right"),wjcCore.addClass(t,"wj-glyph-left"),t=o[3].querySelector("span"),wjcCore.removeClass(t,"wj-glyph-step-forward"),wjcCore.addClass(t,"wj-glyph-step-backward")):(t=o[0].querySelector("span"),wjcCore.removeClass(t,"wj-glyph-step-forward"),wjcCore.addClass(t,"wj-glyph-step-backward"),t=o[1].querySelector("span"),wjcCore.removeClass(t,"wj-glyph-right"),wjcCore.addClass(t,"wj-glyph-left"),t=o[2].querySelector("span"),wjcCore.removeClass(t,"wj-glyph-left"),wjcCore.addClass(t,"wj-glyph-right"),t=o[3].querySelector("span"),wjcCore.removeClass(t,"wj-glyph-step-backward"),wjcCore.addClass(t,"wj-glyph-step-forward")))}};_SheetTabs.controlTemplate='<div wj-part="sheet-container" class="wj-sheet" style="height:100%;position:relative"><div wj-part="sheet-page" class="wj-btn-group wj-sheet-page"><button type="button" class="wj-btn wj-btn-default"><span class="wj-sheet-icon wj-glyph-step-backward"></span></button><button type="button" class="wj-btn wj-btn-default"><span class="wj-sheet-icon wj-glyph-left"></span></button><button type="button" class="wj-btn wj-btn-default"><span class="wj-sheet-icon wj-glyph-right"></span></button><button type="button" class="wj-btn wj-btn-default"><span class="wj-sheet-icon wj-glyph-step-forward"></span></button></div><div class="wj-sheet-tab" style="height:100%;overflow:hidden"><ul wj-part="container"></ul></div><div wj-part="new-sheet" class="wj-new-sheet"><span class="wj-sheet-icon wj-glyph-file"></span></div></div>';export class _UnboundSortDescription{constructor(e,t){this._column=e,this._ascending=t}get column(){return this._column}get ascending(){return this._ascending}};export class SortManager{constructor(e){this._owner=e,this._sortDescriptions=new wjcCore.CollectionView,this._committedList=[new ColumnSortDescription(-1,!0)],this._sortDescriptions.newItemCreator=(()=>new ColumnSortDescription(-1,!0))}get sortDescriptions(){return this._sortDescriptions}set sortDescriptions(e){this._sortDescriptions=e,this.commitSort()}addSortLevel(e,t=!0){var o=this._sortDescriptions.addNew();null!=e&&!isNaN(e)&&wjcCore.isInt(e)&&(o.columnIndex=e),o.ascending=t,this._sortDescriptions.commitNew()}deleteSortLevel(e){var t;(t=null!=e?this._getSortItem(e):this._sortDescriptions.currentItem)&&this._sortDescriptions.remove(t)}copySortLevel(){var e=this._sortDescriptions.currentItem;if(e){var t=this._sortDescriptions.addNew();t.columnIndex=parseInt(e.columnIndex),t.ascending=e.ascending,this._sortDescriptions.commitNew()}}editSortLevel(e,t){null!=e&&(this._sortDescriptions.currentItem.columnIndex=e),null!=t&&(this._sortDescriptions.currentItem.ascending=t)}moveSortLevel(e){var t=this._sortDescriptions.currentItem;if(t){var o=this._sortDescriptions.sourceCollection,i=o.indexOf(t),l=i+e;i>-1&&l>-1&&(o.splice(i,1),o.splice(l,0,t),this._sortDescriptions.refresh(),this._sortDescriptions.moveCurrentTo(t))}}checkSortItemExists(e){for(var t=0,o=this._sortDescriptions.itemCount;t<o;t++)if(+this._sortDescriptions.items[t].columnIndex===e)return t;return-1}commitSort(e=!0){var t,o,i,l,n,s,r,a,h,d,c,_,u,g,w,m,f=this,C=f._owner,p=f._owner.itemsSource instanceof wjcCore.CollectionView,S={};if(f._owner.selectedSheet&&0!==f._owner.columns.length){if(C._needCopyToSheet=!1,s=C.selectedSheet._unboundSortDesc,e&&C.undoStack.stackSize>0&&(r=new _SortColumnAction(C)),f._sortDescriptions.itemCount>0?f._committedList=f._cloneSortList(f._sortDescriptions.items):f._committedList=[new ColumnSortDescription(-1,!0)],d=C.selectedSheet._filterDefinition,C.collectionView){for(C._isSorting=!0,C.beginUpdate(),(a=C.editableCollectionView)&&a.currentEditItem&&-1!==a.items.indexOf(a.currentEditItem)&&!f._isEmpty(a.currentEditItem)&&a.commitEdit(),C.collectionView.beginUpdate(),C.selectedSheet.grid.collectionView.beginUpdate(),(i=C.collectionView.sortDescriptions).clear(),h=C.selection.clone(),m=C.allowAddNew&&C.newRowAtTop?2:1,_=[],n=0;n<C.rows.length-m;n++)(w=(g=C.rows[n+m]).dataItem)&&(_[u=null!=w._itemIdx?w._itemIdx:n]=g.visible);for(p||(l=C.selectedSheet.grid.collectionView.sortDescriptions).clear(),C.collectionView.sourceCollection.map((e,t)=>{e._itemIdx=t}),C.selection=h,navigator.userAgent.toLowerCase().indexOf("chrome")>-1&&(C.collectionView.useStableSort=!0,p||(C.selectedSheet.grid.collectionView.useStableSort=!0)),n=0;n<f._sortDescriptions.itemCount;n++)(t=f._sortDescriptions.items[n]).columnIndex>-1&&(o=new wjcCore.SortDescription(C.columns[t.columnIndex].binding,t.ascending),i.push(o),p||(C.collectionView.sortDescriptions.push(o),l.push(o)));for(C.selectedSheet.selectionRanges.clear(),C.collectionView.endUpdate(),C.selectedSheet.grid.collectionView.endUpdate(),h=C.selection.clone(),c=C.collectionView._view.slice(),n=0;n<c.length;n++)n!==(w=c[n])._itemIdx&&C._updateFormulaForReorderingRows(w._itemIdx+m,n+m),C._updateCellStyleForReorderingRows(w._itemIdx+m,n+m,S);for(n=0;n<C.rows.length-m;n++)(w=(g=C.rows[n+m]).dataItem)&&(u=null!=w._itemIdx?w._itemIdx:n,g.visible=_[u]);C.selectedSheet._styledCells=S,C.selection=h,C.endUpdate(),C._copyColumnsToSelectedSheet(),C._isSorting=!1}else{for(s.clear(),n=0;n<f._sortDescriptions.itemCount;n++)(t=f._sortDescriptions.items[n]).columnIndex>-1&&s.push(new _UnboundSortDescription(C.columns[t.columnIndex],t.ascending));setTimeout(()=>{d&&(C.filter.filterDefinition=d)},10)}r&&(r.saveNewState(),C.undoStack._addAction(r)),C._copiedRanges=null,C._needCopyToSheet=!0}}cancelSort(){this._sortDescriptions.sourceCollection=this._committedList.slice()}clearSort(){this._sortDescriptions.sourceCollection=[],this.commitSort()}_getColumnIndex(e){for(var t=0,o=this._owner.columns.length;t<o;t++)if(this._owner.columns[t].binding===e)return t;return-1}_getSortItem(e){var t=this.checkSortItemExists(e);if(t>-1)return this._sortDescriptions.items[t]}_cloneSortList(e){for(var t=[],o=0;o<e.length;o++)t[o]=e[o].clone();return t}_updateSortSortDescription(e,t,o=!0){let i,l;for(i=this._sortDescriptions.items.length-1;i>=0;i--)l=this._sortDescriptions.items[i],o?l.columnIndex>e&&(l.columnIndex+=t):l.columnIndex>=e+t?l.columnIndex-=t:l.columnIndex>=e&&this._sortDescriptions.remove(l)}_isEmpty(e){var t=Object.prototype.hasOwnProperty;if(null==e)return!0;if(e.length>0)return!1;if(0===e.length)return!0;for(var o in e)if(t.call(e,o))return!1;return!0}};export class ColumnSortDescription{constructor(e,t){this._columnIndex=e,this._ascending=t}get columnIndex(){return this._columnIndex}set columnIndex(e){this._columnIndex=+e}get ascending(){return this._ascending}set ascending(e){this._ascending=e}clone(){return new ColumnSortDescription(this._columnIndex,this._ascending)}};export class UndoStack{constructor(e){this.MAX_STACK_SIZE=500,this._stack=[],this._pointer=-1,this._resizingTriggered=!1,this.undoStackChanged=new wjcCore.Event;let t=this;t._owner=e,t._owner.prepareCellForEdit.addHandler(t._initCellEditAction,t),t._owner.cellEditEnded.addHandler((e,o)=>{t._pendingAction&&(!o.data||46!==o.data.keyCode&&8!==o.data.keyCode)&&t._pendingAction instanceof _EditAction&&!t._pendingAction.isPaste&&t._afterProcessCellEditAction(t)},t),t._owner.pasting.addHandler(t._initCellEditActionForPasting,t),t._owner.pastingCell.addHandler((e,o)=>{t._pendingAction&&(t._pendingAction instanceof _EditAction?t._pendingAction.updateForPasting(o.range):t._pendingAction instanceof _CutAction&&t._pendingAction.updateForPasting(o.range))},t),t._owner.pasted.addHandler(()=>{t._pendingAction&&(t._pendingAction instanceof _EditAction&&t._pendingAction.isPaste?t._afterProcessCellEditAction(t):t._pendingAction instanceof _CutAction&&(t._pendingAction.saveNewState(),t._addAction(t._pendingAction),t._pendingAction=null))},t),t._owner.resizingColumn.addHandler((e,o)=>{0!==t.stackSize&&t._owner.selectedSheet&&(t._resizingTriggered||(t._pendingAction=new _ColumnResizeAction(t._owner,o.panel,o.col),t._resizingTriggered=!0))},t),t._owner.resizedColumn.addHandler((e,o)=>{t._pendingAction instanceof _ColumnResizeAction&&t._pendingAction.saveNewState()&&t._addAction(t._pendingAction),t._pendingAction=null,t._resizingTriggered=!1},t),t._owner.resizingRow.addHandler((e,o)=>{0!==t.stackSize&&t._owner.selectedSheet&&(t._resizingTriggered||(t._pendingAction=new _RowResizeAction(t._owner,o.panel,o.row),t._resizingTriggered=!0))},t),t._owner.resizedRow.addHandler((e,o)=>{t._pendingAction instanceof _RowResizeAction&&t._pendingAction.saveNewState()&&t._addAction(t._pendingAction),t._pendingAction=null,t._resizingTriggered=!1},t),t._owner.draggingRowColumn.addHandler((e,o)=>{0!==t.stackSize&&t._owner.selectedSheet&&o.isShiftKey&&(o.isDraggingRows?t._pendingAction=new _RowsChangedAction(t._owner):t._pendingAction=new _ColumnsChangedAction(t._owner))},t),t._owner.droppingRowColumn.addHandler(()=>{t._pendingAction&&t._pendingAction.saveNewState()&&t._addAction(t._pendingAction),t._pendingAction=null},t)}get stackSize(){return null==this._stackSize?this.MAX_STACK_SIZE:this._stackSize}set stackSize(e){wjcCore.isNumber(e)&&(e<0?this._stackSize=0:e>this.MAX_STACK_SIZE?this._stackSize=this.MAX_STACK_SIZE:this._stackSize=Math.floor(e))}get canUndo(){return this._pointer>-1&&this._pointer<this._stack.length}get canRedo(){return this._pointer+1>-1&&this._pointer+1<this._stack.length}onUndoStackChanged(){this.undoStackChanged.raise(this)}undo(){let e;this.canUndo&&(e=this._stack[this._pointer],this._beforeUndoRedo(e),e.undo(),this._pointer--,this.onUndoStackChanged())}redo(){let e;this.canRedo&&(this._pointer++,e=this._stack[this._pointer],this._beforeUndoRedo(e),e.redo(),this.onUndoStackChanged())}clear(){this._stack.length=0}_addAction(e){this._stack.length>0&&this._stack.length>this._pointer+1&&this._stack.splice(this._pointer+1,this._stack.length-this._pointer-1),this._stack.length>=this.stackSize&&this._stack.splice(0,this._stack.length-this.stackSize+1),this._pointer=this._stack.length,this._stack.push(e),this.onUndoStackChanged()}_pop(){let e;return this._pointer<0?null:(e=this._stack[this._pointer],this._pointer--,e)}_updateCurrentAction(e){let t;this._pointer<0||(t=this._stack[this._pointer])instanceof e&&t.saveNewState()}_initCellEditAction(e,t){0!==this.stackSize&&this._owner.selectedSheet&&(this._pendingAction=new _EditAction(this._owner,t.range))}_initCellEditActionForPasting(){0!==this.stackSize&&this._owner.selectedSheet&&(this._owner._isCutting?this._pendingAction=new _CutAction(this._owner):(this._pendingAction=new _EditAction(this._owner),this._pendingAction.markIsPaste()))}_afterProcessCellEditAction(e){e._pendingAction&&(e._pendingAction instanceof _EditAction&&e._pendingAction.saveNewState()&&e._addAction(this._pendingAction),e._pendingAction=null)}_beforeUndoRedo(e){this._owner.selectedSheetIndex=e.sheetIndex}};export class Table{constructor(e,t,o,i,l){if(this._showHeaderRow=!0,this._showTotalRow=!1,this._showBandedColumns=!1,this._showBandedRows=!0,this._alterFirstColumn=!1,this._alterLastColumn=!1,this._orgHeaderCellsContent=[],!t.isValid)throw"The range of this table is invalid.";this._name=e,this._range=t.clone(),this._style=o,null!=i&&i.length>0&&this._pushTableColumns(i),null!=l&&(null!=l.showHeaderRow&&(this._showHeaderRow=l.showHeaderRow),null!=l.showTotalRow&&(this._showTotalRow=l.showTotalRow),null!=l.showBandedColumns&&(this._showBandedColumns=l.showBandedColumns),null!=l.showBandedRows&&(this._showBandedRows=l.showBandedRows),null!=l.alterFirstColumn&&(this._alterFirstColumn=l.alterFirstColumn),null!=l.alterLastColumn&&(this._alterLastColumn=l.alterLastColumn))}get name(){return this._name}set name(e){var t,o;if(null==e||""===e)throw"The name of the Table should not be empty.";this._name.toLowerCase()!==e.toLowerCase()&&(o=this._name,this._name=e,this._owner&&(!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this)),this._owner._updateFormulasWithNameUpdating(o,e,!0),t&&(t.saveNewState(),this._owner.undoStack._addAction(t),t=null)))}get sheet(){return this._sheet}get style(){return this._style}set style(e){var t;e.name!==this._style.name&&(this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this)),this._style=e,this._owner&&(t&&(t.saveNewState(),this._owner.undoStack._addAction(t),t=null),this._owner.refresh()))}get showHeaderRow(){return this._showHeaderRow}set showHeaderRow(e){var t,o;if(e!==this._showHeaderRow&&(this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this)),o=this._showHeaderRow,this._showHeaderRow=e,this._owner))try{this._owner.beginUpdate(),this._adjustTableRangeWithHeaderRow(),t&&(t.saveNewState(),this._owner.undoStack._addAction(t))}catch(e){throw this._showHeaderRow=o,e}finally{t=null,this._owner.endUpdate()}}get showTotalRow(){return this._showTotalRow}set showTotalRow(e){var t,o;if(e!==this._showTotalRow&&(this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this)),o=this._showTotalRow,this._showTotalRow=e,this._owner))try{this._owner.beginUpdate(),this._adjustTableRangeWithTotalRow(),t&&(t.saveNewState(),this._owner.undoStack._addAction(t))}catch(e){throw this._showTotalRow=o,e}finally{t=null,this._owner.endUpdate()}}get showBandedColumns(){return this._showBandedColumns}set showBandedColumns(e){var t;e!==this._showBandedColumns&&(this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this)),this._showBandedColumns=e,this._owner&&(t&&(t.saveNewState(),this._owner.undoStack._addAction(t),t=null),this._owner.refresh()))}get showBandedRows(){return this._showBandedRows}set showBandedRows(e){var t;e!==this._showBandedRows&&(this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this)),this._showBandedRows=e,this._owner&&(t&&(t.saveNewState(),this._owner.undoStack._addAction(t),t=null),this._owner.refresh()))}get alterFirstColumn(){return this._alterFirstColumn}set alterFirstColumn(e){var t;e!==this._alterFirstColumn&&(this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this)),this._alterFirstColumn=e,this._owner&&(t&&(t.saveNewState(),this._owner.undoStack._addAction(t),t=null),this._owner.refresh()))}get alterLastColumn(){return this._alterLastColumn}set alterLastColumn(e){var t;e!==this._alterLastColumn&&(this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this)),this._alterLastColumn=e,this._owner&&(t&&(t.saveNewState(),this._owner.undoStack._addAction(t),t=null),this._owner.refresh()))}getRange(e=TableSection.All,t){let o;switch(e){case TableSection.Data:o=this._getDataRange();break;case TableSection.Header:o=this._getHeaderRange();break;case TableSection.Footer:o=this._getFooterRange();break;default:o=this._range.clone()}if(null!=t&&o){let e=this._getColumnIndex(t);if(null==e)return null;o.col=o.col2=o.leftCol+e}return o}getColumns(){return this._columns?this._columns.slice():[]}insertRows(e,t,o=!0){var i,l,n,s,r,a=this.getRange(),h=!1;if(null==t&&(t=1),!wjcCore.isInt(t)||t<1)return!1;if(0===e&&this._showHeaderRow||e===this._range.rowSpan-1&&this._showTotalRow||e<0||e>=this._range.rowSpan)return!1;if(this._owner){if(this._owner.beginUpdate(),s=this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid,o){if(n=new wjcGrid.CellRange(a.bottomRow+1,a.col,a.bottomRow+1,a.col2),this._sheet._canShiftCells(n)){if(i=this._sheet._needAddRowCountForInsertTableRows(t,a),s.collectionView){for(r=s.itemsSource instanceof wjcCore.CollectionView,s.collectionView.beginUpdate(),l=0;l<i;l++)r?s.itemsSource.sourceCollection.push({}):s.itemsSource.push({});s.collectionView.endUpdate()}else for(l=0;l<i;l++)s.rows.push(new wjcGrid.Row);this._sheet._moveDownCells(t,n),h=!0}}else this._canInsertRowsWithoutShift(t)&&(h=!0);h&&(this._sheet._moveDownCellsWithinTable(e,t,a),this._updateTableRange(0,t,0,0)),this._owner.endUpdate()}else this._updateTableRange(0,t,0,0),h=!0;return h}deleteRows(e,t,o=!0){var i,l=!1,n=this.getRange();null==t&&(t=1),!wjcCore.isInt(t)||t<1||0===e&&this._showHeaderRow||e===this._range.rowSpan-1&&this._showTotalRow||e<0||e>=this._range.rowSpan||e+t>this._range.rowSpan-(this._showTotalRow?1:0)||(this._owner?(this._owner.beginUpdate(),o?(i=new wjcGrid.CellRange(n.bottomRow+1,n.col,n.bottomRow+1,n.col2),this._sheet._canShiftCells(i)&&(l=!0)):l=!0,l&&(this._sheet._moveUpCellsWithinTable(e,t,n),o&&this._sheet._moveUpCells(t,i),this._updateTableRange(0,-t,0,0)),this._owner.endUpdate()):this._updateTableRange(0,-t,0,0))}_addColumn(e,t){var o,i=this.getRange();if(e<=0||e>this._columns.length)throw"The column index is out of range.";t=this._getUniqueColumnName(e,t),(o=new TableColumn(t))._attach(this),this._columns.splice(e,0,o),this.showHeaderRow&&this._owner&&this._sheet&&(this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid).setCellData(i.topRow,i.leftCol+e,t)}_updateCell(e,t,o){var i,l=e-this._range.topRow,n=t-this._range.leftCol;null!=this._style&&(i=this._getTableCellAppliedStyles(l,n),this._applyStylesForCell(i,o))}_updateTableRange(e,t,o,i){this._range.row<=this._range.row2?(this._range.row+=e,this._range.row2+=t):(this._range.row2+=e,this._range.row+=t),this._range.col<=this._range.col2?(this._range.col+=o,this._range.col2+=i):(this._range.col2+=o,this._range.col+=i)}_setTableRange(e,t){var o;if(this._range=e,null!=t)for(this._columns.splice(0,this._columns.length),o=0;o<t.length;o++)this._columns.push(t[o])}_updateColumnName(e,t){var o=this._columns[e];t=this._getUniqueColumnName(null,t),o.name=t,this._showHeaderRow&&this._owner&&this._sheet&&(this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid).setCellData(this._range.topRow,this._range.leftCol+e,t)}_updateColumnTotalRowContent(e,t){var o,i;null==t&&(t=this._columns.indexOf(e)),t<0||(e.totalRowFunction?i=null!=(o=this._getSubtotalFunction(e.totalRowFunction.toLowerCase()))?"=subtotal("+o+",["+e.name+"])":"="===e.totalRowFunction[0]?e.totalRowFunction:"="+e.totalRowFunction:0===t?(e.totalRowLabel||(e.totalRowLabel="Total"),i=e.totalRowLabel):i=e.totalRowLabel,this._owner&&this._sheet&&(this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid).setCellData(this._range.bottomRow,this._range.leftCol+t,i,!1))}_attachSheet(e){var t=this.getRange();if(!(this._sheet&&this._owner||(this._sheet=e,this._owner=e._owner,null==this._owner))){if(this._owner._containsMergedCells(this._range,e))throw"Table does not allow the merged cell within the table.";null==this._style&&(this._style=this._owner.getBuiltInTableStyle("TableStyleMedium9")),null!=this._columns&&0!==this._columns.length||this._generateColumns(this._showHeaderRow);try{this._owner.beginUpdate(),this._showHeaderRow&&1===t.rowSpan&&this._adjustTableRangeWithHeaderRow(),this._showTotalRow&&this._updateTotalRow()}finally{this._owner.endUpdate()}}}_detachSheet(){this._sheet=null,this._owner=null}_pushTableColumns(e){var t,o;for(this._columns=[],o=0;o<e.length;o++)(t=e[o])._attach(this),this._columns.push(t)}_generateColumns(e){var t,o,i,l,n,s=this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid;if(!this._range.isValid)throw"The range of the table is invalid.";this._columns=[];for(var r=0;r<this._range.columnSpan;r++)l=this._sheet.grid.columns[this._range.leftCol+r],n=this._range.topRow*this._sheet.grid.columns.length+this._range.leftCol+r,1===this._range.rowSpan?t=this._getUniqueColumnName(r+1):(null==(t=this._sheet.grid.getCellData(this._range.topRow,this._range.leftCol+r,!1))&&(t=""),wjcCore.isString(t)&&"="===t[0]&&(t=this._owner.evaluate(t,"",this._sheet,!1)),i=this._sheet._styledCells[n],t=this._owner._formatEvaluatedResult(t,l,i?i.format:""),t=this._getUniqueColumnName(r+1,t.toString())),e&&this._range.rowSpan>1&&(this._orgHeaderCellsContent[r]=this._sheet.grid.getCellData(this._range.topRow,this._range.leftCol+r,!1),isNaN(+t)||l.format||i&&i.format||(i?i.format="@":this._sheet._styledCells[n]={format:"@"}),s.setCellData(this._range.topRow,this._range.leftCol+r,t,!1)),(o=new TableColumn(t))._attach(this),0===r?o._totalRowLabel="Total":r===this._range.columnSpan-1&&(o._totalRowFunction="Sum"),this._columns.push(o)}_getTableCellAppliedStyles(e,t){var o,i={},l=!1,n=!1,s=0;return this._showHeaderRow&&(s=1),this._showHeaderRow&&0===e?l=!0:this._showTotalRow&&e===this._range.rowSpan-1&&(n=!0),this._extendStyle(i,this._style.wholeTableStyle,e,t,l,n),l||n||(!this._showBandedColumns||null==this._style.firstBandedColumnStyle&&null==this._style.secondBandedColumnStyle||(t%((o=this._style.firstBandedColumnStyle?null==this._style.firstBandedColumnStyle.size?1:this._style.firstBandedColumnStyle.size:1)+(this._style.secondBandedColumnStyle?null==this._style.secondBandedColumnStyle.size?1:this._style.secondBandedColumnStyle.size:1))>=o?this._style.secondBandedColumnStyle&&this._extendStyle(i,this._style.secondBandedRowStyle,e,t,l,n):this._style.firstBandedColumnStyle&&this._extendStyle(i,this._style.firstBandedColumnStyle,e,t,l,n)),!this._showBandedRows||null==this._style.firstBandedRowStyle&&null==this._style.secondBandedRowStyle||((e-s)%((o=this._style.firstBandedRowStyle?null==this._style.firstBandedRowStyle.size?1:this._style.firstBandedRowStyle.size:1)+(this._style.secondBandedRowStyle?null==this._style.secondBandedRowStyle.size?1:this._style.secondBandedRowStyle.size:1))>=o?this._style.secondBandedRowStyle&&this._extendStyle(i,this._style.secondBandedRowStyle,e,t,l,n):this._style.firstBandedRowStyle&&this._extendStyle(i,this._style.firstBandedRowStyle,e,t,l,n))),this._alterLastColumn&&t===this._range.columnSpan-1&&this._style.lastColumnStyle&&this._extendStyle(i,this._style.lastColumnStyle,e,t,l,n),this._alterFirstColumn&&0===t&&this._style.firstColumnStyle&&this._extendStyle(i,this._style.firstColumnStyle,e,t,l,n),l?(this._style.headerRowStyle&&this._extendStyle(i,this._style.headerRowStyle,e,t,l,n),t===this._range.columnSpan-1&&this._style.lastHeaderCellStyle&&this._extendStyle(i,this._style.lastHeaderCellStyle,e,t,l,n),0===t&&this._style.firstHeaderCellStyle&&this._extendStyle(i,this._style.firstHeaderCellStyle,e,t,l,n)):n&&(this._style.totalRowStyle&&this._extendStyle(i,this._style.totalRowStyle,e,t,l,n),t===this._range.columnSpan-1&&this._style.lastTotalCellStyle&&this._extendStyle(i,this._style.lastTotalCellStyle,e,t,l,n),0===t&&this._style.firstTotalCellStyle&&this._extendStyle(i,this._style.firstTotalCellStyle,e,t,l,n)),i}_applyStylesForCell(e,t){var o,i=t.style;for(var l in e)(o=e[l])&&(i[l]=o)}_extendStyle(e,t,o,i,l,n){var s;for(var r in t)null!==(s=t[r])&&(r.indexOf("borderTop")>-1?(0===o||n)&&(e[r]=s):r.indexOf("borderBottom")>-1?(o===this._range.rowSpan-1||l)&&(e[r]=s):r.indexOf("borderLeft")>-1?0===i&&(e[r]=s):r.indexOf("borderRight")>-1?i===this._range.columnSpan-1&&(e[r]=s):r.indexOf("borderHorizontal")>-1?o<this._range.rowSpan-1&&("borderHorizontalStyle"===r?e.borderBottomStyle=s:"borderHorizontalWidth"===r?e.borderBottomWidth=s:e.borderBottomColor=s):r.indexOf("borderVertical")>-1?i<this._range.columnSpan-1&&("borderVerticalStyle"===r?e.borderRightStyle=s:"borderVerticalWidth"===r?e.borderRightWidth=s:e.borderRightColor=s):e[r]=s)}_getSubtotalFunction(e){switch(e){case"average":return"101";case"countnums":return"102";case"count":return"103";case"max":return"104";case"min":return"105";case"stddev":return"107";case"sum":return"109";case"var":return"110"}return null}_checkColumnNameExist(e){var t,o=this.getColumns();for(t=0;t<o.length;t++)if(o[t].name.toLowerCase()===e.toLowerCase())return!0;return!1}_adjustTableRangeWithHeaderRow(){var e,t,o,i,l=this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid;if(this._showHeaderRow){if(this._sheet._needMoveDownTable(this)){if(o=this.getRange(),i=new wjcGrid.CellRange(o.bottomRow+1,o.col,o.bottomRow+1,o.col2),!this._sheet._canShiftCells(i))throw"The operation is not allowed.  The operation is attempting to shift the cells in a table or a merged cell on the current sheet.";1===this._sheet._needAddRowCountForInsertTableRows(1,o)&&(l.collectionView?(l.collectionView.beginUpdate(),l.itemsSource instanceof wjcCore.CollectionView?l.itemsSource.sourceCollection.push({}):l.itemsSource.push({}),l.collectionView.endUpdate()):l.rows.push(new wjcGrid.Row)),this._sheet._moveDownCells(1,i),this._sheet._moveDownTable(this)}for(this._range.row<=this._range.row2?this._range.row-=1:this._range.row2-=1,e=0;e<this._columns.length;e++)t=this._columns[e],this._orgHeaderCellsContent[e]=l.getCellData(this._range.topRow,this._range.leftCol+e,!1),l.setCellData(this._range.topRow,this._range.leftCol+e,t.name)}else{for(e=this._range.leftCol;e<=this._range.rightCol;e++)l.setCellData(this._range.topRow,e,"");this._range.row<=this._range.row2?this._range.row+=1:this._range.row2+=1}}_adjustTableRangeWithTotalRow(){var e,t,o,i=this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid;if(t=this.getRange(),o=new wjcGrid.CellRange(t.bottomRow+1,t.col,t.bottomRow+1,t.col2),this._showTotalRow){if(this._sheet._canShiftCells(o))1===this._sheet._needAddRowCountForInsertTableRows(1,t)&&(i.collectionView?(i.collectionView.beginUpdate(),i.itemsSource instanceof wjcCore.CollectionView?i.itemsSource.sourceCollection.push({}):i.itemsSource.push({}),i.collectionView.endUpdate()):i.rows.push(new wjcGrid.Row)),this._sheet._moveDownCells(1,o),this._owner._updateAffectedFormula(this._range.bottomRow+1,1,!0,!0,this.getRange());else if(!this._beneathRowIsEmpty())throw"The operation is not allowed.  The operation is attempting to shift the cells in a table or a merged cell on the current sheet.";this._range.row<=this._range.row2?this._range.row2+=1:this._range.row+=1,this._updateTotalRow()}else{for(e=this._range.leftCol;e<=this._range.rightCol;e++)i.setCellData(this._range.bottomRow,e,"");this._sheet._canShiftCells(o)&&(this._owner._updateAffectedFormula(this._range.bottomRow,1,!1,!0,this.getRange()),this._sheet._moveUpCells(1,o)),this._range.row<=this._range.row2?this._range.row2-=1:this._range.row-=1}}_updateTotalRow(){let e;if(this.showTotalRow)for(let t=0;t<this._columns.length;t++)e=this._columns[t],this._updateColumnTotalRowContent(e,t)}_getUniqueColumnName(e,t){var o,i=1;if(null!=t&&""!==t||(t="Column"+e),this._checkColumnNameExist(t)){for(o=t+i;this._checkColumnNameExist(o);)o=t+ ++i;t=o}return t}_moveColumns(e,t){if(!this._columns)return;let o=this._columns[e];this._columns.splice(e,1),t<0&&(t=this._columns.length),this._columns.splice(t,0,o)}_canInsertRowsWithoutShift(e){var t,o,i,l,n,s=this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid;if(this._range.bottomRow+e>=s.rows.length)return!1;for(t=1;t<=e;t++)for(o=this._range.bottomRow+t,i=this._range.leftCol;i<=this._range.rightCol;i++)if(l=s.getCellData(o,i,!1),n=this._sheet.getCellStyle(o,i),null!=l&&""!==l||null!=n)return!1;return!0}_beneathRowIsEmpty(){let e,t,o,i,l,n,s=this._range.bottomRow+1,r=this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid;if(s>=r.rows.length)return!1;for(e=this._range.leftCol;e<=this._range.rightCol;e++){if(null!=(t=r.getCellData(this._range.bottomRow+1,e,!1))&&""!==t)return!1;if(null!=(o=this._sheet.getCellStyle(this._range.bottomRow+1,e)))return!1;if(null!=(i=this._sheet.findTable(s,e)))return null;if(l=s*r.columns.length+e,null!=(n=this._sheet._mergedRanges[l]))return!1}return!0}_getDataRange(){var e=this._range.topRow,t=this._range.bottomRow;return this._showHeaderRow&&(e+=1),this._showTotalRow&&(t-=1),new wjcGrid.CellRange(e,this._range.leftCol,t,this._range.rightCol)}_getHeaderRange(){return this._showHeaderRow?new wjcGrid.CellRange(this._range.topRow,this._range.leftCol,this._range.topRow,this._range.rightCol):null}_getFooterRange(){return this._showTotalRow?new wjcGrid.CellRange(this._range.bottomRow,this._range.leftCol,this._range.bottomRow,this._range.rightCol):null}_getColumnIndex(e){var t,o,i;if(wjcCore.isInt(e)&&e>=0&&e<this._columns.length)t=e;else{e instanceof TableColumn?o=e.name.toLowerCase():wjcCore.isString(e)&&""!==e&&(o=e.toLowerCase()),i=this.getColumns();for(var l=0;l<i.length;l++)if(i[l].name.toLowerCase()===o){t=l;break}}return t}};export class TableColumn{constructor(e,t,o,i=!0){this._name=e,this._totalRowLabel=t,this._totalRowFunction=o,null!=i&&(this._showFilterButton=i)}get table(){return this._table}get name(){return this._name}set name(e){e!==this._name&&(this._name=e)}get totalRowLabel(){return this._totalRowLabel}set totalRowLabel(e){e!==this._totalRowLabel&&(this._totalRowLabel=e,this._updateTableTotalInfo())}get totalRowFunction(){return this._totalRowFunction}set totalRowFunction(e){e!==this._totalRowFunction&&(this._totalRowFunction=e,this._updateTableTotalInfo())}get showFilterButton(){return this._showFilterButton}set showFilterButton(e){this._showFilterButton!==e&&(this._showFilterButton=e)}_attach(e){this._table=e}_updateTableTotalInfo(){this._table&&this._table.showTotalRow&&(this._table._updateColumnTotalRowContent(this),this._table._owner&&this._table._owner.refresh())}};export class TableStyle{constructor(e,t=!1){this._name=e,this._isBuiltIn=t}get name(){return this._name}set name(e){e!==this._name&&(this._name=e)}get wholeTableStyle(){return this._wholeTableStyle}set wholeTableStyle(e){this._wholeTableStyle=e}get firstBandedColumnStyle(){return this._firstBandedColumnStyle}set firstBandedColumnStyle(e){this._firstBandedColumnStyle=e}get secondBandedColumnStyle(){return this._secondBandedColumnStyle}set secondBandedColumnStyle(e){this._secondBandedColumnStyle=e}get firstBandedRowStyle(){return this._firstBandedRowStyle}set firstBandedRowStyle(e){this._firstBandedRowStyle=e}get secondBandedRowStyle(){return this._secondBandedRowStyle}set secondBandedRowStyle(e){this._secondBandedRowStyle=e}get firstColumnStyle(){return this._firstColumnStyle}set firstColumnStyle(e){this._firstColumnStyle=e}get lastColumnStyle(){return this._lastColumnStyle}set lastColumnStyle(e){this._lastColumnStyle=e}get headerRowStyle(){return this._headerRowStyle}set headerRowStyle(e){this._headerRowStyle=e}get totalRowStyle(){return this._totalRowStyle}set totalRowStyle(e){this._totalRowStyle=e}get firstHeaderCellStyle(){return this._firstHeaderCellStyle}set firstHeaderCellStyle(e){this._firstHeaderCellStyle=e}get lastHeaderCellStyle(){return this._lastHeaderCellStyle}set lastHeaderCellStyle(e){this._lastHeaderCellStyle=e}get firstTotalCellStyle(){return this._firstTotalCellStyle}set firstTotalCellStyle(e){this._firstTotalCellStyle=e}get lastTotalCellStyle(){return this._lastTotalCellStyle}set lastTotalCellStyle(e){this._lastTotalCellStyle=e}get isBuiltIn(){return this._isBuiltIn}};export var TableSection;!function(e){e[e.All=0]="All",e[e.Data=1]="Data",e[e.Header=2]="Header",e[e.Footer=3]="Footer"}(TableSection||(TableSection={}));export class FlexSheetValueFilter extends wjcGridFilter.ValueFilter{constructor(e){super(e)}apply(e){var t,o=this.column.grid;return!(o instanceof FlexSheet)||(!this.showValues||!Object.keys(this.showValues).length||(o.rows[e]instanceof wjcGrid._NewRowTemplate||(t=this.dataMap||this.column.dataMap,e=t?t.getDisplayValue(o.getCellValue(e,this.column.index)):o.getCellValue(e,this.column.index,!0),void 0!=this.showValues[e])))}};export class FlexSheetValueFilterEditor extends wjcGridFilter.ValueFilterEditor{updateEditor(){var e,t,o,i,l,n,s,r,a,h=this.filter.column,d=h.grid,c=h.index,_=[],u={};if(this.filter.uniqueValues||null!=d.itemsSource&&null!=d.childItemsPath)super.updateEditor();else{for(m=0;m<d.rows.length;m++)l=this.filter.apply(m),i=this.filter.showValues,this.filter.showValues=null,n=d.filter._filter(m),this.filter.showValues=i,(!(t=d.getMergedRange(d.cells,m,c))||m===t.topRow&&c===t.leftCol)&&((e=d.rows[m])instanceof HeaderRow||e instanceof wjcGrid.GroupRow||e instanceof wjcGrid._NewRowTemplate||!(e.visible||!l&&n)||(o=d.getCellValue(m,c),s=this.filter.dataMap?this.filter.dataMap.getDisplayValue(o):d.getCellValue(m,c,!0),o=""===o?null:o,r=d.getCellData(m,c,!0),u[s]||(u[s]=!0,a=r&&"="===r[0]?m+"_"+c:"",_.push({value:o,text:s,cellRef:a}))));var g=this.filter.showValues;if(g&&0!=Object.keys(g).length){for(var w in g)for(m=0;m<_.length;m++)if(g[w]&&""!==_[m].cellRef&&_[m].cellRef===g[w].cellRef)g[_[m].text]={show:!0,cellRef:_[m].cellRef},_[m].show=!0,delete g[w];else if(_[m].text==w){_[m].show=!0;break}}else for(var m=0;m<_.length;m++)_[m].show=!0;this._lbValues.isContentHtml=h.isContentHtml,this._cmbFilter.text=this.filter.filterText,this._filterText=this._cmbFilter.text.toLowerCase(),this._view.pageSize=this.filter.maxValues,this._view.sourceCollection=_,this._view.moveCurrentToPosition(-1)}}updateFilter(){var e=null,t=this._view.items;if(this._filterText||this._cbSelectAll.indeterminate){e={};for(var o=0;o<t.length;o++){var i=t[o];i.show&&(e[i.text]={show:!0,cellRef:i.cellRef})}}this._filter.showValues=e,this._filter.filterText=this._filterText}};export class FlexSheetConditionFilter extends wjcGridFilter.ConditionFilter{constructor(e){super(e)}apply(e){var t,o,i,l,n=this.column,s=n.grid,r=this.condition1,a=this.condition2;if(!(s instanceof FlexSheet))return!0;if(!this.isActive)return!0;if(s.rows[e]instanceof wjcGrid._NewRowTemplate)return!0;""===(t=s.getCellValue(e,n.index))&&n.dataType!==wjcCore.DataType.String&&(t=null),o=i=t,(l=this.dataMap||n.dataMap)?o=i=t=l.getDisplayValue(t):wjcCore.isDate(t)?(wjcCore.isString(r.value)||wjcCore.isString(a.value))&&(o=i=t=s.getCellValue(e,n.index,!0)):wjcCore.isNumber(t)?(o=i=t=wjcCore.Globalize.parseFloat(s.getCellValue(e,n.index,!0)),0!==t||n.dataType||(r.isActive&&""===r.value&&(o=t.toString()),a.isActive&&""===a.value&&(i=i.toString()))):null==t&&(r.isActive&&wjcCore.isNumber(r.value)&&(o=NaN),a.isActive&&wjcCore.isNumber(a.value)&&(i=NaN));var h=r.apply(o),d=a.apply(i);return r.isActive&&a.isActive?this.and?h&&d:h||d:r.isActive?h:!a.isActive||d}};export class FlexSheetColumnFilter extends wjcGridFilter.ColumnFilter{constructor(e,t){super(e,t),this._valueFilter=new FlexSheetValueFilter(t),this._conditionFilter=new FlexSheetConditionFilter(t)}};export class FlexSheetColumnFilterEditor extends wjcGridFilter.ColumnFilterEditor{constructor(e,t,o=!0){super(e,t,o);var i,l,n=this;o&&(this._divSort.style.display=""),i=this.cloneElement(this._btnAsc),l=this.cloneElement(this._btnDsc),this._btnAsc.parentNode.replaceChild(i,this._btnAsc),this._btnDsc.parentNode.replaceChild(l,this._btnDsc),i.addEventListener("click",e=>{n._sortBtnClick(e,!0)}),l.addEventListener("click",e=>{n._sortBtnClick(e,!1)})}_showFilter(e){e==wjcGridFilter.FilterType.Value&&null==this._edtVal&&(this._edtVal=new FlexSheetValueFilterEditor(this._divEdtVal,this.filter.valueFilter)),super._showFilter(e)}_sortBtnClick(e,t){var o,i,l=this.filter.column,n=l.grid.sortManager;e.preventDefault(),e.stopPropagation(),(o=n.checkSortItemExists(l.index))>-1?(n.sortDescriptions.moveCurrentToPosition(o),n.sortDescriptions.currentItem.ascending=t,i=-o):(n.addSortLevel(l.index,t),i=-(n.sortDescriptions.items.length-1)),n.moveSortLevel(i),n.commitSort(),this.onButtonClicked()}cloneElement(e){for(var t=e.cloneNode();e.firstChild;)t.appendChild(e.lastChild);return t}};export class FlexSheetFilter extends wjcGridFilter.FlexGridFilter{get filterDefinition(){for(var e={filters:[]},t=0;t<this._filters.length;t++){var o=this._filters[t];if(o&&o.column&&this.grid.columns.indexOf(o.column)>-1)if(o.conditionFilter.isActive){var i=o.conditionFilter;e.filters.push({columnIndex:o.column.index,type:"condition",condition1:{operator:i.condition1.operator,value:i.condition1.value},and:i.and,condition2:{operator:i.condition2.operator,value:i.condition2.value}})}else if(o.valueFilter.isActive){var l=o.valueFilter;e.filters.push({columnIndex:o.column.index,type:"value",filterText:l.filterText,showValues:l.showValues})}}return JSON.stringify(e)}set filterDefinition(e){var t=JSON.parse(wjcCore.asString(e));this.clear();for(var o=0;o<t.filters.length;o++){var i=t.filters[o],l=this.grid.columns[i.columnIndex],n=this.getColumnFilter(l,!0);if(n)switch(i.type){case"condition":var s=n.conditionFilter;s.condition1.value=l.dataType==wjcCore.DataType.Date?wjcCore.changeType(i.condition1.value,l.dataType,null):i.condition1.value,s.condition1.operator=i.condition1.operator,s.and=i.and,s.condition2.value=l.dataType==wjcCore.DataType.Date?wjcCore.changeType(i.condition2.value,l.dataType,null):i.condition2.value,s.condition2.operator=i.condition2.operator;break;case"value":var r=n.valueFilter;r.filterText=i.filterText,r.showValues=i.showValues}}this.apply()}apply(){var e=this;e.grid.deferUpdate(()=>{for(var t,o,i,l=-1,n=0;n<e.grid.rows.length;n++)if(!((t=e.grid.rows[n])instanceof HeaderRow||n<=l))if(l=-1,o=e._filter(n),t instanceof wjcGrid.GroupRow){if(i=t.getCellRange(),null==t.dataItem||t.dataItem instanceof wjcCore.CollectionViewGroup)t.visible=e._checkGroupVisible(i);else if(t.visible=o,l=i.bottomRow,i.isValid)for(var s=i.topRow;s<=i.bottomRow;s++)e.grid.rows[s].visible=o}else t.visible=o;e.grid._isCopying||e.grid._isUndoing||e.grid._isSorting||e.onFilterApplied()})}editColumnFilter(e,t){var o=this,i=o.grid;o.closeEditor(),e=o._asColumn(e);var l=document.createElement("div"),n=o.getColumnFilter(e),s=new FlexSheetColumnFilterEditor(l,n,o.showSortButtons);wjcCore.addClass(l,"wj-dropdown-panel"),o._divEdt=l,o._edtCol=e;var r=new wjcGrid.CellRangeEventArgs(i.cells,new wjcGrid.CellRange(-1,e.index));if(o.onFilterChanging(r),r.cancel)return o._divEdt=null,void(o._edtCol=null);r.cancel=!0,i.undoStack.stackSize>0&&(o._undoAcion=new _FilteringAction(i)),i.rightToLeft&&(l.dir="rtl"),s.filterChanged.addHandler(()=>{r.cancel=!1,o._filterChanged=!0,setTimeout(()=>{r.cancel||(o.apply(),o._undoAcion&&(o._undoAcion.saveNewState(),i.undoStack._addAction(o._undoAcion),o._undoAcion=null))})}),s.buttonClicked.addHandler(()=>{o.closeEditor(),i.focus(),o.onFilterChanged(r)}),s.lostFocus.addHandler(()=>{setTimeout(()=>{var e=wjcCore.Control.getControl(o._divEdt);e&&!e.containsFocus()&&o.closeEditor()},10)}),i._edtHdl._commitRowEdits(),i.scrollIntoView(-1,e.index,!0);var a=o.grid.columnHeaders,h=t?t.row:a.rows.length-1,d=t?t.col:e.index,c=a.getCellBoundingRect(h,d),_=document.elementFromPoint(c.left+c.width/2,c.top+c.height/2);(_=wjcCore.closest(_,".wj-cell"))?wjcCore.showPopup(l,_,!1,!1,!1):wjcCore.showPopup(l,c),o._setAriaExpanded(_,!0),o._setAriaExpanded(i.cells.getCellElement(-1,d),!0);let u=s.hostElement.querySelectorAll("input");for(let e=0;e<u.length;e++){let t=u[e];if(t.offsetHeight>0&&t.tabIndex>-1&&!t.disabled){t.focus();break}}s.containsFocus()||s.focus()}closeEditor(){this._undoAcion&&!this._filterChanged&&(this._undoAcion=null),super.closeEditor()}getColumnFilter(e,t=!0){if(wjcCore.isString(e)?e=this.grid.columns.getColumn(e):wjcCore.isNumber(e)&&(e=this.grid.columns[e]),!e)return null;e=wjcCore.asType(e,wjcGrid.Column);for(var o=0;o<this._filters.length;o++)if(this._filters[o].column==e)return this._filters[o];if(t){var i=new FlexSheetColumnFilter(this,e);return this._filters.push(i),i}return null}_checkGroupVisible(e){for(var t,o=!0,i=e.topRow+1;i<=e.bottomRow;i++)if(t=this.grid.rows[i])if(t instanceof wjcGrid.GroupRow)o=this._checkGroupVisible(t.getCellRange());else if(o=this._filter(i))break;return o}};