"use strict";var Ge=Object.defineProperty;var He=(r,t,n)=>t in r?Ge(r,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[t]=n;var U=(r,t,n)=>He(r,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@univerjs/core"),l=require("@univerjs/sheets"),e=require("@univerjs/engine-formula"),w=require("rxjs"),me=require("@univerjs/rpc"),ye={id:"formula.command.insert-function",type:c.CommandType.COMMAND,handler:async(r,t)=>{const{list:n}=t,a=r.get(c.ICommandService),i=new c.ObjectMatrix;n.forEach(u=>{const{range:m,primary:f,formula:s}=u,{row:d,column:L}=f,T=c.Tools.generateRandomId(6);i.setValue(d,L,{f:s,si:T});const{startRow:I,startColumn:A,endRow:S,endColumn:p}=m;for(let N=I;N<=S;N++)for(let E=A;E<=p;E++)(N!==d||E!==L)&&i.setValue(N,E,{si:T})});const o={value:i.getData()};return a.executeCommand(l.SetRangeValuesCommand.id,o)}},te={type:c.CommandType.MUTATION,id:"sheet.mutation.data-validation-formula-mark-dirty",handler(){return!0}};function Ye(r,t,n){var a;return r==null||r[t]==null||((a=r[t])==null?void 0:a[n])==null}function Ne(r,t,n){var a;if(n){if(r&&r[t]&&((a=r[t])!=null&&a[n]))return delete r[t][n],{[t]:{[n]:null}}}else if(r&&r[t])return delete r[t],{[t]:null}}var D=(r=>(r[r.MoveRange=0]="MoveRange",r[r.MoveRows=1]="MoveRows",r[r.MoveCols=2]="MoveCols",r[r.InsertRow=3]="InsertRow",r[r.InsertColumn=4]="InsertColumn",r[r.RemoveRow=5]="RemoveRow",r[r.RemoveColumn=6]="RemoveColumn",r[r.DeleteMoveLeft=7]="DeleteMoveLeft",r[r.DeleteMoveUp=8]="DeleteMoveUp",r[r.InsertMoveDown=9]="InsertMoveDown",r[r.InsertMoveRight=10]="InsertMoveRight",r[r.SetName=11]="SetName",r[r.RemoveSheet=12]="RemoveSheet",r[r.SetDefinedName=13]="SetDefinedName",r[r.RemoveDefinedName=14]="RemoveDefinedName",r))(D||{});const Xe=[11,12,13,14];function we(r,t,n){const{type:a}=n;return Xe.includes(a)?We(r,t):Ke(r,t,n)}function We(r,t){const n=[],a=[];return Object.keys(t).forEach(i=>{const o=t[i],u=r[i];if(o==null||u==null)return!0;Object.keys(o).forEach(m=>{const f=new c.ObjectMatrix(o[m]||{}),s=new c.ObjectMatrix(u[m]||{}),d=new c.ObjectMatrix,L=new c.ObjectMatrix;if(f.forValue((p,N,E)=>{if(E==null)return!0;const P=de(E);P!==null&&(d.setValue(p,N,P),L.setValue(p,N,s.getValue(p,N)))}),d.getSizeOf()===0)return;const T={subUnitId:m,unitId:i,cellValue:d.getMatrix()},I={id:l.SetRangeValuesMutation.id,params:T};a.push(I);const A={subUnitId:m,unitId:i,cellValue:L.getMatrix()},S={id:l.SetRangeValuesMutation.id,params:A};n.push(S)})}),{undos:n,redos:a}}function Ke(r,t,n){const{redoFormulaData:a,undoFormulaData:i}=Qe(r,t,n);if(c.Tools.diffValue(a,i))return{undos:[],redos:[]};const o=[],u=[];return Object.keys(a).forEach(m=>{Object.keys(a[m]).forEach(f=>{if(Object.keys(a[m][f]).length!==0){const s={subUnitId:f,unitId:m,cellValue:a[m][f]},d={id:l.SetRangeValuesMutation.id,params:s};o.push(d)}})}),Object.keys(i).forEach(m=>{Object.keys(i[m]).forEach(f=>{if(Object.keys(i[m][f]).length!==0){const s={subUnitId:f,unitId:m,cellValue:i[m][f]},d={id:l.SetRangeValuesMutation.id,params:s};u.push(d)}})}),{undos:u,redos:o}}function Qe(r,t,n){const a={},i={},{type:o,unitId:u,sheetId:m,range:f,from:s,to:d}=n;return new Set([...Object.keys(r),...Object.keys(t)]).forEach(T=>{if(Ye(r,T,m))return;new Set([...Object.keys(r[T]||{}),...Object.keys(t[T]||{})]).forEach(A=>{var b,x;const S=(b=r[T])==null?void 0:b[A],p=(x=t[T])==null?void 0:x[A],N=new c.ObjectMatrix(S||{}),E=new c.ObjectMatrix(p||{});let P=[];T!==u||A!==m?P=ke(E):P=je(N,o,s,d,f);const M=ct(P,N,E),C=ft(P,N);a[T]||(a[T]={}),i[T]||(i[T]={}),a[T][A]={...a[T][A],...M},i[T][A]={...i[T][A],...C}})}),{redoFormulaData:a,undoFormulaData:i}}function je(r,t,n,a,i){const o=[];return r.forValue((u,m,f)=>{if(f==null||!xe(f))return!0;const s=c.cellToRange(u,m);let d=null,L=!1;if([0,1,2].includes(t))d=$e(t,n,a,s);else if(i!=null){const T=ze(t,i,s);d=T.newCell,L=T.isReverse}L?o.unshift({oldCell:s,newCell:d}):o.push({oldCell:s,newCell:d})}),o}function ke(r){const t=[];return r.forValue((n,a,i)=>{if(i==null||!xe(i))return!0;const o=c.cellToRange(n,a);t.push({oldCell:o,newCell:o})}),t}function $e(r,t,n,a){if(t==null||n==null)return null;switch(r){case 0:return Ze(t,n,a);case 1:return Je(t,n,a);case 2:return et(t,n,a);default:return null}}function ze(r,t,n){let a=null,i=!1;switch(r){case 3:a=tt(t,n),i=!0;break;case 4:a=nt(t,n),i=!0;break;case 5:a=at(t,n);break;case 6:a=it(t,n);break;case 7:a=rt(t,n);break;case 8:a=ot(t,n);break;case 9:a=ut(t,n),i=!0;break;case 10:a=mt(t,n),i=!0;break}return{newCell:a,isReverse:i}}function Ze(r,t,n){const a=l.handleMoveRange({id:l.EffectRefRangId.MoveRangeCommandId,params:{toRange:t,fromRange:r}},n);return l.runRefRangeMutations(a,n)}function Je(r,t,n){const a=l.handleMoveRows({id:l.EffectRefRangId.MoveRowsCommandId,params:{toRange:t,fromRange:r}},n);return l.runRefRangeMutations(a,n)}function et(r,t,n){const a=l.handleMoveCols({id:l.EffectRefRangId.MoveColsCommandId,params:{toRange:t,fromRange:r}},n);return l.runRefRangeMutations(a,n)}function tt(r,t){const n=l.handleInsertRow({id:l.EffectRefRangId.InsertRowCommandId,params:{range:r,unitId:"",subUnitId:"",direction:c.Direction.DOWN}},t);return l.runRefRangeMutations(n,t)}function nt(r,t){const n=l.handleInsertCol({id:l.EffectRefRangId.InsertColCommandId,params:{range:r,unitId:"",subUnitId:"",direction:c.Direction.RIGHT}},t);return l.runRefRangeMutations(n,t)}function at(r,t){const n=l.handleIRemoveRow({id:l.EffectRefRangId.RemoveRowCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function it(r,t){const n=l.handleIRemoveCol({id:l.EffectRefRangId.RemoveColCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function rt(r,t){const n=l.handleDeleteRangeMoveLeft({id:l.EffectRefRangId.DeleteRangeMoveLeftCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function ot(r,t){const n=l.handleDeleteRangeMoveUp({id:l.EffectRefRangId.DeleteRangeMoveUpCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function ut(r,t){const n=l.handleInsertRangeMoveDown({id:l.EffectRefRangId.InsertRangeMoveDownCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function mt(r,t){const n=l.handleInsertRangeMoveRight({id:l.EffectRefRangId.InsertRangeMoveRightCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function ct(r,t,n){const a=new c.ObjectMatrix({});return r.forEach(i=>{const{oldCell:o,newCell:u}=i,{startRow:m,startColumn:f}=o,s=n.getValue(m,f)||t.getValue(m,f),d=de(s);if(a.setValue(m,f,{f:null,si:null}),u){const{startRow:L,startColumn:T}=u;a.setValue(L,T,d)}}),a.getMatrix()}function ft(r,t){const n=new c.ObjectMatrix({});return r.reverse().forEach(a=>{const{oldCell:i,newCell:o}=a,{startRow:u,startColumn:m}=i,f=t.getValue(u,m),s=de(f);if(o){const{startRow:d,startColumn:L}=o;n.setValue(d,L,{f:null,si:null})}n.setValue(u,m,s)}),n.getMatrix()}function de(r){if(r==null)return;const{f:t,si:n,x:a=0,y:i=0}=r,o=c.isFormulaString(t),u=c.isFormulaId(n);if(!o&&!u)return{f:null,si:null};const m={};return u&&(m.si=n),o&&a===0&&i===0&&(m.f=t),m.f===void 0&&(m.f=null),m.si===void 0&&(m.si=null),m}function lt(r){const t=new c.ObjectMatrix({});return new c.ObjectMatrix(r).forValue((a,i,o)=>{const u=de(o);u&&t.setValue(a,i,u)}),t.getMatrix()}function xe(r){const t=(r==null?void 0:r.f)||"",n=(r==null?void 0:r.si)||"",a=c.isFormulaString(t),i=c.isFormulaId(n);return!!(a||i)}function Ue(r,t,n,a,i,o){if((i==null||i.length===0)&&(o==null||o.length===0)){if(r===n&&t===a)return!0}else if((r===i||i==null||i.length===0)&&t===o)return!0;return!1}function qe(r,t,n=0,a=0){const i=[];for(let o=0,u=r.length;op.endRow&&s.startRow>p.endRow))return;P==null&&(P={startRow:p.startRow,endRow:p.endRow,startColumn:p.startColumn,endColumn:p.endColumn,rangeType:c.RANGE_TYPE.NORMAL});const M=l.handleMoveRows({id:l.EffectRefRangId.MoveRowsCommandId,params:{toRange:s,fromRange:f}},P),C=l.runRefRangeMutations(M,P);if(C==null)return e.ErrorType.REF;N=Pe(E,C,f,s,p,P)}else if(i===D.MoveCols){if(f==null||s==null)return;const E=Ee(p,f);let P=c.getIntersectRange(p,f);if(P==null&&(f.endColumn
(r[r.NOT_REGISTER=1]="NOT_REGISTER",r[r.SUCCESS=2]="SUCCESS",r[r.WAIT=3]="WAIT",r[r.ERROR=4]="ERROR",r))(ee||{}),bt=Object.defineProperty,yt=Object.getOwnPropertyDescriptor,xt=(r,t,n,a)=>{for(var i=a>1?void 0:a?yt(t,n):t,o=r.length-1,u;o>=0;o--)(u=r[o])&&(i=(a?u(t,n,i):u(i))||i);return a&&i&&bt(t,n,i),i},Ie=(r,t)=>(n,a)=>t(n,a,r);exports.RegisterOtherFormulaService=class extends c.Disposable{constructor(n,a,i){super();U(this,"_formulaCacheMap",new Map);U(this,"_formulaChangeWithRange$",new w.Subject);U(this,"formulaChangeWithRange$",this._formulaChangeWithRange$.asObservable());U(this,"_formulaResult$",new w.Subject);U(this,"formulaResult$",this._formulaResult$.asObservable());U(this,"calculateStarted$",new w.BehaviorSubject(!1));this._commandService=n,this._activeDirtyManagerService=a,this._lifecycleService=i,this._initFormulaRegister(),this._initFormulaCalculationResultChange()}dispose(){super.dispose(),this._formulaChangeWithRange$.complete(),this._formulaResult$.complete(),this.calculateStarted$.complete()}_ensureCacheMap(n,a){let i=this._formulaCacheMap.get(n);i||(i=new Map,this._formulaCacheMap.set(n,i));let o=i.get(a);return o||(o=new Map,i.set(a,o)),o}_createFormulaId(n,a){return`formula.${n}_${a}_${c.Tools.generateRandomId(8)}`}_initFormulaRegister(){this._activeDirtyManagerService.register(te.id,{commandId:te.id,getDirtyData(a){return{dirtyUnitOtherFormulaMap:a.params}}});const n=a=>{const{unitId:i,subUnitId:o,formulaText:u,formulaId:m,ranges:f}=a;if(!this._ensureCacheMap(i,o).has(m))return;const d={unitId:i,subUnitId:o,formulaMap:{[m]:{f:u,ranges:f}}};this._commandService.executeCommand(e.SetOtherFormulaMutation.id,d).then(()=>{this._commandService.executeCommand(te.id,{[i]:{[o]:{[m]:!0}}})})};this.disposeWithMe(this._formulaChangeWithRange$.pipe(w.bufferWhen(()=>this.calculateStarted$.pipe(w.filter(a=>a)))).subscribe(a=>a.forEach(n))),this.disposeWithMe(this._formulaChangeWithRange$.pipe(w.filter(()=>this.calculateStarted$.getValue())).subscribe(n))}_initFormulaCalculationResultChange(){this.disposeWithMe(this._commandService.onCommandExecuted(n=>{if(n.id===e.SetFormulaCalculationResultMutation.id){const a=n.params,{unitOtherData:i}=a,o={};for(const u in i){const m=i[u],f={};o[u]=f;for(const s in m){const d=this._ensureCacheMap(u,s),L=m[s],T=[];f[s]=T;for(const I in L){const A=L[I];if(d.has(I)){const S=d.get(I);if(!S)continue;S.result||(S.result={});const p=new c.ObjectMatrix(A),N=new c.ObjectMatrix(S.result);p.forValue((E,P,M)=>{N.setValue(E,P,M)}),S.status=ee.SUCCESS,S.callbacks.forEach(E=>{E(A)}),S.callbacks.clear(),T.push(S)}}}}this._formulaResult$.next(o)}}))}registerFormulaWithRange(n,a,i,o=[{startRow:0,endRow:0,startColumn:0,endColumn:0}],u){const m=this._createFormulaId(n,a);return this._ensureCacheMap(n,a).set(m,{result:void 0,status:ee.WAIT,formulaId:m,callbacks:new Set,extra:u}),this._formulaChangeWithRange$.next({unitId:n,subUnitId:a,formulaText:i,formulaId:m,ranges:o}),m}deleteFormula(n,a,i){const o={unitId:n,subUnitId:a,formulaIdList:i};this._commandService.executeCommand(e.RemoveOtherFormulaMutation.id,o);const u=this._ensureCacheMap(n,a);i.forEach(m=>u.delete(m))}getFormulaValue(n,a,i){const o=this._ensureCacheMap(n,a),u=o.get(i);return u?u.status===ee.SUCCESS||u.status===ee.ERROR?Promise.resolve(u):new Promise(m=>{u.callbacks.add(()=>{m(o.get(i))})}):Promise.resolve(null)}getFormulaValueSync(n,a,i){return this._ensureCacheMap(n,a).get(i)}};exports.RegisterOtherFormulaService=xt([Ie(0,c.ICommandService),Ie(1,e.IActiveDirtyManagerService),Ie(2,c.Inject(c.LifecycleService))],exports.RegisterOtherFormulaService);const ne="sheets-formula.base.config";var V=(r=>(r[r.FORCED=0]="FORCED",r[r.WHEN_EMPTY=1]="WHEN_EMPTY",r[r.NO_CALCULATION=2]="NO_CALCULATION",r))(V||{});const _e={},Ut="sheets-formula.remote.config",De={};var qt=Object.defineProperty,gt=Object.getOwnPropertyDescriptor,ht=(r,t,n,a)=>{for(var i=a>1?void 0:a?gt(t,n):t,o=r.length-1,u;o>=0;o--)(u=r[o])&&(i=(a?u(t,n,i):u(i))||i);return a&&i&&qt(t,n,i),i},K=(r,t)=>(n,a)=>t(n,a,r);const Fe={done:0,count:0},Ae={onlyLocal:!0};exports.TriggerCalculationController=class extends c.Disposable{constructor(n,a,i,o,u,m,f){var d;super();U(this,"_waitingCommandQueue",[]);U(this,"_executingDirtyData",{forceCalculation:!1,dirtyRanges:[],dirtyNameMap:{},dirtyDefinedNameMap:{},dirtyUnitFeatureMap:{},dirtyUnitOtherFormulaMap:{},clearDependencyTreeCache:{}});U(this,"_setTimeoutKey",-1);U(this,"_startExecutionTime",0);U(this,"_totalCalculationTaskCount",0);U(this,"_doneCalculationTaskCount",0);U(this,"_executionInProgressParams",null);U(this,"_restartCalculation",!1);U(this,"_calculationMode",V.WHEN_EMPTY);U(this,"_forceCalculating",!1);U(this,"_progress$",new w.BehaviorSubject(Fe));U(this,"progress$",this._progress$.asObservable());this._commandService=n,this._activeDirtyManagerService=a,this._logService=i,this._configService=o,this._formulaDataModel=u,this._localeService=m,this._registerOtherFormulaService=f;const s=this._configService.getConfig(ne);this._calculationMode=(d=s==null?void 0:s.initialFormulaComputing)!=null?d:V.WHEN_EMPTY,this._commandExecutedListener(),this._initialExecuteFormulaProcessListener(),this._initialExecuteFormula()}_emitProgress(n){this._progress$.next({done:this._doneCalculationTaskCount,count:this._totalCalculationTaskCount,label:n})}_startProgress(){this._doneCalculationTaskCount=0,this._totalCalculationTaskCount=1;const n=this._localeService.t("formula.progress.analyzing");this._emitProgress(n)}_calculateProgress(n){if(this._executionInProgressParams){const{totalFormulasToCalculate:a,completedFormulasCount:i,totalArrayFormulasToCalculate:o,completedArrayFormulasCount:u}=this._executionInProgressParams;if(this._doneCalculationTaskCount=i+u,this._totalCalculationTaskCount=a+o,this._totalCalculationTaskCount===0)return;this._emitProgress(n)}}_completeProgress(){this._doneCalculationTaskCount=this._totalCalculationTaskCount=1;const n=this._localeService.t("formula.progress.done");this._emitProgress(n)}clearProgress(){this._doneCalculationTaskCount=0,this._totalCalculationTaskCount=0,this._emitProgress()}dispose(){super.dispose(),this._progress$.next(Fe),this._progress$.complete()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((n,a)=>{if(this._activeDirtyManagerService.get(n.id)){if(n.id===l.SetRangeValuesMutation.id){const i=n.params;if(a&&a.onlyLocal===!0||i.trigger===l.SetStyleCommand.id||i.trigger===l.SetBorderCommand.id||i.trigger===l.ClearSelectionFormatCommand.id)return}this._waitingCommandQueue.push(n),clearTimeout(this._setTimeoutKey),this._setTimeoutKey=setTimeout(()=>{const i=this._generateDirty(this._waitingCommandQueue);this._executingDirtyData=this._mergeDirty(this._executingDirtyData,i),this._executionInProgressParams==null?this._commandService.executeCommand(e.SetFormulaCalculationStartMutation.id,{...this._executingDirtyData},Ae):(this._restartCalculation=!0,this._commandService.executeCommand(e.SetFormulaCalculationStopMutation.id,{})),this._waitingCommandQueue=[]},100)}}))}_generateDirty(n){const a=[],i={},o={},u={},m={},f={};for(const s of n){const d=this._activeDirtyManagerService.get(s.id);if(d==null)continue;const L=d.getDirtyData(s),{dirtyRanges:T,dirtyNameMap:I,dirtyDefinedNameMap:A,dirtyUnitFeatureMap:S,dirtyUnitOtherFormulaMap:p,clearDependencyTreeCache:N}=L;T!=null&&this._mergeDirtyRanges(a,T),I!=null&&this._mergeDirtyNameMap(i,I),A!=null&&this._mergeDirtyNameMap(o,A),S!=null&&this._mergeDirtyUnitFeatureOrOtherFormulaMap(u,S),p!=null&&this._mergeDirtyUnitFeatureOrOtherFormulaMap(m,p),N!=null&&this._mergeDirtyNameMap(f,N)}return{dirtyRanges:a,dirtyNameMap:i,dirtyDefinedNameMap:o,dirtyUnitFeatureMap:u,dirtyUnitOtherFormulaMap:m,forceCalculation:!1,clearDependencyTreeCache:f,maxIteration:this._configService.getConfig(e.ENGINE_FORMULA_CYCLE_REFERENCE_COUNT)}}_mergeDirty(n,a){const i=[...n.dirtyRanges,...a.dirtyRanges],o={...n.dirtyNameMap},u={...n.dirtyDefinedNameMap},m={...n.dirtyUnitFeatureMap},f={...n.dirtyUnitOtherFormulaMap},s={...n.clearDependencyTreeCache};this._mergeDirtyNameMap(o,a.dirtyNameMap),this._mergeDirtyNameMap(u,a.dirtyDefinedNameMap),this._mergeDirtyUnitFeatureOrOtherFormulaMap(m,a.dirtyUnitFeatureMap),this._mergeDirtyUnitFeatureOrOtherFormulaMap(f,a.dirtyUnitOtherFormulaMap),this._mergeDirtyNameMap(s,a.clearDependencyTreeCache);const d=n.maxIteration||a.maxIteration;return{dirtyRanges:i,dirtyNameMap:o,dirtyDefinedNameMap:u,dirtyUnitFeatureMap:m,dirtyUnitOtherFormulaMap:f,forceCalculation:!!this._forceCalculating,clearDependencyTreeCache:s,maxIteration:d}}_mergeDirtyRanges(n,a){for(const i of a){let o=!1;for(const u of n)if(i.unitId===u.unitId&&i.sheetId===u.sheetId){const{startRow:m,startColumn:f,endRow:s,endColumn:d}=i.range,{startRow:L,startColumn:T,endRow:I,endColumn:A}=u.range;if(m===L&&f===T&&s===I&&d===A){o=!0;break}}o||n.push(i)}}_mergeDirtyNameMap(n,a){Object.keys(a).forEach(i=>{n[i]==null&&(n[i]={}),Object.keys(a[i]).forEach(o=>{var u;(u=a[i])!=null&&u[o]&&(n[i][o]=a[i][o])})})}_mergeDirtyUnitFeatureOrOtherFormulaMap(n,a){Object.keys(a).forEach(i=>{n[i]==null&&(n[i]={}),Object.keys(a[i]).forEach(o=>{n[i][o]==null&&(n[i][o]={}),Object.keys(a[i][o]).forEach(u=>{n[i][o][u]=a[i][o][u]||!1})})})}_initialExecuteFormulaProcessListener(){let n=null,a=0;this.disposeWithMe(this._commandService.onCommandExecuted(i=>{if(i.id===e.SetFormulaCalculationStartMutation.id){const{forceCalculation:u=!1}=i.params;u&&(this._forceCalculating=!0)}else i.id===e.SetFormulaCalculationStopMutation.id&&this.clearProgress();if(i.id!==e.SetFormulaCalculationNotificationMutation.id)return;const o=i.params;if(o.stageInfo!=null){const{stage:u}=o.stageInfo;if(u===e.FormulaExecuteStageType.START){if(this._calculationMode===V.NO_CALCULATION)return;a===0&&(this._startExecutionTime=performance.now()),a++,n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>{n=null,this._startProgress()},1e3)}else if(u===e.FormulaExecuteStageType.CURRENTLY_CALCULATING){if(this._executionInProgressParams=o.stageInfo,n===null){const m=this._localeService.t("formula.progress.calculating");this._calculateProgress(m)}}else if(u===e.FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA){if(this._executionInProgressParams=o.stageInfo,n===null){const m=this._localeService.t("formula.progress.array-analysis");this._calculateProgress(m)}}else if(u===e.FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA&&(this._executionInProgressParams=o.stageInfo,n===null)){const m=this._localeService.t("formula.progress.array-calculation");this._calculateProgress(m)}}else{const u=o.functionsExecutedState;let m="";switch(a--,u){case e.FormulaExecutedStateType.NOT_EXECUTED:m="No tasks are being executed anymore",this._resetExecutingDirtyData();break;case e.FormulaExecutedStateType.STOP_EXECUTION:m="The execution of the formula has been stopped",a=0;break;case e.FormulaExecutedStateType.SUCCESS:m="Formula calculation succeeded",(a===0||a===-1)&&(m+=`. Total time consumed: ${performance.now()-this._startExecutionTime} ms`),this._resetExecutingDirtyData();break;case e.FormulaExecutedStateType.INITIAL:m="Waiting for calculation",this._resetExecutingDirtyData();break}(a===0||a===-1)&&(n?(clearTimeout(n),n=null,this.clearProgress()):this._completeProgress(),a=0,this._doneCalculationTaskCount=0,this._totalCalculationTaskCount=0,this._forceCalculating=!1),u===e.FormulaExecutedStateType.STOP_EXECUTION&&this._restartCalculation?(this._restartCalculation=!1,this._commandService.executeCommand(e.SetFormulaCalculationStartMutation.id,{...this._executingDirtyData},Ae)):this._executionInProgressParams=null,this._logService.debug("[TriggerCalculationController]",m)}}))}_resetExecutingDirtyData(){this._executingDirtyData={dirtyRanges:[],dirtyNameMap:{},dirtyDefinedNameMap:{},dirtyUnitFeatureMap:{},dirtyUnitOtherFormulaMap:{},forceCalculation:!1,clearDependencyTreeCache:{}}}_initialExecuteFormula(){const n=this._getDirtyDataByCalculationMode(this._calculationMode);this._commandService.executeCommand(e.SetFormulaCalculationStartMutation.id,n,Ae),this._registerOtherFormulaService.calculateStarted$.next(!0)}_getDirtyDataByCalculationMode(n){const a=n===V.FORCED,i=n===V.WHEN_EMPTY?this._formulaDataModel.getFormulaDirtyRanges():[];return{forceCalculation:a,dirtyRanges:i,dirtyNameMap:{},dirtyDefinedNameMap:{},dirtyUnitFeatureMap:{},dirtyUnitOtherFormulaMap:{},clearDependencyTreeCache:{},maxIteration:this._configService.getConfig(e.ENGINE_FORMULA_CYCLE_REFERENCE_COUNT)}}};exports.TriggerCalculationController=ht([K(0,c.ICommandService),K(1,e.IActiveDirtyManagerService),K(2,c.ILogService),K(3,c.IConfigService),K(4,c.Inject(e.FormulaDataModel)),K(5,c.Inject(c.LocaleService)),K(6,c.Inject(exports.RegisterOtherFormulaService))],exports.TriggerCalculationController);var Bt=Object.defineProperty,vt=Object.getOwnPropertyDescriptor,Vt=(r,t,n,a)=>{for(var i=a>1?void 0:a?vt(t,n):t,o=r.length-1,u;o>=0;o--)(u=r[o])&&(i=(a?u(t,n,i):u(i))||i);return a&&i&&Bt(t,n,i),i},X=(r,t)=>(n,a)=>t(n,a,r);exports.UpdateFormulaController=class extends c.Disposable{constructor(t,n,a,i,o,u,m,f){super(),this._univerInstanceService=t,this._commandService=n,this._lexerTreeBuilder=a,this._formulaDataModel=i,this._sheetInterceptorService=o,this._definedNamesService=u,this._configService=m,this._injector=f,this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations:t=>this._getUpdateFormula(t)})),this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(t.params)if(t.id===l.RemoveSheetMutation.id){const{subUnitId:n,unitId:a}=t.params;this._handleWorkbookDisposed(a,n)}else t.id===l.InsertSheetMutation.id&&this._handleInsertSheetMutation(t.params)})),this.disposeWithMe(this._commandService.beforeCommandExecuted((t,n)=>{if(t.id===l.SetRangeValuesMutation.id){const a=t.params;if(n&&n.onlyLocal===!0||a.trigger===l.SetStyleCommand.id||a.trigger===l.SetBorderCommand.id||a.trigger===l.ClearSelectionFormatCommand.id)return;this._handleSetRangeValuesMutation(a)}})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(c.UniverInstanceType.UNIVER_SHEET).subscribe(t=>this._handleWorkbookAdded(t))),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(c.UniverInstanceType.UNIVER_SHEET).pipe(w.map(t=>t.getUnitId())).subscribe(t=>this._handleWorkbookDisposed(t)))}_handleSetRangeValuesMutation(t){const{subUnitId:n,unitId:a,cellValue:i}=t;if(i==null)return;const o=this._formulaDataModel.updateFormulaData(a,n,i),u={[a]:{[n]:o}};this._commandService.executeCommand(l.SetRangeValuesMutation.id,{unitId:a,subUnitId:n,cellValue:lt(o)},{onlyLocal:!0,fromFormula:!0}),this._formulaDataModel.updateArrayFormulaCellData(a,n,i),this._formulaDataModel.updateArrayFormulaRange(a,n,i),this._commandService.executeCommand(e.SetFormulaDataMutation.id,{formulaData:u},{onlyLocal:!0}),this._commandService.executeCommand(e.SetArrayFormulaDataMutation.id,{arrayFormulaRange:this._formulaDataModel.getArrayFormulaRange(),arrayFormulaCellData:this._formulaDataModel.getArrayFormulaCellData()},{onlyLocal:!0,remove:!0})}_handleWorkbookDisposed(t,n){const a=this._formulaDataModel.getFormulaData(),i=Ne(a,t,n),o=this._formulaDataModel.getArrayFormulaRange(),u=Ne(o,t,n),m=this._formulaDataModel.getArrayFormulaCellData(),f=Ne(m,t,n);i&&this._commandService.executeCommand(e.SetFormulaDataMutation.id,{formulaData:i},{onlyLocal:!0}),u&&f&&this._commandService.executeCommand(e.SetArrayFormulaDataMutation.id,{arrayFormulaRange:o,arrayFormulaCellData:m},{onlyLocal:!0})}_handleInsertSheetMutation(t){const{sheet:n,unitId:a}=t,i=this._formulaDataModel.getFormulaData(),{id:o,cellData:u}=n,m=new c.ObjectMatrix(u),f=e.initSheetFormulaData(i,a,o,m);this._commandService.executeCommand(e.SetFormulaDataMutation.id,{formulaData:f},{onlyLocal:!0})}_handleWorkbookAdded(t){var s;const n={},a=t.getUnitId(),i={[a]:{}};t.getSheets().forEach(d=>{var A;const L=d.getCellMatrix(),T=d.getSheetId(),I=e.initSheetFormulaData(n,a,T,L);i[a][T]=(A=I[a])==null?void 0:A[T]}),this._commandService.executeCommand(e.SetFormulaDataMutation.id,{formulaData:i},{onlyLocal:!0});const u=this._configService.getConfig(ne),m=(s=u==null?void 0:u.initialFormulaComputing)!=null?s:V.WHEN_EMPTY,f=this._getDiryDataByCalculationMode(m);this._commandService.executeCommand(e.SetFormulaCalculationStartMutation.id,f,{onlyLocal:!0})}_getDiryDataByCalculationMode(t){const n=t===V.FORCED,a=t===V.WHEN_EMPTY?this._formulaDataModel.getFormulaDirtyRanges():[];return{forceCalculation:n,dirtyRanges:a,dirtyNameMap:{},dirtyDefinedNameMap:{},dirtyUnitFeatureMap:{},dirtyUnitOtherFormulaMap:{},clearDependencyTreeCache:{}}}_getUpdateFormula(t){const n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET);if(!n)return{undos:[],redos:[]};const a=he(n,t);if(a){const{unitSheetNameMap:i}=this._formulaDataModel.getCalculateData(),o=this._formulaDataModel.getFormulaData(),{newFormulaData:u}=this._getFormulaReferenceMoveInfo(o,i,a),{undos:m,redos:f}=we(o,u,a);return{undos:m,redos:f}}return{undos:[],redos:[]}}_getFormulaReferenceMoveInfo(t,n,a){if(!c.Tools.isDefine(t))return{newFormulaData:{},oldFormulaData:{}};const i=Object.keys(t);if(i.length===0)return{newFormulaData:{},oldFormulaData:{}};const o={},u={};for(const m of i){const f=t[m];if(f==null)continue;const s=Object.keys(f);c.Tools.isDefine(o[m])||(o[m]={}),c.Tools.isDefine(u[m])||(u[m]={});for(const d of s){const L=new c.ObjectMatrix(f[d]||{}),T=new c.ObjectMatrix;L.forValue((I,A,S)=>{var _;if(!S)return!0;const{f:p,x:N,y:E,si:P}=S,M=this._lexerTreeBuilder.sequenceNodesBuilder(p);if(M==null)return!0;let C=!1;const b=[];for(let F=0,O=M.length;F