var ExcelData,ExcelKind;
function ConfirmImport() {
    $.ajax({
        type: "POST",
        url: "/Admin/KqProductRuleSet/Import?r=" + Math.random(1),
        data: "ExcelData=" + encodeURIComponent(JSON.stringify(ExcelData)),
        dataType: "text",
        success: function (data) {
            if (data == "success") {
                layer.msg("导入成功", { time: 2000 }, function () {
                    window.location.reload();
                });
            } else {
                layer.msg(data);
            }
        }
    });
}

var excel;
layui.config({
    base: '/layuiadmin/' //静态资源所在路径
}).extend({
    myexcel: 'layui/lay/modules/excel',
    index: 'lib/index' //主入口模块
}).use(['index', 'table', 'excel', 'laydate'], function () {
    var $ = layui.$
        , form = layui.form
        , table = layui.table;

    //- 筛选条件-日期
    var laydate = layui.laydate;
    

    //excel导入
    excel = layui.excel;        
    $('#ExcelFile').change(function (e) {
        var files = e.target.files;
        excel.importExcel(files, { }, function (data) {
            ExcelData = data[0].sheet1;
        });
    });

    //监听单元格编辑
    table.on('edit(LAY-list-manage)', function(obj){
        var value = obj.value //得到修改后的值
        ,data = obj.data //得到所在行所有键值
        ,field = obj.field; //得到字段
        if(field == "Sort"){
            $.ajax({
                type: "POST",
                url: "/Admin/KqProductRuleSet/Sort?r=" + Math.random(1),
                data: "Id=" + data.Id + "&Sort=" + value,
                dataType: "text",
                success: function (data) {
                }
            });
        }
    });
    
    //列表数据
    table.render({
        elem: '#LAY-list-manage'
        , url: '/Admin/KqProductRuleSet/IndexData' //模拟接口
        , cols: [[
            { type: 'checkbox', fixed: 'left' }
    		, {field:'Id', fixed: 'left', title:'ID', width:80, sort: true, unresize: true}
            ,{field:'StatusName', width: 200, title:'状态', sort: true}
,{field:'Deposit', width: 200, title:'押金', sort: true}
,{field:'ActiveCount', width: 200, title:'活动政策台数', sort: true}
,{field:'ActivePrice', width: 200, title:'活动政策价格', sort: true}
,{field:'MerStaStartDate', width: 200, title:'活动开始时间', sort: true}
,{field:'MerStaEndDate', width: 200, title:'活动结束时间', sort: true}
,{field:'MerStaProfit', width: 200, title:'达标奖励', sort: true}
,{field:'MerStaMonths', width: 200, title:'激活后达标月', sort: true}
,{field:'MerStaTradeForMonth', width: 200, title:'激活后每月达标交易', sort: true}
,{field:'ActStartDate', width: 200, title:'活动开始时间', sort: true}
,{field:'ActEndDate', width: 200, title:'活动结束时间', sort: true}
,{field:'ActDeposit', width: 200, title:'激活押金', sort: true}
,{field:'ActFirst', width: 200, title:'激活首刷', sort: true}
,{field:'ActFirstDeposit', width: 200, title:'激活首刷押金', sort: true}
,{field:'ActPrize', width: 200, title:'激活奖励金额', sort: true}
,{field:'ActPosCount', width: 200, title:'激活赠机台数', sort: true}
,{field:'OpenStartDate', width: 200, title:'活动开始时间', sort: true}
,{field:'OpenEndDate', width: 200, title:'活动结束时间', sort: true}
,{field:'OpenStaDays', width: 200, title:'达标天数', sort: true}
,{field:'OpenStaTrade', width: 200, title:'达标交易', sort: true}
,{field:'OpenStaPrize', width: 200, title:'达标奖励1', sort: true}
,{field:'OpenStaPrize2', width: 200, title:'达标奖励2', sort: true}
,{field:'CycleStartDate', width: 200, title:'活动开始时间', sort: true}
,{field:'CycleEndDate', width: 200, title:'活动结束时间', sort: true}
,{field:'CycleIsOtherName', width: 200, title:'是否允许划拨给他人', sort: true}
,{field:'CyclePosDays', width: 200, title:'领机天数', sort: true}
,{field:'PullNewStartDate', width: 200, title:'活动开始时间', sort: true}
,{field:'PullNewEndDate', width: 200, title:'活动结束时间', sort: true}
,{field:'PullNewExtendDays', width: 200, title:'延长领机天数', sort: true}
,{field:'BigTotalAmount', width: 200, title:'购买机起始价', sort: true}
,{field:'BigExtendCycleDays', width: 200, title:'延长循环周期天数', sort: true}
,{field:'SubsidyStartDate', width: 200, title:'活动开始时间', sort: true}
,{field:'SubsidyEndDate', width: 200, title:'活动结束时间', sort: true}
,{field:'FlowCardStartDate', width: 200, title:'活动开始时间', sort: true}
,{field:'FlowCardEndDate', width: 200, title:'活动结束时间', sort: true}
,{field:'FlowCardFreeDays', width: 200, title:'免收天数', sort: true}
,{field:'FlowCardFee', width: 200, title:'费用', sort: true}
,{field:'FeeOfDays', width: 200, title:'扣费频率（天）', sort: true}
,{field:'FlowCardDirectProfit', width: 200, title:'直属上级返佣', sort: true}
,{field:'HelpStartDate', width: 200, title:'活动开始时间', sort: true}
,{field:'HelpEndDate', width: 200, title:'活动结束时间', sort: true}
,{field:'HelpMonths', width: 200, title:'计算自然月', sort: true}
,{field:'HelpFee', width: 200, title:'扶植期费率', sort: true}
,{field:'HelpSteadyFee', width: 200, title:'稳定期费率', sort: true}
,{field:'FeeBindDays', width: 200, title:'绑定起天数', sort: true}
,{field:'FeeFixed', width: 200, title:'固定手续费', sort: true}
,{field:'FeeRate', width: 200, title:'费率', sort: true}

            , {field:'Sort', fixed: 'right', title:'排序', width:80, edit: 'text'}
            , { title: '操作', align: 'center', fixed: 'right', toolbar: '#table-list-tools' }
        ]]
        , where: {
            OrgId: OrgId
        }
        , page: true
        , limit: 30
        , height: 'full-220'
        , text: '对不起，加载出现异常！'
        , done: function (res, curr, count) {
            $(".layui-none").text("无数据");
        }
    });

    //监听工具条
    table.on('tool(LAY-list-manage)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            var index = layer.confirm('确定要删除吗？删除后不能恢复！', function (index) {
                $.ajax({
                    type: "POST",
                    url: "/Admin/KqProductRuleSet/Delete?r=" + Math.random(1),
                    data: "Id=" + data.Id,
                    dataType: "text",
                    success: function (data) {
                        if (data == "success") {                            
                            obj.del();
                            layer.close(index);
                        } else {
                            parent.layer.msg(data);
                        }
                    }
                });
            });
        } else if (obj.event === 'edit') {
            var tr = $(obj.tr);
            var perContent = layer.open({
                type: 2
                , title: '产品规则配置-编辑'
                , content: 'Edit?Id=' + data.Id + '&OrgId=' + OrgId + ''
                , maxmin: true
                , area: ['500px', '450px']
                , btn: ['确定', '取消']
                , yes: function (index, layero) {
                    var iframeWindow = window['layui-layer-iframe' + index]
                        , submitID = 'LAY-list-front-submit'
                        , submit = layero.find('iframe').contents().find('#' + submitID);

                    setTimeout(function () { 
                        layero.find('iframe').contents().find('.layui-tab-item').each(function (i) {
                            var errObj = $(this).find('.layui-form-danger');
                            if (errObj.length > 0) {
                                iframeWindow.element.tabChange('mytabbar', String(i + 1));
                                submit.click();
                            }
                        });                        
                    }, 300);

                    
                    
                    
                    

                    //监听提交
                    iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                        var field = data.field; //获取提交的字段
                        var userdata = "";
                        for (var prop in field) {
                            userdata += prop + "=" + encodeURIComponent(field[prop]) + "&";
                        }
                        //提交 Ajax 成功后，静态更新表格中的数据
                        //$.ajax({});
                        
                        $.ajax({
                            type: "POST",
                            url: "/Admin/KqProductRuleSet/Edit?r=" + Math.random(1),
                            data: userdata,
                            dataType: "text",
                            success: function (data) {
                                layer.close(index); //关闭弹层
                                if (data == "success") {
                                    table.reload('LAY-list-manage'); //数据刷新
                                } else {
                                    layer.msg(data);
                                }
                            }
                        });
                    });

                    submit.trigger('click');
                }
                , success: function (layero, index) {

                }
            });
            layer.full(perContent);
        }
    });


    //监听搜索
    form.on('submit(LAY-list-front-search)', function (data) {
        var field = data.field;

        //执行重载
        table.reload('LAY-list-manage', {
            where: field
        });
    });
    form.on('submit(LAY-list-front-searchall)', function (data) {
        table.reload('LAY-list-manage', {
            where: null
        });
    });

    //事件
    var active = {
        batchdel: function () {
            var checkStatus = table.checkStatus('LAY-list-manage')
                , data = checkStatus.data; //得到选中的数据
            if (data.length < 1) {
                parent.layer.msg("请选择要删除的项");
            } else {
                var ids = "";
                $.each(data, function (index, value) {
                    ids += data[index].Id + ",";
                });
                ids = ids.substring(0, ids.length - 1);
                var index = layer.confirm('确定要删除吗？删除后不能恢复！', function (index) {
                    $.ajax({
                        type: "POST",
                        url: "/Admin/KqProductRuleSet/Delete?r=" + Math.random(1),
                        data: "Id=" + ids,
                        dataType: "text",
                        success: function (data) {
                            layer.close(index);
                            if (data == "success") {
                                table.reload('LAY-list-manage');
                            } else {
                                layer.msg(data);
                            }
                        }
                    });
                });
            }
        }
        , add: function () {
            var perContent = layer.open({
                type: 2
                , title: '产品规则配置-添加'
                , content: 'Add?OrgId=' + OrgId + ''
                , maxmin: true
                , area: ['500px', '450px']
                , btn: ['确定', '取消']
                , yes: function (index, layero) {
                    var iframeWindow = window['layui-layer-iframe' + index]
                        , submitID = 'LAY-list-front-submit'
                        , submit = layero.find('iframe').contents().find('#' + submitID);

                    setTimeout(function () { 
                        layero.find('iframe').contents().find('.layui-tab-item').each(function (i) {
                            var errObj = $(this).find('.layui-form-danger');
                            if (errObj.length > 0) {
                                iframeWindow.element.tabChange('mytabbar', String(i + 1));
                                submit.click();
                            }
                        });                        
                    }, 300);

                    
                    
                    
                    

                    //监听提交
                    iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                        var field = data.field; //获取提交的字段
                        var userdata = "";
                        for (var prop in field) {
                            userdata += prop + "=" + encodeURIComponent(field[prop]) + "&";
                        }
                        //提交 Ajax 成功后，静态更新表格中的数据
                        //$.ajax({});
                        
                        $.ajax({
                            type: "POST",
                            url: "/Admin/KqProductRuleSet/Add?r=" + Math.random(1),
                            data: userdata,
                            dataType: "text",
                            success: function (data) {
                                layer.close(index); //关闭弹层
                                if (data == "success") {
                                    table.reload('LAY-list-manage'); //数据刷新
                                } else {
                                    layer.msg(data);
                                }
                            }
                        });
                    });

                    submit.trigger('click');
                }
            });
            layer.full(perContent);
        }
        , ImportData: function () {
            ExcelKind = 1;
            layer.open({
                type: 1,
                title: '导入',
                maxmin: false,
                area: ['460px', '280px'],
                content: $('#excelForm'),
                cancel: function () {
                }
            });
            $("#excelTemp").html('<a href="/excelfile/模板文件.xlsx">点击下载模板文件</a>');
        }
        , ExportExcel: function () {
            var userdata = '';
            $(".layuiadmin-card-header-auto input").each(function (i) {
                userdata += $(this).attr('name') + '=' + encodeURIComponent($(this).val()) + '&';
            });
            $(".layuiadmin-card-header-auto select").each(function (i) {
                userdata += $(this).attr('name') + '=' + encodeURIComponent($(this).val()) + '&';
            });
            $.ajax({
                type: "GET",
                url: "/Admin/KqProductRuleSet/ExportExcel?r=" + Math.random(1),
                data: userdata,
                dataType: "json",
                success: function (data) {
                    data.Obj.unshift(data.Fields);
                    excel.exportExcel(data.Obj, data.Info, 'xlsx');
                }
            });
        }
        , Open: function () {
            var checkStatus = table.checkStatus('LAY-list-manage')
                , data = checkStatus.data; //得到选中的数据
            if(data.length < 1){
                parent.layer.msg("请选择要开启的项");
            }else{
                var ids = "";
                $.each(data, function (index, value) {
                    ids += data[index].Id + ",";
                });
                ids = ids.substring(0, ids.length - 1);
                var index = layer.confirm('确定要开启吗？', function (index) {
                    $.ajax({
                        type: "POST",
                        url: "/Admin/KqProductRuleSet/Open?r=" + Math.random(1),
                        data: "Id=" + ids,
                        dataType: "text",
                        success: function (data) {
                            layer.close(index);
                            if (data == "success") {
                                table.reload('LAY-list-manage');
                            } else {
                                layer.msg(data);
                            }
                        }
                    });
                });
            }
        }
        , Close: function () {
            var checkStatus = table.checkStatus('LAY-list-manage')
                , data = checkStatus.data; //得到选中的数据
            if(data.length < 1){
                parent.layer.msg("请选择要关闭的项");
            }else{
                var ids = "";
                $.each(data, function (index, value) {
                    ids += data[index].Id + ",";
                });
                ids = ids.substring(0, ids.length - 1);
                var index = layer.confirm('确定要关闭吗？', function (index) {
                    $.ajax({
                        type: "POST",
                        url: "/Admin/KqProductRuleSet/Close?r=" + Math.random(1),
                        data: "Id=" + ids,
                        dataType: "text",
                        success: function (data) {
                            layer.close(index);
                            if (data == "success") {
                                table.reload('LAY-list-manage');
                            } else {
                                layer.msg(data);
                            }
                        }
                    });
                });
            }
        }
    };

    $('.layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
});