// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://@sbaseurl@/jsapi/jsapi/esri/copyright.txt and http://www.arcgis.com/apps/webappbuilder/copyright.txt for details.

//>>built
define("dojo/_base/declare dojo/_base/lang dojo/Evented dojo/on dojo/Deferred dijit/_WidgetBase jimu/utils ../utils jimu/LayerInfos/LayerInfos esri/geometry/geometryEngine esri/geometry/Extent esri/tasks/query esri/tasks/QueryTask esri/tasks/StatisticDefinition esri/layers/FeatureLayer ./clientStatistic".split(" "),function(x,f,y,n,r,z,q,l,A,B,C,D,E,p,F,t){return x([z,y],{oidFieldType:"esriFieldTypeOID",constructor:function(a){this.uniqueID=q.getRandomString();this.map=a.map;this.useSelection=a.useSelection;
this.filterByExtent=a.filterByExtent;this.returnFeatures=a.returnFeatures;this.statistic=a.statistic;this.dataSource=a.dataSource;this.config=a.config;this.isDateType=!!(this.config&&this.config.data||{}).dateConfig;this.layerInfosObj=A.getInstanceSync();this.layerObject=a.layerObject;this.timeIntervalHandle=this.filterChangedHandle=this.updateEndHandle=this.refreshIntervalHandle=this.selectionHandle=this.exchetChangeHandle=this._oldQueryParameter=this._queryParameter=this._layerUrl=null;this._loadingTypes=
{};this.extents=this.getBookmarkExtents(a.appConfig)},start:function(){this.showLoading("sl-get-lyobj");this._tryGetLayerObject("sl-get-lyobj").then(function(){this.hideLoading("sl-get-lyobj");this.awake();this._listenEventsContinuousAccessFeatures()}.bind(this),function(a){console.error(a.message||a);this.hideLoading("sl-get-lyobj");this._onFailed()}.bind(this))},awake:function(){this.sleeping=!1;this._getFeaturesForFirst()},sleep:function(){this.sleeping=!0},destroy:function(){this._loadingTypes=
{};this._removeHandles();this.inherited(arguments)},_getFeaturesForFirst:function(){this._trigerCallback()},_listenEventsContinuousAccessFeatures:function(){if(this.layerObject&&this.layerInfo){var a=this._shouldAccessClientFeatures();this.useSelection&&(this._resetSelectionHandle(),this.selectionHandle=n(this.layerObject,"selection-complete,selection-clear",f.hitch(this,function(){this._trigerCallback()})));a||(this._resetFilterChangedHandle(),this.filterChangedHandle=n(this.layerInfo,"filterChanged",
f.hitch(this,function(b){b&&b.zoomAfterFilter&&this.filterByExtent||this._trigerCallback()})));a&&(this._resetUpdateEndHandle(),this.updateEndHandle=n(this.layerObject,"update-end",f.hitch(this,function(){this._trigerCallback()})));this.filterByExtent&&this.map&&(this._resetExtentChangeHandle(),this.exchetChangeHandle=n(this.map,"extent-change",f.hitch(this,function(){this.emit("start");this._trigerCallback(!0)})));a||(this._setTimeListener(),this._resetRefreshIntervalHandle(),this.refreshIntervalHandle=
n(this.layerObject,"refresh-interval-change",f.hitch(this,this._setTimeListener)))}},_setTimeListener:function(){var a=this._getLayerRefreshInterval();a?(this._resetTimeIntervalHandle(),this.timeIntervalHandle=setInterval(f.hitch(this,function(){this._trigerCallback()}),6E4*a)):this._resetTimeIntervalHandle()},_trigerCallback:function(a){var b=this.computingTheWayToGetFeatures();if(!a||2!==b||!this._isLayerOnDemandMode())switch(this.emit("start"),b){case 1:this._getFeaturesFromSelection(this.map,
this.layerObject,this.filterByExtent,f.hitch(this,this._onDataUpdate));break;case 2:this._getClientFeaturesFromMap(this.map,this.layerObject,this.filterByExtent,f.hitch(this,this._onDataUpdate));break;case 3:this._getStatisticsFeaturesForServer(f.hitch(this,this._onDataUpdate))}},computingTheWayToGetFeatures:function(){var a=0;return this.sleeping||!this.layerObject?a:a=this._isMapLayer()?this._shouldAccessFeaturesBySelection()?1:this._shouldAccessClientFeatures()?2:3:0},_getClientFeaturesFromMap:function(a,
b,c,e){var d=b.graphics;c&&(d=this._filterFeaturesByExtent(a.extent,d));d=this._sortClientFeaturesByObjID(d,b);e(d)},_getFeaturesFromSelection:function(a,b,c,e){var d=[],g=!1;d=b.getSelectedFeatures();g=!0;c&&(d=this._filterFeaturesByExtent(a.extent,d));d.isSelectedFeatures=g;d=this._sortClientFeaturesByObjID(d,b);e(d)},_getStatisticsFeaturesForServer:function(a){this._updateLayerInfoFilter();this._tryGenerateQueryParameter();this._shouldLaunchQuery()&&(this.showLoading("sl-sev-st"),this.queryDeferred=
this._doQuery(),this.queryDeferred.then(f.hitch(this,function(b){this.queryDeferred=null;this.hideLoading("sl-sev-st");b=b.features||[];b=this._calculateAverageWithNullValueAsZero(b,this.config);a(b,!0)}),f.hitch(this,function(b){this.queryDeferred=null;console.error(b.message||b);this.hideLoading("sl-sev-st");this._onFailed("sl-sev-st")})))},_updateLayerInfoFilter:function(){if(this.dataSource&&"undefined"!==typeof this.dataSource.layerId){var a=this.layerInfosObj.getLayerInfoById(this.dataSource.layerId);
a&&(this._layerFilter=a.getFilter())}},_onFailed:function(){this.emit("failed")},hideLoading:function(a){this._loadingTypes[a]=!1;this._shouldHideLoading()&&this._hideLoading()},showLoading:function(a){this._loadingTypes[a]=!0;this._showLoading()},_showLoading:function(){this.emit("loading",this.uniqueID)},_hideLoading:function(){this.emit("unloading",this.uniqueID)},_shouldHideLoading:function(){if(this._loadingTypes)return Object.keys(this._loadingTypes).map(function(a){return this._loadingTypes[a]}.bind(this)).every(function(a){return!a})},
_onDataUpdate:function(a,b){a=this._getValueByFeatures(a,b);this.emit("data-update",a);setTimeout(function(){this.emit("done")}.bind(this),500)},_getValueByFeatures:function(a,b){if(!a||!a.length)return null;var c=null;this.returnFeatures?a&&(c={features:a,hasStatisticsed:!!b}):c=this._getValueForNumber(a);return c},_getValueForNumber:function(a){return this._isNeededCalculateForClient()?t.statistic(this.statistic,this.dataSource,a):t.getSingleValueForServerStatFeature(a)},_isMapLayer:function(){return"DATA_SOURCE_FEATURE_LAYER_FROM_MAP"===
this.dataSource.dataSourceType},_isLayerOnDemandMode:function(){return this.layerObject&&this.layerObject.currentMode===F.MODE_ONDEMAND},_shouldAccessFeaturesBySelection:function(){return this.useSelection&&this.layerObject&&this.layerObject.getSelectedFeatures().length},_shouldAccessClientFeatures:function(){var a=this.config&&this.config.data&&"feature"===this.config.data.mode,b=this.isDateType,c=this._isSupportServerStatByExtent();return a||b||!c},_isSupportServerStatByExtent:function(){var a=
this.layerObject&&this.layerObject.version&&10.11<=Number(this.layerObject.version),b=this._isLayerSupportStatistics();return a&&b},_isLayerSupportStatistics:function(){if(this.layerObject&&this.layerObject.url){var a=!1;return a=this.layerObject.advancedQueryCapabilities?!!this.layerObject.advancedQueryCapabilities.supportsStatistics:!!this.layerObject.supportsStatistics}},_getLayerRefreshInterval:function(){if(this.layerObject&&this.layerObject.refreshInterval)return this.layerObject.refreshInterval},
_sortClientFeaturesByObjID:function(a,b){if(0<a.length){var c=q.getObjectIdField(b);c&&(b=a[0])&&b.attributes&&b.attributes.hasOwnProperty(c)&&a.sort(function(e,d){e.attributes||(e.attributes={});d.attributes||(d.attributes={});e=e.attributes[c];d=d.attributes[c];return e<d?-1:e>d?1:0})}return a},_filterFeaturesByExtent:function(a,b){var c=a.normalize();return b=b.filter(f.hitch(this,function(e){try{if(e.geometry){var d="point"===e.geometry.type||"multipoint"===e.geometry;return c.some(f.hitch(this,
function(g){return d?g.contains(e.geometry):B.intersects(g,e.geometry)}))}}catch(g){console.error(g)}return!1}))},_calculateAverageWithNullValueAsZero:function(a,b){if(!this._shouldCalcAvgForNullValue(b)||!a||!a.length)return a;b=b.data&&b.data.valueFields;if(!b||!b.length)return a;var c=b.map(function(e){return e+"_sum"});a.forEach(function(e){var d=e.attributes;if(d){var g=d.STAT_COUNT;"undefined"===typeof g?(g=d.stat_count,delete d.stat_count):delete d.STAT_COUNT;var h,k,u;c.forEach(function(m){u=
m.replace(/_SUM$/gi,"");var v=l.upperCaseString(m);m=l.lowerCaseString(m);var w=l.upperCaseString(u+"_AVG");h=d[v];"undefined"===typeof h?(h=d[m],delete d[m]):delete d[v];!h&&"number"!==typeof h||!g?d[w]=null:(k=h/g,d[w]=k)})}});return a},_shouldCalcAvgForNullValue:function(a){var b=a&&a.data&&a.data.mode,c=a&&a.data&&a.data.operation;a=a&&a.data&&a.data.nullValue;return b&&("category"===b||"field"===b)&&a&&"average"===c},_shouldLaunchQuery:function(){var a=!0,b=!(!this.queryDeferred||this.queryDeferred.isResolved()||
this.queryDeferred.isRejected()),c=q.isEqual(this._queryParameter,this._oldQueryParameter);b&&c&&(a=!1);this._oldQueryParameter=f.clone(this._queryParameter);return a},_getOutStatistics:function(a){var b=a.fields,c=a.type,e=a.nullValue,d=c;e&&"avg"===c&&(d="sum");a=null;b&&b.length?(a=b.map(function(g){var h=l.upperCaseString(g+"_"+d),k=new p;k.statisticType=d;k.onStatisticField=g;k.outStatisticFieldName=h;return k}.bind(this)),e&&"avg"===c&&(b=new p,b.statisticType="count",b.onStatisticField=this._getStatisticsFieldForCountType(this.layerObject),
b.outStatisticFieldName="STAT_COUNT",a.push(b))):(b=new p,b.statisticType="count",b.onStatisticField=this._getStatisticsFieldForCountType(this.layerObject),b.outStatisticFieldName="STAT_COUNT",a=[b]);return a},_tryGenerateQueryParameter:function(){this._queryParameter={};this._layerUrl&&(this._queryParameter.url=this._layerUrl);this._layerFilter&&(this._queryParameter.where=this._layerFilter);if(this.returnFeatures)this.statistic&&(this._queryParameter.outStatistics=this._getOutStatistics(this.statistic),
this.statistic.groupByFields&&(this._queryParameter.groupByFieldsForStatistics=this.statistic.groupByFields));else if(this.statistic){var a=this.statistic.type;var b=this.statistic.field;var c=l.upperCaseString(b+"_"+a);"count"===this.statistic.type&&(b=this._getStatisticsFieldForCountType(this.layerObject),c="STAT_COUNT");var e=new p;e.statisticType=a;e.onStatisticField=b;e.outStatisticFieldName=c;this._queryParameter.outStatistics=[e]}},_getStatisticsFieldForCountType:function(a){var b=null;a&&
(b=(a=(a=a.fields)&&a.filter(function(c){return c.type===this.oidFieldType}.bind(this))[0])&&a.name);return b||"*"},_doQuery:function(){var a=new r;if(!this._queryParameter)return a.reject("Empty query parameter."),a;if(!this._queryParameter.url)return a.reject("Empty layer url."),a;var b=new E(this._queryParameter.url),c=new D;c.where=this._queryParameter.where||"1\x3d1";c.returnGeometry=!1;if(this.dataSource.filterByExtent&&this.map){var e=this.map.extent;c.geometry=e;c.cacheHint=this.supportCacheHint(e)}this._queryParameter.groupByFieldsForStatistics&&
(c.groupByFieldsForStatistics=this._queryParameter.groupByFieldsForStatistics);if(this._hasVaildOutStatistics(this._queryParameter.outStatistics))c.outStatistics=this._queryParameter.outStatistics;else return a.reject("Invaild outStatistics of query params."),a;this._queryParameter.orderByFields&&(c.orderByFields=this._queryParameter.orderByFields);return b.execute(c)},_hasVaildOutStatistics:function(a){return a&&a.length?a.every(function(b){return this._isTrueOrZero(b.onStatisticField)&&this._isTrueOrZero(b.outStatisticFieldName)&&
!!b.statisticType}.bind(this)):!1},_isTrueOrZero:function(a){return!!a||0===a},_tryGetLayerObject:function(){var a=new r;if("DATA_SOURCE_FEATURE_LAYER_FROM_MAP"!==this.dataSource.dataSourceType)return a.resolve(),a;var b=this.layerInfosObj.getLayerInfoById(this.dataSource.layerId);if(b)return this.layerInfo=b,this.layerObject?(this._layerUrl=this.layerObject.url,a.resolve(),a):b.getLayerObject().then(f.hitch(this,function(c){this.layerObject=c;this._layerUrl=this.layerObject.url}));a.reject("invaild data source");
return a},_isNeededCalculateForClient:function(){var a=this.layerObject&&this.useSelection&&0<this.layerObject.getSelectedFeatures().length,b=this._isSupportServerStatByExtent();return a||!b},_resetExtentChangeHandle:function(){this.exchetChangeHandle&&this.exchetChangeHandle.remove&&(this.exchetChangeHandle.remove(),this.exchetChangeHandle=null)},_resetUpdateEndHandle:function(){this.updateEndHandle&&this.updateEndHandle.remove&&(this.updateEndHandle.remove(),this.updateEndHandle=null)},_resetFilterChangedHandle:function(){this.filterChangedHandle&&
this.filterChangedHandle.remove&&(this.filterChangedHandle.remove(),this.filterChangedHandle=null)},_resetSelectionHandle:function(){this.selectionHandle&&this.selectionHandle.remove&&(this.selectionHandle.remove(),this.selectionHandle=null)},_resetRefreshIntervalHandle:function(){this.refreshIntervalHandle&&this.refreshIntervalHandle.remove&&(this.refreshIntervalHandle.remove(),this.refreshIntervalHandle=null)},_resetTimeIntervalHandle:function(){this.timeIntervalHandle&&(clearInterval(this.timeIntervalHandle),
this.timeIntervalHandle=null)},_removeHandles:function(){this._resetExtentChangeHandle();this._resetUpdateEndHandle();this._resetFilterChangedHandle();this._resetSelectionHandle();this._resetRefreshIntervalHandle();this._resetTimeIntervalHandle();this._resetSelectionHandle()},supportCacheHint:function(a){return this.appConfig?(this.extents||[]).some(function(b){b=this.getTargetExtent(b);return this.isSameExtent(a,b)}.bind(this)):!1},getBookmarkExtents:function(a){a=this.getBookmarkConfig(a);return this.getExtendsFromBookmarkConfigs(a)},
getBookmarkConfig:function(a){if(!a)return[];var b=[];b=b.concat(a.widgetOnScreen&&a.widgetOnScreen.widgets||[]);b=b.concat(a.widgetPool&&a.widgetPool.widgets||[]);(a.widgetPool&&a.widgetPool.groups||[]).forEach(function(c){b=b.concat(c.widgets)});return b.filter(function(c){return"Bookmark"===c.name}).map(function(c){return c.config})},getExtentsFormBookmarkConfig:function(a){if(a&&a.bookmarks2D&&a.bookmarks2D.length)return a.bookmarks2D.map(function(b){return b.extent})},isSameExtent:function(a,
b){a=this.getCleanExtent(a);b=this.getCleanExtent(b);return l.isEqual(a,b)},getTargetExtent:function(a){return this.map&&this.map.getTargetExtent?this.map.getTargetExtent(new C(a)):a},getCleanExtent:function(a){if(a)return{xmax:a.xmax,xmin:a.xmin,ymax:a.ymax,ymin:a.ymin}},getExtendsFromBookmarkConfigs:function(a){var b=[];a.forEach(function(c){c=this.getExtentsFormBookmarkConfig(c)||[];b=b.concat(c)}.bind(this));return b}})});