var ExcelData, ExcelKind;
function ConfirmImport() {
    $.ajax({
        type: "POST",
        url: "/Admin/PosMachinesTwo/Import?r=" + Math.random(1),
        data: "Kind=" + ExcelKind + "&ExcelData=" + encodeURIComponent(JSON.stringify(ExcelData)),
        dataType: "text",
        success: function (data) {
            if (data == "success") {
                layer.msg("导入成功", { time: 2000 }, function () {
                    window.location.reload();
                });
            } else if (data.indexOf("warning") == 0) {
                var datalist = data.split('|');
                layer.alert(datalist[0], { time: 20000 }, 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;
    var layCreateDate = laydate.render({
        elem: '#ActivationTime',
        type: 'date',
        range: true,
        trigger: 'click',
        change: function (value, date, endDate) {
            var op = true;
            if (date.year == endDate.year && endDate.month - date.month <= 1) {
                if (endDate.month - date.month == 1 && endDate.date > date.date) {
                    op = false;
                    layCreateDate.hint('日期范围请不要超过1个月');
                    setTimeout(function () {
                        $(".laydate-btns-confirm").addClass("laydate-disabled");
                    }, 1);
                }
            } else {
                op = false;
                layCreateDate.hint('日期范围请不要超过1个月');
                setTimeout(function () {
                    $(".laydate-btns-confirm").addClass("laydate-disabled");
                }, 1);
            }
            if (op) {
                $('#ActivationTime').val(value);
            }
        }
    });

    //- 筛选条件-日期
    var laydates = layui.laydate;
    var layCreateDate = laydates.render({
        elem: '#BindingTime',
        type: 'date',
        range: true,
        trigger: 'click',
        change: function (value, date, endDate) {
            var op = true;
            if (date.year == endDate.year && endDate.month - date.month <= 1) {
                if (endDate.month - date.month == 1 && endDate.date > date.date) {
                    op = false;
                    layCreateDate.hint('日期范围请不要超过1个月');
                    setTimeout(function () {
                        $(".laydate-btns-confirm").addClass("laydate-disabled");
                    }, 1);
                }
            } else {
                op = false;
                layCreateDate.hint('日期范围请不要超过1个月');
                setTimeout(function () {
                    $(".laydate-btns-confirm").addClass("laydate-disabled");
                }, 1);
            }
            if (op) {
                $('#BindingTime').val(value);
            }
        }
    });


    //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/PosMachinesTwo/Sort?r=" + Math.random(1),
                data: "Id=" + data.Id + "&Sort=" + value,
                dataType: "text",
                success: function (data) {
                }
            });
        }
    });

    //列表数据
    table.render({
        elem: '#LAY-list-manage'
        , url: '/Admin/PosMachinesTwo/IndexsData' //模拟接口
        , cols: [[
            { type: 'checkbox', fixed: 'left' }
            , { field: 'PosSn', width: 200, title: 'SN编号', sort: true }
            , { field: 'BrandId', width: 200, title: '产品类型', sort: true }
            , { field: 'UserIdMakerCode', width: 200, title: '创客编号', sort: true }
            , { field: 'UserIdRealName', width: 200, title: '创客姓名', sort: true }
            , { field: 'StoreIdCode', width: 200, title: '所在仓库编号', sort: true }
            , { field: 'StoreIdName', width: 200, title: '所在仓库名称', sort: true }
            , { field: 'StoreMakerCode', width: 200, title: '仓库所属人', sort: true }
            , { field: 'RecycEndDate', width: 200, title: '循环截止时间', sort: true }
            , { field: 'AmountYk', width: 200, title: '应扣金额', sort: true }
            , { field: 'Amountk', width: 200, title: '已扣金额', sort: true }
            , { field: 'AmountDk', width: 200, title: '待扣金额', sort: true }
            // , { field: 'BindMerchantIdMerchantNo', width: 200, title: '绑定商户编号', sort: true }
            // , { field: 'BindMerchantIdMerchantName', width: 200, title: '绑定商户姓名', sort: true }
            // , { field: 'PosSnType', width: 200, title: '机具类型', sort: true }
            // , { field: 'DeviceType', width: 200, title: '设备类型', sort: true }
            // , { field: 'BindingState', width: 200, title: '绑定状态', sort: true }
            // , { field: 'ActivationState', width: 200, title: '激活状态', sort: true }
            // , { field: 'ActivationTime', width: 200, title: '激活时间', sort: true }
            // , { field: 'BindingTime', width: 200, title: '绑定时间', sort: true }
            // , { field: 'TransferTime', width: 200, title: '划拨时间', sort: true }
            // , { field: 'CreateDate', width: 200, title: '入库时间', sort: true }
            // , { field: 'RecycStartDate', width: 200, title: '循环开始时间', sort: true }
            // , { field: 'SourcePosSn', width: 200, title: '来源机具', sort: true }
            // , { field: 'UserInfo', width: 200, title: '大盟主券标记', sort: true }
            // , { field: 'OpCode', width: 200, title: '所属运营中心', sort: true }
            // , { field: 'IsFirst', width: 200, title: '是否第一台机具', sort: true }
            // , { field: 'SeoKeyword', width: 200, title: '实际押金金额', sort: true }
            // , { field: 'PrizeParams', width: 200, title: '设置押金金额', sort: true }
        ]]
        , where: {

        }
        , page: true
        , limit: 30
        , height: 'full-' + String($('.layui-card-header').height() + 130)
        , text: '对不起，加载出现异常！'
        , done: function (res, curr, count) {
            $("#TotalCount").text(res.other.TotalCount);
            $("#AmountYks").text(res.other.AmountYks);
            $("#AmountDks").text(res.other.AmountDks);
            $(".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/PosMachinesTwo/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 + ''
                , 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/PosMachinesTwo/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;
        field.ShowFlag = 1;
        if (field.UserIdMakerCode == "" && field.UserIdRealName == "" && field.StoreIdCode == "" && field.StoreIdName == "" && field.PosSn == "" && field.BindingStateSelect == "" && field.ActivationStateSelect == "" && field.ActivationDateData == "" && field.BindingDateData == "" && field.BrandId == "" && field.IsStoreSelect == "" && field.OpCode == "") {
            layer.alert('请输入查询条件');
        }
        else {
            //执行重载
            table.reload('LAY-list-manage', {
                where: field,
                page: {
                    curr: 1
                }
            });
        }
    });
    form.on('submit(LAY-list-front-searchall)', function (data) {
        var field = data.field;
        field.ShowFlag = 1;
        field.UserIdMakerCode = "";
        field.UserIdRealName = "";
        field.StoreIdCode = "";
        field.StoreIdName = "";
        field.PosSn = "";
        field.BindingStateSelect = "";
        field.ActivationStateSelect = "";
        field.ActivationDateData = "";
        field.BindingDateData = "";
        field.BrandId = "";
        field.IsStoreSelect = "";
        field.OpCode = "";

        table.reload('LAY-list-manage', {
            where: field,
            page: {
                curr: 1
            }
        });
    });

    //事件
    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/PosMachinesTwo/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'
                , 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/PosMachinesTwo/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);
        }
        , RejectStore: function () {
            ExcelKind = 1;
            layer.open({
                type: 1,
                title: '机具驳回仓库导入',
                maxmin: false,
                area: ['460px', '280px'],
                content: $('#excelForm'),
                cancel: function () {
                }
            });
            $("#excelTemp").html('<a href="/users/机具驳回仓库模版.xlsx">点击下载机具驳回仓库模版</a>');
        }
        , 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()) + '&';
            });
            var index = layer.load(1, {
                shade: [0.5, '#000']
            });
            $.ajax({
                type: "GET",
                url: "/Admin/PosMachinesTwo/ExportExcel?r=" + Math.random(1),
                data: userdata,
                dataType: "json",
                success: function (data) {
                    data.Obj.unshift(data.Fields);
                    excel.exportExcel(data.Obj, data.Info, 'xlsx');
                    layer.close(index);
                }
            });
        }
        , 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/PosMachinesTwo/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/PosMachinesTwo/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) : '';
    });
});