NLargeList_wev8.js 23.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
define(['mUtil', "Component", "wev-loading", "fieldParseHelper", "mService", "pageExpandHelper"], function (mUtil, Component, WevLoading, fieldHelper, mService, pageExpandHelper) {
    var NLargeList = function (options) {
        var _list = {}, rowidMap = {}, $comp, $list, $errorTip, pageid;

        Component.super(this, options);

        this.type = "NLargeList";
        this.tpl = this.type + "_html";
        this.css = this.type + "_css";
        this.keysOfSkipedVarParse = ['dataSource', 'dataurl', 'showSet'];
        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 = {
            dataSource: {
                type: 'mock'     //cube mock sql url api
            },
            pageStart: 1,
            pageSize: 10,
            showSet: {
                common: {
                    imgfield: "",
                    titlefield: "",
                    otherfields: []
                },
                cube: {
                    imgfield: {},
                    titlefield: {},
                    otherfields: []
                }
            },
            quickSearch: {
                hide: false,
                tip: "",
                fields: []
            },
            advancedSearch: {
                enable: false
            },
            btns: [],
            options: {
                readonly: false,
                showOnePage: false      //显示一页
            },
            relate: {},
            onload: function () { },
            standalone: true
        };
        
        this.beforeMount = function(){
            vm.pageStart = isNaN(vm.pageStart) ? 1 : vm.pageStart;
            //判断url是否包含变量
            vm.needReplaceUrl = mUtil.containsVariables(vm.options.dataurl);
            vm.isCube = vm.dataSource.type == 'cube';
            //过滤历史数据中静态页中的扩展按钮,改为动态获取
            if (vm.btns) {
                vm.btns = vm.btns.filter(function (ele) {
                    //历史数据无vm.pageExtend参数
                    if (ele.id.startsWith("pageexpandBtn")) vm.pageExtend = true;
                    return !ele.id.startsWith("pageexpandBtn");
                });
            }
        };
        
        this.mounted = function () {
            var that = this;
            pageid = this.pageid;
            $comp = this.$comp;
            $errorTip = this.$el.find(".wev-error");
            $list = $comp.find(".wev-table-view");

            // 初始化列表数据
            _list.refreshList(function () {
                mUtil.eval(vm.onload, that.pageid);
            });
            // 初始化搜索功能
            _list.initSearch();
            
            //初始化自定义按钮,切换显示按钮
            _list.initBtns(this.pageid);

            //绑定单条数据点击事件
            $comp.on("click.nav", "a.wev-navigate-right, .wev-file", function (e) {
                if($(e.target).closest('.wev-file[data-docid]').length) return;

                var $this = $(this);
                var item = util.getDataItem($this)||{};
                
                if (vm.options.readonly) return;
                
                if (vm.callback && mUtil.isFunction(vm.callback.click)) {
                    vm.callback.click.call(this, item);
                }
                if (vm.isCube && vm.relate.modeid != -1 && vm.options.urltype == 0){
                    if (vm.layoutUrl) return $u(vm.layoutUrl + "&billid=" + item.id);
                    Mobile_NS.getLayoutUrl(vm.relate.modeid, 1, item.id);
                }else if(item.dataurl){
                    var dataurl = item.dataurl;
                    if(item.dataurl.indexOf("javascript:") == -1){
                        $u(dataurl);
                    }else{
                        mUtil.eval(dataurl, that.pageid);
                    }
                }
            });
            // 解析布局url
            vm.isCube && vm.relate.modeid != -1 && !vm.options.readonly && vm.options.urltype === 0 && util.parseLayoutUrl();
        };
        
        this.reload = function (args, callback) {
            _list.state.dynamicParam = {};
            if (mUtil.isObject(args)) {
                $.extend(_list.state.dynamicParam, args);
            }
            _list.refreshList(callback);
        };
        
        _list.state = {
            timestamp: 0,
            pageNo: vm.pageStart - 1,
            currPage: 0,
            list: [],
            conditions: {},
            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.conditions = {};
            });
            // 搜索框事件
            $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.conditions.searchKey = encodeURIComponent(this.value);
                _list.refreshList();
                this.blur();
            });
            
            if (!vm.isCube || !vm.advancedSearch.enable) return;
            // 高级搜索
            require(["css!listAdvancedSearch_css"]);
            
            var timestamp = new Date().valueOf(), pageid = this.pageid.split("_").slice(1).join("."), id = this.id;
            
            $search.on("click.advancedSearch", ".wev-search-advanced", function () {
                require(["mService"], function (mService) {
                    mService.show("search", {
                        _identity: id + "_" + timestamp,
                        pageid: pageid,
                        id: id,
                        searchid: vm.dataSource.searchid,
                        conditions: JSON.stringify(vm.advancedSearch.fields),
                        title: vm.advancedSearch.title
                    });
                });
            });
        };

        _list.initBtns = function () {
            var that = this;
            if (vm.pageExtend) {
                var cfg = {
                    pageid: pageid,
                    searchid: vm.dataSource.searchid
                };
                pageExpandHelper.parsePageExpand($comp.find(".wev-search"), that.id, cfg);
            }

            if (!vm.btns.length) return;

            $(".wev-list-btn-container", $comp).on("click", ".btn.wev-btn-custom", 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,
                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();
                mUtil.trigger('dataload', that.pageid, that.id);

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

                        // 日历+列表的情况
                        if('auto' === $comp.css('overflow-y')) {
                            $container = $comp;
                        }

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

        _list.loadData = function (callback) {
            var that = this,
                state = _list.state,
                timestamp = new Date().valueOf(),
                sourceType = vm.dataSource.type,
                showView = vm.showSet[sourceType] || vm.showSet.common;
            
            state.timestamp = timestamp;
            state.pageNo++;
            state.currPage++;

            var currPageParam = mUtil.getPageParam(that.pageid) || {},
                defReqParam = $.extend({}, currPageParam,state.dynamicParam,state.conditions),
                searchKey = typeof(defReqParam.searchKey) != 'undefined' ? defReqParam.searchKey || "" : defReqParam.search_key || "",
                commonReqParam = {
                    pageNo: state.pageNo, 
                    pageSize: vm.pageSize, 
                    searchKey: searchKey
                },
                defInnerParam = $.extend({}, commonReqParam, {
                    PAGE_NO: state.pageNo, 
                    PAGE_SIZE: vm.pageSize, 
                    SEARCH_KEY: searchKey
                });
            
            commonReqParam = $.extend(defReqParam, commonReqParam);
            
            var showError = function(msg){
                callback(false, false);
                $errorTip.html(msg).show();
            };
            
            if(sourceType == 'cube'){
                if(!vm.dataSource.searchid){
                    showError(mUtil.getLabel(6112, "内容来源未配置,请联系管理员。"));
                    return;
                }
                //拓展请求参数
                var fieldparse = fieldHelper.parseFieldIds(JSON.stringify(showView));
                var requestParam = $.extend({}, commonReqParam, {
                    action: "getDatas", 
                    searchid: vm.dataSource.searchid, 
                    fieldparse: fieldparse,
                    searchFields: JSON.stringify(vm.quickSearch.fields || [])
                });
                var actionUrl = mUtil.getActionUrl(this.type, requestParam, this.pageid);
                mUtil.getJSON(actionUrl, function (result) {
                    result = result.data;
                    if (timestamp != state.timestamp) return;
                    
                    var convertResult = _list.convertShowDatas4CubeSearch(result, showView);
                    _list.renderData(convertResult.billDatas, convertResult.showDatas, result.totalSize, callback);
                }, showError);
            }else if(sourceType == 'mock'){
                var mockData = vm.dataSource.mockData;
                var requestParam = commonReqParam;
                var result;
                if(mUtil.isArray(mockData)){
                    var matchFields = JSON.stringify(showView).match(/\{(\w+)\}/g);
                    result = fieldHelper.convertFieldMockData(mockData, state.pageNo, vm.pageSize, decodeURIComponent(requestParam.searchKey || ""), matchFields);
                }
                if(result){
                    var convertResult = _list.convertShowDatas(result.datas.map(function(data){return data.dataMap}), showView);
                    _list.renderData(convertResult.billDatas, convertResult.showDatas, result.totalSize, callback);
                }else{
                    showError(mUtil.getLabel(6112, "内容来源未配置,请联系管理员。"));
                }
            }else if(sourceType == 'sql' && !vm.standalone){
                //拓展请求参数
                var requestParam = $.extend({}, commonReqParam, {
                    action: "getSqlDatas",
                    mec_id: that.id
                });
                
                var actionUrl = mUtil.getActionUrl(this.type, requestParam, this.pageid);
                
                mUtil.getJSON(actionUrl, function (result) {
                    result = result.data;
                    if (timestamp != state.timestamp) return;
                    
                    var convertResult = _list.convertShowDatas(result.datas, showView);
                    _list.renderData(convertResult.billDatas, convertResult.showDatas, result.totalSize, callback);
                }, showError);
            }else if(sourceType == 'url'){
                var urlConfig = vm.dataSource.urlConfig || {}, path = urlConfig.path || "";
                var sourceUrl = mUtil.replaceVal(path, defInnerParam);
                commonReqParam.searchKey = commonReqParam.searchKey ? decodeURIComponent(commonReqParam.searchKey) : "";
                var requestParam = commonReqParam;
                var formats = urlConfig.formats || {};
                require(["apiHelper"], function(apiHelper){
                    apiHelper.requestUrl(sourceUrl, formats, requestParam, function(result){
                        if (timestamp != state.timestamp) return;
                        
                        var 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;
                        }
                        var convertResult = _list.convertShowDatas(datas, showView);
                        _list.renderData(convertResult.billDatas, convertResult.showDatas, totalSize, callback);
                    }, showError);
                });
            }else if(sourceType == 'api'){
                var apiConfig = vm.dataSource.apiConfig || {api: {},request: {},response: {}};
                defInnerParam.SEARCH_KEY = defInnerParam.SEARCH_KEY ? decodeURIComponent(defInnerParam.SEARCH_KEY) : "";
                //请求参数
                var requestParam = $.extend({}, commonReqParam, defInnerParam);
                require(["apiHelper"], function(apiHelper){
                    apiHelper.callApi(apiConfig, requestParam, function(result){
                        if (timestamp != state.timestamp) return;
                        
                        var formats = 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;
                        }
                        var convertResult = _list.convertShowDatas(datas, showView);
                        _list.renderData(convertResult.billDatas, convertResult.showDatas, totalSize, callback);
                    }, showError);
                });
            }else{
                showError(mUtil.getLabel(6113, '不支持的数据来源类型,请检查配置。'));
            }
        };
        
        _list.renderData = function(datas, showDatas, totalSize, callback){
            var that = this,
                state = _list.state;
            
            var currPage = state.currPage;
            var pageSize = vm.pageSize;
            
            mUtil.concat(state.list, datas);
            
            var templateHtml = [
                '{@each datas as d}',
                '<li data-id="${d.rowid}" class="wev-table-view-cell wev-media">',
                    '<a href="javascript:void(0);" class="wev-navigate-right{@if vm.options.readonly} wev-data-readonly"{@else}" data-ignoreviewimg{@/if}>',
                        '<div class="wev-table-checkbox"></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>',
                '</li>',
                '{@/each}'
            ].join('');

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

            $list.append($newList);

            mUtil.trigger("onpagechange", that.pageid, that.id, [state.pageNo , $newList]);

            util.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);
        };

        _list.convertShowDatas4CubeSearch = function(originDatas, viewset){
            var convertShowDataItem = function(billdata, fieldmap, fieldset){
                var imgfield = fieldset.imgfield, otherfields = fieldset.otherfields;
                //图片字段
                var imgDisplay = fieldHelper.isSettingValue(imgfield), imgFValue = '';
                imgDisplay && (imgFValue = fieldHelper.getFieldValue(imgfield, billdata, fieldmap, true, vm.options.readonly));
                //其他字段
                var otherFValue = [];
                if(mUtil.isArray(otherfields)){
                    otherfields.forEach(function(rowfields) {
                        var rowFieldValue = [];
                        rowfields.forEach(function(colfield) {
                            if(fieldHelper.isSettingValue(colfield)){
                                var colFieldValue = fieldHelper.getFieldValue(colfield, billdata, fieldmap, false, vm.options.readonly);
                                rowFieldValue.push('<div class="wev-col">'+colFieldValue+'</div>');
                            }
                        });
                        if(rowFieldValue.length > 0){
                            otherFValue.push(rowFieldValue.join(''));
                        }
                    });
                }

                var titleDisplay = fieldHelper.getFieldValue(fieldset.titlefield, billdata, fieldmap);

                return {
                    rowid           : billdata._rowid,
                    id              : billdata.keyvalue,
                    imgFieldValue   : imgFValue,
                    titleFieldValue : titleDisplay,
                    otherFieldValue : otherFValue
                };
            };
            var fieldmap = originDatas.fieldMap, listDatas = [], showDatas = [];
            
            originDatas.datas.forEach(function(data){
                var dataItem = $.extend({}, data.dataMap);
                var dataId = data.keyvalue;
                var dataurl = _list.parseDataUrl(data.dataMap, vm.options.dataurl, dataId);
                
                dataItem._rowid = data._rowid = mUtil.UUID();
                dataItem.id = dataId;
                dataItem.dataurl = dataurl;
                listDatas.push(dataItem);
                
                var showDataItem = convertShowDataItem(data, fieldmap, viewset);
                showDatas.push(showDataItem);
            });
            return {
                billDatas: listDatas,
                showDatas: showDatas
            };
        };
        
        _list.convertShowDatas = function(originDatas, viewset){
            return {
                billDatas: originDatas,
                showDatas: originDatas.map(function (d) {
                    d._rowid = mUtil.UUID();
                    d.dataurl = _list.parseDataUrl(d, vm.options.dataurl);
                    d = JSON.parse(Component.replaceMutilLanguage(JSON.stringify(d), mUtil.getUserLanguage()));
                    return {
                        rowid           : d._rowid,
                        imgFieldValue   : mUtil.replaceValAndVarParser(viewset.imgfield, fieldHelper.getFirstDataByFielddesc(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; })
                    };
                })
            }
        };
        
        _list.parseDataUrl = function(billData, originUrl, billid){
            var dataurl = "",
                useCustomUrl = (vm.isCube && (vm.options.urltype == 1 || vm.relate.modeid == -1)) || !vm.isCube;
            if(useCustomUrl && originUrl){
                dataurl = vm.needReplaceUrl ? fieldHelper.replaceVal(originUrl, billData) : originUrl;
                if(dataurl.indexOf("javascript:") == -1 && vm.isCube){
                    if(!vm.options.isNewLayout && dataurl.indexOf("&billid=") == -1 && dataurl.indexOf("?billid=") == -1){
                        dataurl += (dataurl.indexOf("?") == -1 ? "?" : "&") + "billid=" + billid;
                    }
                }
            }else{
                dataurl = "javascript:void(0);";
            }
            return dataurl;
        };
        
        var util = {
            parseLayoutUrl: function() {
                var url = mUtil.getActionUrl("service.FormComponent", { action: "resolveDefaultLayout" });

                mUtil.getJSON(url, { modelid: vm.relate.modeid, appid: vm.relate.appid, uitype: 1 }, function (result) {
                    vm.layoutUrl = result.data || "";
                    require(["mApi/other"]);//TODO 预加载
                }, function (errMsg) { });
            },
            getDataItem: function ($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;
            },
            initLazyImg: function () {
                require(["lazyImgHelper"]);
            }
        };
        
        _list.initSearch = _list.initSearch.bind(this);
        _list.refreshList = _list.refreshList.bind(this);
        _list.loadData = _list.loadData.bind(this);
        _list.renderData = _list.renderData.bind(this);
        _list.convertShowDatas = _list.convertShowDatas.bind(this);
        _list.initBtns = _list.initBtns.bind(this);
    };

    return Component.init(NLargeList);
});