APIList_wev8.js 11 KB
define(['mUtil', "Component", "wev-loading"], function (mUtil, Component, WevLoading) {
	var APIList = function (options) {
		var _list = {}, $comp, $list, $errorTip;

		Component.super(this, options);

		this.type = "APIList";
		this.tpl = this.type + "_html";
		this.keysOfSkipedVarParse = ['imgfield', 'titlefield', 'otherfields'];
        this.dataload = true;
		this.components = {
			loading: new WevLoading({
				delay: 300,
				animation: 1
			}),
			moreLoading: new WevLoading({
				btn: 1,
				onclick: function (hideLoading) {
					_list.loadData(hideLoading);
				}
			})
		};

		var vm = this.viewModel = {
			apiConfig: {
				api: {},
				request: {},
				response: {}
			},
			pageStart: 1,
			pageSize: 10,
			normalview: {
				imgfield: "",
				titlefield: "",
				otherfields: []
			},
			normalSearch: {
				hide: false,
				tip: ""
			},
			btns: [],
			swipe: {
				enable: true,
				items: []
			},
			options: {
				readonly: false,
				selectable: false,		//数据可选
				showOnePage: false		//显示一页
			},
			onload: function () { },
			standalone: true
		};
		
		this.beforeMount = function(){
			vm.pageStart = isNaN(vm.pageStart) ? 1 : vm.pageStart;
			vm.standalone && vm.swipe.items.map(function(ele) {
				ele.id = mUtil.UUID();
				return ele;
			});
		};
		
		this.mounted = function () {
		    var that = this;
			
			$comp = this.$comp;
			$errorTip = this.$el.find(".wev-error");
			
			$list = $comp.find(".wev-table-view");
			
			// 初始化列表数据
            _list.refreshList(function () {
				mUtil.eval(vm.onload, that.pageid);
                mUtil.trigger('dataload', that.pageid, that.id);
			});
			// 初始化搜索功能
			_list.initSearch();
			
			//初始化自定义按钮,切换显示按钮
			_list.initBtns(this.pageid);
			
			//绑定单条数据,左滑按钮点击事件
			$comp.on("click.nav", "a.wev-navigate-right, .wev-table-checkbox, .wev-file", function (e) {
				var $this = $(this);
				var item = getDataItem($this)||{};
				var isImg = e.target.tagName.toLowerCase() === "img";
				var isFile = $this.hasClass("wev-file");
				
				//选择数据checkbox
				if($this.hasClass("wev-table-checkbox") || (vm.options.readonly && !isImg && !isFile)){
					var $li = $this.closest(".wev-table-view-cell");
					$li.toggleClass("checked");
					
					//选择数据功能 阻止冒泡和默认行为
					e.stopPropagation();
					e.preventDefault();
					return;
				}
				if (vm.options.readonly) return;
				vm.callback && mUtil.isFunction(vm.callback.click) && vm.callback.click.call({target: this, rowData: item});
			}).on("click.swipeAction", ".btnBox", function () {
				var swipeId = $(this).attr("id"), that = this;
				var rowData = getDataItem($(this))||{};
				vm.swipe.items.every(function(ele){
					if(ele.id === swipeId){
						ele.click && ele.click.call({target: that, rowData: rowData});
						return false;
					}
					return true;
				});
			});
		};

		function getDataItem($el) {
			var _rowid = $el.closest("li.wev-table-view-cell").data("id"), rowData;
			_list.state.list.every(function(ele, i) {
				if(_rowid === ele._rowid){
					rowData = ele;
					return false;
				}
				return true;
			});
			return rowData;
		}

		this.reload = function (args, callback) {
		    _list.state.dynamicParam = {};
			if (mUtil.isObject(args)) {
				$.extend(_list.state.dynamicParam, args);
			}
			_list.refreshList(callback);
		};
		
		this.getCheckedData = function(callback){
		    var checkList = [];
		    $list.find(".wev-table-view-cell.checked").each(function(){
		        var rowData = getDataItem($(this));
		        rowData && checkList.push(rowData);
		    });
            mUtil.isFunction(callback) && callback(checkList);
		};
		
		this.toggleData = function(flag){
			if(!vm.options.selectable) return;
			$list.find(".wev-table-view-cell").toggleClass("checked", flag);
		};
		
		_list.state = {
			timestamp: 0,
			pageNo: vm.pageStart - 1,
			currPage: 0,
			list: [],
			searchKey: "",
			dynamicParam: {}
		};
		
		_list.initSearch = function () {
			var $search = $(".wev-search", $comp),
				$searchInput = $("input", $search);

			$search.on("click.active", ".wev-placeholder", function (e) {
				$search.addClass("wev-active").removeClass("wev-inactive");
				$searchInput.focus();
			}).on("click.clear", ".wev-clear-btn", function () {
				$searchInput.val("").focus().triggerHandler("input");
				_list.state.searchKey = "";
			});
			// 搜索框事件
			$searchInput.on("blur", function () {
				if (this.value) return;

				$search.removeClass("wev-active").addClass("wev-inactive");
			}).on("input", function () {
				$search.toggleClass("wev-has-value", !!this.value);
			}).on("keyup", function (e) {
				if (e.keyCode !== 13) return;

				_list.state.searchKey = this.value;
				_list.refreshList();
				this.blur();
			});
		};

		_list.initBtns = function (pageid) {
			if (!vm.btns.length) return;

			$(".wev-list-btn-container", $comp).on("click", ".btn", function () {
				var $btn = $(this);
				
				var index = $(this).data("index");

				mUtil.eval(vm.btns[index].click, pageid);
			});
		};
		
		_list.refreshList = function (cb) {
            var that = this;
			var coms = this.components;
			var loading = coms.loading;
			var moreLoading = coms.moreLoading;
			var state = _list.state;

			state.pageNo = vm.pageStart - 1;
			state.currPage = 0;
			state.list = [];

			loading.setRefs(this.$comp, "wev-refreshing");
			loading.show();

			_list.loadData(function (hasMore, noData) {
				loading.hide();
				moreLoading.hide(hasMore, noData);
                cb && cb();

                // 支持上拉刷新功能
                if(mUtil.canPullToRefresh(that.id) && hasMore) {
                    require(['pullToRefreshHelper'], function (PullToRefresh) {
                        var $pageContent = $comp.closest('.page-content');

                        new PullToRefresh({
                            el: $list,
                            container: $pageContent.get(0),
                            loadData: _list.loadData,
                            loading: that.components.moreLoading
                        });
                    });
                }
			});
		};

		_list.loadData = function (callback) {
			var that = this;
			var state = _list.state;
			var timestamp = new Date().valueOf();

			state.timestamp = timestamp;
			state.pageNo++;
			state.currPage++;

			var pageNo = state.pageNo;
			var currPage = state.currPage;
			var pageSize = vm.pageSize;
			
			var innerParam = {};
			
			//请求参数
            $.extend(true, innerParam, mUtil.getPageParam(this.pageid), state.dynamicParam, {
                pageNo: state.pageNo, 
                pageSize: vm.pageSize, 
                searchKey: _list.state.searchKey,
                PAGE_NO: state.pageNo, 
                PAGE_SIZE: vm.pageSize, 
                SEARCH_KEY: _list.state.searchKey
            });
            
			require(["apiHelper"], function(apiHelper){
				apiHelper.callApi(vm.apiConfig, innerParam, function(result){
					if (timestamp != state.timestamp) return;
					
					var formats = vm.apiConfig.response.formats, totalSize = 0, datas;
					if(formats.DATAS){
						datas = mUtil.getKeyValue(formats.DATAS, result);
						totalSize = formats.TOTAL_SIZE ? parseInt(mUtil.getKeyValue(formats.TOTAL_SIZE, result)) : datas.length;
					}else{
						datas = [{}];
						totalSize = 1;
					}
					
					datas.map(function(ele) {
						ele._rowid = mUtil.UUID();
						return ele;
					});
					
					mUtil.concat(state.list, datas);
					var templateHtml = [
						'{@each datas as d}',
						'<li data-id="${d.rowid}" class="wev-table-view-cell wev-media{@if d.checkMode} check-mode{@/if}{@if d.checked} checked{@/if}">',
							'<a class="wev-navigate-right {@if d.readonly}wev-data-readonly{@/if}" href="javascript:void(0);">',
								'<div class="wev-table-checkbox"><i class="wev-css-icon '+(vm.options.selectable ? 'wev-multi-check' : 'wev-single-check') + '"></i></div>',
								'<div class="wev-media-object wev-pull-left">',
									'$${d.imgFieldValue}',
								'</div>',
								'<div class="wev-media-body">',
									'$${d.titleFieldValue}',
									'{@each d.otherFieldValue as row}',
									'<div class="wev-ellipsis">',
										'$${row}',
									'</div>',
									'{@/each}',
								'</div>',
							'</a>',
							'{@if d.swipeContent}',
							'<div class="wev-slider-handle">$${d.swipeContent}</div>',
							'{@/if}',
						'</li>',
						'{@/each}'
					].join('');

					var html = mUtil.parseTemplate(templateHtml, { datas: _list.getShowDatas(datas, vm.normalview)});
					var $newList = $(html);
					
					if (currPage == 1) {
						$list.html("");
					}

					$list.append($newList);
					initLazyImg();
					
					var totalPageCount = totalSize % pageSize === 0 ? totalSize / pageSize : parseInt(totalSize / pageSize) + 1;
					var hasMore = (currPage < totalPageCount) && !vm.options.showOnePage;
					var noData = totalSize <= 0;

					$errorTip.hide();
					callback(hasMore, noData);
					mUtil.renderVarParser(vm.needParseVar);
					initSwipe($newList, that.pageid);
				}, function(errMsg){
					callback(false, false);
					$errorTip.html(errMsg).show();
				});
			});
		};


		_list.getShowDatas = function (jsonDatas, viewset) {
		    var that = this, _apiListId = $p("_apiListId"), _selectListIds = $p("_selectListIds"), _dataIDKey = $p("_dataIDKey"), 
						checkMode = (_apiListId === that.id && _dataIDKey);
			return jsonDatas.map(function (d) {
					d = JSON.parse(Component.replaceMutilLanguage(JSON.stringify(d), mUtil.getUserLanguage()));
					return {
					rowid: d._rowid,
					imgFieldValue: mUtil.replaceValAndVarParser(viewset.imgfield, d), // 图片
					titleFieldValue: mUtil.replaceValAndVarParser(viewset.titlefield, d), // 标题
					otherFieldValue: viewset.otherfields.map(function (field) {
						return mUtil.replaceValAndVarParser(field, d);
					}).filter(function (v) { return v; }),
					readonly: vm.options.readonly,
					swipeContent: getSwipeContent(d),
					checkMode: checkMode,
					checked: checkMode && ~_selectListIds.split(",").indexOf(d[_dataIDKey])
				};
			});
		};
		
		function getSwipeContent(data){
			if(!vm.swipe.enable || vm.swipe.items.length == 0) return "";
			var template = [
			    '<div class="btnContainer">',
				    '<div class="btnContainerInner">',
				    '{@each datas as d}',
					    '<div id="${d.id}" class="btnBox" {@if d.bgcolor}style="background-color:${d.bgcolor}"{@/if}>{@if d.text}${d.text}{@else}<img src="${d.icon}"/>{@/if}</div>',
					'{@/each}',
					'</div>',
				'</div>'
			].join('');
			return mUtil.replaceVal(mUtil.parseTemplate(template, { datas: vm.swipe.items}), data);
		}
		
		function initSwipe($ele, pageid) {
			if(!vm.swipe.enable || vm.swipe.items.length == 0) return;

			require(["swipeHelper", "css!listSwipe_css"], function (h) {
				$ele.each(function () {
					h.swipe($(this).children("a"), pageid);
				});
			});
		}

		function initLazyImg() {
			require(["lazyImgHelper"]);
		}

		_list.refreshList = _list.refreshList.bind(this);
		_list.loadData = _list.loadData.bind(this);
		_list.getShowDatas = _list.getShowDatas.bind(this);
	};

	return Component.init(APIList);
});