/**
 * 初始化 kendo ui Table 的封装
 * 约定：toolbar的id为 (kdtableId + "Toolbar")
 * @author LiaoYun 2019-09-17  945505778@qq.com
 */
(function () {
	var KDTable = function (kdtableId, url, columns) {
		this.kdtableId = kdtableId;
		this.url = Feng.ctxPath + url;
		this.method = "post";
		this.columns = columns;
		this.height = "";						                                    //默认表格高度665
		this.scrollable = true;
		this.selectable = true;                                                     //是否允许选择
		this.groupable = false;                                                     //是否允许分组
		this.serverPaging = true;                                                   //服务端分页
		this.sortable = false;                                                      //是否允许排序
		this.serverSorting = false;                                                 //服务端排序
		this.filterable = false;                                                    //是否允许过滤
		this.serverFiltering = false;                                               //服务端过滤
		this.pageSize = 10;                                                         //每次分页加载18条数据
		this.resizable = true;                                                      //表格宽度允许拖动
		this.reorderable = true;                                                    //是否允许拖动列来改变列的显示顺序
		this.columnMenu = true;
		this.alwaysVisible = false;                                                 //是否在列表数据没有达到分页时显示分页组件
		this.readData = {};                                                         //后台传递的自定义参数
		this.queryParams = {};                                                      //固定的查询条件
		this.fields = {};                                                           //data type of the field {number|string|boolean|date} default is string
		if (columns!=null && columns.length>0) {
			// 添加序号列
			columns.unshift({field: "rowNumber", title: "序号", width:"80px", template: "<span class='row-number'></span>"});
			for(var i=0; i<columns.length; i++){
				var temp = columns[i];
				if (!temp) {
					break;
				}
				if (temp.type!=null && temp.type!='' && typeof(temp)!="undefined") {
					this.fields[temp.field] = {'type': temp.type};
				} else {
					this.fields[temp.field] = {'type': 'string'};
				}
			}
		}
	};
	
	KDTable.prototype = {
		/**
         * 初始化kendo table
         */
		init: function() {
			var tableId = this.kdtableId;
			var me = this;
			this.btInstance = $("#" + tableId).kendoGrid({
				dataSource:{
					transport:{
						read: {
							url: this.url,                                          //The remote service url.
							type: this.method,                                      //The request type.
							dataType: "json",                                       //The data type of the returned result.
							contentType: "application/x-www-form-urlencoded",
							data: this.readData                                     //The additional custom parameters sent to the remote service.
						},
						parameterMap: function(options, operation){
							console.log("====> 查询数据 ======");
							console.log(options);
							if (operation == "read") {
								var parameter = {};
								$.each(options, function(name, value){
									if (name === 'take') {
										parameter.limit = value;
									} else if (name === 'skip') {
										parameter.offset = value
									} else if (name === 'sort') {
										parameter.sort = value[0].field;
										parameter.order = value[0].dir
									} else if (name === 'page') {
										
									} else if (name === 'pageSize'){
										
									}else {
										parameter[name] = value;
									}
								});
								//设置固定的查询条件
								if (me.queryParams) {
									$.each(me.queryParams, function(name, value){
										parameter[name] = value;
									});
								}
								// 如果有动态查询条件
								if (me.readData) {
									$.each(me.readData, function(name, value){
										parameter[name] = value;
									});
								}
								return parameter;
							}
						}
					},
					schema: {
						data: "rows",
						total: "total"
					},
					pageSize: this.pageSize,
					serverPaging: this.serverPaging,
					sortable: this.sortable,
					serverSorting: this.serverSorting,
					alwaysVisible: this.alwaysVisible
				},
				// 设置分页的序号
				dataBound: function() {
					var rows = this.items();
					var page = this.pager.page() - 1;
					var pagesize = this.pager.pageSize();
					$(rows).each(function () {
						var index = $(this).index() + 1 + page * pagesize;
						var rowLabel = $(this).find(".row-number");
						if (rowLabel && rowLabel.length>0) {
							$(rowLabel).html(index);
						}
					});
				},
				columns: this.columns,
				fields: this.fields,
				height: this.height,
				scrollable: this.scrollable,
				selectable: this.selectable,
				groupable: this.groupable,
				filterable: this.filterable,
				serverFiltering: this.serverFiltering,
				resizable: this.resizable,
				columnMenu: this.columnMenu,
				reorderable: this.reorderable,
				sortable: this.sortable,
				serverSorting: this.serverSorting,
				pageable: {
			        refresh: true,
			        pageSizes: [10, 50, 100, 500, 1000],
			        buttonCount: 5
			    }
			});
			return this;
		},
		/**
         * 向后台传递的自定义参数
         * @param param
         */
        setQueryParams: function (param) {
            this.readData = param;
        },
        clearQueryParams: function() {
        	this.readData = {};
		},
        /**
         * 设置分页  server | client
         */
        setPaginationType: function(val) {
        	if (val === "server") {
        		this.serverPaging = true;
			} else if (val === "client") {
				this.serverPaging = false;
			}
		},
		/**
		 * 设置数据过滤方式 server | client
		 */
		setFilterType: function(val) {
			if (val === "server") {
				this.filterable = true;
        		this.serverFiltering = true;
			} else if (val === "client") {
				this.filterable = true;
			}
		},
		/**
		 * 设置排序 server | client
		 */
		setSortType: function(val) {
			if (val === "server") {
				this.sortable = true;
        		this.serverSorting = true;
			} else if (val === "client") {
				this.sortable = true;
			}
		},
		/**
		 * 选择方式 true or false or 'row' or 'multiple row' or 'cell' or 'multiple cell'
		 */
		setSelectable: function(bl) {
			this.selectable = bl;
		},
		getSelections: function() {
			var grid = $("#"+this.kdtableId+",.k-grid-content").data("kendoGrid");
//			var grid = $("#"+this.kdtableId).data("kendoGrid");
			var selected = [];
			var rows = grid.select();
//			console.log(rows);
			for(var i=0; i<rows.length; i++){
				var temp = rows.eq(i);
				var className = temp.parent().parent().parent().attr("class");
//				console.log("class=" + temp.parent().parent().parent().attr("class"));
				if (className === 'k-grid-content-locked') {
					continue;
				}
				selected.push(grid.dataItem(rows[i]))
			}
			return selected;
		},
		refresh: function(val) {
			// 清空历史动态查询条件
			this.readData = {};
			var grid = $("#"+this.kdtableId).data("kendoGrid");
			if (val && val.query) {
				var filter = [];
				var flag = false;
				for (var key of Object.keys(val.query)) {
					// console.log(key + ': ' + val.query[key]);
					var value = val.query[key];
					if (value!=null && value!='' && typeof(value)!="undefined") {
						this.readData[key] = value;
						flag = true;
					}else {
						delete val.query[key];
					}
				}
				if (flag && this.serverSorting) {
					val.query.page = 1;
					val.query.pageSize = this.pageSize;
					val.query.take = this.pageSize;
					val.query.skip = 0;
					grid.dataSource.query(val.query);
				} else {
					grid.dataSource.read();
				}
			} else {
				grid.dataSource.read();
			}
		},
		/**
		 * 设置固定的查询条件 {name1:value1, name2:value2}
		 */
		setConstantQueryParams: function(val) {
			if (val != null) {
				var temp = {};
				$.each(val, function(name, value){
					if (value!=null && value!='' && typeof(value)!="undefined") {
						temp[name] = value;
					}
				});
				this.queryParams = temp;
			}
		},
		/**
		 * 设置每页查询条数
		 */
		pageSize: function(val) {
			this.pageSize = val;
		}
	};
	
	window.KDTable = KDTable;
}());