/**
 * [OElove] (C)2010-2099 oelove.com biz
 * Email: service@phpcoo.com ,phpcoo@qq.com
 * This is NOT a freeware, use is subject to license terms
 * $ Last update 2020/03/10 by bo $
*/
var _inst_oepage = null;
(function ($) {
  function scrollList () {
      this.options = {};
      this.cache_next_page = '1';
  }
  scrollList.prototype = {
    _scroll: function () {
        //记录滚动cache
        $(this.options.el).find('.scroll').scroll(function () {
            var height = $(this).scrollTop();
            oeui_cache.cacheScrollTop(height);
        });
    },
    pullUpLoad: function (option) {
        var _this = this;
        var defaults = {
            el: '',
            url: '',
            listWrap: '',
            data: {},
            type: 'POST'
        }
        _this.options = $.extend({}, defaults, option);
        if(typeof _this.options.el == 'string') {
            _this.options.el = document.querySelector(_this.options.el);
        }
        this._scroll();
    
        //获取cache list
        if (oeui_cache.getCacheTotalPage() > 1 && oeui_cache.isLoadCacheList()) {
            var cache_list_data = oeui_cache.getCacheList();
            if (typeof(cache_list_data) == "undefined") {
                cache_list_data = "";
            }
            var cache_height = oeui_cache.getCacheScrollTop();
            this.cache_next_page = oeui_cache.getCacheNextPage();
            if (this.cache_next_page != "" || this.cache_next_page == '0') {
                $("#page").val(this.cache_next_page);
                _this.options.data.page = this.cache_next_page;
            } else {
                _this.options.data.page = '0'
            }
            var data = $(cache_list_data);
            $(_this.options.listWrap).html(data);
            var top = $(_this.options.listWrap).find('.item:last-child').css('top');
            var height = $(_this.options.listWrap).find('.item:last-child').height();
            $(_this.options.listWrap).html(data).css('height', (parseFloat(top) + height)+'px');
            $(_this.options.el).find('.scroll').scrollTop(cache_height);
            _this.pull_cache = 1; //0.02.06
        }
    
        var router_c = oeui_cache.getUrlparam('c');
        var arr = [];
        arr.push(router_c);
        sessionStorage.setItem('oeui_router', JSON.stringify(arr));

        setTimeout(function () {
            var pullUpLoad = OEUI.pullUpLoad({
                el: _this.options.el,
                pullUp: function (pullUp) {
                    if(_this.options.data.page == '' || _this.cache_next_page == '0') {
                        pullUp.complete();
                        return;
                    }
                    $.ajax({
                        type: _this.options.type,
                        url: _this.options.url,
                        data: _this.options.data,
                        success: function (json) {
                            var res = JSON.parse(json);
                            if(res.response == '1') {
                                _this.options.data.page = res.nextpage;

                                oeui_cache.cacheNextPage(res.nextpage);
                                oeui_cache.cacheTotalPage(res.pagecount);
                                var str = res.result;
                                // var reg = /src=[\"\'\s]+[../|..\\]*[^\.]*\.jpg\"/;
                                // str = str.replace(reg, '');
                                // oeui_cache.cacheList(str);
                                if (res.nextpage == '2') {
                                    oeui_cache.clearScrollTop();
                                }
                            }
                            option.success({
                                type: 'ajax',
                                scroll: pullUp,
                                response: res
                            });
                        },
                        error: function () {
                            OEUI.toast({
                                text: '网络繁忙，请稍后再试'
                            });
                            if(typeof option.error == 'function') {
                                option.error();
                            }
                        }
                    });
                }
            });
            option.success({
                type: 'cache',
                scroll: pullUpLoad
            });
        })
    },
    pullDownRefresh: function (option) {
        var _this = this;
        var defaults = {
            el: '',
            url: '',
            listWrap: '',
            data: {},
            type: 'POST'
        }
        if(this.options.data && this.options.data.page) {
            defaults.page = this.options.data.page;
        }
        _this.options = $.extend({}, defaults, option);
        if(typeof _this.options.el == 'string') {
            _this.options.el = document.querySelector(_this.options.el);
        }
        OEUI.pullDownRefresh({
            el: _this.options.el,
            refresh: function (pullDown) {
                _this.options.data.page = '1';
                $.ajax({
                    type: _this.options.type,
                    url: _this.options.url,
                    data: _this.options.data,
                    success: function (json) {
                        pullDown.complete();
                        var res = JSON.parse(json);
                        if(res.response == '1') {
                            oeui_cache.cacheNextPage(res.nextpage);
                            oeui_cache.cacheTotalPage(res.pagecount); //0.02.10
                            var str = res.result;
                            var reg = /src=[\"\'\s]+[../|..\\]*[^\.]*\.jpg\"/;
                            str = str.replace(reg, '');
                            oeui_cache.cacheList(str);
                            _this.options.data.page = res.nextpage;
                            _this.cache_next_page = res.nextpage;
                        } 
                        option.success(res);
                    },
                    error: function () {
                        OEUI.toast({
                            text: '网络繁忙，请稍后再试'
                        });
                        if(option.error) {
                            option.error();
                        }
                    }
                });
            }
        });
    },
    setData: function (data) {
        this.options.data = $.extend({}, this.options.data, data);
    }
  }
  if(!window['scrollList']) {
      window.scrollList = scrollList;
  }
})($);


$(function () {
    //会员列表
    function User () {
        this.pull_box_id = "pull_box";
        this.pull_data_id = "pull_data";
        this.scroll = null; //下拉组件
        this.page = '1';
        this.heightArray = [0, 0];
        this.is_get_height = false;

        this.scrollList = new scrollList();
        
        this.setHeight();
        this.pullDownRefresh();
        this.pullUpLoad();
        this.backTop();
    }
    User.prototype = {
        //设置初始高度
        setHeight: function () {
            var height = document.getElementById('pull_data').clientHeight;
            this.heightArray = [height, height];
        },
        //上拉分页
        pullUpLoad: function () {
            var _this = this;
            var data = {
                c: WAP_C,
                a: 'list',
                datatype: 'json',
                page: _this.page
            }
            var param = $.extend({}, data);
            this.scrollList.pullUpLoad({
                el: document.getElementById(_this.pull_box_id),
                listWrap: document.getElementById(_this.pull_data_id),
                url: WAP_APPFILE,
                data: param,
                success: function (data) {
                    _this.scroll = data.scroll;
                    var res = data.response;
                    if(data.type == 'ajax') {
                        if(res.response == '1') {
                            if(res.result != '') {
                                var domNode = $(res.result);
                                domNode.css('opacity', '0');
                                $('#'+ _this.pull_data_id).append(domNode);
                                var img = domNode.find('img');
                                var p = img.map(function (i, v) {
                                    return new Promise(function (resolve, reject) {
                                        v.onload = function () {
                                            resolve();
                                        };
                                    });
                                });
                                Promise.all(p).then(function () {
                                    _this.waterfall(domNode);
                                    LazyLoad('.lazyload');
                                    var html = $('#pull_data').html();
                                    sessionStorage.setItem('oeui_list', html);
                                });
                            }
                            if(res.nextpage != '0') {
                                _this.scroll.done();
                            } else if (res.pagecount == '0' && res.result == '') {
                                _this.scroll.noData(true);
                            } else if(res.pagecount != '0') {
                                _this.scroll.complete();
                            } else {
                                _this.scroll.noData();
                            }
                        } else {
                            if (res.result) {
                                OEUI.toast({
                                    text: res.result
                                });
                            } else {
                                OEUI.toast({
                                    text: '网络繁忙，请稍后再试'
                                });
                            }
                        }
                    } else if (data.type == 'cache') {
                        _this.scroll = data.scroll;
                    }
                }
            });
        },
        //下拉刷新
        pullDownRefresh: function () {
            var _this = this;
            var data = {
                c: WAP_C,
                a: 'list',
                datatype: 'json',
                page: _this.page
            }
            var param = $.extend({}, data);
            this.scrollList.pullDownRefresh({
                el: document.getElementById(_this.pull_box_id),
                listWrap: document.getElementById(_this.pull_data_id),
                url: WAP_APPFILE,
                data: param,
                success: function (data) {
                    var res = data;
                    if(res.response == '1') {
                        if(res.result != '') {
                            $('#'+ _this.pull_data_id).html($(res.result)).css('height', 'auto');
                            _this.heightArray = [0,0];
                            var domNode = $(res.result);
                            domNode.css('opacity', '0');
                            $('#'+ _this.pull_data_id).html(domNode);
                            var img = domNode.find('img');
                            var p = img.map(function (i, v) {
                                return new Promise(function (resolve, reject) {
                                    v.onload = function () {
                                      resolve();
                                    };
                                });
                            });
                            Promise.all(p).then(function () {
                                _this.waterfall(domNode);
                                LazyLoad('.lazyload');
                                _this.scroll.refresh();
                            });
                        }
                        if(res.nextpage != '0') {
                            _this.scroll.done();
                        } else if (res.pagecount == '0' && res.result == '') {
                            _this.scroll.noData(true);
                        } else if(res.pagecount != '0') {
                            _this.scroll.complete();
                        } else {
                            _this.scroll.noData();
                        }
                    } else {
                        if (res.result) {
                            OEUI.toast({
                                text: res.result
                            });
                        } else {
                            OEUI.toast({
                                text: '网络繁忙，请稍后再试'
                            });
                        }
                    }
                }
            });
        },
        //瀑布流
        waterfall: function (nodeList) {
            if(!this.is_get_height) {
                this.setHeight();
                this.is_get_height = true;
            }
            //取得所有盒子
            var boxes = nodeList.map(function (i, v) {
                if (v.nodeName != '#text') {
                    return v;
                }
            });

            if (boxes.length == 0) {
                return;
            }

            var boxW = boxes[0].offsetWidth;
            var col = Math.floor(window.innerWidth / boxW);
            var cover = null;

            for (var i = 0; i < boxes.length; i++) {
                if (i < col && this.heightArray.length <= 2 && this.heightArray[i] == 0) {
                    //第一行
                    boxes[i].style.top = 0;
                    boxes[i].style.left = i * boxW + 'px';
                    boxes[i].style.opacity = '1';
                    cover = boxes[i].querySelector('.cover');
                    if(cover && cover.length > 0) {
                        cover.style.height = cover.offsetHeight + 'px';
                    }
                    this.heightArray[i] = boxes[i].offsetHeight;
                } else {
                    //其他行
                    //  1. 找到数组的最小值
                    //      使用展开运算符...，将nums展开，之后，传递给Math.min(),就可以取得最小高度
                    var minH = Math.min.apply(Math, this.heightArray);
                    var minIndex = this.heightArray.indexOf(minH);
                    boxes[i].style.top = minH + 'px';
                    boxes[i].style.left = minIndex * boxW + 'px';
                    boxes[i].style.opacity = '1';
                    cover = boxes[i].querySelector('.cover');
                    if(cover && cover.length > 0) {
                        cover.style.height = cover.offsetHeight + 'px';
                    }

                    this.heightArray[minIndex] = minH + boxes[i].offsetHeight;
                }
            }

            $('#'+ this.pull_data_id).css('height', Math.max.apply(Math, this.heightArray) + 'px');
        },
        //返回顶部
        backTop: function () {
            var _this = this;
            var scroll = $('#'+ _this.pull_box_id+' .scroll')[0];
            $('[f="back_to_top"]').on('click', function () {
                _this.animateToTop(scroll.scrollTop, 0, 4, function (value) {
                    scroll.scrollTop = value;
                });
            });
        },
        //返回顶部动画
        animateToTop: function (m, n, rate, cb) {
            if(m == n || typeof m != 'number') {
                return;
            }
            if(!window.requestAnimationFrame) {
                requestAnimationFrame = function (fn) {
                    setTimeout(fn, 1000/60);
                }
            }
            n = n || 0;
            rate = rate || 2;
            var step = function () {
                m = m + (n - m)/rate;
                if(m<1) {
                    cb(n, true);
                    return;
                }
                cb(m, false);
                requestAnimationFrame(step);
            }
            step();
        },
        //刷新
        refresh: function () {
          
        }
    }
    _inst_oepage = new User();


    //懒加载
    function LazyLoad (el, options) {
        if (!(this instanceof LazyLoad)) {
            return new LazyLoad(el);
        }

        this.setting = $.extend({}, { src: 'data-src', srcset: 'data-srcset', selector: '.lazyload' }, options);

        if (typeof el === 'string') {
            el = document.querySelectorAll(el);
        }
        this.images = Array.prototype.slice.call(el);

        this.listener = this.loadImage();
        this.listener();
        this.initEvent();
    }
    LazyLoad.prototype = {
        loadImage () {
            var _this = this;
            return this.throttle(function () {
                var startIndex = 0;
                while (startIndex < _this.images.length) {
                    var image = _this.images[startIndex];
                    if (_this.isElementInViewport(image)) {
                        var src = image.getAttribute(_this.setting.src);
                        var srcset = image.getAttribute(_this.setting.srcset);
                        if (image.tagName.toLowerCase() === 'img') {
                            if (src) {
                                image.src = src;
                            }
                            if (srcset) {
                                image.srcset = srcset;
                            }
                        } else {
                            image.style.backgroundImage = 'url('+ src +')';
                        }
                        _this.images.splice(startIndex, 1);
                        continue;
                    }
                    startIndex++;
                }
                if (!_this.images.length) {
                    _this.destroy();
                }
            });
        },
        initEvent () {
            document.querySelector('#pull_box .scroll').addEventListener('scroll', this.listener, false);
        },
        destroy () {
            document.querySelector('#pull_box .scroll').addEventListener('scroll', this.listener, false);
            this.images = [];
            this.listener = null;
        },
        throttle (fn, interval) {
            var timer = null;
            var firstTime = true;
            interval || (interval = 500);
      
            return function () {
                var args = Array.prototype.slice.call(arguments);
                if (firstTime) {
                    // 第一次加载
                    fn.apply(this, args);
                    return firstTime = false;
                }
      
                if (timer) {
                    // 定时器正在执行中，跳过
                    return;
                }
      
                timer = setTimeout(function () {
                    clearTimeout(timer);
                    timer = null;
                    fn.apply(this, args);
                }, interval);
            }
        },
        isElementInViewport (el) {
            var rect = el.getBoundingClientRect();
            var top = rect.top;
            var height = rect.height; 
            var left = rect.left;
            var width = rect.width;
            var w = window.innerWidth || document.documentElement.clientWidth;
            var h = window.innerHeight || document.documentElement.clientHeight;
            return (
                top <= h &&
                (top + height) >= 0 &&
                left <= w &&
                (left + width) >= 0
            );
        }
    }
    
});