/**
 * 基于excel.js的功能进行table的扩展
 * 使用步骤:

  1) 引入'tableExt'组件
  2) 开启导出功能的配置:exportOpt
  3) 在table的cols配置exportable:true开启excel导出功能
  4) 根据需要进行字段格式化：exportFormat:function(){}
  5) 通过tableExt.getLayuiTable() 获取原生的 layui table对象，然后再用layui 的table对象进行监听操作。

    完整实例：

    layui.config({
        base: '${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'tableExt', 'jquery', 'layer'], function(){                !!!!------- step 1)!!!!
        var tableExt = layui.tableExt;
        var layer = layui.layer;
        var $ = layui.jquery;

        tableExt.render({
            elem: '#test-table-reload'
            ,url: '${ctx}/member/getMemberData'
            ,cols: [[
                {checkbox: true}
                ,{field:'id', title: '操作',toolbar: '#table-toolbar'}
                ,{field:'status', title: '状态',
                    templet: function(d){
                        return d.status == '0' ? '正常' : '';
                    },
                    exportable:true,            //开启导出功能                     !!!!------- step 3)!!!!
                    expFormat: function(data){  //格式导出的化字段                  !!!!------- step 3)!!!!
                        console.log("expFormat:", data);
                        return "哈哈";
                    }
                }
                ,{field:'name', title: '姓名', exportable:true}
                ,{field:'roles', title: '角色'}
                ,{field:'login_name', title: '登录帐号'}
                ,{field:'mobile', title: '手机号'}
                ,{field:'hiredate', title: '入职时间'}
            ]]
            ,done: function(res, curr, count){
                console.log("customer done", res);
            },exportOpt:{                           //导出选项配置                    !!!------- step 2)!!!
                ele:'#exportBtn',                   //导出的Dom元素
                headerTitle: '员工列表',             //excel表格的标题
                pageData:false,                     //true:导出的数据为页面数据，false:最大导出maxAmount条数据
                maxAmount: 1000,                    //当pageData为false生效
                fileName: '员工导出',
                where: function (){                 //当pageData为false时生效，过滤的条件
                    var ret = {};
                    ret.name= $("#form-name").val();
                    return ret;
                }
            }
        });

        var table = tableExt.getLayTable();                                         !!!------- step 4)!!!

        //监听行工具事件
        table.on('tool(table-toolbar)', function(obj){
            var data = obj.data;
            var memberId = data.id;
            if(obj.event === 'del'){
                layer.confirm('真的删除所选人员吗？', function(index){
                    $.post('${ctx}/member/delMember', {id: memberId}, function(result){
                        if("ok" == result){
                            layer.msg("删除成功");
                            obj.del();
                            layer.close(index);
                        }else{
                            layer.msg("删除失败");
                        }
                    });
                });
            } else if(obj.event === 'edit'){
                goMemberform('修改员工信息', '${ctx}/member/memberForm?id=' + memberId);
            }
        });
    });


 *
 */

