;
(function($, window, document, undefined) {
	var fixedObj, options, cache;

	//定义FixedTable的构造函数
	var FixedTable = function(ele, opt) {
		this.$element = ele,
			this.defaults = {
				winMarginBottom: 53,
				emptyMsg: "<p style='background:red;font-size:20px;margin-top:30px;padding:1rem 0 ;color:#ffffff;text-align:center;'>没有查到数据！</p>",
				leftColStyles: [],
				leftTop: undefined,
				leftBottom: undefined,
				rightTop: undefined,
				rightBottom: undefined,
				orderActiveClass: 'fixed-order-active',
				cache: {
					leftEl: undefined,
					leftTopEl: undefined,
					leftBottomEl: undefined,
					leftTopTableEl: undefined,
					leftBottomTableEl: undefined,

					rightEl: undefined,
					rightTopEl: undefined,
					rightBottomEl: undefined,
					rightTopTableEl: undefined,
					rightBottomTableEl: undefined
				}
			},
			this.options = $.extend({}, this.defaults, opt)
	};

	//定义FixedTable的方法
	FixedTable.prototype = {
		init: function() {
			var options = this.options;
			var cache = options.cache;
			var fixedObj = this;
			var $$this = $(fixedObj.$element);
			return this.$element.each(function() {
				var $$this = $(this);
				//清空当前对象
				$(this).html('');
				if (isEmpty(options.leftTop) ||
					isEmpty(options.leftBottom) ||
					isEmpty(options.rightTop) ||
					isEmpty(options.rightBottom)) {
					$(this).html(options.emptyMsg);
					return;
				}
				//初始化左边壳
				initLeftWrapper();
				//初始化左上角
				initLeftTop();
				//初始化左下角
				initLeftBottom();

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

				$(window).on('resize', function() {
					adjustWidthHeight();
				});
				adjustWidthHeight();

				//绑定滑动事件
				bindScrollEvent();

			});
		},
		reloadData: function(leftBottomJson, rightBottomJson) {
			console.log('reload data 。。 ')
			this.options.leftBottom = leftBottomJson;
			this.options.rightBottom = rightBottomJson;
			var leftBottomEl = this.options.cache.leftBottomEl;
			var rightBottomEl = this.options.cache.rightBottomEl;

			leftBottomEl.unbind();
			rightBottomEl.unbind();
			leftBottomEl.remove();
			rightBottomEl.remove();
			//初始化左下角
			initLeftBottom();
			//初始化右下角
			initRightBottom(true);


			//重新绑定滑动事件
			adjustWidthHeight();
			//绑定滑动事件
			bindScrollEvent();

		}
	};

	function isEmpty(obj) {
		if (obj == undefined)
			return true;
		if (obj == null)
			return true;
		if ($.isEmptyObject(obj))
			return true;
		if (obj.rows && obj.rows.length == 0)
			return true;
		return false;
	}

	function bindScrollEvent() {

		var rightBottomEl = cache.rightBottomEl;

		//设置iscroll
		var myScroll = new IScroll($('.right-bottom')[0], {
			scrollX: true,
			scrollY: true,
			probeType: 3
		});
		//阻止默认滚动
		rightBottomEl.on('touchmove mousewheel', function(e) {
			e.preventDefault();
		});

		//固定上左表头的滚动
		myScroll.on('scroll', updatePosition);
		myScroll.on('scrollEnd', updatePosition);
		myScroll.scrollTo(0, 0, 1000, IScroll.utils.ease.elastic);
	}
	//初始化左上角
	function initLeftTop(obj) {
		//创建左大列
		var leftEl = cache.leftEl;
		//左上角的div
		var leftTopEl = cache.leftTopEl = $('<div class="left-top"></div>');
		leftEl.append(leftTopEl);

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

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

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

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

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

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

		//右上表格
		var rightTopTableEl = 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>');
		});
		cache.rightTopTableEl.prepend($row);
	}
	//初始化右下角
	function initRightBottom(reload) {
		//创建右大列
		var rightEl = cache.rightEl;
		//右下角的div
		var rightBottomEl = cache.rightBottomEl = $('<div class="right-bottom"></div>');
		rightEl.append(rightBottomEl);

		//右下表格
		var rightBottomTableEl = cache.rightBottomTableEl = $('<table></table>');
		rightBottomEl.append(rightBottomTableEl);
		//填充数据
		fillTable(rightBottomTableEl, options.rightBottom.rows);
		if (reload == undefined || reload == false) {
			//给rightTop增加一行隐藏的行，方便设置宽度
			insertHiddenRowToRightTopFirstRow(options.rightBottom.rows);
		}
	}

	//
	function initLeftColStyles() {
		var leftColStyles = options.leftColStyles;
		if (leftColStyles && leftColStyles.length > 0) {
			$.each(leftColStyles, function(i, item) {
				cache.leftBottomTableEl.find('tr td:nth-child(' + (i + 1) + ') div').css(item);
				cache.leftBottomTableEl.find('tr td:nth-child(' + (i + 1) + ')').css(item);
			});
		} else {
			var maxTrCols = undefined;
			var max = 0;
			$.each(cache.leftTopTableEl.find('tr'), function(i, item) {
				var tds = $(this).find('td');
				if (tds.length > max) {
					max = tds.length;
					maxTrCols = tds;
				}
			});
			var leftBottomfirstTrCols = cache.leftBottomTableEl.find('tr:first').find('td');
			if (maxTrCols != undefined && max == leftBottomfirstTrCols.length) {
				for (var i = 0; i < max; i++) {
					var maxWidth = Math.max($(leftBottomfirstTrCols[i]).width(), $(maxTrCols[i]).width());
					$(leftBottomfirstTrCols[i]).width(maxWidth);
					$(maxTrCols[i]).width(maxWidth);
				}
			}
		}
	}

	//填充表格数据
	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 != undefined && 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 != undefined && $.trim(id) != '') {
			$col.attr('id', id);
		}
		var $div = $("<div></div>");
		if (text != undefined && 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 != undefined) {
			$.each(ext, function(key, value) {
				$col.attr(key, value);
			});
		}
	}

	function updatePosition() {
		var leftBottomTableEl = cache.leftBottomTableEl;
		var rightTopTableEl = cache.rightTopTableEl;
		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 win = $(window);
		var $element = fixedObj.$element;
		var leftEl = cache.leftEl;
		var leftBottomEl = cache.leftBottomEl;
		var rightEl = cache.rightEl;
		var rightTopTableEl = cache.rightTopTableEl;
		var rightBottomEl = cache.rightBottomEl;
		var rightBottomTableEl = cache.rightBottomTableEl;
		var winHeight = win.height() - $element.offset().top - options.winMarginBottom;
		var tableHeight = winHeight - rightTopTableEl.height();

		leftBottomEl.height(tableHeight);
		rightBottomEl.height(tableHeight);

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

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

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

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

	//设置右边上下两个table的宽度
	function setRightTopTableWidth() {
		var rightTopTableEl = cache.rightTopTableEl;
		var rightBottomTableEl = cache.rightBottomTableEl;
		rightTopTableEl.width(rightBottomTableEl.width());
	}
	//设置表头每列宽度
	function setRightTopTableColWidths() {
		var rightTopTableEl = cache.rightTopTableEl;
		//获取列宽
		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 = 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 leftEl = cache.leftEl;
		var rightBottomTableEl = cache.rightBottomTableEl;
		var win = $(window);
		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 rightBottomTableEl = cache.rightBottomTableEl;
		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 leftBottomTableEl = cache.leftBottomTableEl;
		var rightBottomTableEl = cache.rightBottomTableEl;
		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');
				}
			}
		});
	}
	//在插件中使用FixedTable对象
	$.fn.fixed_table = function(opt) {
		//创建FixedTable的实体
		fixedObj = new FixedTable(this, opt);
		options = fixedObj.options;
		cache = options.cache;
		//调用其方法
		fixedObj.init();
		return fixedObj;
	};

	/**************** 扩展jquery方法  ****************/
	$.fixed_table = {
		getTdObjJson: function(param, fieldMap) {
			var tdObj = JSON.parse(JSON.stringify(param));
			if (tdObj != undefined && !$.isEmptyObject(tdObj)) {
				// console.log(JSON.stringify(tdObj));
				var text = tdObj.text;
				if (text.indexOf('@find:') == 0) {
					//说明需要动态取值
					var dataKey = text.replace('@find:', '');
					tdObj.text = $.fixed_table.get(fieldMap, dataKey);
				}
				var ext = tdObj.ext;
				if (ext != undefined && !$.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] = $.fixed_table.get(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: $.fixed_table.get(item, field)
						});
					}
				});
				rows.push({
					"cols": cols
				});
			});
			json.rows = rows;
			return json
		},
		get: function(item, key) {
			if (item == undefined || key == undefined || item[key] == undefined) {
				return "";
			}
			return item[key].toString();
		}
	}

})(jQuery, window, document);
