;
(function($) {
		$.fixed_table = {
			getTdObjJson:function(param,fieldMap){
				var tdObj = JSON.parse(JSON.stringify(param));
				if(tdObj && !$.isEmptyObject(tdObj)){
					// console.log(JSON.stringify(tdObj));
					var text = tdObj.text;
					if(text.indexOf('@find:')==0){
						//说明需要动态取值
						var dataKey = text.replace('@find:',''); 
						tdObj.text = fieldMap[dataKey]; 
					}
					var ext = tdObj.ext;
					if(ext && !$.isEmptyObject(ext)){
						$.each(ext,function(key,value){
							if($.isEmptyObject(value)){
								return;
							}
							if(value.indexOf('@find:')==0){
								//说明需要动态取值
								var dataKey = value.replace('@find:',''); 
								// console.log(value+"---"+fieldMap[dataKey])
								ext[key] = fieldMap[dataKey]; 
							}
						});
					}
				}
				return tdObj;
			},
			getTableJson: function(data, fields) {
				if (!data || data.length == 0) {
					return {};
				}
				var json = {};
				var rows = [];
				$.each(data, function(i, item) {
					var cols = [];
					$.each(fields, function(k, field) {
						if($.isPlainObject(field)){
							var tdObj = $.fixed_table.getTdObjJson(field,item);
							cols.push(tdObj);
						}else{
							cols.push({
								text:item[field]
							});
						}
					});
					rows.push({
						"cols": cols
					});
				});
				json.rows = rows;
				return json
			}
		}
		$.fn.fixed_table = function(options) {
			var defaults = {
				winMarginBottom: 53,
				emptyMsg: '',
				leftColStyles: [{
					background: '#ffaa00'
				}, {
					background: '#ffaa00'
				}], 
				leftTop: undefined,
				leftBottom: undefined,
				rightTop: undefined,
				rightBottom: undefined,
				orderActiveClass: 'fixed-order-active',
				cache: {
					leftEl: undefined,
					leftTopEl: undefined,
					leftBottomeEl: undefined,
					leftTopTableEl: undefined,
					leftBottomTableEl: undefined,

					rightEl: undefined,
					rightTopEl: undefined,
					rightBottomEl: undefined,
					rightTopTableEl: undefined,
					rightBottomTableEl: undefined
				}
			};

			var options = $.extend(defaults, options);
			return this.each(function() {
					var $$this = $(this);
					//清空当前对象
					$(this).html('');
					if (!options.leftTop || $.isEmptyObject(options.leftTop) ||
						!options.leftBottom || $.isEmptyObject(options.leftBottom) ||
						!options.rightTop || $.isEmptyObject(options.rightTop) ||
						!options.rightBottom || $.isEmptyObject(options.rightBottom)) {
						$(this).html(options.emptyMsg);
						return;
					}
					//初始化左边壳
					initLeftWrapper(this);
					//初始化左上角
					initLeftTop(this);
					//初始化左下角
					initLeftBottom(this);

					//初始化右边壳
					initRightWrapper(this);
					//初始化右上角
					initRightTop(this);
					//初始化右下角
					initRightBottom(this);

					//初始化左上角
					function initLeftTop(obj) {
						//创建左大列
						var leftEl = options.cache.leftEl;
						//左上角的div
						var leftTopEl = options.cache.leftTopEl = $('<div class="left-top"></div>');
						leftEl.append(leftTopEl);

						//左上表格
						var leftTopTableEl = options.cache.leftTopTableEl = $('<table></table>');
						leftTopEl.append(leftTopTableEl);

						fillTable(leftTopTableEl, options.leftTop.rows);
					}

					function initLeftWrapper(obj) {
						var leftEl = options.cache.leftEl = $('<div class="left"></div>');
						//添加左大列
						$(obj).append(leftEl);
					}

					//初始化左下角
					function initLeftBottom(obj) {
						//左大列
						var leftEl = options.cache.leftEl;
						//左下角的div
						var leftBottomeEl = options.cache.leftBottomeEl = $('<div class="left-bottom"></div>');
						leftEl.append(leftBottomeEl);
						//左下角表格
						var leftBottomTableEl = options.cache.leftBottomTableEl = $('<table></table>');
						leftBottomeEl.append(leftBottomTableEl);
						//填充表格数据
						fillTable(leftBottomTableEl, options.leftBottom.rows)
						//设置数据库的宽度等样式
						initLeftColStyles();
					}

					function initRightWrapper(obj) {
						var rightEl = options.cache.rightEl = $('<div class="right"></div>');
						//添加右大列
						$(obj).append(rightEl);
					}

					//初始化右上角
					function initRightTop(obj) {
						//创建右大列
						var rightEl = options.cache.rightEl;
						//右上角的div
						var rightTopEl = options.cache.rightTopEl = $('<div class="right-top"></div>');
						rightEl.append(rightTopEl);

						//右上表格
						var rightTopTableEl = options.cache.rightTopTableEl = $('<table></table>');
						rightTopEl.append(rightTopTableEl);
						//填充数据
						fillTable(rightTopTableEl, options.rightTop.rows);
					}
					//给rightTop增加一行隐藏的行，方便设置宽度
					function insertHiddenRowToRightTopFirstRow(rightBottomTableRows) {
						if (rightBottomTableRows.length == 0) {
							return;
						}
						var firstRowCols = rightBottomTableRows[0].cols;
						var $row = $('<tr></tr>');
						$.each(firstRowCols, function(i, col) {
							$row.append('<td><div></div></td>');
						});
						options.cache.rightTopTableEl.prepend($row);
					}
					//初始化右下角
					function initRightBottom(obj) {
						//创建右大列
						var rightEl = options.cache.rightEl;
						//右下角的div
						var rightBottomEl = options.cache.rightBottomEl = $('<div class="right-bottom"></div>');
						rightEl.append(rightBottomEl);

						//右下表格
						var rightBottomTableEl = options.cache.rightBottomTableEl = $('<table></table>');
						rightBottomEl.append(rightBottomTableEl);
						//填充数据
						fillTable(rightBottomTableEl, options.rightBottom.rows);

						//给rightTop增加一行隐藏的行，方便设置宽度
						insertHiddenRowToRightTopFirstRow(options.rightBottom.rows);
					}

					//
					function initLeftColStyles() {
						var leftColStyles = options.leftColStyles;
						if (leftColStyles && leftColStyles.length > 0) {
							$.each(leftColStyles, function(i, item) {
								options.cache.leftBottomTableEl.find('tr td:nth-child(' + (i + 1) + ') div').css(item);
								options.cache.leftBottomTableEl.find('tr td:nth-child(' + (i + 1) + ')').css(item);
							});
						}
					}

					//填充表格数据
					function fillTable($el, data, thOrtd) {
						if (!data) return;
						$.each(data, function(i, row) {
							var $row = $('<tr></tr>');
							setRow($row, row);
							$.each(row.cols, function(j, col) {
								var $col = $('<td></td>');
								setCol($col, col);
								$row.append($col);
							});
							$el.append($row);
						});
					}


					//设置行的属性
					function setRow($row, data) {
						var id = data.id;
						var style = data.style;
						var ext = data.ext;

						if (id && $.trim(id) != '') {
							$row.attr('id', id);
						}
						if (style && !$.isEmptyObject(style)) {
							$row.css(style);
						}
						if (ext) {
							$.each(ext, function(key, value) {
								$row.attr(key, value);
							});
						}
					}
					//设置简单方式列，只有text文本的
					function setSimpleCol($col, text) {
						var $div = $("<div></div>");
						if (text && text != '') {
							$div.html(text);
							$col.append($div);
						} else {
							$col.html($div);
						}
					}
					//设置列的属性
					function setCol($col, data) {
						if (!$.isPlainObject(data)) {
							setSimpleCol($col, data);
							return;
						}
						var id = data.id;
						var order = data.order;
						var colspan = data.colspan;
						var rowspan = data.rowspan;
						var text = data.text;
						var style = data.style;
						var ext = data.ext;
						
						if (id && $.trim(id) != '') {
							$col.attr('id', id);
						}
						var $div = $("<div></div>");
						if (text && text != '') {
							$div.html(text);
							$col.append($div);
						} else {
							$col.html($div);
						}
						if (colspan && parseInt(colspan) > 1) {
							$col.attr('colspan', colspan);
						}
						if (rowspan && parseInt(rowspan) > 1) {
							$col.attr('rowspan', rowspan);
						}
						if (style && !$.isEmptyObject(style)) {
							$div.css(style);
						}
						if (order && !$.isEmptyObject(order)) {
							var orderField = order.orderField;
							var orderType = order.orderType;
							var active = order.active;
							if (orderType == undefined || orderType == 'asc') {
								$div.attr('orderField', orderField).addClass('orderField').append(
									'<span class="mui-icon mui-icon-arrowup"></span>');
							} else if (orderType == 'desc') {
								$div.attr('orderField', orderField).addClass('orderField').append(
									'<span class="mui-icon mui-icon-arrowdown"></span>');
							}
							if (active == true) {
								$div.children('span').addClass(options.orderActiveClass);
							}
						}
						if (ext) {
							$.each(ext, function(key,value) {
								$col.attr(key, value);
							});
						}
					}

					function updatePosition() {
						var a = this.y;
						var b = this.x;
						leftBottomTableEl.css('transform', 'translate(0px, ' + a + 'px) translateZ(0px)');
						rightTopTableEl.css('transform', 'translate(' + b + 'px, 0px) translateZ(0px)');
					}
					//动态计算容器最大高度
					function adjustWidthHeight() {
						var winHeight = win.height() - $$this.offset().top - options.winMarginBottom;
						var tableHeight = winHeight - rightTopTableEl.height();
						leftBottomEl.height(tableHeight);
						rightBottomEl.height(tableHeight);

						rightEl.css('margin-left', leftEl.width());
						rightEl.width($$this.width() - leftEl.width());
						if (rightBottomTableEl.width() < rightEl.width()) {
							rightBottomTableEl.width('100%');
						}

						//设置表头每列宽度
						setRightTopTableColWidths();

						//设置右边上下两个table的宽度
						setRightTopTableWidth();

						//设置leftBottom的表格的各行行高
						setLeftBottomTableRowHeights();
					}

					//设置右边上下两个table的宽度
					function setRightTopTableWidth() {
						rightTopTableEl.width(rightBottomTableEl.width());
					}
					//设置表头每列宽度
					function setRightTopTableColWidths() {
						//获取列宽
						var colWitdhs = getRigthBottomTableColWidths();
						if (!colWitdhs || colWitdhs.length == 0)
							return;
						//查询	rightTopTable 是否有跨行的列，如果有，不考虑跨列的情况
						// 如果没有跨行的，上下高度都可适应

						var rowSpanTop1Count = rightTopTableEl.find('td').filter(function() {
							return $(this).attr('rowspan') > 1;
						}).length;
						
						var rightTopTableRows;
						if(rowSpanTop1Count>0){
							rightTopTableRows = rightTopTableEl.find('tr:first');
						}else{
							rightTopTableRows = rightTopTableEl.find('tr');
						}

					$.each(rightTopTableRows, function(k) {
						var index = 0;
						var rightBottomTableFirstTrEl = options.cache.rightBottomTableEl.find('tr:first');
						$.each($(this).find('td'), function(i) {
							var colspan = $(this).attr('colspan');
							var colCount = 1;
							if (colspan && parseInt(colspan) > 1) {
								//如果当前合并了单元格
								colCount = parseInt(colspan);
							}
							var w = calculateColWidth(index, colCount, colWitdhs);
							var curWidth = $(this).find('div').width();
							if (w < curWidth && colCount == 1) {
								var $td = rightBottomTableFirstTrEl.find('td:eq(' + (index) + ')');
								$td.find('div').width(curWidth);
								$(this).find('div').width(curWidth);
							} else {
								$(this).find('div').width(w);
							}
							index += colCount;
						});
					});
				}

				//获取列宽
				function getRigthBottomTableColWidths() {
					var firstTrDivs = rightBottomTableEl.find('tr:first>td>div');
					var colWitdhs = [];
					if (firstTrDivs) {
						//查询表格的自然宽度是否超过了手机宽度，如果超过了 要给每一个单元格加宽
						var offsetWidth = win.width() - leftEl.width() - rightBottomTableEl.width() - 15;
						var oneColOffsetWidth = 0;
						if (offsetWidth > 0) {
							oneColOffsetWidth = offsetWidth / firstTrDivs.length;
						}
						$.each(firstTrDivs, function(i) {
							var width = $(this).width() + oneColOffsetWidth;
							$(this).width(width)
							colWitdhs.push(width);
						});
					}
					return colWitdhs;
				}

				//计算单个单元格的宽度
				function calculateColWidth(index, colspan, colWitdhs) {
					var width = 0;
					for (var i = 0; i < colspan; i++) {
						width += colWitdhs[index + i]
					}
					return width;
				}

				//获取行高
				function getRigthBottomTableRowHeightsAndIsMultipleLineInfos() {
					var rowInfos = [];
					var rows = rightBottomTableEl.find('tr');
					if (rows && rows.length > 0) {
						$.each(rows, function() {
							var tr = $(this);
							var multipleLine = isMultipleLine($(this));
							var height = $(this).find('td:nth-child(1)').height();
							rowInfos.push({
								height: height,
								isMultipleLine: multipleLine
							});
						});
					}
					return rowInfos;
				}
				//判断是否有本行数据已换行
				function isMultipleLine($tr) {
					if (!$tr) {
						return false;
					}
					var divs = $tr.find('td>div');
					for (var i = 0; i < divs.length; i++) {
						if ($(divs[i]).css('word-break') == 'break-all') {
							return true;
						}
					}
					return false;
				}

				//设置行高
				function setLeftBottomTableRowHeights() {
					var rowInfos = getRigthBottomTableRowHeightsAndIsMultipleLineInfos();
					if (!rowInfos || rowInfos.length == 0) {
						return;
					}
					$.each(leftBottomTableEl.find('tr>td:nth-child(1)'), function(i, item) {
						var rowInfo = rowInfos[i];
						var height = rowInfo.height;
						var rigthBottomTableRowMultipleLine = rowInfo.isMultipleLine;
						var leftBottomTableRowMultipleLine = isMultipleLine($(this).parent());

						if (rigthBottomTableRowMultipleLine) {
							$(this).height(height);
							var div = $('div', this).css({
								'height': 'auto',
								'white-space': 'normal',
								'word-break': 'break-all',
								'word-wrap': 'break-word',
								'text-align': 'center',
								'line-height': '16px'
							});
							//如果当前div的高度超出了右边行的高度，反向赋值
							if (div.height() > height) {
								rightBottomTableEl.find('tr:nth-child(' + (i + 1) + ')>td:nth-child(1)>div').height(div.height()).css(
									'line-height', div.height() + 'px');
							}
						} else if (leftBottomTableRowMultipleLine) {
							//如果当前div的高度超出了右边行的高度，反向赋值
							// console.log($(this).css('padding-bottom')+"--" + $(this).find('div').css('margin'))
							if ($(this).height() > height) {
								rightBottomTableEl.find('tr:nth-child(' + (i + 1) + ')>td:nth-child(1)>div').height($(this).height()).css(
									'line-height', $(this).height() + 'px');
							}
						}
					});
				}


				var win = $(window);
				var leftEl = options.cache.leftEl;
				var rightEl = options.cache.rightEl;

				var leftBottomEl = options.cache.leftBottomeEl;
				var leftBottomTableEl = options.cache.leftBottomTableEl;
				var rightTopTableEl = options.cache.rightTopTableEl;
				var rightBottomEl = options.cache.rightBottomEl;
				var rightBottomTableEl = options.cache.rightBottomTableEl;

				win.on('resize', adjustWidthHeight); adjustWidthHeight();

				//设置iscroll
				var myScroll = new IScroll(rightBottomEl[0], {
					scrollX: true,
					scrollY: true,
					probeType: 3
				});

				//阻止默认滚动
				rightBottomEl.on('touchmove mousewheel', function(e) {
					e.preventDefault();
					return false;
				});

				//固定上左表头的滚动
				myScroll.on('scroll', updatePosition); myScroll.on('scrollEnd', updatePosition);
			});
	};
})(jQuery);
