/**
 * 需在页面定义三个元素 tr的元素当作当前元素 id 自定义 默认header
 * tr的父级元素 table id默认为tr的id加Parent后缀
 * 浮动表格元素 table id默认为tr的id加Roll后缀
 *
 * 21-03-04 zzd 注意：历史遗留问题在使用reset方法时column的key应为columns
 * */

window.sort=require('../utilities/sort');
window.Header = function getHeader(object) {
    this._header = object.el || '#header';  //基点元素
    this._columns = object.column;   //列名
    this._data = object.data;   //被排序数据
    this._restorationColumn = object.restorationColumn; //恢复原数据基准字段
    this._fixedTop = object.fixedTop || 0;  //同级浮动元素高度，使当前元素追加该元素高度浮动
    this._offset = object.offset || 0;  //偏移量
    this._is_restorationColumn_asc = object.is_restorationColumn_asc || false;    //恢复原数据基准字段的排序类型 true:asc false:desc
    this._vue = object.vue || null; //vue容器
    this._checkbox = object.checkbox || 'checkData';    //全选数据列名
    this._closeFloat = object.closeFloat || false;  //是否开启浮动

    let _this = this;
    let _parentNode = $(_this._header);
    let sortType = {};
    let columnArr = [];
    // form fixed
    let _headerParent = $(_this._header+"Parent");
    let _parentNodeTemp = _parentNode.clone();
    //滚动监听
    function fixed() {
        let _parentNode_top = _parentNode.offset().top;
        $(window).scroll(function(){
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            if (scrollTop > _parentNode_top-_this._fixedTop) {
                $(_this._header+"Roll").removeClass('d-none');
            } else {
                $(_this._header+"Roll").addClass('d-none');
            }
            let scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
            if (scrollLeft > 0){
                _parentNodeTemp.css('margin-left',0-(scrollLeft));
            }else{
                _parentNodeTemp.css('margin-left',"");
            }
        });
        let resetTrWidth = function(){
            _parentNodeTemp.css('width',($(document).width()-_parentNodeTemp.offset().left*2)+'px');
                // _this._columns.forEach(function (column){
                //     let protoTargetWidth = (parseInt($("#dom_" + column.name ).css('width')))-16;
                //     let floatingColumn = $("#dom_" + column.name + "_temp");
                //     floatingColumn.css('width', protoTargetWidth);
                //     floatingColumn.find('span').css('width', protoTargetWidth);
                // })
        };
        $(window).resize(resetTrWidth);
        setTimeout(resetTrWidth,200)
    }

    /**
     * column :{customization : null || bool   --是否自定义
     *          dom : null || element           --自定义元素
     *          style :  null || string         --样式
     *          name : null || string           --字段名,英文
     *          value : string                  --列名
     *          neglect : null || bool          --是否忽略排序
     *         }
     * */
    //点击事件触发的排序规则
    function rule(column,column_sort,column_sort_temp=null) {
        return function () {
            if (!sortType[column.name]){
                sortType[column.name] = 'asc';
                columnArr.push(column.name);
                column_sort.removeClass('fa-sort').addClass('fa-sort-asc');
                if (column_sort_temp) column_sort_temp.removeClass('fa-sort').addClass('fa-sort-asc');
                let columnArrTemp = [];
                columnArrTemp.push.apply(columnArrTemp,columnArr);
                window.sort.sort(_this._data,columnArrTemp,sortType);
                return ;
            }
            if (sortType[column.name] === 'asc'){
                sortType[column.name] = 'desc';
                column_sort.removeClass('fa-sort-asc').addClass('fa-sort-desc');
                if (column_sort_temp)column_sort_temp.removeClass('fa-sort-asc').addClass('fa-sort-desc');
                let columnArrTemp = [];
                columnArrTemp.push.apply(columnArrTemp,columnArr);
                window.sort.sort(_this._data,columnArrTemp,sortType);
                return ;
            }
            if (sortType[column.name] === 'desc'){
                delete sortType[column.name];
                columnArr.some(function (name, index) {
                    if (name === column.name){
                        columnArr.splice(index,1);
                        return true;
                    }
                });
                column_sort.removeClass('fa-sort-desc').addClass('fa-sort');
                if (column_sort_temp)column_sort_temp.removeClass('fa-sort-desc').addClass('fa-sort');
                if (columnArr.length === 0){
                    //希尔排序
                    let arr = [];
                    arr.push.apply(arr,_this._data);
                    let len = arr.length;
                    for(let gap = Math.floor(len / 2); gap > 0; gap = Math.floor(gap / 2)) {
                        for(let i = gap; i < len; i++) {
                            let j = i;
                            let current = arr[i];
                            if (_this._is_restorationColumn_asc){
                                while(j - gap >= 0 && Number(current[_this._restorationColumn]) < Number(arr[j - gap][_this._restorationColumn])) {
                                    arr[j] = arr[j - gap];
                                    j = j - gap;
                                }
                            }else{
                                while(j - gap >= 0 && Number(current[_this._restorationColumn]) > Number(arr[j - gap][_this._restorationColumn])) {
                                    arr[j] = arr[j - gap];
                                    j = j - gap;
                                }
                            }
                            arr[j] = current;
                        }
                    }
                    _this._data.length = 0;
                    _this._data.push.apply(_this._data,arr);
                    return;
                }
                let columnArrTemp = [];
                columnArrTemp.push.apply(columnArrTemp,columnArr);
                window.sort.sort(_this._data,columnArrTemp,sortType);
            }
        }
    }
    //追加表头字段
    function append() {
        _this._columns.forEach(function (column) {
            if (column.customization){
                let _th = $("<th id='dom_"+column.name+"'><span style='display: inline-block'></span></th>");
                $(_th.children()[0]).append(column.dom);
                _parentNode.append(_th);
            }else{
                let _td = "<th id='dom_"+column.name+"' style='";
                if(!column.neglect){
                    _td += "cursor: pointer;"
                }
                if (column.style) _td += column.style;
                _td += "' ";
                if (column.class) _td += "class='"+column.class+"'";
                _td += ">";
                _td += "<span style='display: inline-block'>";
                if(!column.neglect){
                    _td += "<span id='sort_"+column.name+"' class='fa fa-sort'></span>";
                }
                _td += column.value+"</span>";
                _td += "</th>";
                _parentNode.append(_td);
                if (!column.neglect) {
                    let column_sort = $('#sort_' + column.name);
                    let column_dom = $('#dom_'+column.name);
                    column_dom.on('click',rule(column,column_sort));
                }
            }
        });
    }
    //追加浮动表头：克隆表头元素，改变元素属性
    function cloneDom(){
        let height = _parentNode.height();
        _parentNodeTemp.css('position',"fixed");
        _parentNodeTemp.css('top',_this._fixedTop+"px");
        _parentNodeTemp.css('z-index',"1030");
        _parentNodeTemp.css('width',_headerParent.width()+"px");
        _parentNodeTemp.css('background',"rgb(255, 255, 255)");
        _parentNodeTemp.addClass('text-center');
        _parentNodeTemp.height(height);
        _parentNodeTemp.attr('id',_parentNode.attr('id')+"Temp");
        $(_this._header+"Roll").append(_parentNodeTemp);
        _this._columns.forEach(function (column) {
            let column_dom = $('#dom_'+column.name);
            let column_dom_temp = column_dom.clone();
            let columnNameDom = column_dom_temp.children()[0];
            if (column.customization){
                if (column.type === 'checkAll'){
                    var checkbox = $($(columnNameDom).children()[0]).children()[0];
                    checkbox.id = checkbox.id+"_temp";
                }
            }
            if (!column.neglect){
                $(columnNameDom).children()[0].id = 'sort_'+column.name+"_temp";
            }
            column_dom_temp.attr('id','dom_'+column.name+"_temp");
            $(columnNameDom).css('width',column_dom.width()+_this._offset);
            _parentNodeTemp.append(column_dom_temp);
            if (!column.neglect){
                let column_sort = $('#sort_'+column.name);
                let column_sort_temp = $('#sort_'+column.name+"_temp");
                column_dom.off('click');
                column_dom.on('click',rule(column,column_sort,column_sort_temp));
                column_dom_temp.on('click',rule(column,column_sort,column_sort_temp));
            }
            if (column.customization){
                if (column.type === 'checkAll'){
                    checkAll($(checkbox),column.column);
                }
            }
        });
    }
    //初始化
    this.init = function() {
        append();
        if (_this._closeFloat)return;
        fixed();
        cloneDom();
    };

    this.reset = function(params = null){
        _parentNode.empty();
        _parentNodeTemp.empty();
        if (params)for (let key in params)this["_"+key] = params[key];
        this.init();
    };

    function checkAll(dom,column){
        dom.on('click',function () {
            if ($(this).is(":checked")== true) {
                _this._vue[_this._checkbox].length = 0;
                _this._data.forEach(function (object) {
                    if (column) {
                        object = object[column];
                    }
                    _this._vue[_this._checkbox].push(object);
                });
            } else {
                _this._vue[_this._checkbox].length = 0;
                _this._vue.$forceUpdate();
            }
        });
    }
};