layui.define(['table', 'jquery', 'excel', 'layer'],function (exports) {
    var table = layui.table;
    var excel = layui.excel;
    var $ = layui.jquery;
    var dataItem= [];

    var opt = {
        exportOpt:{
            ele:'#ele',         //导出的Dom元素
            pageData:true,      //true:导出的数据为页面数据，false:最大导出maxAmount条数据
            maxAmount: 1000,     //当pageData为false生效
            where:{}            //当pageData为false时生效，过滤的条件
        }
    };

    var tableExt = {
        render: function(options){
            var $this = this;
            var doneFunc =options.done;
            var isDF = $.isFunction(doneFunc);
            if(isDF){
                options.done = undefined;
            }
            opt.done = function(res, curr, count){       //layuiTable加载完成后的回调
                dataItem = res.data;
                if(isDF){
                    doneFunc.call(this, res, curr, count);
                }
                $this.bindExport();
            };
            opt = $.extend(opt, options);
            table.render(opt);
        },
        reload: function(id, options){
            var $this = this;
            var doneFunc = options.done;
            var isDF = $.isFunction(doneFunc);
            if(isDF){
                options.done = undefined;
            }
            options.done = function(res, curr, count){
                dataItem = res.data;
                if(options.cols != undefined){
                    opt.cols = cols;
                }
                if(isDF){
                    doneFunc.call(this, res, curr, count);
                }
                $this.bindExport();
            }

            if(this.isStr(id)){
                table.reload(id, options);
            }else{
                table.reload(options);
            }
        },
        isStr: function isString(str){
            return (typeof str=='string')&&str.constructor==String;
        },
        bindExport: function(){
            var $this = this;
            $(opt.exportOpt.ele).off('click');
            $(opt.exportOpt.ele).on('click', function(){
                $this.activeExport();
            });
        },
        getLayTable : function () {
            return table;
        },
        activeExport: function(){
            var SEPTAG = "-@#@-";
            var url = opt.url;
            if(opt.exportOpt != undefined && $(opt.exportOpt.ele) != undefined){
                if(!opt.exportOpt.pageData){//非导出当前页数据，则导出上限为maxAmount的数据
                    var whereData = {};
                    if($.isFunction(opt.exportOpt.where)){
                        whereData = opt.exportOpt.where.call();
                    }
                    var queryWhere = $.extend({limit: opt.exportOpt.maxAmount, page: 1}, whereData);
                    $.ajax({
                        url: url,
                        type: 'post',
                        async: false,
                        data: queryWhere,
                        success: function($result){
                            var result = eval("(" + $result + ")");
                            if(result.data && result.data.length > 0){
                                dataItem = result.data;
                            }else{
                                dataItem = [""];
                            }
                        }
                    });
                }
                var header = {};
                var headerFilter = {};
                var formatFuns = {};
                var firstField = "";
                $.each(opt.cols[0], function(idx, item){
                    if(item.exportable){
                        if (item.exportChildren) {
                            for (var i = 0; i < item.exportChildren.length; i++) {
                                var child = item.exportChildren[i];
                                header[child.field] = child.title;
                            }
                        } else {
                            header[item.field] = item.title;
                        }
                        if($.isFunction(item.expFormat)){
                            formatFuns[item.field] = item.expFormat;
                        }
                        if(firstField == ""){
                            firstField = item.field;
                        }else{
                            headerFilter[item.field] = item.field;
                        }
                    }
                });

                var colTitleHeader = {};
                for(att in header){
                    colTitleHeader[att] = SEPTAG + header[att];
                }

                dataItem.unshift(colTitleHeader);
                var headerTmp = {};
                headerTmp[firstField] = SEPTAG;
                dataItem.unshift(headerTmp);
                var headerFilterConfig = {};
                var headCount = 0;
                headerFilterConfig[firstField] = function(value, line, data){
                    if(line[firstField] == SEPTAG){
                        return {
                            v: opt.exportOpt.headerTitle,// v 代表单元格的值
                            s:{// s 代表样式
                                alignment: {
                                    horizontal: 'center',
                                    vertical: 'center',
                                },
                                font: { sz: 15, bold: true, color: { rgb: "000000" } },
                                fill: { bgColor: { indexed: 64 }, fgColor: { rgb: "cccccc" } },
                                /*border:{
                                    bottom:{ style: "thin", color: "cccccc"},
                                }*/
                            }
                        }
                    }else{
                        if(headCount == 0){
                            headCount = 1;
                            if(value != undefined && (value+"").indexOf(SEPTAG) != -1){
                                return (value+"").substring(5);
                            }
                            return value;
                        }else{
                            if(value != undefined && (value+"").indexOf(SEPTAG) != -1){
                                return (value+"").substring(5);
                            }
                            var func_ = formatFuns[firstField];
                            if($.isFunction(func_)){
                                if(line != "" && line != undefined){
                                    return func_.call(this, line);
                                }
                                return "";
                            }else{
                                return value;
                            }
                        }
                    }
                };

                var colCount = 1;
                $.each(header, function(i, field) {
                    colCount++;
                    if(i != firstField){
                        var func_ = formatFuns[i];
                        if($.isFunction(func_)){
                            headerFilterConfig[i] = function(value, line, data){
                                if(value != undefined && (value+"").indexOf(SEPTAG) != -1){
                                    return (value+"").substring(5);
                                }

                                if(value != undefined && line != undefined ){
                                    return func_.call(this, line);
                                }
                            };
                        }else{
                            headerFilterConfig[i] = function(value, line, data){
                                if(value != undefined && (value+"").indexOf(SEPTAG) != -1){
                                    return value.substring(5);
                                }
                                return value;
                            }
                            //headerFilterConfig[i] = headerFilter[i];
                        }
                    }
                });

                var data = excel.filterExportData(dataItem, headerFilterConfig);
                var label = excel.numToTitle(colCount);
                var mergeConf = excel.makeMergeConfig([
                    ['A1', label+'1']
                ]);
                var colConfigOpt = {};
                colConfigOpt["A"] = 80;
                colConfigOpt[label] = 80;
                var colConfig = excel.makeColConfig(colConfigOpt, 80);
                var size = dataItem.length;
                var rowConfigOpt = {};
                rowConfigOpt["1"] = 40;
                rowConfigOpt["" + (size)] = 20;
                var rowConfig = excel.makeRowConfig(rowConfigOpt, 20);

                excel.exportExcel({
                    "sheet1": data
                }, opt.exportOpt.fileName+'.xlsx', 'xlsx',{
                    extend: {
                        // extend 中可以指定某个 sheet 的属性，如果不指定 sheet 则所有 sheet 套用同一套属性
                        "sheet1": {
                            // 以下配置仅 sheet1 有效
                            '!merges': mergeConf,
                            '!cols': colConfig,
                            '!rows': rowConfig
                        }
                    }
                });
            }
        }
    }
    exports("tableExt",tableExt);
});