BarChart_wev8.js 9.41 KB
define(['mUtil', "Component", "wev-loading","chartHelper"],function(mUtil, Component, WevLoading,chartHelper) {
	var BarChart = function(options) {
		var _barChart = {}, $errorTip, $chartContainer;
		
		Component.super(this, options);
		
		this.type = "BarChart";
		this.tpl = this.type + "_html";
		this.css = "chart_css";
		
		this.components = {
			loading: new WevLoading({
				delay: 300,
				animation: 1
			})
		};

		var vm = this.viewModel = {
			data : [],
			dataAxis : "xAxis",//xAxis 横向 yAxis 纵向
			height : 300,//图表高度
			title : {
				show : false,
				x : "center",
				y : 0,
				text : "",//标题
				subtext: ""//副标题
			},
			grid : {},
			legend : {
				show : true,//是否显示图例
				bottom : 0,//图例底部边距
				textStyle : {
					color : "#333"//字体颜色
				}
			},
			axisLabel : {
				interval : 'auto',//坐标标签间隔,0表示显示所有坐标
				rotate : 0,//坐标标签旋转角度
				fontSize : 12//坐标标签字体大小

			},
			isShowMarkPoint : false,//在最大和最小柱状上显示具体的数值
			isShowMarkLine : false,//在图表上显示一根平均值的标线
			color:"#c23531,#2f4554,#61a0a8,#d48265,#91c7ae,#749f83,#ca8622,#bda29a,#6e7074,#546570,#c4ccd3",//颜色,默认
			labelFormat:"",
			advancedSearch: {},
			standalone : true
		};
		
		this.beforeMount = function(){
			var style = "";
			var height = parseFloat(vm.height) || 300;
			var width = parseFloat(vm.width);

			style += "height:" + height + "px;";
			style += width && ("width:" + width + "px;") || "";

			vm.style = style;

			if(mUtil.isString(vm.click) && vm.click != ""){
				var dataurl = vm.click;
				vm.click = function(params){
					var url = dataurl.replace(/\{_chart_name}/g, params.name).replace(/\{_chart_seriesName}/g, params.seriesName).replace(/\{_chart_value}/g, params.value);
					$u(url);
				};
			}

			vm.title = vm.title.text || '';
			var grid = vm.grid;
			if (vm.dataAxis == 'yAxis') {
				grid.right = grid.right || (vm.isShowMarkLine ? 30 : 12);
				grid.top = vm.isShowMarkPoint ? 45 : 15;
			} else {
				grid.right = grid.right || (vm.isShowMarkPoint ? 20 : 12);
				grid.top = vm.isShowMarkPoint ? 45 : (vm.isShowMarkLine ? 20 : 15);
			}
			grid.left = grid.left || 10;
			grid.bottom = vm.legend.show ? 35 : 10;
			grid.containLabel = true;

			vm.grid = grid;
		};
		
		this.mounted = function(){
			$errorTip = this.$el.find(".wev-error");
			$chartContainer = this.$el.find(".wev-chart");
			
			this.refresh();
		};
		
		this.refresh = function(){
			var loading = this.components.loading;

			loading.setRefs(this.$comp, "wev-refreshing");
			loading.show();
			
			var hideLoading = loading.hide.bind(loading);

			if(vm.standalone && mUtil.isArray(vm.data)){
				_barChart.buildChart(vm.data, hideLoading);
            } else {
				_barChart.loadData(hideLoading);
            }
		};
		
		this.cacheSearchLast = function(searchLast){//上一次查询参数map
			vm.searchLast = searchLast;
		};

		_barChart.loadData = function(callback) {
			var actionUrl = vm.data;
			var that = this;
			var timestamp = new Date().valueOf();    //时间戳

			that.timestamp = timestamp;

            if(!vm.standalone) {
				actionUrl = mUtil.getActionUrl(this.type, { action: "getDatas", "mec_id": vm.id }, this.pageid);
			} 
			
			if (!actionUrl) return;

			mUtil.getJSON(actionUrl, {}, function (result) {
				if (timestamp != that.timestamp) return;

				_barChart.buildChart(result.data, callback);
				$errorTip.html("").hide();
				
				if (!vm.advancedSearch.enable) return;
				vm.toolbox = {
					showTitle: false,
					itemSize: 28,
					right: vm.grid.right || 20,
					top: vm.grid.top || 20,
					feature: {
						myTool: {
							show: true,
							icon: 'image:///mobilemode/mobile/images/plugin/filter.png',
							onclick: function () {
								require(["mService"], function (mService) {
									mService.show("customsearch", {
										id: that.id,
										pageid: that.pageid,
										searchLast: vm.searchLast || {},
										conditions: vm.advancedSearch.asFields,
										title: vm.title || ""
									});
								});
							}
						}
					}
				};
			}, function(res){
				$errorTip.html(res).show();
				$chartContainer.hide();
				mUtil.isFunction(callback) && callback.call(this);
			});
		};
		
		_barChart.buildChart = function(datas, callback) {
			var that = this;
			
            require(["echarts"], function(echarts){
            	// 基于准备好的dom,初始化echarts实例
    			var theChart = echarts.init($chartContainer[0]);
    			
    			var op_legend_data = [];
    			
    			var op_category_data = [];
    			
    			var op_series_meta = [];
    			
    			for(var i = 0; i < datas.length; i++){
    				var da = datas[i];
    				
    				var j = 0;
    				for(var key in da){
    					var value = da[key];
    					if(i == 0 && j > 0){
    						op_legend_data.push(key);
    					}
    					if(j == 0){
    						op_category_data.push(value);
    					}
    					if(j > 0){
    						var op_series_one = op_series_meta[j - 1];
    						if(!op_series_one){
    							op_series_one = {};
    							op_series_meta[j - 1] = op_series_one;
    						}
    						if(i == 0){
    							op_series_one.name = key;
    						}
    						var op_series_one_data = op_series_one.data;
    						if(!op_series_one_data){
    							op_series_one_data = [];
    							op_series_one.data = op_series_one_data;
    						}
    						op_series_one_data.push(value);
    					}
    					j++;
    				}
    			}
    			
    			var op_markPoint_show = vm.isShowMarkPoint;
    			var op_markLine_show = vm.isShowMarkLine;

				var op_series = [], colorArr = [];
				if (vm.color) colorArr = vm.color.split(",");
				var isSingle = op_series_meta.length == 1 && colorArr.length > 0;

    			for(var i = 0; i < op_series_meta.length; i++){
					var series_data = op_series_meta[i]["data"];
					var max = Math.max.apply(null, series_data),
						min = Math.min.apply(null, series_data);
					if (isSingle) {
						series_data = [];
						op_series_meta[i]["data"].forEach(function (item, index) {
							if (max == item) max = index;
							if (min == item) min = index;
							series_data.push({
								value: item,
								itemStyle: {
									color: colorArr[index%colorArr.length]
								}
							});
						});
					}
    				var op_series_one = {
    			        name: op_series_meta[i].name,
    			        type: 'bar',
    			        data: series_data,
									barMaxWidth: 35
						};
    				if(op_markPoint_show){
    					op_series_one.markPoint = {
    		                data : [
								{ type: 'max', name: '最大值', itemStyle: {
									color: isSingle ? colorArr[max] : null
								}},
								{ type: 'min', name: '最小值', itemStyle: {
									color: isSingle ? colorArr[min] : null
								}}
    			            ],
    		                symbolSize : 50,
	   		                itemStyle: {
	   				                normal: {
	   				                    label: {
	   				                        show: true,
	   				                        formatter:function(obj){
	   				                        	return chartHelper.formatNumber(obj.value, vm.labelFormat);
	   						                }
	   				                     }
	   		                		}
	   		                }
    		            };
    				}
    				if(op_markLine_show){
    					op_series_one.markLine = {
    		                data : [
    		                    {type : 'average', name: '平均值'}
    		                ],
    		                itemStyle: {
    				              normal: {
    				                  label: {
    				                      show: true,
    				                      formatter:function(obj){
    				                    	  return chartHelper.formatNumber(obj.value, vm.labelFormat);
    						              }
    				                   }
    				              }
    		                }
    					};
    				}

    				op_series.push(op_series_one);
    			}
    			
    			var dataAxis = vm.dataAxis || "yAxis";
    			
    			//图例
    			var legend = vm.legend;
    			//图例数据
    			legend.data = op_legend_data; //['蒸发量','降水量'],
					legend.bottom = 5;

					var categoryAxis = [{
    				type : 'category',
    				data : op_category_data,
    				axisLabel : vm.axisLabel
    			}];
    			var valueAxis = [{
    				type : 'value'
    			}];

    			var option = {
							tooltip: {
								trigger: 'axis',
								axisPointer: {
									type: 'shadow'
								},
								confine: true,
								position: function (point, params, dom, rect, size) {
									dom.style.transform = "translateZ(0)";
								}
							},
    			    grid: vm.grid,
    			    legend: legend,
    			    calculable : true,
    			    xAxis : (dataAxis == "yAxis") ? categoryAxis : valueAxis,
    			    yAxis : (dataAxis == "yAxis") ? valueAxis : categoryAxis,
    			    series : op_series,
    			    toolbox : vm.toolbox
    			};
    			
				var color = vm.color;

    			if(color){
    				option.color = color.split(",");
    			}
    			
    			// 使用刚指定的配置项和数据显示图表。
    			theChart.setOption(option);
    			
    			if(vm.click && mUtil.isFunction(vm.click)){
    				theChart.on('click', function (params) {
    					vm.click.call(this, params);
    				});
    			}
				
				mUtil.isFunction(callback) && callback.call(this);
            });
		};

		_barChart.buildChart = _barChart.buildChart.bind(this);
		_barChart.loadData = _barChart.loadData.bind(this);
    };

    return Component.init(BarChart);
});